diff --git a/ai2thor/_quality_settings.py b/ai2thor/_quality_settings.py index fe58829b2e..024fe7cfbf 100644 --- a/ai2thor/_quality_settings.py +++ b/ai2thor/_quality_settings.py @@ -1,11 +1,13 @@ # GENERATED FILE - DO NOT EDIT -DEFAULT_QUALITY = 'Ultra' -QUALITY_SETTINGS = {'DONOTUSE': 0, - 'High': 5, - 'High WebGL': 8, - 'Low': 2, - 'Medium': 3, - 'MediumCloseFitShadows': 4, - 'Ultra': 7, - 'Very High': 6, - 'Very Low': 1} \ No newline at end of file +DEFAULT_QUALITY = "Ultra" +QUALITY_SETTINGS = { + "DONOTUSE": 0, + "High": 5, + "High WebGL": 8, + "Low": 2, + "Medium": 3, + "MediumCloseFitShadows": 4, + "Ultra": 7, + "Very High": 6, + "Very Low": 1, +} diff --git a/ai2thor/benchmarking.py b/ai2thor/benchmarking.py index 5e6762c801..9b916aa5a0 100644 --- a/ai2thor/benchmarking.py +++ b/ai2thor/benchmarking.py @@ -109,7 +109,7 @@ def name(self): @abstractmethod def benchmark(self, env, action_config, add_key_values={}): raise NotImplementedError - + def step_for_config(self, env, action_config, out_errors): evt = None try: @@ -119,7 +119,7 @@ def step_for_config(self, env, action_config, out_errors): out_errors["message"] = str(te) # TODO catch runtime error return evt - + def step(self, env, action, out_errors, **kwargs): evt = None try: @@ -133,7 +133,6 @@ def step(self, env, action, out_errors, **kwargs): def same(self, x): return x - def aggregate_by(self, records, dimensions, transform=True, aggregate_out_key=None): if not isinstance(dimensions, list): dimensions = [dimensions] @@ -154,7 +153,7 @@ def aggregate_by(self, records, dimensions, transform=True, aggregate_out_key=No { "count": len(slice), aggregate_out_key: np.sum([v[self.aggregate_key()] for v in slice]) - / len(slice) + / len(slice), } ) for dimension, slice in groups @@ -166,12 +165,12 @@ def aggregate_by(self, records, dimensions, transform=True, aggregate_out_key=No "count": len(slice), aggregate_out_key: np.sum([v[self.aggregate_key()] for v in slice]) / len(slice), - "index": slice[0]["index"] if len(slice) == 1 else 0 + "index": slice[0]["index"] if len(slice) == 1 else 0, } if "timeout" in aggregate and aggregate["timeout"]: aggregate["timeout_message"] = aggregate["message"] if len(slice) == 1: - aggregate["index"] = slice[0]["index"] + aggregate["index"] = slice[0]["index"] aggregated_groups[dimension] = aggregate return aggregated_groups @@ -215,7 +214,8 @@ def transform_aggregate(self, report): if self.only_transformed_key: del report[self.aggregate_key()] return report - + + class PhysicsSimulateCountBenchmarker(Benchmarker): def __init__(self, only_transformed_key=False): self.only_transformed_key = only_transformed_key @@ -254,23 +254,22 @@ def transform_aggregate(self, report): if self.only_transformed_key: del report[self.aggregate_key()] return report - - + class UnityActionBenchmarkRunner(BenchmarkConfig): def __clean_action(self, action: Union[str, Dict[str, Any]]): - if isinstance(action, str): + if isinstance(action, str): return {"action": action, "args": {}} if "args" not in action: - action_name = action.pop('action', None) - return {"action":action_name, "args":{**action}} + action_name = action.pop("action", None) + return {"action": action_name, "args": {**action}} else: return {**action, "args": action.get("args", {})} def __get_complete_action_dict(self, action_group): group_copy = copy.deepcopy(action_group) actions_copy = group_copy["actions"] - + group_copy["actions"] = [ self.__clean_action(a) for a in actions_copy @@ -286,9 +285,9 @@ def __get_complete_action_dict(self, action_group): if group_copy["selector"] == "random": group_copy["selector"] = default_selector elif group_copy["selector"] == "sequence": - group_copy['it'] = iter(group_copy["actions"]) - - group_copy["selector"] = lambda x: next(group_copy['it']) + group_copy["it"] = iter(group_copy["actions"]) + + group_copy["selector"] = lambda x: next(group_copy["it"]) group_copy["sample_count"] = len(group_copy["actions"]) # TODO: potentially add more selectors if group_copy["selector"] is None: @@ -332,16 +331,10 @@ def __set_object_filter(self, env): def __teleport_to_random_reachable(self, env, house=None): evt = env.step(action="GetReachablePositions") - if ( - house is not None - and "metadata" in house - and not evt.metadata["lastActionSuccess"] - ): + if house is not None and "metadata" in house and not evt.metadata["lastActionSuccess"]: if "agent" in house["metadata"]: logger.info("Teleporting") - evt = env.step( - dict(action="TeleportFull", forceAction=True, **house["metadata"]) - ) + evt = env.step(dict(action="TeleportFull", forceAction=True, **house["metadata"])) if ( not evt.metadata["lastActionSuccess"] @@ -408,14 +401,12 @@ def centroid(poly): standing=True, ) ) - + def __init_env(self): args = self.init_params controller_params = copy.deepcopy(args) if "server_class" in args: - controller_params["server_type"] = controller_params[ - "server_class" - ].server_type + controller_params["server_type"] = controller_params["server_class"].server_type del controller_params["server_class"] env = ai2thor.controller.Controller(**args) return env, controller_params @@ -438,10 +429,7 @@ def __create_experiments(self): experiment_list = [ [ - [ - (scene, procedural_house, benchmarker, i) - for benchmarker in self.benchmarkers - ] + [(scene, procedural_house, benchmarker, i) for benchmarker in self.benchmarkers] for i in range(self.experiment_sample_count) ] for (scene, procedural_house) in scene_list @@ -463,20 +451,16 @@ def __create_experiments(self): return experiment_list def benchmark(self, action_map={}): - + env, controller_params = self.__init_env() experiment_list = self.__create_experiments() hostname = "" try: - hostname = ( - subprocess.check_output("hostname -f", shell=True) - .decode("utf8") - .strip() - ) + hostname = subprocess.check_output("hostname -f", shell=True).decode("utf8").strip() except Exception as e: logger.exception(f"Could not run 'hostname -f' {str(e)}") pass - + run_in_editor = controller_params["start_unity"] == False and controller_params["port"] benchmark_map = { "title": self.name, @@ -486,7 +470,7 @@ def benchmark(self, action_map={}): "platform": platform.system(), "arch": env._build.platform.__name__, "ran_in_editor": run_in_editor, - "commit_id": env._build.commit_id if hasattr(env._build, 'commit_id') else None, + "commit_id": env._build.commit_id if hasattr(env._build, "commit_id") else None, "filter_object_types": self.filter_object_types, "experiment_sample_count": self.experiment_sample_count, }, @@ -511,9 +495,7 @@ def benchmark(self, action_map={}): if house is not None: success = self.__create_procedural_house(env, house) if not success: - logger.warn( - f"Procedural house creation failed for house {house['id']}" - ) + logger.warn(f"Procedural house creation failed for house {house['id']}") continue house_id = house["id"] logger.info(f"------ Scene: '{scene}', house={house_id}") @@ -522,12 +504,12 @@ def benchmark(self, action_map={}): k: self.__get_complete_action_dict(group) for k, group in action_map.items() } records = [] - + for action_group_name, action_group in action_setup.items(): print(f"---- Action group: {action_group_name}") if self.teleport_random_before_actions: self.__teleport_to_random_reachable(env, house) - + for i in range(action_group["sample_count"]): # print(f"Selector {action_group['selector']} action_g? {action_group} actions {action_group['actions']}") action_config = action_group["selector"](action_group["actions"]) @@ -541,14 +523,14 @@ def benchmark(self, action_map={}): "scene": scene, "experiment_index": experiment_index, "benchmarker": benchmarker.name(), - "index": i + "index": i, }, ) records.append(record) if "timeout" in record and record["timeout"]: timeout = True break - + if timeout: break @@ -568,7 +550,11 @@ def benchmark(self, action_map={}): by_action_single = {} i = 0 for benchmarker in self.benchmarkers: - benchmarker_records = [r for r in records_by_benchmarker[benchmarker.name()] if r["benchmarker"] == benchmarker.name()] + benchmarker_records = [ + r + for r in records_by_benchmarker[benchmarker.name()] + if r["benchmarker"] == benchmarker.name() + ] # print(f"---- benc {benchmarker_records}") # print("-----------") by_benchmarker.update(benchmarker.aggregate_by(benchmarker_records, "benchmarker")) @@ -583,7 +569,8 @@ def benchmark(self, action_map={}): ) by_action_and_group.update( benchmarker.aggregate_by( - benchmarker_records, ["scene", "house", "benchmarker", "action_group", "action"] + benchmarker_records, + ["scene", "house", "benchmarker", "action_group", "action"], ) ) @@ -592,10 +579,10 @@ def benchmark(self, action_map={}): benchmarker.aggregate_by( benchmarker_records, ["scene", "house", "benchmarker", "action_group", "action", "index"], - transform=False + transform=False, ) ) - + by_action_group.update( benchmarker.aggregate_by( benchmarker_records, ["scene", "house", "benchmarker", "action_group"] @@ -604,10 +591,11 @@ def benchmark(self, action_map={}): if i == 0: with open("debug.json", "w") as f: json.dump(benchmarker_records, f) - i+=1 + i += 1 - - house_or_scene = lambda scene, house: scene if scene != "Procedural" or scene == "ProceduralAB" else house + house_or_scene = lambda scene, house: ( + scene if scene != "Procedural" or scene == "ProceduralAB" else house + ) benchmark_map["action_groups"] = { group_name: [a["action"] for a in group["actions"]] for group_name, group in action_map.items() @@ -625,47 +613,46 @@ def benchmark(self, action_map={}): # print(by_action_and_group) # # aggregate_copy = copy.deepcopy(aggregate) - + # print(f"------ aggregate {benchmarker_name} {action_group} : {aggregate_copy}") # print("---------") - - - - benchmark_map["benchmarks"][benchmarker_name][ - house_or_scene(scene, house_id) - ][action_group] = aggregate_copy + + benchmark_map["benchmarks"][benchmarker_name][house_or_scene(scene, house_id)][ + action_group + ] = aggregate_copy for ( scene, house_id, benchmarker_name, action_group, - action + action, ), aggregate in by_action_and_group.items(): - benchmark_map["benchmarks"][benchmarker_name][ - house_or_scene(scene, house_id) - ][action_group]["by_actions"][action] = aggregate + benchmark_map["benchmarks"][benchmarker_name][house_or_scene(scene, house_id)][ + action_group + ]["by_actions"][action] = aggregate - for ( scene, house_id, benchmarker_name, action_group, action, - index + index, ), aggregate in by_action_single.items(): - if "individual" not in benchmark_map["benchmarks"][benchmarker_name][ - house_or_scene(scene, house_id) - ][action_group]["by_actions"][action]: - benchmark_map["benchmarks"][benchmarker_name][ + if ( + "individual" + not in benchmark_map["benchmarks"][benchmarker_name][ house_or_scene(scene, house_id) - ][action_group]["by_actions"][action]["individual"] = [] - - benchmark_map["benchmarks"][benchmarker_name][ - house_or_scene(scene, house_id) - ][action_group]["by_actions"][action]["individual"].append(aggregate) + ][action_group]["by_actions"][action] + ): + benchmark_map["benchmarks"][benchmarker_name][house_or_scene(scene, house_id)][ + action_group + ]["by_actions"][action]["individual"] = [] + benchmark_map["benchmarks"][benchmarker_name][house_or_scene(scene, house_id)][ + action_group + ]["by_actions"][action]["individual"].append(aggregate) for ( scene, @@ -673,22 +660,22 @@ def benchmark(self, action_map={}): benchmarker_name, action_name, ), aggregate in by_action_across.items(): - benchmark_map["benchmarks"][benchmarker_name][ - house_or_scene(scene, house_id) - ][action_name] = aggregate + benchmark_map["benchmarks"][benchmarker_name][house_or_scene(scene, house_id)][ + action_name + ] = aggregate for (scene, house_id, benchmarker_name), aggregate in by_scene.items(): - benchmark_map["benchmarks"][benchmarker_name][ - house_or_scene(scene, house_id) - ]["scene"] = aggregate + benchmark_map["benchmarks"][benchmarker_name][house_or_scene(scene, house_id)][ + "scene" + ] = aggregate if scene == "Procedural" or scene == "ProceduralAB": print(f"----- house or scene: {house_or_scene(scene, house_id)}") - benchmark_map["benchmarks"][benchmarker_name][ - house_or_scene(scene, house_id) - ]["scene"]["procedural"] = True - benchmark_map["benchmarks"][benchmarker_name][ - house_or_scene(scene, house_id) - ]["scene"]["house_id"] = house_id + benchmark_map["benchmarks"][benchmarker_name][house_or_scene(scene, house_id)][ + "scene" + ]["procedural"] = True + benchmark_map["benchmarks"][benchmarker_name][house_or_scene(scene, house_id)][ + "scene" + ]["house_id"] = house_id for benchmarker_name, aggregate in by_benchmarker.items(): benchmark_map["benchmarks"][benchmarker_name]["global"] = aggregate diff --git a/ai2thor/build.py b/ai2thor/build.py index bbd2f1ab39..5e8a36c15e 100644 --- a/ai2thor/build.py +++ b/ai2thor/build.py @@ -9,7 +9,13 @@ from ai2thor.util.lock import LockSh, LockEx from ai2thor.util import atomic_write import io -from ai2thor.platform import STR_PLATFORM_MAP, OSXIntel64, Linux64, CloudRendering, StandaloneWindows64 +from ai2thor.platform import ( + STR_PLATFORM_MAP, + OSXIntel64, + Linux64, + CloudRendering, + StandaloneWindows64, +) import platform logger = logging.getLogger(__name__) @@ -57,7 +63,9 @@ def __init__(self): self.server_types = ["FIFO", "WSGI"] self.url = None self.unity_proc = None - external_system_platforms = dict(Linux=Linux64, Darwin=OSXIntel64, Windows=StandaloneWindows64) + external_system_platforms = dict( + Linux=Linux64, Darwin=OSXIntel64, Windows=StandaloneWindows64 + ) self.platform = external_system_platforms[platform.system()] def download(self): @@ -71,14 +79,7 @@ def lock_sh(self): @property def base_dir(self): - return os.path.join( - os.path.dirname( - os.path.dirname( - os.path.realpath(__file__) - ) - ), - "unity" - ) + return os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "unity") class ExternalBuild(object): @@ -101,13 +102,9 @@ def lock_sh(self): @property def base_dir(self): - return os.path.dirname( - os.path.dirname( - os.path.dirname( - os.path.dirname(self.executable_path) - ) + return os.path.dirname( + os.path.dirname(os.path.dirname(os.path.dirname(self.executable_path))) ) - ) class Build(object): @@ -155,9 +152,7 @@ def download(self): logger.debug("%s exists - skipping download" % (self.executable_path,)) def zipfile(self): - zip_data = ai2thor.downloader.download( - self.url, self.sha256(), self.include_private_scenes - ) + zip_data = ai2thor.downloader.download(self.url, self.sha256(), self.include_private_scenes) return zipfile.ZipFile(io.BytesIO(zip_data)) @@ -217,9 +212,7 @@ def url(self): @property def name(self): - return build_name( - self.platform.name(), self.commit_id, self.include_private_scenes - ) + return build_name(self.platform.name(), self.commit_id, self.include_private_scenes) def unlock(self): if self._lock: diff --git a/ai2thor/controller.py b/ai2thor/controller.py index a3897c0166..057dc44fd8 100644 --- a/ai2thor/controller.py +++ b/ai2thor/controller.py @@ -448,8 +448,7 @@ def __init__( { func for func in dir(action_hook_runner) - if callable(getattr(action_hook_runner, func)) - and not func.startswith("__") + if callable(getattr(action_hook_runner, func)) and not func.startswith("__") } if self.action_hook_runner is not None else None @@ -461,8 +460,7 @@ def __init__( # numbers.Integral works for numpy.int32/64 and Python int if not isinstance(self.gpu_device, numbers.Integral) or self.gpu_device < 0: raise ValueError( - "Invalid gpu_device: '%s'. gpu_device must be >= 0" - % self.gpu_device + "Invalid gpu_device: '%s'. gpu_device must be >= 0" % self.gpu_device ) elif cuda_visible_devices: if self.gpu_device >= len(cuda_visible_devices): @@ -485,9 +483,7 @@ def __init__( if quality not in QUALITY_SETTINGS: valid_qualities = [ - q - for q, v in sorted(QUALITY_SETTINGS.items(), key=lambda qv: qv[1]) - if v > 0 + q for q, v in sorted(QUALITY_SETTINGS.items(), key=lambda qv: qv[1]) if v > 0 ] raise ValueError( @@ -499,9 +495,7 @@ def __init__( elif QUALITY_SETTINGS[quality] == 0: raise ValueError( "Quality {} is associated with an index of 0. " - "Due to a bug in unity, this quality setting would be ignored.".format( - quality - ) + "Due to a bug in unity, this quality setting would be ignored.".format(quality) ) self.server_class = None @@ -522,7 +516,7 @@ def __init__( self.server_class = ai2thor.fifo_server.FifoServer else: self.server_class = server_class - + self._build = None self.interactive_controller = InteractiveControllerPrompt( @@ -621,7 +615,6 @@ def __init__( self.server.set_init_params(init_return) logging.info(f"Initialize return: {init_return}") - def _build_server(self, host, port, width, height): if self.server is not None: return @@ -654,7 +647,7 @@ def _build_server(self, host, port, width, height): timeout=self.server_timeout, depth_format=self.depth_format, add_depth_noise=self.add_depth_noise, - start_unity=self.start_unity + start_unity=self.start_unity, ) def __enter__(self): @@ -711,8 +704,7 @@ def reset(self, scene=None, **init_params): if ( scene in self.robothor_scenes() - and self.initialization_parameters.get("agentMode", "default").lower() - != "locobot" + and self.initialization_parameters.get("agentMode", "default").lower() != "locobot" ): warnings.warn( "You are using a RoboTHOR scene without using the standard LoCoBot.\n" @@ -758,7 +750,7 @@ def reset(self, scene=None, **init_params): warnings.warn( "On reset and upon initialization, agentMode='bot' has been renamed to agentMode='locobot'." ) - + self.last_event = self.step( action="Initialize", raise_for_failure=True, @@ -897,9 +889,7 @@ def prune_releases(self): # sort my mtime ascending, keeping the 3 most recent, attempt to prune anything older all_dirs = list( - filter( - os.path.isdir, map(lambda x: os.path.join(rdir, x), os.listdir(rdir)) - ) + filter(os.path.isdir, map(lambda x: os.path.join(rdir, x), os.listdir(rdir))) ) dir_stats = defaultdict(lambda: 0) for d in all_dirs: @@ -1029,9 +1019,7 @@ def step(self, action: Union[str, Dict[str, Any]] = None, **action_args): # XXX should be able to get rid of this with some sort of deprecation warning if "AI2THOR_VISIBILITY_DISTANCE" in os.environ: - action["visibilityDistance"] = float( - os.environ["AI2THOR_VISIBILITY_DISTANCE"] - ) + action["visibilityDistance"] = float(os.environ["AI2THOR_VISIBILITY_DISTANCE"]) self.last_action = action @@ -1095,9 +1083,7 @@ def step(self, action: Union[str, Dict[str, Any]] = None, **action_args): ]: raise ValueError(self.last_event.metadata["errorMessage"]) elif raise_for_failure: - raise RuntimeError( - self.last_event.metadata.get("errorMessage", f"{action} failed") - ) + raise RuntimeError(self.last_event.metadata.get("errorMessage", f"{action} failed")) return self.last_event @@ -1120,9 +1106,7 @@ def unity_command(self, width, height, headless): # code finds the device_uuids for each GPU and then figures out the mapping # between the CUDA device ids and the Vulkan device ids. - cuda_vulkan_mapping_path = os.path.join( - self.base_dir, "cuda-vulkan-mapping.json" - ) + cuda_vulkan_mapping_path = os.path.join(self.base_dir, "cuda-vulkan-mapping.json") with LockEx(cuda_vulkan_mapping_path): if not os.path.exists(cuda_vulkan_mapping_path): vulkan_result = None @@ -1151,14 +1135,9 @@ def unity_command(self, width, height, headless): elif "deviceUUID" in l: device_uuid = l.split("=")[1].strip() if device_uuid in device_uuid_to_vulkan_gpu_index: - assert ( - current_gpu - == device_uuid_to_vulkan_gpu_index[device_uuid] - ) + assert current_gpu == device_uuid_to_vulkan_gpu_index[device_uuid] else: - device_uuid_to_vulkan_gpu_index[ - device_uuid - ] = current_gpu + device_uuid_to_vulkan_gpu_index[device_uuid] = current_gpu nvidiasmi_result = None try: @@ -1184,9 +1163,7 @@ def unity_command(self, width, height, headless): current_gpu = int(gpu_match.group(1)) uuid_match = re.match(".*\\(UUID: GPU-([^)]+)\\)", l) - nvidia_gpu_index_to_device_uuid[current_gpu] = uuid_match.group( - 1 - ) + nvidia_gpu_index_to_device_uuid[current_gpu] = uuid_match.group(1) cuda_vulkan_mapping = {} for ( @@ -1198,18 +1175,16 @@ def unity_command(self, width, height, headless): f"Could not find a Vulkan device corresponding" f" to the CUDA device with UUID {device_uuid}." ) - cuda_vulkan_mapping[ - cuda_gpu_index - ] = device_uuid_to_vulkan_gpu_index[device_uuid] + cuda_vulkan_mapping[cuda_gpu_index] = device_uuid_to_vulkan_gpu_index[ + device_uuid + ] with open(cuda_vulkan_mapping_path, "w") as f: json.dump(cuda_vulkan_mapping, f) else: with open(cuda_vulkan_mapping_path, "r") as f: # JSON dictionaries always have strings as keys, need to re-map here - cuda_vulkan_mapping = { - int(k): v for k, v in json.load(f).items() - } + cuda_vulkan_mapping = {int(k): v for k, v in json.load(f).items()} command += f" -force-device-index {cuda_vulkan_mapping[self.gpu_device]}" @@ -1227,9 +1202,7 @@ def _start_unity_thread(self, env, width, height, server_params, image_name): # print("Viewer: http://%s:%s/viewer" % (host, port)) command = self.unity_command(width, height, self.headless) - env.update( - self._build.platform.launch_env(self.width, self.height, self.x_display) - ) + env.update(self._build.platform.launch_env(self.width, self.height, self.x_display)) makedirs(self.log_dir) extra_args = {} @@ -1325,8 +1298,7 @@ def _branch_commits(self, branch): else: try: res = requests.get( - "https://api.github.com/repos/allenai/ai2thor/commits?sha=%s" - % branch + "https://api.github.com/repos/allenai/ai2thor/commits?sha=%s" % branch ) if res.status_code == 404: raise ValueError("Invalid branch name: %s" % branch) @@ -1360,9 +1332,7 @@ def _branch_commits(self, branch): return [c["sha"] for c in payload] def local_commits(self): - git_dir = os.path.normpath( - os.path.dirname(os.path.realpath(__file__)) + "/../.git" - ) + git_dir = os.path.normpath(os.path.dirname(os.path.realpath(__file__)) + "/../.git") commits = ( subprocess.check_output( "git --git-dir=" + git_dir + " log -n 10 --format=%H", shell=True @@ -1399,7 +1369,9 @@ def find_build(self, local_build, commit_id, branch, platform): if platform is None: candidate_platforms = ai2thor.platform.select_platforms(request) else: - candidate_platforms = [STR_PLATFORM_MAP[platform] if isinstance(platform, str) else platform] + candidate_platforms = [ + STR_PLATFORM_MAP[platform] if isinstance(platform, str) else platform + ] builds = self.find_platform_builds( candidate_platforms, request, commits, releases_dir, local_build @@ -1442,12 +1414,9 @@ def find_build(self, local_build, commit_id, branch, platform): ] for build in builds: errors = build.platform.validate(request) - message = ( - "Platform %s failed validation with the following errors: %s\n " - % ( - build.platform.name(), - "\t\n".join(errors), - ) + message = "Platform %s failed validation with the following errors: %s\n " % ( + build.platform.name(), + "\t\n".join(errors), ) instructions = build.platform.dependency_instructions(request) if instructions: @@ -1565,9 +1534,7 @@ def stop_unity(self): class BFSSearchPoint: - def __init__( - self, start_position, move_vector, heading_angle=0.0, horizon_angle=0.0 - ): + def __init__(self, start_position, move_vector, heading_angle=0.0, horizon_angle=0.0): self.start_position = start_position self.move_vector = defaultdict(lambda: 0.0) self.move_vector.update(move_vector) @@ -1648,8 +1615,7 @@ def enqueue_island_points(p): point_to_find = queue.pop() for p in self.grid_points: dist = math.sqrt( - ((point_to_find["x"] - p["x"]) ** 2) - + ((point_to_find["z"] - p["z"]) ** 2) + ((point_to_find["x"] - p["x"]) ** 2) + ((point_to_find["z"] - p["z"]) ** 2) ) if dist < 0.05: @@ -1671,9 +1637,7 @@ def key_for_point(self, point): def _build_graph_point(self, graph, point): for p in self.grid_points: - dist = math.sqrt( - ((point["x"] - p["x"]) ** 2) + ((point["z"] - p["z"]) ** 2) - ) + dist = math.sqrt(((point["x"] - p["x"]) ** 2) + ((point["z"] - p["z"]) ** 2)) if dist <= (self.grid_size + 0.01) and dist > 0: graph.add_edge(self.key_for_point(point), self.key_for_point(p)) @@ -1704,9 +1668,7 @@ def move_relative_points(self, all_points, graph, position, rotation): def plan_horizons(self, agent_horizon, target_horizon): actions = [] horizon_step_map = {330: 3, 0: 2, 30: 1, 60: 0} - look_diff = ( - horizon_step_map[int(agent_horizon)] - horizon_step_map[int(target_horizon)] - ) + look_diff = horizon_step_map[int(agent_horizon)] - horizon_step_map[int(target_horizon)] if look_diff > 0: for i in range(look_diff): actions.append(dict(action="LookDown")) @@ -1793,16 +1755,10 @@ def enqueue_points(self, agent_position): self.visited_seen_points, ) ): - self.enqueue_point( - BFSSearchPoint(agent_position, dict(x=-1 * self.grid_size)) - ) + self.enqueue_point(BFSSearchPoint(agent_position, dict(x=-1 * self.grid_size))) self.enqueue_point(BFSSearchPoint(agent_position, dict(x=self.grid_size))) - self.enqueue_point( - BFSSearchPoint(agent_position, dict(z=-1 * self.grid_size)) - ) - self.enqueue_point( - BFSSearchPoint(agent_position, dict(z=1 * self.grid_size)) - ) + self.enqueue_point(BFSSearchPoint(agent_position, dict(z=-1 * self.grid_size))) + self.enqueue_point(BFSSearchPoint(agent_position, dict(z=1 * self.grid_size))) self.visited_seen_points.append(agent_position) def search_all_closed(self, scene_name): @@ -1881,16 +1837,10 @@ def prune_points(self): for gp in self.grid_points: found = False for x in [1, -1]: - found |= ( - key_for_point(gp["x"] + (self.grid_size * x), gp["z"]) - in final_grid_points - ) + found |= key_for_point(gp["x"] + (self.grid_size * x), gp["z"]) in final_grid_points for z in [1, -1]: - found |= ( - key_for_point(gp["x"], (self.grid_size * z) + gp["z"]) - in final_grid_points - ) + found |= key_for_point(gp["x"], (self.grid_size * z) + gp["z"]) in final_grid_points if found: pruned_grid_points.append(gp) @@ -1919,10 +1869,7 @@ def find_visible_receptacles(self): forceVisible=True, ) ) - if ( - visibility_object_id is None - and obj["objectType"] in visibility_object_types - ): + if visibility_object_id is None and obj["objectType"] in visibility_object_types: visibility_object_id = obj["objectId"] for point in self.grid_points: @@ -2054,17 +2001,13 @@ def initialize_scene(self): pickupable = {} is_open = {} - for obj in filter( - lambda x: x["receptacle"], self.last_event.metadata["objects"] - ): + for obj in filter(lambda x: x["receptacle"], self.last_event.metadata["objects"]): for oid in obj["receptacleObjectIds"]: self.object_receptacle[oid] = obj is_open[obj["objectId"]] = obj["openable"] and obj["isOpen"] - for obj in filter( - lambda x: x["receptacle"], self.last_event.metadata["objects"] - ): + for obj in filter(lambda x: x["receptacle"], self.last_event.metadata["objects"]): for oid in obj["receptacleObjectIds"]: if obj["openable"] or ( obj["objectId"] in self.object_receptacle @@ -2079,9 +2022,7 @@ def initialize_scene(self): shuffled_keys = list(open_pickupable.keys()) random.shuffle(shuffled_keys) for oid in shuffled_keys: - position_target = self.object_receptacle[self.target_objects[0]][ - "position" - ] + position_target = self.object_receptacle[self.target_objects[0]]["position"] position_candidate = self.object_receptacle[oid]["position"] dist = math.sqrt( (position_target["x"] - position_candidate["x"]) ** 2 diff --git a/ai2thor/docker.py b/ai2thor/docker.py index a31e75ee77..c8bd470382 100644 --- a/ai2thor/docker.py +++ b/ai2thor/docker.py @@ -58,8 +58,7 @@ def bridge_gateway(): return output else: raise Exception( - "Didn't receive a single ip address from network inspect bridge: %s" - % output + "Didn't receive a single ip address from network inspect bridge: %s" % output ) diff --git a/ai2thor/fifo_server.py b/ai2thor/fifo_server.py index 666619e7f8..f3afcd44bd 100644 --- a/ai2thor/fifo_server.py +++ b/ai2thor/fifo_server.py @@ -44,8 +44,10 @@ class FieldType(IntEnum): THIRD_PARTY_FLOW = 16 END_OF_MESSAGE = 255 + import signal + # Define the function to be called on timeout def handle_fifo_connect_timeout(signum, frame): raise TimeoutError("FIFO server failed to conect to Unity in time.") @@ -64,7 +66,7 @@ def __init__( timeout: Optional[float] = 100.0, depth_format=ai2thor.server.DepthFormat.Meters, add_depth_noise: bool = False, - start_unity: bool = True + start_unity: bool = True, ): if not start_unity: raise NotImplemented @@ -123,9 +125,7 @@ def __init__( def _create_header(self, message_type, body): return struct.pack(self.header_format, message_type, len(body)) - def _read_with_timeout( - self, server_pipe, message_size: int, timeout: Optional[float] - ): + def _read_with_timeout(self, server_pipe, message_size: int, timeout: Optional[float]): if timeout is None: return server_pipe.read(message_size) @@ -259,9 +259,7 @@ def _send_message(self, message_type, body): self.client_pipe.flush() def receive(self, timeout: Optional[float] = None): - metadata, files = self._recv_message( - timeout=self.timeout if timeout is None else timeout - ) + metadata, files = self._recv_message(timeout=self.timeout if timeout is None else timeout) if metadata is None: raise ValueError("no metadata received from recv_message") diff --git a/ai2thor/hooks/metadata_hook.py b/ai2thor/hooks/metadata_hook.py index 2225c1721e..5f08d631ad 100644 --- a/ai2thor/hooks/metadata_hook.py +++ b/ai2thor/hooks/metadata_hook.py @@ -10,5 +10,4 @@ class MetadataHook(Protocol): - def __call__(self, metadata: Dict[str, Any], controller: "Controller"): - ... + def __call__(self, metadata: Dict[str, Any], controller: "Controller"): ... diff --git a/ai2thor/hooks/procedural_asset_hook.py b/ai2thor/hooks/procedural_asset_hook.py index 6aee37f609..171ce5173f 100644 --- a/ai2thor/hooks/procedural_asset_hook.py +++ b/ai2thor/hooks/procedural_asset_hook.py @@ -13,13 +13,13 @@ from typing import Dict, Any, List -from objathor.asset_conversion.util import ( - get_existing_thor_asset_file_path, - create_runtime_asset_file, +from objathor.asset_conversion.util import ( + get_existing_thor_asset_file_path, + create_runtime_asset_file, get_existing_thor_asset_file_path, change_asset_paths, add_default_annotations, - load_existing_thor_asset_file + load_existing_thor_asset_file, ) logger = logging.getLogger(__name__) @@ -31,9 +31,8 @@ ".msgpack.gz", } -def get_all_asset_ids_recursively( - objects: List[Dict[str, Any]], asset_ids: List[str] -) -> List[str]: + +def get_all_asset_ids_recursively(objects: List[Dict[str, Any]], asset_ids: List[str]) -> List[str]: """ Get all asset IDs in a house. """ @@ -46,6 +45,7 @@ def get_all_asset_ids_recursively( assets_set.remove("") return list(assets_set) + def create_asset( thor_controller, asset_id, @@ -55,7 +55,7 @@ def create_asset( load_file_in_unity=False, extension=None, raise_for_failure=True, - fail_if_not_unity_loadable=False + fail_if_not_unity_loadable=False, ): return create_assets( thor_controller=thor_controller, @@ -69,6 +69,7 @@ def create_asset( raise_for_failure=raise_for_failure, ) + def create_assets( thor_controller: Any, asset_ids: List[str], @@ -81,9 +82,7 @@ def create_assets( raise_for_failure=True, ): copy_to_dir = ( - os.path.join(thor_controller._build.base_dir) - if copy_to_dir is None - else copy_to_dir + os.path.join(thor_controller._build.base_dir) if copy_to_dir is None else copy_to_dir ) multi_create_unity_loadable = dict( @@ -124,7 +123,7 @@ def create_assets( save_dir=copy_to_dir, asset_id=asset_id, load_file_in_unity=load_asset_in_unity, - verbose=verbose + verbose=verbose, ) if not load_asset_in_unity: @@ -133,9 +132,7 @@ def create_assets( # out_dir=asset_target_dir, object_name=asset_id, force_extension=file_extension # ) asset = change_asset_paths(asset=asset, save_dir=copy_to_dir) - asset = add_default_annotations( - asset=asset, asset_directory=asset_dir, verbose=verbose - ) + asset = add_default_annotations(asset=asset, asset_directory=asset_dir, verbose=verbose) create_prefab_action = { "action": "CreateRuntimeAsset", "asset": asset, @@ -150,15 +147,15 @@ def create_assets( asset_args = add_default_annotations( asset=asset_args, asset_directory=asset_dir, verbose=verbose ) - multi_create_unity_loadable["assets"].append( - asset_args - ) - + multi_create_unity_loadable["assets"].append(asset_args) + if fail_if_not_unity_loadable: - error_strs = ', '.join(errors) - extensions = ', '.join(EXTENSIONS_LOADABLE_IN_UNITY) - raise RuntimeError(f"Set to fail if files are not loadable in unity. Invalid extension of files `{error_strs}` must be of any of extensions {extensions}") - + error_strs = ", ".join(errors) + extensions = ", ".join(EXTENSIONS_LOADABLE_IN_UNITY) + raise RuntimeError( + f"Set to fail if files are not loadable in unity. Invalid extension of files `{error_strs}` must be of any of extensions {extensions}" + ) + events = [] # Slow pass asset data to pipe if len(create_with_data_actions): @@ -189,23 +186,21 @@ def create_assets_if_not_exist( asset_ids, asset_directory, copy_to_dir, - asset_symlink, # TODO remove + asset_symlink, # TODO remove stop_if_fail, load_file_in_unity, extension=None, verbose=False, raise_for_failure=True, - fail_if_not_unity_loadable=False + fail_if_not_unity_loadable=False, ): evt = controller.step( action="AssetsInDatabase", assetIds=asset_ids, updateProceduralLRUCache=True ) asset_in_db = evt.metadata["actionReturn"] - assets_not_created = [ - asset_id for (asset_id, in_db) in asset_in_db.items() if not in_db - ] - + assets_not_created = [asset_id for (asset_id, in_db) in asset_in_db.items() if not in_db] + events = create_assets( thor_controller=controller, asset_ids=assets_not_created, @@ -214,16 +209,19 @@ def create_assets_if_not_exist( verbose=verbose, load_file_in_unity=load_file_in_unity, extension=extension, - fail_if_not_unity_loadable=fail_if_not_unity_loadable + fail_if_not_unity_loadable=fail_if_not_unity_loadable, ) - for (evt, i) in zip(events, range(len(events))) : + for evt, i in zip(events, range(len(events))): if not evt.metadata["lastActionSuccess"]: # TODO do a better matching of asset_ids and event - asset_id = assets_not_created[i] if i < len(events) else None - asset_path = get_existing_thor_asset_file_path(out_dir=asset_directory, asset_id=asset_id) if asset_id is not None else "" + asset_id = assets_not_created[i] if i < len(events) else None + asset_path = ( + get_existing_thor_asset_file_path(out_dir=asset_directory, asset_id=asset_id) + if asset_id is not None + else "" + ) warnings.warn( - f"Could not create asset `{asset_path}`." - f"\nError: {evt.metadata['errorMessage']}" + f"Could not create asset `{asset_path}`." f"\nError: {evt.metadata['errorMessage']}" ) return events[-1] @@ -248,7 +246,6 @@ def create_assets_if_not_exist( # ) # if stop_if_fail: # return evt - class ProceduralAssetHookRunner: @@ -309,9 +306,7 @@ def SpawnAsset(self, action, controller): def GetHouseFromTemplate(self, action, controller): template = action["template"] - asset_ids = get_all_asset_ids_recursively( - [v for (k, v) in template["objects"].items()], [] - ) + asset_ids = get_all_asset_ids_recursively([v for (k, v) in template["objects"].items()], []) return create_assets_if_not_exist( controller=controller, asset_ids=asset_ids, @@ -338,9 +333,7 @@ def CreateHouse(self, action, controller): asset_ids = list(set(obj["assetId"] for obj in house["objects"])) evt = controller.step(action="AssetsInDatabase", assetIds=asset_ids) asset_in_db = evt.metadata["actionReturn"] - assets_not_created = [ - asset_id for (asset_id, in_db) in asset_in_db.items() if in_db - ] + assets_not_created = [asset_id for (asset_id, in_db) in asset_in_db.items() if in_db] not_created_set = set(assets_not_created) not_objeverse_not_created = not_created_set.difference(self.objaverse_uid_set) if len(not_created_set): diff --git a/ai2thor/interact.py b/ai2thor/interact.py index a9b97da60a..8e0593d7dd 100644 --- a/ai2thor/interact.py +++ b/ai2thor/interact.py @@ -79,9 +79,7 @@ def __init__( action_set = {a.name for a in default_actions} self.default_interact_commands = { - k: v - for (k, v) in default_interact_commands.items() - if v["action"] in action_set + k: v for (k, v) in default_interact_commands.items() if v["action"] in action_set } def interact( @@ -101,7 +99,7 @@ def interact( self._interact_commands = default_interact_commands.copy() - command_message = u"Enter a Command: Move \u2190\u2191\u2192\u2193, Rotate/Look Shift + \u2190\u2191\u2192\u2193, Quit 'q' or Ctrl-C" + command_message = "Enter a Command: Move \u2190\u2191\u2192\u2193, Rotate/Look Shift + \u2190\u2191\u2192\u2193, Quit 'q' or Ctrl-C" print(command_message) for a in self.next_interact_command(): new_commands = {} @@ -155,9 +153,7 @@ def add_command(cc, action, **args): ) if len(event.metadata["inventoryObjects"]) > 0: - inventoryObjectId = event.metadata["inventoryObjects"][0][ - "objectId" - ] + inventoryObjectId = event.metadata["inventoryObjects"][0]["objectId"] if ( o["receptacle"] and (not o["openable"] or o["isOpen"]) @@ -169,30 +165,16 @@ def add_command(cc, action, **args): objectId=inventoryObjectId, receptacleObjectId=o["objectId"], ) - add_command( - command_counter, "MoveHandAhead", moveMagnitude=0.1 - ) - add_command( - command_counter, "MoveHandBack", moveMagnitude=0.1 - ) - add_command( - command_counter, "MoveHandRight", moveMagnitude=0.1 - ) - add_command( - command_counter, "MoveHandLeft", moveMagnitude=0.1 - ) - add_command( - command_counter, "MoveHandUp", moveMagnitude=0.1 - ) - add_command( - command_counter, "MoveHandDown", moveMagnitude=0.1 - ) + add_command(command_counter, "MoveHandAhead", moveMagnitude=0.1) + add_command(command_counter, "MoveHandBack", moveMagnitude=0.1) + add_command(command_counter, "MoveHandRight", moveMagnitude=0.1) + add_command(command_counter, "MoveHandLeft", moveMagnitude=0.1) + add_command(command_counter, "MoveHandUp", moveMagnitude=0.1) + add_command(command_counter, "MoveHandDown", moveMagnitude=0.1) add_command(command_counter, "DropHandObject") elif o["pickupable"]: - add_command( - command_counter, "PickupObject", objectId=o["objectId"] - ) + add_command(command_counter, "PickupObject", objectId=o["objectId"]) self._interact_commands = default_interact_commands.copy() self._interact_commands.update(new_commands) @@ -306,9 +288,7 @@ def json_write(name, obj): lambda event: event.depth_frame, lambda x: x, lambda name, x: np.save( - name.strip(".png").strip("./") - if image_dir == "." - else name.strip(".png"), + name.strip(".png").strip("./") if image_dir == "." else name.strip(".png"), x.astype(np.float32), ), ), @@ -327,12 +307,14 @@ def json_write(name, obj): frame = transform(frame) image_name = os.path.join( image_dir, - "{}{}".format( - frame_filename, "{}".format(suffix) if image_per_frame else "" - ), + "{}{}".format(frame_filename, "{}".format(suffix) if image_per_frame else ""), ) print("Image {}, {}".format(image_name, image_dir)) save(image_name, frame) elif condition: - print("No frame '{}' present, call initialize with the right parameters".format(frame_filename)) + print( + "No frame '{}' present, call initialize with the right parameters".format( + frame_filename + ) + ) diff --git a/ai2thor/mock_real_server.py b/ai2thor/mock_real_server.py index fc55480f1d..e7de206100 100644 --- a/ai2thor/mock_real_server.py +++ b/ai2thor/mock_real_server.py @@ -40,22 +40,22 @@ def step(): content = request.json metadata = { - u"sequenceId": content["sequenceId"], - u"agents": [ + "sequenceId": content["sequenceId"], + "agents": [ { - u"agentId": 0, - u"screenHeight": self.height, - u"screenWidth": self.width, - u"lastAction": content["action"], - u"lastActionSuccess": True, + "agentId": 0, + "screenHeight": self.height, + "screenWidth": self.width, + "lastAction": content["action"], + "lastActionSuccess": True, } ], } result = { - u"image": [random_image(self.height, self.width).tostring()], - u"image_depth": [], - u"metadata": metadata, + "image": [random_image(self.height, self.width).tostring()], + "image_depth": [], + "metadata": metadata, } out = msgpack.packb(result, use_bin_type=True) diff --git a/ai2thor/offline_controller.py b/ai2thor/offline_controller.py index fe67cdbe42..32ec6c1e69 100644 --- a/ai2thor/offline_controller.py +++ b/ai2thor/offline_controller.py @@ -22,9 +22,7 @@ def __init__(self, base_dir, grid_size=0.25): self.grid_size = grid_size self.base_dir = base_dir if grid_size < 0.25: - raise Exception( - "must adjust granularity of key_for_point for smaller grid sizes" - ) + raise Exception("must adjust granularity of key_for_point for smaller grid sizes") def reset(self, scene_name): self.scene_name = scene_name @@ -100,9 +98,7 @@ def look(self, new_horizon): if new_horizon < -30 or new_horizon > 30: return None else: - return self.find_position( - self.position_x, self.position_z, self.rotation, new_horizon - ) + return self.find_position(self.position_x, self.position_z, self.rotation, new_horizon) def look_up(self): return self.look(self.camera_horizon - 30) @@ -190,9 +186,7 @@ def index_metadata(base_dir, scene_name): pos = agent["position"] key = ai2thor.controller.key_for_point(pos["x"], pos["z"]) pos_id = os.path.splitext(os.path.basename(g))[0] - event_path = os.path.join( - "%s/%s/events/%s.pickle" % (base_dir, scene_name, pos_id) - ) + event_path = os.path.join("%s/%s/events/%s.pickle" % (base_dir, scene_name, pos_id)) positions_index[key].append( { "event": event_path, diff --git a/ai2thor/platform.py b/ai2thor/platform.py index 8794423e13..f70557e407 100644 --- a/ai2thor/platform.py +++ b/ai2thor/platform.py @@ -57,9 +57,7 @@ def dependency_instructions(cls, request): displays = cls._valid_x_displays(request.width, request.height) if displays: - message += "The following valid displays were found %s" % ( - ", ".join(displays) - ) + message += "The following valid displays were found %s" % (", ".join(displays)) else: message += "If you have a NVIDIA GPU, please run: sudo ai2thor-xorg start" @@ -95,9 +93,7 @@ def _validate_screen(cls, display_screen_str, width, height): # this Xlib.display will find a valid screen if an # invalid screen was passed in (e.g. :0.9999999 -> :0.1) if screen_parts[1] != str(disp_screen.get_default_screen()): - errors.append( - "Invalid display, non-existent screen: %s" % display_screen_str - ) + errors.append("Invalid display, non-existent screen: %s" % display_screen_str) if "GLX" not in disp_screen.list_extensions(): errors.append( @@ -126,9 +122,7 @@ def _validate_screen(cls, display_screen_str, width, height): % (display_screen_str, disp_screen.screen()["root_depth"]) ) except (Xlib.error.DisplayNameError, Xlib.error.DisplayConnectionError) as e: - errors.append( - "Invalid display: %s. Failed to connect %s " % (display_screen_str, e) - ) + errors.append("Invalid display: %s. Failed to connect %s " % (display_screen_str, e)) return errors @@ -151,9 +145,7 @@ def _valid_x_displays(cls, width, height): valid_displays.append(disp_screen_str) except Xlib.error.DisplayConnectionError as e: - warnings.warn( - "could not connect to X Display: %s, %s" % (display_str, e) - ) + warnings.warn("could not connect to X Display: %s, %s" % (display_str, e)) return valid_displays @@ -162,9 +154,7 @@ def validate(cls, request): if request.headless: return [] elif request.x_display: - return cls._validate_screen( - request.x_display, request.width, request.height - ) + return cls._validate_screen(request.x_display, request.width, request.height) elif cls._select_x_display(request.width, request.height) is None: return ["No valid X display found"] else: @@ -179,9 +169,7 @@ def old_executable_path(cls, base_dir, name): @classmethod def executable_path(cls, base_dir, name): plist = cls.parse_plist(base_dir, name) - return os.path.join( - base_dir, name + ".app", "Contents/MacOS", plist["CFBundleExecutable"] - ) + return os.path.join(base_dir, name + ".app", "Contents/MacOS", plist["CFBundleExecutable"]) @classmethod def parse_plist(cls, base_dir, name): @@ -219,18 +207,22 @@ def validate(cls, request): class WebGL(BasePlatform): pass + class StandaloneWindows64(BasePlatform): @classmethod def executable_path(cls, base_dir, name): return os.path.join(base_dir, name) + def select_platforms(request): candidates = [] - system_platform_map = dict(Linux=(Linux64,CloudRendering), Darwin=(OSXIntel64,), Windows=(StandaloneWindows64,)) + system_platform_map = dict( + Linux=(Linux64, CloudRendering), Darwin=(OSXIntel64,), Windows=(StandaloneWindows64,) + ) for p in system_platform_map.get(request.system, ()): if not p.enabled: continue - # + # # if p == CloudRendering and request.x_display is not None: # continue candidates.append(p) @@ -238,5 +230,9 @@ def select_platforms(request): STR_PLATFORM_MAP = dict( - CloudRendering=CloudRendering, Linux64=Linux64, OSXIntel64=OSXIntel64, WebGL=WebGL, StandaloneWindows64=StandaloneWindows64 + CloudRendering=CloudRendering, + Linux64=Linux64, + OSXIntel64=OSXIntel64, + WebGL=WebGL, + StandaloneWindows64=StandaloneWindows64, ) diff --git a/ai2thor/robot_controller.py b/ai2thor/robot_controller.py index b639daac38..c96fe2c0be 100644 --- a/ai2thor/robot_controller.py +++ b/ai2thor/robot_controller.py @@ -115,34 +115,47 @@ def step(self, action=None, **action_args): third_party_height = event.screen_height third_party_depth_width = event.screen_width third_party_depth_height = event.screen_height - if 'thirdPartyCameras' in agent_metadata and \ - len(agent_metadata['thirdPartyCameras']) > 0 and \ - 'screenWidth' in agent_metadata['thirdPartyCameras'][0] and \ - 'screenHeight' in agent_metadata['thirdPartyCameras'][0]: - third_party_width = agent_metadata['thirdPartyCameras'][0]['screenWidth'] - third_party_height = agent_metadata['thirdPartyCameras'][0]['screenHeight'] - third_party_depth_width = agent_metadata['thirdPartyCameras'][0]['depthWidth'] - third_party_depth_height = agent_metadata['thirdPartyCameras'][0]['depthHeight'] - - + if ( + "thirdPartyCameras" in agent_metadata + and len(agent_metadata["thirdPartyCameras"]) > 0 + and "screenWidth" in agent_metadata["thirdPartyCameras"][0] + and "screenHeight" in agent_metadata["thirdPartyCameras"][0] + ): + third_party_width = agent_metadata["thirdPartyCameras"][0]["screenWidth"] + third_party_height = agent_metadata["thirdPartyCameras"][0]["screenHeight"] + third_party_depth_width = agent_metadata["thirdPartyCameras"][0]["depthWidth"] + third_party_depth_height = agent_metadata["thirdPartyCameras"][0]["depthHeight"] image_mapping = { - 'image':lambda x: event.add_image(x, flip_y=False, flip_rb_colors=False), - 'image-thirdParty-camera': lambda x: event.add_third_party_camera_image_robot(x, third_party_width, third_party_height), - 'image_thirdParty_depth': lambda x: event.add_third_party_image_depth_robot(x, dtype=np.float64, flip_y=False, depth_format=self.depth_format, depth_width=third_party_depth_width, depth_height=third_party_depth_height), - 'image_depth':lambda x: event.add_image_depth_robot( + "image": lambda x: event.add_image(x, flip_y=False, flip_rb_colors=False), + "image-thirdParty-camera": lambda x: event.add_third_party_camera_image_robot( + x, third_party_width, third_party_height + ), + "image_thirdParty_depth": lambda x: event.add_third_party_image_depth_robot( + x, + dtype=np.float64, + flip_y=False, + depth_format=self.depth_format, + depth_width=third_party_depth_width, + depth_height=third_party_depth_height, + ), + "image_depth": lambda x: event.add_image_depth_robot( x, self.depth_format, camera_near_plane=self.camera_near_plane, camera_far_plane=self.camera_far_plane, - depth_width=agent_metadata.get('depthWidth', agent_metadata['screenWidth']), - depth_height=agent_metadata.get('depthHeight', agent_metadata['screenHeight']), + depth_width=agent_metadata.get("depthWidth", agent_metadata["screenWidth"]), + depth_height=agent_metadata.get("depthHeight", agent_metadata["screenHeight"]), flip_y=False, dtype=np.float64, ), } for key in image_mapping.keys(): - if key == 'image_depth' and 'depthWidth' in agent_metadata and agent_metadata['depthWidth'] != agent_metadata['screenWidth']: + if ( + key == "image_depth" + and "depthWidth" in agent_metadata + and agent_metadata["depthWidth"] != agent_metadata["screenWidth"] + ): warnings.warn("Depth and RGB images are not the same resolutions") if key in payload and len(payload[key]) > i: diff --git a/ai2thor/server.py b/ai2thor/server.py index 4091188abc..46e5f09b10 100644 --- a/ai2thor/server.py +++ b/ai2thor/server.py @@ -42,7 +42,7 @@ def __getitem__(self, key: str): return m @abstractmethod - def mask(self, key: str, default: Optional[np.ndarray]=None) -> Optional[np.ndarray]: + def mask(self, key: str, default: Optional[np.ndarray] = None) -> Optional[np.ndarray]: pass @abstractmethod @@ -58,7 +58,6 @@ def __len__(self): return len(self._masks) - class LazyInstanceSegmentationMasks(LazyMask): def __init__(self, image_ids_data: bytes, metadata: dict): @@ -66,7 +65,7 @@ def __init__(self, image_ids_data: bytes, metadata: dict): self._loaded = False screen_width = metadata["screenWidth"] screen_height = metadata["screenHeight"] - item_size = int(len(image_ids_data)/(screen_width * screen_height)) + item_size = int(len(image_ids_data) / (screen_width * screen_height)) self._unique_integer_keys: Optional[Set[np.uint32]] = None self._empty_mask: Optional[np.ndarray] = None @@ -78,7 +77,7 @@ def __init__(self, image_ids_data: bytes, metadata: dict): # is always equal to 255 self._alpha_channel_value = 255 - elif item_size == 3: # 3 byte per pixel for backwards compatibility, RGB24 texture + elif item_size == 3: # 3 byte per pixel for backwards compatibility, RGB24 texture # this is more expensive than the 4 byte variant since copying is required frame = read_buffer_image(image_ids_data, screen_width, screen_height) self.instance_segmentation_frame_uint32 = np.concatenate( @@ -89,13 +88,15 @@ def __init__(self, image_ids_data: bytes, metadata: dict): axis=2, ) self.instance_segmentation_frame_uint32.dtype = np.uint32 - self.instance_segmentation_frame_uint32 = self.instance_segmentation_frame_uint32.squeeze() + self.instance_segmentation_frame_uint32 = ( + self.instance_segmentation_frame_uint32.squeeze() + ) self._alpha_channel_value = 0 # At this point we should have a 2d matrix of shape (height, width) # with a 32bit uint as the value - self.instance_colors: Dict[str, List[int]]= {} + self.instance_colors: Dict[str, List[int]] = {} self.class_colors: Dict[str, List[List[int]]] = {} for c in metadata["colors"]: cls = c["name"] @@ -109,7 +110,6 @@ def __init__(self, image_ids_data: bytes, metadata: dict): self.class_colors[cls].append(c["color"]) - @property def empty_mask(self) -> np.ndarray: if self._empty_mask is None: @@ -128,7 +128,7 @@ def unique_integer_keys(self) -> Set[np.uint32]: def _integer_color_key(self, color: List[int]) -> np.uint32: a = np.array(color + [self._alpha_channel_value], dtype=np.uint8) # mypy complains, but it is safe to modify the dtype on an ndarray - a.dtype = np.uint32 # type: ignore + a.dtype = np.uint32 # type: ignore return a[0] def _load_all(self): @@ -140,8 +140,7 @@ def _load_all(self): self._loaded = True - - def mask(self, key: str, default: Optional[np.ndarray]=None) -> Optional[np.ndarray]: + def mask(self, key: str, default: Optional[np.ndarray] = None) -> Optional[np.ndarray]: if key not in self.instance_colors: return default elif key in self._masks: @@ -174,11 +173,13 @@ def _load_all(self): break self._loaded = True - def mask(self, key: str, default: Optional[np.ndarray]=None) -> Optional[np.ndarray]: + def mask(self, key: str, default: Optional[np.ndarray] = None) -> Optional[np.ndarray]: if key in self._masks: return self._masks[key] - class_mask = np.zeros(self.instance_masks.instance_segmentation_frame_uint32.shape, dtype=bool) + class_mask = np.zeros( + self.instance_masks.instance_segmentation_frame_uint32.shape, dtype=bool + ) if key == "background": # "background" is a special name for any color that wasn't included in the metadata @@ -197,7 +198,10 @@ def mask(self, key: str, default: Optional[np.ndarray]=None) -> Optional[np.ndar elif "|" not in key: for color in self.instance_masks.class_colors.get(key, []): - mask = self.instance_masks.instance_segmentation_frame_uint32 == self.instance_masks._integer_color_key(color) + mask = ( + self.instance_masks.instance_segmentation_frame_uint32 + == self.instance_masks._integer_color_key(color) + ) class_mask = np.logical_or(class_mask, mask) if class_mask.any(): @@ -206,6 +210,7 @@ def mask(self, key: str, default: Optional[np.ndarray]=None) -> Optional[np.ndar else: return default + class LazyDetections2D(Mapping): def __init__(self, instance_masks: LazyInstanceSegmentationMasks): @@ -232,11 +237,12 @@ def __eq__(self, other: object): else: return False + class LazyInstanceDetections2D(LazyDetections2D): def __init__(self, instance_masks: LazyInstanceSegmentationMasks): super().__init__(instance_masks) - self._detections2d : Dict[str, Optional[Tuple[int, int, int, int]]] = {} + self._detections2d: Dict[str, Optional[Tuple[int, int, int, int]]] = {} def __eq__(self, other: object): if isinstance(other, self.__class__): @@ -281,7 +287,7 @@ def __init__(self, instance_masks: LazyInstanceSegmentationMasks): super().__init__(instance_masks) self._loaded = False - self._detections2d : Dict[str, Optional[Tuple[Tuple[int, int, int, int], ...]]] = {} + self._detections2d: Dict[str, Optional[Tuple[Tuple[int, int, int, int], ...]]] = {} def __eq__(self, other: object): if isinstance(other, self.__class__): @@ -316,7 +322,10 @@ def __getitem__(self, cls: str) -> Optional[Tuple[Tuple[int, int, int, int], ... detections = [] for color in self.instance_masks.class_colors.get(cls, []): - mask = self.instance_masks.instance_segmentation_frame_uint32 == self.instance_masks._integer_color_key(color) + mask = ( + self.instance_masks.instance_segmentation_frame_uint32 + == self.instance_masks._integer_color_key(color) + ) bb = self.mask_bounding_box(mask) if bb: detections.append(bb) @@ -347,9 +356,7 @@ def cv2img(self): def add_third_party_camera_image(self, third_party_image_data): self.third_party_camera_frames.append( - read_buffer_image( - third_party_image_data, self.screen_width, self.screen_height - ) + read_buffer_image(third_party_image_data, self.screen_width, self.screen_height) ) @@ -523,9 +530,7 @@ def process_colors(self): self.object_id_to_color[name] = c_key def objects_by_type(self, object_type): - return [ - obj for obj in self.metadata["objects"] if obj["objectType"] == object_type - ] + return [obj for obj in self.metadata["objects"] if obj["objectType"] == object_type] def process_colors_ids(self, image_ids_data): @@ -534,34 +539,32 @@ def process_colors_ids(self, image_ids_data): self.class_detections2D = LazyClassDetections2D(self.instance_masks) self.instance_detections2D = LazyInstanceDetections2D(self.instance_masks) - def _image_depth(self, image_depth_data, **kwargs): - item_size = int(len(image_depth_data)/(self.screen_width * self.screen_height)) + item_size = int(len(image_depth_data) / (self.screen_width * self.screen_height)) multipliers = { DepthFormat.Normalized: 1.0, DepthFormat.Meters: (kwargs["camera_far_plane"] - kwargs["camera_near_plane"]), - DepthFormat.Millimeters: (kwargs["camera_far_plane"] - kwargs["camera_near_plane"]) * 1000.0 + DepthFormat.Millimeters: (kwargs["camera_far_plane"] - kwargs["camera_near_plane"]) + * 1000.0, } target_depth_format = kwargs["depth_format"] # assume Normalized for backwards compatibility source_depth_format = DepthFormat[self.metadata.get("depthFormat", "Normalized")] - multiplier = multipliers[target_depth_format]/multipliers[source_depth_format] + multiplier = multipliers[target_depth_format] / multipliers[source_depth_format] - if item_size == 4: # float32 + if item_size == 4: # float32 image_depth_out = read_buffer_image( image_depth_data, self.screen_width, self.screen_height, dtype=np.float32 ).squeeze() - elif item_size == 3: # 3 byte 1/256.0 precision, legacy depth binary format - image_depth = read_buffer_image( - image_depth_data, self.screen_width, self.screen_height - ) + elif item_size == 3: # 3 byte 1/256.0 precision, legacy depth binary format + image_depth = read_buffer_image(image_depth_data, self.screen_width, self.screen_height) image_depth_out = ( image_depth[:, :, 0] + image_depth[:, :, 1] / np.float32(256) - + image_depth[:, :, 2] / np.float32(256 ** 2) + + image_depth[:, :, 2] / np.float32(256**2) ) multiplier /= 256.0 @@ -586,9 +589,7 @@ def add_third_party_camera_image_robot(self, third_party_image_data, width, heig read_buffer_image(third_party_image_data, width, height) ) - def add_third_party_image_depth_robot( - self, image_depth_data, depth_format, **kwargs - ): + def add_third_party_image_depth_robot(self, image_depth_data, depth_format, **kwargs): multiplier = 1.0 camera_far_plane = kwargs.pop("camera_far_plane", 1) camera_near_plane = kwargs.pop("camera_near_plane", 0) @@ -600,9 +601,9 @@ def add_third_party_image_depth_robot( multiplier = 1000.0 image_depth = ( - read_buffer_image( - image_depth_data, depth_width, depth_height, **kwargs - ).reshape(depth_height, depth_width) + read_buffer_image(image_depth_data, depth_width, depth_height, **kwargs).reshape( + depth_height, depth_width + ) * multiplier ) self.third_party_depth_frames.append(image_depth.astype(np.float32)) @@ -620,9 +621,9 @@ def add_image_depth_robot(self, image_depth_data, depth_format, **kwargs): multiplier = 1000.0 image_depth = ( - read_buffer_image( - image_depth_data, depth_width, depth_height, **kwargs - ).reshape(depth_height, depth_width) + read_buffer_image(image_depth_data, depth_width, depth_height, **kwargs).reshape( + depth_height, depth_width + ) * multiplier ) self.depth_frame = image_depth.astype(np.float32) @@ -631,9 +632,7 @@ def add_image_depth(self, image_depth_data, **kwargs): self.depth_frame = self._image_depth(image_depth_data, **kwargs) def add_third_party_image_depth(self, image_depth_data, **kwargs): - self.third_party_depth_frames.append( - self._image_depth(image_depth_data, **kwargs) - ) + self.third_party_depth_frames.append(self._image_depth(image_depth_data, **kwargs)) def add_third_party_image_normals(self, normals_data): self.third_party_normals_frames.append( @@ -657,22 +656,18 @@ def add_image_flows(self, image_flows_data): def add_third_party_camera_image(self, third_party_image_data): self.third_party_camera_frames.append( - read_buffer_image( - third_party_image_data, self.screen_width, self.screen_height - ) + read_buffer_image(third_party_image_data, self.screen_width, self.screen_height) ) def add_image(self, image_data, **kwargs): - self.frame = read_buffer_image( - image_data, self.screen_width, self.screen_height, **kwargs - )[ + self.frame = read_buffer_image(image_data, self.screen_width, self.screen_height, **kwargs)[ :, :, :3 ] # CloudRendering returns 4 channels instead of 3 def add_image_ids(self, image_ids_data): self.instance_segmentation_frame = read_buffer_image( image_ids_data, self.screen_width, self.screen_height - )[:, :, :3] + )[:, :, :3] self.process_colors_ids(image_ids_data) @@ -681,9 +676,7 @@ def add_third_party_image_ids(self, image_ids_data): image_ids_data, self.screen_width, self.screen_height )[:, :, :3] - self.third_party_instance_segmentation_frames.append( - instance_segmentation_frame - ) + self.third_party_instance_segmentation_frames.append(instance_segmentation_frame) instance_masks = LazyInstanceSegmentationMasks(image_ids_data, self.metadata) self.third_party_instance_masks.append(instance_masks) self.third_party_class_masks.append(LazyClassSegmentationMasks(instance_masks)) @@ -691,12 +684,12 @@ def add_third_party_image_ids(self, image_ids_data): def add_image_classes(self, image_classes_data): self.semantic_segmentation_frame = read_buffer_image( image_classes_data, self.screen_width, self.screen_height - )[:, :, :3] + )[:, :, :3] def add_third_party_image_classes(self, image_classes_data): self.third_party_semantic_segmentation_frames.append( read_buffer_image(image_classes_data, self.screen_width, self.screen_height)[:, :, :3] - ) + ) def cv2image(self): warnings.warn("Deprecated - please use event.cv2img") @@ -769,8 +762,7 @@ def set_init_params(self, init_params): def create_event(self, metadata, files): if metadata["sequenceId"] != self.sequence_id: raise ValueError( - "Sequence id mismatch: %s vs %s" - % (metadata["sequenceId"], self.sequence_id) + "Sequence id mismatch: %s vs %s" % (metadata["sequenceId"], self.sequence_id) ) events = [] diff --git a/ai2thor/tests/build_controller.py b/ai2thor/tests/build_controller.py index 2e410adc22..2939493a3a 100644 --- a/ai2thor/tests/build_controller.py +++ b/ai2thor/tests/build_controller.py @@ -2,6 +2,7 @@ import os from ai2thor.controller import Controller + class TestController(Controller): def __init__(self, **kwargs): self.force_opengl = os.environ.get("FORCE_OPENGL", False) @@ -14,12 +15,13 @@ def unity_command(self, width, height, headless): # force OpenGLCore to get used so that the tests run in a consistent way # With low power graphics cards (such as those in the test environment) # Metal behaves in inconsistent ways causing test failures - + # This is not needed for cloudrendering - if self.force_opengl: + if self.force_opengl: command.append("-force-glcore") return command + def build_controller(**args): platform = os.environ.get("TEST_PLATFORM") if platform: @@ -38,4 +40,4 @@ def build_controller(**args): # used for resetting c._original_initialization_parameters = c.initialization_parameters - return c \ No newline at end of file + return c diff --git a/ai2thor/tests/fifo_client.py b/ai2thor/tests/fifo_client.py index b002797e82..1c5ac0f87a 100644 --- a/ai2thor/tests/fifo_client.py +++ b/ai2thor/tests/fifo_client.py @@ -14,9 +14,7 @@ def send(self, field_type, body): if self.server_pipe is None: self.server_pipe = open(self.server_pipe_path, "wb") - header = struct.pack( - ai2thor.fifo_server.FifoServer.header_format, field_type, len(body) - ) + header = struct.pack(ai2thor.fifo_server.FifoServer.header_format, field_type, len(body)) self.server_pipe.write(header + body) diff --git a/ai2thor/tests/test_arm.py b/ai2thor/tests/test_arm.py index 4137f02fa2..ecd2e76f78 100644 --- a/ai2thor/tests/test_arm.py +++ b/ai2thor/tests/test_arm.py @@ -27,7 +27,7 @@ height=300, fieldOfView=45, agentCount=1, - agentMode="stretch" + agentMode="stretch", ) _wsgi_controller = dict(server_class=WsgiServer, **shared_args) @@ -44,6 +44,7 @@ def load_house(filename): house = json.load(f) return house + def run(controller, actions_json_filename): actions = None with open(os.path.join(ARM_TEST_DATA_PATH, actions_json_filename)) as f: @@ -55,10 +56,11 @@ def run(controller, actions_json_filename): # metadata_returns.append(copy.deepcopy(evt.metadata)) return last_event + @pytest.mark.parametrize("controller_args", fifo) def test_arm_pickup_object(controller_args): controller = build_controller(**controller_args) - + house = load_house("procthor_train_1.json") evt = controller.step(action="CreateHouse", house=house) @@ -76,13 +78,13 @@ def test_arm_pickup_object(controller_args): controller.stop() - assert ["Plate|surface|5|45"] == evt.metadata['arm']['heldObjects'] + assert ["Plate|surface|5|45"] == evt.metadata["arm"]["heldObjects"] @pytest.mark.parametrize("controller_args", fifo) def test_arm_object_intersect(controller_args): controller = build_controller(**controller_args) - + house = load_house("procthor_train_1_laptop.json") evt = controller.step(action="CreateHouse", house=house) @@ -96,19 +98,26 @@ def test_arm_object_intersect(controller_args): prev_event = run(controller, "pickup_object.json") - evt = controller.step(**{ - "action": "RotateWristRelative", - "yaw": 200, - "physicsSimulationParams": {"autoSimulation": False}, - "returnToStart": True, - "speed": 1 - }) + evt = controller.step( + **{ + "action": "RotateWristRelative", + "yaw": 200, + "physicsSimulationParams": {"autoSimulation": False}, + "returnToStart": True, + "speed": 1, + } + ) assert not evt.metadata["lastActionSuccess"] controller.stop() - diff = DeepDiff(evt.metadata['arm'], prev_event.metadata['arm'], significant_digits=2, ignore_numeric_type_changes=True) + diff = DeepDiff( + evt.metadata["arm"], + prev_event.metadata["arm"], + significant_digits=2, + ignore_numeric_type_changes=True, + ) print(diff) assert diff == {} @@ -116,7 +125,7 @@ def test_arm_object_intersect(controller_args): @pytest.mark.parametrize("controller_args", fifo) def test_arm_body_object_intersect(controller_args): controller = build_controller(**controller_args) - + house = load_house("procthor_train_1.json") evt = controller.step(action="CreateHouse", house=house) @@ -132,13 +141,14 @@ def test_arm_body_object_intersect(controller_args): assert evt.metadata["lastActionSuccess"] - evt = controller.step(** - {"action": "RotateWristRelative", - "yaw": -10, - "physicsSimulationParams": {"autoSimulation": False}, - "returnToStart": True, - "speed": 1 - } + evt = controller.step( + **{ + "action": "RotateWristRelative", + "yaw": -10, + "physicsSimulationParams": {"autoSimulation": False}, + "returnToStart": True, + "speed": 1, + } ) print( @@ -153,15 +163,21 @@ def test_arm_body_object_intersect(controller_args): controller.stop() - diff = DeepDiff(evt.metadata['arm'], prev_event.metadata['arm'], significant_digits=2, ignore_numeric_type_changes=True) + diff = DeepDiff( + evt.metadata["arm"], + prev_event.metadata["arm"], + significant_digits=2, + ignore_numeric_type_changes=True, + ) print(diff) assert diff == {} + # TODO: rewrite once new stretch parameters ar in # @pytest.mark.parametrize("controller_args", fifo) # def test_arm_pickup_drop_sequence(controller_args): # controller = build_controller(**controller_args) - + # house = load_house("procthor_train_1.json") # evt = controller.step(action="CreateHouse", house=house) @@ -176,7 +192,7 @@ def test_arm_body_object_intersect(controller_args): # evt = run(controller, "pickup_plate_before_intersect.json") # assert ["Plate|surface|5|45"] == evt.metadata['arm']['heldObjects'] - + # evt = run(controller, "object_drop.json") # assert evt.metadata['arm']['heldObjects'] == [] @@ -187,7 +203,7 @@ def test_arm_body_object_intersect(controller_args): # plate_metadata = object_dict["Plate|surface|5|45"] # object_target = { -# 'position': {'x': 9.562429428100586, 'y': 1.0261509418487549, 'z': 0.37188154458999634}, +# 'position': {'x': 9.562429428100586, 'y': 1.0261509418487549, 'z': 0.37188154458999634}, # 'rotation': {'x': 359.0494384765625, 'y': 28.759014129638672, 'z': 0.06256783753633499}, # 'parentReceptacles': ['CounterTop|2|0'] # } diff --git a/ai2thor/tests/test_controller.py b/ai2thor/tests/test_controller.py index 9c6419a960..71b38c9515 100644 --- a/ai2thor/tests/test_controller.py +++ b/ai2thor/tests/test_controller.py @@ -35,9 +35,13 @@ def fake_cr_exists(self): def fake_not_exists(self): return False -def fake_find_platform_builds(self, canditate_platorms, request, commits, releases_dir, local_build): + +def fake_find_platform_builds( + self, canditate_platorms, request, commits, releases_dir, local_build +): return [] + def fake_exists(self): return True @@ -53,11 +57,14 @@ def fake_darwin_system(): def noop_download(self): pass + def select_platforms_linux_cr(request): return (Linux64, CloudRendering) + def select_platforms_cr(request): - return (CloudRendering, ) + return (CloudRendering,) + @classmethod def fake_validate(cls, request): @@ -120,7 +127,9 @@ def test_osx_build_missing(mocker): with pytest.raises(Exception) as ex: c = controller() - assert str(ex.value).startswith("No build exists for arch=Darwin platforms=OSXIntel64 and commits:") + assert str(ex.value).startswith( + "No build exists for arch=Darwin platforms=OSXIntel64 and commits:" + ) def test_osx_build_invalid_commit_id(mocker): @@ -133,7 +142,8 @@ def test_osx_build_invalid_commit_id(mocker): assert ( str(ex.value) - == "Invalid commit_id: %s - no build exists for arch=Darwin platforms=OSXIntel64" % fake_commit_id + == "Invalid commit_id: %s - no build exists for arch=Darwin platforms=OSXIntel64" + % fake_commit_id ) @@ -190,9 +200,7 @@ def test_linux_invalid_linux64_valid_cr(mocker): mocker.patch("ai2thor.controller.ai2thor.build.Build.exists", fake_exists) mocker.patch("ai2thor.controller.ai2thor.build.Build.download", noop_download) mocker.patch("ai2thor.controller.ai2thor.platform.select_platforms", select_platforms_linux_cr) - mocker.patch( - "ai2thor.controller.ai2thor.platform.CloudRendering.validate", fake_validate - ) + mocker.patch("ai2thor.controller.ai2thor.platform.CloudRendering.validate", fake_validate) mocker.patch( "ai2thor.controller.ai2thor.platform.Linux64.validate", fake_invalid_linux64_validate, @@ -211,9 +219,7 @@ def test_linux_valid_linux64_valid_cloudrendering(mocker): mocker.patch("ai2thor.controller.platform_system", fake_linux_system) mocker.patch("ai2thor.controller.ai2thor.build.Build.exists", fake_exists) mocker.patch("ai2thor.controller.ai2thor.build.Build.download", noop_download) - mocker.patch( - "ai2thor.controller.ai2thor.platform.CloudRendering.validate", fake_validate - ) + mocker.patch("ai2thor.controller.ai2thor.platform.CloudRendering.validate", fake_validate) mocker.patch("ai2thor.controller.ai2thor.platform.Linux64.validate", fake_validate) fake_commit_id = "1234567TEST" @@ -228,9 +234,7 @@ def test_linux_valid_linux64_valid_cloudrendering_enabled_cr(mocker): mocker.patch("ai2thor.controller.ai2thor.build.Build.exists", fake_exists) mocker.patch("ai2thor.controller.ai2thor.build.Build.download", noop_download) mocker.patch("ai2thor.controller.ai2thor.platform.select_platforms", select_platforms_cr) - mocker.patch( - "ai2thor.controller.ai2thor.platform.CloudRendering.validate", fake_validate - ) + mocker.patch("ai2thor.controller.ai2thor.platform.CloudRendering.validate", fake_validate) mocker.patch("ai2thor.controller.ai2thor.platform.Linux64.validate", fake_validate) mocker.patch("ai2thor.platform.CloudRendering.enabled", True) mocker.patch("ai2thor.platform.Linux64.enabled", False) @@ -263,9 +267,7 @@ def test_linux_missing_linux64(mocker): mocker.patch("ai2thor.controller.platform_system", fake_linux_system) mocker.patch("ai2thor.controller.ai2thor.build.Build.exists", fake_cr_exists) mocker.patch("ai2thor.controller.ai2thor.build.Build.download", noop_download) - mocker.patch( - "ai2thor.controller.ai2thor.platform.CloudRendering.validate", fake_validate - ) + mocker.patch("ai2thor.controller.ai2thor.platform.CloudRendering.validate", fake_validate) mocker.patch("ai2thor.platform.CloudRendering.enabled", True) mocker.patch("ai2thor.controller.ai2thor.platform.select_platforms", select_platforms_linux_cr) @@ -418,9 +420,7 @@ def test_last_action(mocker): mocker.patch("ai2thor.controller.platform_system", fake_darwin_system) mocker.patch("ai2thor.controller.ai2thor.build.Build.exists", fake_exists) mocker.patch("ai2thor.controller.ai2thor.build.Build.download", noop_download) - fake_event = Event( - dict(screenWidth=300, screenHeight=300, colors=[], lastActionSuccess=True) - ) + fake_event = Event(dict(screenWidth=300, screenHeight=300, colors=[], lastActionSuccess=True)) c = controller() c.last_event = fake_event action1 = dict(action="RotateRight") @@ -437,6 +437,7 @@ def test_last_action(mocker): assert c.last_action == action2 assert e.metadata["lastActionSuccess"] + def test_unity_command_force_device_index(mocker): pass @@ -512,7 +513,6 @@ def test_unity_command_force_device_index(mocker): # ] - def test_unity_command(mocker): mocker.patch("ai2thor.controller.platform_system", fake_linux_system) mocker.patch("ai2thor.controller.ai2thor.build.Build.exists", fake_exists) diff --git a/ai2thor/tests/test_event.py b/ai2thor/tests/test_event.py index e33a55d813..bec7873395 100644 --- a/ai2thor/tests/test_event.py +++ b/ai2thor/tests/test_event.py @@ -3257,9 +3257,7 @@ def event_with_frame(event): metadata = json.loads(f.read()) e = Event(metadata) - with open( - os.path.join(TESTS_DATA_DIR, "instance_segmentation_frame_rgb24.raw"), "rb" - ) as f: + with open(os.path.join(TESTS_DATA_DIR, "instance_segmentation_frame_rgb24.raw"), "rb") as f: seg_frame_data = f.read() e.add_image_ids(seg_frame_data) @@ -3425,48 +3423,80 @@ def test_objects_by_test(event): assert all_mugs == mug_object_ids assert event.objects_by_type("FOO") == [] + def test_depth_float32(): metadata = json.loads(json.dumps(metadata_simple)) metadata["depthFormat"] = "Meters" - data = open(os.path.join(TESTS_DATA_DIR, "image-depth-datafloat32.raw"), "rb").read() + data = open(os.path.join(TESTS_DATA_DIR, "image-depth-datafloat32.raw"), "rb").read() event_float32 = Event(metadata) event_float32.add_image_depth( - data, - depth_format=DepthFormat.Meters, - camera_near_plane=0.1, - camera_far_plane=20.0, - add_noise=False - ) + data, + depth_format=DepthFormat.Meters, + camera_near_plane=0.1, + camera_far_plane=20.0, + add_noise=False, + ) + + assert np.all( + event_float32.depth_frame[0:1, 0:8] + == np.array( + [ + [ + 0.82262456, + 0.82262456, + 0.82262456, + 0.82262456, + 0.82262456, + 0.82262456, + 0.82262456, + 0.82262456, + ] + ], + dtype=np.float32, + ) + ) - assert np.all(event_float32.depth_frame[0:1, 0:8] == np.array([[0.82262456, 0.82262456, 0.82262456, 0.82262456, 0.82262456, 0.82262456, 0.82262456, 0.82262456]], dtype=np.float32)) def test_depth_256(): metadata = json.loads(json.dumps(metadata_simple)) if "depthFormat" in metadata: - del(metadata["depthFormat"]) + del metadata["depthFormat"] event_256 = Event(metadata) - data = open(os.path.join(TESTS_DATA_DIR, "image-depth-data256.raw"), "rb").read() + data = open(os.path.join(TESTS_DATA_DIR, "image-depth-data256.raw"), "rb").read() event_256.add_image_depth( - data, - depth_format=DepthFormat.Meters, - camera_near_plane=0.1, - camera_far_plane=20.0, - add_noise=False) - assert np.all(event_256.depth_frame[0:1, 0:8] == np.array([[0.8223207, 0.8223207, 0.8223207, 0.8223207, 0.8223207, 0.8223207, 0.8223207, 0.8223207]], dtype=np.float32)) + data, + depth_format=DepthFormat.Meters, + camera_near_plane=0.1, + camera_far_plane=20.0, + add_noise=False, + ) + assert np.all( + event_256.depth_frame[0:1, 0:8] + == np.array( + [ + [ + 0.8223207, + 0.8223207, + 0.8223207, + 0.8223207, + 0.8223207, + 0.8223207, + 0.8223207, + 0.8223207, + ] + ], + dtype=np.float32, + ) + ) def test_process_colors(event_complex): event_complex.process_colors assert len(event_complex.color_to_object_id.keys()) == 125 assert event_complex.color_to_object_id[(207, 119, 70)] == "Spatula3.001" - assert ( - event_complex.color_to_object_id[(141, 139, 54)] - == "Cabinet|-00.63|+00.39|-02.51" - ) - assert ( - event_complex.color_to_object_id[(29, 84, 249)] == "Spoon|-00.50|+00.78|-01.45" - ) + assert event_complex.color_to_object_id[(141, 139, 54)] == "Cabinet|-00.63|+00.39|-02.51" + assert event_complex.color_to_object_id[(29, 84, 249)] == "Spoon|-00.50|+00.78|-01.45" assert event_complex.color_to_object_id[(235, 57, 90)] == "Spoon" assert event_complex.object_id_to_color["Spatula3.001"] == (207, 119, 70) @@ -3486,10 +3516,7 @@ def test_process_colors(event_complex): @pytest.mark.parametrize("event_with_segmentation", segmentation_events) def test_lazy_instance_segmentation(event_with_segmentation): assert ( - event_with_segmentation.instance_masks[ - "CoffeeMachine|+00.89|+00.90|-02.13" - ].sum() - == 14833 + event_with_segmentation.instance_masks["CoffeeMachine|+00.89|+00.90|-02.13"].sum() == 14833 ) expected_keys = [ "CoffeeMachine|+00.89|+00.90|-02.13", @@ -3522,23 +3549,29 @@ def test_lazy_instance_segmentation(event_with_segmentation): ] assert list(event_with_segmentation.instance_masks.keys()) == expected_keys + @pytest.mark.parametrize("event_with_segmentation", segmentation_events) def test_test_lazy_instance_contains(event_with_segmentation): assert "CoffeeMachine|+00.89|+00.90|-02.13" in event_with_segmentation.instance_masks assert not "Cabinet|+00.65|+00.48|+00.24" in event_with_segmentation.instance_masks assert not "Foo" in event_with_segmentation.instance_masks + @pytest.mark.parametrize("event_with_segmentation", segmentation_events) def test_test_lazy_class_contains(event_with_segmentation): assert "Cabinet" in event_with_segmentation.class_masks assert not "Window" in event_with_segmentation.class_masks assert not "Foo" in event_with_segmentation.class_masks + @pytest.mark.parametrize("event_with_segmentation", segmentation_events) def test_lazy_instance_detections2d(event_with_segmentation): - assert event_with_segmentation.instance_detections2D[ - "CoffeeMachine|+00.89|+00.90|-02.13" - ] == (509, 371, 599, 576) + assert event_with_segmentation.instance_detections2D["CoffeeMachine|+00.89|+00.90|-02.13"] == ( + 509, + 371, + 599, + 576, + ) @pytest.mark.parametrize("event_with_segmentation", segmentation_events) @@ -3577,9 +3610,7 @@ def test_lazy_class_segmentation_missing(event_with_segmentation): @pytest.mark.parametrize("event_with_segmentation", segmentation_events) def test_lazy_class_segmentation_background(event_with_segmentation): # colors that don't appear in the metadata get labeled as "background" - class_colors_copy = json.loads( - json.dumps(event_with_segmentation.instance_masks.class_colors) - ) + class_colors_copy = json.loads(json.dumps(event_with_segmentation.instance_masks.class_colors)) del event_with_segmentation.instance_masks.class_colors["Cabinet"] if "background" in event_with_segmentation.class_masks._masks: @@ -3612,98 +3643,101 @@ def test_lazy_class_detections2d_missing(event_with_segmentation): with pytest.raises(KeyError): event_with_segmentation.class_detections2D["Stove"] + @pytest.mark.parametrize("event_with_segmentation", segmentation_events) def test_lazy_instance_masks_keys(event_with_segmentation): keys = set( { - 'StoveTopGas|-1.503001|0|-1.06545', - 'Cabinet|+00.95|+02.16|-02.38', - 'Cup|+01.08|+00.90|-00.77', - 'StoveBurner|+00.84|+00.92|-01.50', - 'StandardUpperCabinetHeightWidth|1.28|0|0.18', - 'Spatula|+01.10|+00.91|-00.63', - 'PaperTowelRoll|+01.22|+01.01|-00.52', - 'StoveBase1|0.997|0|-1.302', - 'Cabinet|+00.95|+02.16|-00.76', - 'StoveKnob|+00.67|+00.90|-01.09', - 'StoveBurner|+01.08|+00.92|-01.10', - 'StoveKnob|+00.67|+00.90|-01.37', - 'StandardCounterHeightWidth|0.98|0|0.18', - 'StoveBurner|+00.84|+00.92|-01.10', - 'StandardWallSize|1|0|2', - 'StoveKnob|+00.67|+00.90|-01.52', - 'Microwave|+01.04|+01.68|-01.30', - 'CoffeeMachine|+00.89|+00.90|-02.13', - 'Cabinet|+00.95|+02.44|-01.78', - 'StoveBurner|+01.08|+00.92|-01.50', - 'StandardWallTileHeight1|1.3|0|0.18', - 'StoveKnob|+00.67|+00.90|-01.24', - 'CounterTop|+00.93|+00.95|-00.21', - 'Pan|+00.85|+00.95|-01.08', - 'SaltShaker|+01.19|+00.90|-01.80', - 'PepperShaker|+01.09|+00.90|-01.82', - 'CounterTop|+00.93|+00.95|-02.05', + "StoveTopGas|-1.503001|0|-1.06545", + "Cabinet|+00.95|+02.16|-02.38", + "Cup|+01.08|+00.90|-00.77", + "StoveBurner|+00.84|+00.92|-01.50", + "StandardUpperCabinetHeightWidth|1.28|0|0.18", + "Spatula|+01.10|+00.91|-00.63", + "PaperTowelRoll|+01.22|+01.01|-00.52", + "StoveBase1|0.997|0|-1.302", + "Cabinet|+00.95|+02.16|-00.76", + "StoveKnob|+00.67|+00.90|-01.09", + "StoveBurner|+01.08|+00.92|-01.10", + "StoveKnob|+00.67|+00.90|-01.37", + "StandardCounterHeightWidth|0.98|0|0.18", + "StoveBurner|+00.84|+00.92|-01.10", + "StandardWallSize|1|0|2", + "StoveKnob|+00.67|+00.90|-01.52", + "Microwave|+01.04|+01.68|-01.30", + "CoffeeMachine|+00.89|+00.90|-02.13", + "Cabinet|+00.95|+02.44|-01.78", + "StoveBurner|+01.08|+00.92|-01.50", + "StandardWallTileHeight1|1.3|0|0.18", + "StoveKnob|+00.67|+00.90|-01.24", + "CounterTop|+00.93|+00.95|-00.21", + "Pan|+00.85|+00.95|-01.08", + "SaltShaker|+01.19|+00.90|-01.80", + "PepperShaker|+01.09|+00.90|-01.82", + "CounterTop|+00.93|+00.95|-02.05", } ) assert set(event_with_segmentation.instance_masks.keys()) == keys + @pytest.mark.parametrize("event_with_segmentation", segmentation_events) def test_lazy_instance_detections2d_keys(event_with_segmentation): keys = set( { - 'StoveTopGas|-1.503001|0|-1.06545', - 'Cabinet|+00.95|+02.16|-02.38', - 'Cup|+01.08|+00.90|-00.77', - 'StoveBurner|+00.84|+00.92|-01.50', - 'StandardUpperCabinetHeightWidth|1.28|0|0.18', - 'Spatula|+01.10|+00.91|-00.63', - 'PaperTowelRoll|+01.22|+01.01|-00.52', - 'StoveBase1|0.997|0|-1.302', - 'Cabinet|+00.95|+02.16|-00.76', - 'StoveKnob|+00.67|+00.90|-01.09', - 'StoveBurner|+01.08|+00.92|-01.10', - 'StoveKnob|+00.67|+00.90|-01.37', - 'StandardCounterHeightWidth|0.98|0|0.18', - 'StoveBurner|+00.84|+00.92|-01.10', - 'StandardWallSize|1|0|2', - 'StoveKnob|+00.67|+00.90|-01.52', - 'Microwave|+01.04|+01.68|-01.30', - 'CoffeeMachine|+00.89|+00.90|-02.13', - 'Cabinet|+00.95|+02.44|-01.78', - 'StoveBurner|+01.08|+00.92|-01.50', - 'StandardWallTileHeight1|1.3|0|0.18', - 'StoveKnob|+00.67|+00.90|-01.24', - 'CounterTop|+00.93|+00.95|-00.21', - 'Pan|+00.85|+00.95|-01.08', - 'SaltShaker|+01.19|+00.90|-01.80', - 'PepperShaker|+01.09|+00.90|-01.82', - 'CounterTop|+00.93|+00.95|-02.05', + "StoveTopGas|-1.503001|0|-1.06545", + "Cabinet|+00.95|+02.16|-02.38", + "Cup|+01.08|+00.90|-00.77", + "StoveBurner|+00.84|+00.92|-01.50", + "StandardUpperCabinetHeightWidth|1.28|0|0.18", + "Spatula|+01.10|+00.91|-00.63", + "PaperTowelRoll|+01.22|+01.01|-00.52", + "StoveBase1|0.997|0|-1.302", + "Cabinet|+00.95|+02.16|-00.76", + "StoveKnob|+00.67|+00.90|-01.09", + "StoveBurner|+01.08|+00.92|-01.10", + "StoveKnob|+00.67|+00.90|-01.37", + "StandardCounterHeightWidth|0.98|0|0.18", + "StoveBurner|+00.84|+00.92|-01.10", + "StandardWallSize|1|0|2", + "StoveKnob|+00.67|+00.90|-01.52", + "Microwave|+01.04|+01.68|-01.30", + "CoffeeMachine|+00.89|+00.90|-02.13", + "Cabinet|+00.95|+02.44|-01.78", + "StoveBurner|+01.08|+00.92|-01.50", + "StandardWallTileHeight1|1.3|0|0.18", + "StoveKnob|+00.67|+00.90|-01.24", + "CounterTop|+00.93|+00.95|-00.21", + "Pan|+00.85|+00.95|-01.08", + "SaltShaker|+01.19|+00.90|-01.80", + "PepperShaker|+01.09|+00.90|-01.82", + "CounterTop|+00.93|+00.95|-02.05", } ) assert set(event_with_segmentation.instance_detections2D.keys()) == keys + @pytest.mark.parametrize("event_with_segmentation", segmentation_events) def test_lazy_class_detections2d_keys(event_with_segmentation): keys = set( - { - 'Cabinet', - 'CoffeeMachine', - 'CounterTop', - 'Cup', - 'Microwave', - 'Pan', - 'PaperTowelRoll', - 'PepperShaker', - 'SaltShaker', - 'Spatula', - 'StandardCounterHeightWidth', - 'StandardUpperCabinetHeightWidth', - 'StandardWallSize', - 'StandardWallTileHeight1', - 'StoveBase1', - 'StoveBurner', - 'StoveKnob', - 'StoveTopGas', - } + { + "Cabinet", + "CoffeeMachine", + "CounterTop", + "Cup", + "Microwave", + "Pan", + "PaperTowelRoll", + "PepperShaker", + "SaltShaker", + "Spatula", + "StandardCounterHeightWidth", + "StandardUpperCabinetHeightWidth", + "StandardWallSize", + "StandardWallTileHeight1", + "StoveBase1", + "StoveBurner", + "StoveKnob", + "StoveTopGas", + } ) assert set(event_with_segmentation.class_detections2D.keys()) == keys diff --git a/ai2thor/tests/test_fifo_server.py b/ai2thor/tests/test_fifo_server.py index 4277f05332..bbf6e2c14a 100644 --- a/ai2thor/tests/test_fifo_server.py +++ b/ai2thor/tests/test_fifo_server.py @@ -52,9 +52,7 @@ def generate_metadata_payload(metadata, sequence_id): def generate_multi_agent_metadata_payload(metadata, sequence_id): - return msgpack.dumps( - dict(agents=[metadata, metadata], activeAgentId=1, sequenceId=sequence_id) - ) + return msgpack.dumps(dict(agents=[metadata, metadata], activeAgentId=1, sequenceId=sequence_id)) def test_simple(): diff --git a/ai2thor/tests/test_server.py b/ai2thor/tests/test_server.py index 500650dcf7..a9a16b8ce3 100644 --- a/ai2thor/tests/test_server.py +++ b/ai2thor/tests/test_server.py @@ -19,9 +19,7 @@ def generate_multi_agent_form(metadata, sequence_id=1): + boundary + b'\r\nContent-Type: text/plain; charset="utf-8"\r\nContent-disposition: form-data; name="metadata"\r\n\r\n' ) - data += json.dumps( - dict(agents=agents, sequenceId=sequence_id, activeAgentId=1) - ).encode("utf8") + data += json.dumps(dict(agents=agents, sequenceId=sequence_id, activeAgentId=1)).encode("utf8") data += ( b"\r\n" + boundary diff --git a/ai2thor/tests/test_unity.py b/ai2thor/tests/test_unity.py index 63baa218c8..9db19cdcb1 100644 --- a/ai2thor/tests/test_unity.py +++ b/ai2thor/tests/test_unity.py @@ -28,6 +28,7 @@ from .build_controller import build_controller + # Defining const classes to lessen the possibility of a misspelled key class Actions: AddThirdPartyCamera = "AddThirdPartyCamera" @@ -43,6 +44,7 @@ class ThirdPartyCameraMetadata: rotation = "rotation" fieldOfView = "fieldOfView" + _wsgi_controller = build_controller(server_class=WsgiServer, scene=TEST_SCENE) _fifo_controller = build_controller(server_class=FifoServer, scene=TEST_SCENE) @@ -72,15 +74,16 @@ def save_image(file_path, image, flip_br=False): img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cv2.imwrite(file_path, img) + def depth_to_gray_rgb(data): return (255.0 / data.max() * (data - data.min())).astype(np.uint8) + @pytest.fixture def wsgi_controller(): return reset_controller(_wsgi_controller) - @pytest.fixture def fifo_controller(): return reset_controller(_fifo_controller) @@ -89,9 +92,16 @@ def fifo_controller(): fifo_wsgi = [_fifo_controller, _wsgi_controller] fifo = [_fifo_controller] -BASE_FP28_POSITION = dict(x=-1.5, z=-1.5, y=0.901,) +BASE_FP28_POSITION = dict( + x=-1.5, + z=-1.5, + y=0.901, +) BASE_FP28_LOCATION = dict( - **BASE_FP28_POSITION, rotation={"x": 0, "y": 0, "z": 0}, horizon=0, standing=True, + **BASE_FP28_POSITION, + rotation={"x": 0, "y": 0, "z": 0}, + horizon=0, + standing=True, ) @@ -121,16 +131,17 @@ def assert_near(point1, point2, error_message=""): def images_near(image1, image2, max_mean_pixel_diff=1, debug_save=False, filepath=""): - print("Mean pixel difference: {}, Max pixel difference: {}.".format( - np.mean(np.abs(image1 - image2).flatten()), - np.max(np.abs(image1 - image2).flatten())) + print( + "Mean pixel difference: {}, Max pixel difference: {}.".format( + np.mean(np.abs(image1 - image2).flatten()), np.max(np.abs(image1 - image2).flatten()) + ) ) result = np.mean(np.abs(image1 - image2).flatten()) <= max_mean_pixel_diff if not result and debug_save: # TODO put images somewhere accessible dx = np.where(~np.all(image1 == image2, axis=-1)) img_copy = image1.copy() - diff = (image1 - image2) + diff = image1 - image2 max = np.max(diff) norm_diff = diff / max img_copy[dx] = (255, 0, 255) @@ -140,24 +151,26 @@ def images_near(image1, image2, max_mean_pixel_diff=1, debug_save=False, filepat # img_copy[dx[0][i] : dx[0][i]] = (255.0, 255.0, 255.0) # img_copy[dx] += ((255.0, 255.0, 255.0) * norm_diff[dx])+ img_copy[dx] - test_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + test_name = os.environ.get("PYTEST_CURRENT_TEST").split(":")[-1].split(" ")[0] debug_directory = os.path.join(os.path.join(os.getcwd(), TEST_OUTPUT_DIRECTORY)) # if os.path.exists(debug_directory): # shutil.rmtree(debug_directory) # os.makedirs(debug_directory) - save_image(os.path.join(debug_directory, f'{test_name}_diff.png'), img_copy) - save_image(os.path.join(debug_directory, f'{test_name}_fail.png'), image1) + save_image(os.path.join(debug_directory, f"{test_name}_diff.png"), img_copy) + save_image(os.path.join(debug_directory, f"{test_name}_fail.png"), image1) print(f'Saved failed test images in "{debug_directory}"') return result + def depth_images_near(depth1, depth2, epsilon=1e-5, debug_save=False, filepath=""): # result = np.allclose(depth1, depth2, atol=epsilon) result = np.mean(np.abs(depth1 - depth2).flatten()) <= epsilon - print("Max pixel difference: {}, Mean pixel difference: {}".format( - np.max((depth1 - depth2).flatten()), - np.mean((depth1 - depth2).flatten())) + print( + "Max pixel difference: {}, Mean pixel difference: {}".format( + np.max((depth1 - depth2).flatten()), np.mean((depth1 - depth2).flatten()) + ) ) if not result and debug_save: depth1_gray = depth_to_gray_rgb(depth1) @@ -166,22 +179,23 @@ def depth_images_near(depth1, depth2, epsilon=1e-5, debug_save=False, filepath=" max = np.max(diff) norm_diff = diff / max dx = np.where(np.abs(depth1 - depth2) >= epsilon) - depth_copy[dx] = (norm_diff[dx]*255, norm_diff[dx] * 0, norm_diff[dx] *255) - test_name = os.environ.get('PYTEST_CURRENT_TEST').split(':')[-1].split(' ')[0] + depth_copy[dx] = (norm_diff[dx] * 255, norm_diff[dx] * 0, norm_diff[dx] * 255) + test_name = os.environ.get("PYTEST_CURRENT_TEST").split(":")[-1].split(" ")[0] debug_directory = os.path.join(os.path.join(os.getcwd(), TEST_OUTPUT_DIRECTORY)) # if os.path.exists(debug_directory): # shutil.rmtree(debug_directory) # os.makedirs(debug_directory) - save_image(os.path.join(debug_directory, f'{test_name}_diff.png'), depth_copy) - save_image(os.path.join(debug_directory, f'{test_name}_fail.png'), depth1_gray) + save_image(os.path.join(debug_directory, f"{test_name}_diff.png"), depth_copy) + save_image(os.path.join(debug_directory, f"{test_name}_fail.png"), depth1_gray) np.save( - os.path.join(debug_directory, f'{test_name}_fail-raw.npy'), + os.path.join(debug_directory, f"{test_name}_fail-raw.npy"), depth1.astype(np.float32), ), print(f'Saved failed test images in "{debug_directory}"') return result + def images_far(image1, image2, min_mean_pixel_diff=10): return np.mean(np.abs(image1 - image2).flatten()) >= min_mean_pixel_diff @@ -205,8 +219,7 @@ def test_agent_controller_type_no_longer_accepted(fifo_controller): def test_multi_agent_with_third_party_camera(fifo_controller): fifo_controller.reset(TEST_SCENE, agentCount=2) assert not np.all( - fifo_controller.last_event.events[1].frame - == fifo_controller.last_event.events[0].frame + fifo_controller.last_event.events[1].frame == fifo_controller.last_event.events[0].frame ) event = fifo_controller.step( dict( @@ -216,8 +229,7 @@ def test_multi_agent_with_third_party_camera(fifo_controller): ) ) assert not np.all( - fifo_controller.last_event.events[1].frame - == fifo_controller.last_event.events[0].frame + fifo_controller.last_event.events[1].frame == fifo_controller.last_event.events[0].frame ) @@ -269,7 +281,9 @@ def test_deprecated_segmentation_params(fifo_controller): # renderClassImage has been renamed to renderSemanticSegmentation fifo_controller.reset( - TEST_SCENE, renderObjectImage=True, renderClassImage=True, + TEST_SCENE, + renderObjectImage=True, + renderClassImage=True, ) event = fifo_controller.last_event with warnings.catch_warnings(): @@ -286,7 +300,9 @@ def test_deprecated_segmentation_params2(fifo_controller): # renderClassImage has been renamed to renderSemanticSegmentation fifo_controller.reset( - TEST_SCENE, renderSemanticSegmentation=True, renderInstanceSegmentation=True, + TEST_SCENE, + renderSemanticSegmentation=True, + renderInstanceSegmentation=True, ) event = fifo_controller.last_event @@ -337,12 +353,8 @@ def test_fast_emit(fifo_controller): def test_fifo_large_input(fifo_controller): - random_string = "".join( - random.choice(string.ascii_letters) for i in range(1024 * 16) - ) - event = fifo_controller.step( - dict(action="TestActionReflectParam", rvalue=random_string) - ) + random_string = "".join(random.choice(string.ascii_letters) for i in range(1024 * 16)) + event = fifo_controller.step(dict(action="TestActionReflectParam", rvalue=random_string)) assert event.metadata["actionReturn"] == random_string @@ -428,7 +440,7 @@ def test_simobj_filter(controller): unfiltered_object_ids = sorted([o["objectId"] for o in objects]) filter_object_ids = sorted([o["objectId"] for o in objects[0:3]]) controller.step(dict(action="SetObjectFilter", objectIds=filter_object_ids)) - e = controller.step("Pass") # Must pass for `SetObjectFilter` to take effect + e = controller.step("Pass") # Must pass for `SetObjectFilter` to take effect assert len(e.metadata["objects"]) == len(filter_object_ids) filtered_object_ids = sorted([o["objectId"] for o in e.metadata["objects"]]) assert filtered_object_ids == filter_object_ids @@ -459,9 +471,7 @@ def test_add_third_party_camera(controller): fieldOfView=expectedFieldOfView, ) ) - assert ( - len(e.metadata[MultiAgentMetadata.thirdPartyCameras]) == 1 - ), "there should be 1 camera" + assert len(e.metadata[MultiAgentMetadata.thirdPartyCameras]) == 1, "there should be 1 camera" camera = e.metadata[MultiAgentMetadata.thirdPartyCameras][0] assert_near( camera[ThirdPartyCameraMetadata.position], @@ -478,12 +488,8 @@ def test_add_third_party_camera(controller): ), "initial fieldOfView should have been set" # expects position to be a Vector3, should fail! - event = controller.step( - action="AddThirdPartyCamera", position=5, rotation=dict(x=0, y=0, z=0) - ) - assert not event.metadata[ - "lastActionSuccess" - ], "position should not allow float input!" + event = controller.step(action="AddThirdPartyCamera", position=5, rotation=dict(x=0, y=0, z=0)) + assert not event.metadata["lastActionSuccess"], "position should not allow float input!" # orthographicSize expects float, not Vector3! error_message = None @@ -557,8 +563,7 @@ def test_update_third_party_camera(fifo_controller): ) ) assert ( - len(fifo_controller.last_event.metadata[MultiAgentMetadata.thirdPartyCameras]) - == 1 + len(fifo_controller.last_event.metadata[MultiAgentMetadata.thirdPartyCameras]) == 1 ), "there should be 1 camera" # update camera pose fully @@ -625,9 +630,7 @@ def test_update_third_party_camera(fifo_controller): fieldOfView=fov, ) ) - assert not e.metadata[ - "lastActionSuccess" - ], "fieldOfView should fail outside of (0, 180)" + assert not e.metadata["lastActionSuccess"], "fieldOfView should fail outside of (0, 180)" assert_near( camera[ThirdPartyCameraMetadata.position], expectedPosition, @@ -683,9 +686,7 @@ def test_open_aabb_cache(controller): forceAction=True, raise_for_failure=True, ) - obj = next( - obj for obj in open_event.metadata["objects"] if obj["objectType"] == "Fridge" - ) + obj = next(obj for obj in open_event.metadata["objects"] if obj["objectType"] == "Fridge") open_aabb = obj["axisAlignedBoundingBox"] assert start_aabb["size"] != open_aabb["size"] @@ -695,9 +696,7 @@ def test_open_aabb_cache(controller): forceAction=True, raise_for_failure=True, ) - obj = next( - obj for obj in close_event.metadata["objects"] if obj["objectType"] == "Fridge" - ) + obj = next(obj for obj in close_event.metadata["objects"] if obj["objectType"] == "Fridge") close_aabb = obj["axisAlignedBoundingBox"] assert start_aabb["size"] == close_aabb["size"] @@ -737,9 +736,7 @@ def test_open_interactable_with_filter(controller): controller.step(action, raise_for_failure=True) fridge = next( - obj - for obj in controller.last_event.metadata["objects"] - if obj["objectType"] == "Fridge" + obj for obj in controller.last_event.metadata["objects"] if obj["objectType"] == "Fridge" ) assert fridge["visible"], "Object is not interactable!" assert_near(controller.last_event.metadata["agent"]["position"], position) @@ -748,15 +745,15 @@ def test_open_interactable_with_filter(controller): controller.step("Pass") # Must pass for `SetObjectFilter` to take effect assert controller.last_event.metadata["objects"] == [] controller.step( - action="OpenObject", objectId=fridge["objectId"], raise_for_failure=True, + action="OpenObject", + objectId=fridge["objectId"], + raise_for_failure=True, ) controller.step(dict(action="ResetObjectFilter")) fridge = next( - obj - for obj in controller.last_event.metadata["objects"] - if obj["objectType"] == "Fridge" + obj for obj in controller.last_event.metadata["objects"] if obj["objectType"] == "Fridge" ) assert fridge["isOpen"] @@ -774,19 +771,17 @@ def test_open_interactable(controller): controller.step(action, raise_for_failure=True) fridge = next( - obj - for obj in controller.last_event.metadata["objects"] - if obj["objectType"] == "Fridge" + obj for obj in controller.last_event.metadata["objects"] if obj["objectType"] == "Fridge" ) assert fridge["visible"], "Object is not interactable!" assert_near(controller.last_event.metadata["agent"]["position"], position) event = controller.step( - action="OpenObject", objectId=fridge["objectId"], raise_for_failure=True, + action="OpenObject", + objectId=fridge["objectId"], + raise_for_failure=True, ) fridge = next( - obj - for obj in controller.last_event.metadata["objects"] - if obj["objectType"] == "Fridge" + obj for obj in controller.last_event.metadata["objects"] if obj["objectType"] == "Fridge" ) assert fridge["isOpen"] @@ -798,9 +793,7 @@ def test_open(controller): # helper that returns obj_to_open from a new event def get_object(event, object_id): - return next( - obj for obj in event.metadata["objects"] if obj["objectId"] == object_id - ) + return next(obj for obj in event.metadata["objects"] if obj["objectId"] == object_id) for openness in [0.5, 0.7, 0]: event = controller.step( @@ -822,9 +815,7 @@ def get_object(event, object_id): openness=bad_openness, forceAction=True, ) - assert not event.metadata[ - "lastActionSuccess" - ], "0.0 > Openness > 1.0 should fail!" + assert not event.metadata["lastActionSuccess"], "0.0 > Openness > 1.0 should fail!" # test backwards compatibility on moveMagnitude, where moveMagnitude # is now `openness`, but when moveMagnitude = 0 that corresponds to openness = 1. @@ -835,9 +826,7 @@ def get_object(event, object_id): moveMagnitude=0, ) opened_obj = get_object(event, obj_to_open["objectId"]) - assert ( - abs(opened_obj["openness"] - 1) < 1e-3 - ), "moveMagnitude=0 must have openness=1" + assert abs(opened_obj["openness"] - 1) < 1e-3, "moveMagnitude=0 must have openness=1" assert opened_obj["isOpen"], "moveMagnitude isOpen incorrectly reported!" # another moveMagnitude check @@ -849,9 +838,7 @@ def get_object(event, object_id): moveMagnitude=test_openness, ) opened_obj = get_object(event, obj_to_open["objectId"]) - assert ( - abs(opened_obj["openness"] - test_openness) < 1e-3 - ), "moveMagnitude is not working!" + assert abs(opened_obj["openness"] - test_openness) < 1e-3, "moveMagnitude is not working!" assert opened_obj["isOpen"], "moveMagnitude isOpen incorrectly reported!" # a CloseObject specific check @@ -928,7 +915,8 @@ def test_action_dispatch_server_action_ambiguous(fifo_controller): assert exception_thrown print(exception_message) assert ( - "Ambiguous action: TestActionDispatchSAAmbig Mixing a ServerAction method with overloaded methods is not permitted" in exception_message + "Ambiguous action: TestActionDispatchSAAmbig Mixing a ServerAction method with overloaded methods is not permitted" + in exception_message ) skip_reset(fifo_controller) @@ -962,9 +950,7 @@ def test_action_dispatch_find_conflicts_physics(fifo_controller): def test_action_dispatch_missing_args(fifo_controller): caught_exception = False try: - event = fifo_controller.step( - dict(action="TestActionDispatchNoop", param6="foo") - ) + event = fifo_controller.step(dict(action="TestActionDispatchNoop", param6="foo")) except ValueError as e: caught_exception = True assert caught_exception @@ -996,9 +982,7 @@ def test_action_disptatch_one_param(fifo_controller): def test_action_disptatch_two_param(fifo_controller): - event = fifo_controller.step( - dict(action="TestActionDispatchNoop", param1=True, param2=False) - ) + event = fifo_controller.step(dict(action="TestActionDispatchNoop", param1=True, param2=False)) assert event.metadata["actionReturn"] == "param1 param2" skip_reset(fifo_controller) @@ -1038,9 +1022,7 @@ def test_action_disptatch_all_default(fifo_controller): def test_action_disptatch_some_default(fifo_controller): - event = fifo_controller.step( - dict(action="TestActionDispatchNoopAllDefault2", param12=9.0) - ) + event = fifo_controller.step(dict(action="TestActionDispatchNoopAllDefault2", param12=9.0)) assert event.metadata["actionReturn"] == "somedefault" skip_reset(fifo_controller) @@ -1111,6 +1093,7 @@ def test_jsonschema_metadata(controller): # jsonschema.validate(instance=event.metadata, schema=schema) + @pytest.mark.parametrize("controller", fifo_wsgi) def test_arm_jsonschema_metadata(controller): controller.reset(agentMode="arm") @@ -1126,7 +1109,7 @@ def test_get_scenes_in_build(controller): scenes = set() for g in glob.glob("unity/Assets/Scenes/*.unity"): # we currently ignore the 5xx scenes since they are not being worked on - if not re.match(r'^.*\/FloorPlan5[0-9]+_', g): + if not re.match(r"^.*\/FloorPlan5[0-9]+_", g): scenes.add(os.path.splitext(os.path.basename(g))[0]) event = controller.step(dict(action="GetScenesInBuild"), raise_for_failure=True) @@ -1160,9 +1143,7 @@ def test_get_reachable_positions(controller): def test_per_step_instance_segmentation(fifo_controller): - fifo_controller.reset( - TEST_SCENE, width=300, height=300, renderInstanceSegmentation=False - ) + fifo_controller.reset(TEST_SCENE, width=300, height=300, renderInstanceSegmentation=False) event = fifo_controller.step("RotateRight") assert event.instance_segmentation_frame is None event = fifo_controller.step("Pass", renderInstanceSegmentation=True) @@ -1195,7 +1176,11 @@ def test_change_resolution_image_synthesis(fifo_controller): assert event.depth_frame.shape == (300, 300) assert event.instance_segmentation_frame.shape == (300, 300, 3) assert event.semantic_segmentation_frame.shape == (300, 300, 3) - print("is none? {0} is none other {1} ".format( event.depth_frame is None, first_depth_frame is None)) + print( + "is none? {0} is none other {1} ".format( + event.depth_frame is None, first_depth_frame is None + ) + ) save_image("depth_after_resolution_change_300_300.png", depth_to_gray_rgb(event.depth_frame)) save_image("before_after_resolution_change_300_300.png", depth_to_gray_rgb(first_depth_frame)) @@ -1210,23 +1195,17 @@ def test_change_resolution_image_synthesis(fifo_controller): def test_change_resolution(controller): event = controller.step(dict(action="Pass"), raise_for_failure=True) assert event.frame.shape == (300, 300, 3) - event = controller.step( - dict(action="ChangeResolution", x=400, y=400), raise_for_failure=True - ) + event = controller.step(dict(action="ChangeResolution", x=400, y=400), raise_for_failure=True) assert event.frame.shape == (400, 400, 3) assert event.screen_width == 400 assert event.screen_height == 400 - event = controller.step( - dict(action="ChangeResolution", x=300, y=300), raise_for_failure=True - ) + event = controller.step(dict(action="ChangeResolution", x=300, y=300), raise_for_failure=True) @pytest.mark.parametrize("controller", fifo) def test_teleport_locobot(controller): # Checking y coordinate adjustment works - controller.step( - "TeleportFull", **{**BASE_FP28_LOCATION, "y": 0.95}, raise_for_failure=True - ) + controller.step("TeleportFull", **{**BASE_FP28_LOCATION, "y": 0.95}, raise_for_failure=True) position = controller.last_event.metadata["agent"]["position"] assert_near(position, BASE_FP28_POSITION) @@ -1241,7 +1220,8 @@ def test_teleport_locobot(controller): # Teleporting too high before_position = controller.last_event.metadata["agent"]["position"] controller.step( - "Teleport", **{**BASE_FP28_LOCATION, "y": 1.0}, + "Teleport", + **{**BASE_FP28_LOCATION, "y": 1.0}, ) assert not controller.last_event.metadata[ "lastActionSuccess" @@ -1252,7 +1232,8 @@ def test_teleport_locobot(controller): # Teleporting into an object controller.step( - "Teleport", **{**BASE_FP28_LOCATION, "z": -3.5}, + "Teleport", + **{**BASE_FP28_LOCATION, "z": -3.5}, ) assert not controller.last_event.metadata[ "lastActionSuccess" @@ -1260,7 +1241,8 @@ def test_teleport_locobot(controller): # Teleporting into a wall controller.step( - "Teleport", **{**BASE_FP28_LOCATION, "z": 0}, + "Teleport", + **{**BASE_FP28_LOCATION, "z": 0}, ) assert not controller.last_event.metadata[ "lastActionSuccess" @@ -1301,7 +1283,7 @@ def test_teleport_locobot(controller): # Teleporting with the locobot and drone, which don't support standing agent = "locobot" - + event = controller.reset(agentMode=agent) assert event.metadata["agent"]["isStanding"] is None, agent + " cannot stand!" @@ -1322,11 +1304,9 @@ def test_teleport_locobot(controller): position=dict(x=-1.5, y=0.9, z=-1.5), rotation=dict(x=0, y=90, z=0), horizon=30, - standing=True - ) - assert False, ( - agent + " should not be able to pass in standing to teleport!" + standing=True, ) + assert False, agent + " should not be able to pass in standing to teleport!" except Exception as e: print(f"Exception: {e}") pass @@ -1361,12 +1341,11 @@ def test_teleport_locobot(controller): controller.reset(agentMode="default") + @pytest.mark.parametrize("controller", fifo) def test_teleport_stretch(controller): # Checking y coordinate adjustment works - controller.step( - "TeleportFull", **{**BASE_FP28_LOCATION, "y": 0.95}, raise_for_failure=True - ) + controller.step("TeleportFull", **{**BASE_FP28_LOCATION, "y": 0.95}, raise_for_failure=True) position = controller.last_event.metadata["agent"]["position"] assert_near(position, BASE_FP28_POSITION) @@ -1381,7 +1360,8 @@ def test_teleport_stretch(controller): # Teleporting too high before_position = controller.last_event.metadata["agent"]["position"] controller.step( - "Teleport", **{**BASE_FP28_LOCATION, "y": 1.0}, + "Teleport", + **{**BASE_FP28_LOCATION, "y": 1.0}, ) assert not controller.last_event.metadata[ "lastActionSuccess" @@ -1392,7 +1372,8 @@ def test_teleport_stretch(controller): # Teleporting into an object controller.step( - "Teleport", **{**BASE_FP28_LOCATION, "z": -3.5}, + "Teleport", + **{**BASE_FP28_LOCATION, "z": -3.5}, ) assert not controller.last_event.metadata[ "lastActionSuccess" @@ -1400,7 +1381,8 @@ def test_teleport_stretch(controller): # Teleporting into a wall controller.step( - "Teleport", **{**BASE_FP28_LOCATION, "z": 0}, + "Teleport", + **{**BASE_FP28_LOCATION, "z": 0}, ) assert not controller.last_event.metadata[ "lastActionSuccess" @@ -1441,7 +1423,7 @@ def test_teleport_stretch(controller): # Teleporting with the stretch agent = "stretch" - + event = controller.reset(agentMode=agent) assert event.metadata["agent"]["isStanding"] is False, agent + " cannot stand!" @@ -1452,7 +1434,7 @@ def test_teleport_stretch(controller): position=dict(x=-1.5, y=0.9, z=-1.5), rotation=dict(x=0, y=90, z=0), horizon=30, - standing=True + standing=True, ) print(f"Error Message: {event.metadata['errorMessage']}") @@ -1465,11 +1447,9 @@ def test_teleport_stretch(controller): position=dict(x=-1.5, y=0.9, z=-1.5), rotation=dict(x=0, y=90, z=0), horizon=30, - standing=True - ) - assert False, ( - agent + " should not be able to pass in standing to teleport!" + standing=True, ) + assert False, agent + " should not be able to pass in standing to teleport!" except Exception as e: print(f"Exception: {e}") pass @@ -1505,6 +1485,7 @@ def test_teleport_stretch(controller): controller.reset(agentMode="default") + @pytest.mark.parametrize("controller", fifo_wsgi) def test_get_interactable_poses(controller): fridgeId = next( @@ -1514,9 +1495,7 @@ def test_get_interactable_poses(controller): ) event = controller.step("GetInteractablePoses", objectId=fridgeId) poses = event.metadata["actionReturn"] - assert ( - 600 > len(poses) > 400 - ), "Should have around 400 interactable poses next to the fridge!" + assert 600 > len(poses) > 400, "Should have around 400 interactable poses next to the fridge!" # teleport to a random pose pose = poses[len(poses) // 2] @@ -1524,28 +1503,20 @@ def test_get_interactable_poses(controller): # assumes 1 fridge in the scene fridge = next( - obj - for obj in controller.last_event.metadata["objects"] - if obj["objectType"] == "Fridge" + obj for obj in controller.last_event.metadata["objects"] if obj["objectType"] == "Fridge" ) assert fridge["visible"], "Object is not interactable!" # tests that teleport correctly works with **syntax - assert ( - abs(pose["x"] - event.metadata["agent"]["position"]["x"]) < 1e-3 - ), "Agent x position off!" - assert ( - abs(pose["z"] - event.metadata["agent"]["position"]["z"]) < 1e-3 - ), "Agent z position off!" + assert abs(pose["x"] - event.metadata["agent"]["position"]["x"]) < 1e-3, "Agent x position off!" + assert abs(pose["z"] - event.metadata["agent"]["position"]["z"]) < 1e-3, "Agent z position off!" assert ( abs(pose["rotation"] - event.metadata["agent"]["rotation"]["y"]) < 1e-3 ), "Agent rotation off!" assert ( abs(pose["horizon"] - event.metadata["agent"]["cameraHorizon"]) < 1e-3 ), "Agent horizon off!" - assert ( - pose["standing"] == event.metadata["agent"]["isStanding"] - ), "Agent's isStanding is off!" + assert pose["standing"] == event.metadata["agent"]["isStanding"], "Agent's isStanding is off!" # potato should be inside of the fridge (and, thus, non interactable) potatoId = next( @@ -1654,8 +1625,7 @@ def get_rounded_hulls(**kwargs): return np.array(hulls, dtype=float).round(4).tolist() else: return { - k: np.array(v, dtype=float).round(4).tolist() - for k, v in md["actionReturn"].items() + k: np.array(v, dtype=float).round(4).tolist() for k, v in md["actionReturn"].items() } # All objects @@ -1746,9 +1716,7 @@ def test_get_object_in_frame(controller): ), "x=0.6, y=0.4 should have a cabinet!" query = controller.step("GetObjectInFrame", x=0.3, y=0.5) - assert query.metadata["actionReturn"].startswith( - "Fridge" - ), "x=0.3, y=0.5 should have a fridge!" + assert query.metadata["actionReturn"].startswith("Fridge"), "x=0.3, y=0.5 should have a fridge!" event = controller.reset(renderInstanceSegmentation=True) assert event.metadata["screenHeight"] == 300 @@ -1784,9 +1752,7 @@ def test_get_object_in_frame(controller): event.metadata["actionReturn"] == objectId ), f"Failed at ({x / 300}, {y / 300}) for {objectId} with agent at: {event.metadata['agent']}" - assert ( - num_tested == 29 - ), "There should be 29 objects in the frame, based on the agent's pose!" + assert num_tested == 29, "There should be 29 objects in the frame, based on the agent's pose!" @pytest.mark.parametrize("controller", fifo_wsgi) @@ -1820,7 +1786,7 @@ def test_get_coordinate_from_raycast(controller): query = controller.step("GetCoordinateFromRaycast", x=0.25, y=0.5) assert_near( query.metadata["actionReturn"], - {'x': -0.6037378311157227, 'y': 1.575998306274414, 'z': -1.0518686771392822}, + {"x": -0.6037378311157227, "y": 1.575998306274414, "z": -1.0518686771392822}, ) @@ -1859,7 +1825,8 @@ def test_manipulathor_move(controller): event = controller.reset(scene=TEST_SCENE, agentMode="arm", gridSize=0.25) assert_near( - point1=start_position, point2=event.metadata["agent"]["position"], + point1=start_position, + point2=event.metadata["agent"]["position"], ) event = controller.step(action="MoveAgent", ahead=0.25, right=0.15) @@ -1870,7 +1837,8 @@ def test_manipulathor_move(controller): event = controller.step(action="MoveAgent", ahead=-0.25, right=-0.15) assert_near( - point1=start_position, point2=event.metadata["agent"]["position"], + point1=start_position, + point2=event.metadata["agent"]["position"], ) event = controller.step(action="MoveRight") @@ -1881,7 +1849,8 @@ def test_manipulathor_move(controller): event = controller.step(action="MoveLeft") assert_near( - point1=start_position, point2=event.metadata["agent"]["position"], + point1=start_position, + point2=event.metadata["agent"]["position"], ) event = controller.step(action="MoveAhead") @@ -1892,7 +1861,8 @@ def test_manipulathor_move(controller): event = controller.step(action="MoveBack") assert_near( - point1=start_position, point2=event.metadata["agent"]["position"], + point1=start_position, + point2=event.metadata["agent"]["position"], ) @@ -1942,9 +1912,7 @@ def test_unsupported_manipulathor(controller): event = controller.step(action="PickupObject", x=0.5, y=0.5) assert not event, "PickupObject(x, y) should have failed with agentMode=arm" - objectId = next( - obj["objectId"] for obj in event.metadata["objects"] if obj["pickupable"] - ) + objectId = next(obj["objectId"] for obj in event.metadata["objects"] if obj["pickupable"]) event = controller.step(action="PickupObject", objectId=objectId, forceAction=True) assert not event, "PickupObject(objectId) should have failed with agentMode=arm" @@ -2030,12 +1998,8 @@ def test_randomize_materials_clearOnReset(controller): f2 = controller.step(action="RandomizeMaterials").frame.astype(np.float16) f3 = controller.reset().frame.astype(np.float16) # giving some leway with 0.05, but that as a baseline should be plenty enough - assert ( - np.abs(f1 - f2).flatten() / 255 - ).sum() / 300 / 300 > 0.05, "Expected material change" - assert ( - np.abs(f2 - f3).flatten() / 255 - ).sum() / 300 / 300 > 0.05, "Expected material change" + assert (np.abs(f1 - f2).flatten() / 255).sum() / 300 / 300 > 0.05, "Expected material change" + assert (np.abs(f2 - f3).flatten() / 255).sum() / 300 / 300 > 0.05, "Expected material change" assert ( np.abs(f1 - f3).flatten() / 255 ).sum() / 300 / 300 < 0.01, "Materials should look the same" @@ -2043,12 +2007,8 @@ def test_randomize_materials_clearOnReset(controller): f1 = controller.reset().frame.astype(np.float16) f2 = controller.step(action="RandomizeMaterials").frame.astype(np.float16) f3 = controller.step(action="ResetMaterials").frame.astype(np.float16) - assert ( - np.abs(f1 - f2).flatten() / 255 - ).sum() / 300 / 300 > 0.05, "Expected material change" - assert ( - np.abs(f2 - f3).flatten() / 255 - ).sum() / 300 / 300 > 0.05, "Expected material change" + assert (np.abs(f1 - f2).flatten() / 255).sum() / 300 / 300 > 0.05, "Expected material change" + assert (np.abs(f2 - f3).flatten() / 255).sum() / 300 / 300 > 0.05, "Expected material change" assert ( np.abs(f1 - f3).flatten() / 255 ).sum() / 300 / 300 < 0.01, "Materials should look the same" @@ -2073,12 +2033,8 @@ def test_directionalPush(controller): objectId="Tomato|-03.13|+00.92|-00.39", moveMagnitude=25, ) - start_obj = next( - obj for obj in start.metadata["objects"] if obj["objectType"] == "Tomato" - ) - end_obj = next( - obj for obj in end.metadata["objects"] if obj["objectType"] == "Tomato" - ) + start_obj = next(obj for obj in start.metadata["objects"] if obj["objectType"] == "Tomato") + end_obj = next(obj for obj in end.metadata["objects"] if obj["objectType"] == "Tomato") positions.append((start_obj["position"], end_obj["position"])) assert positions[0][1]["z"] - positions[0][0]["z"] > 0.2 @@ -2109,21 +2065,24 @@ def test_randomize_materials_params(controller): assert not controller.step(action="RandomizeMaterials", useTrainMaterials=False) assert controller.step(action="RandomizeMaterials", inRoomTypes=["Kitchen"]) assert controller.step( - action="RandomizeMaterials", inRoomTypes=["Kitchen", "LivingRoom"], + action="RandomizeMaterials", + inRoomTypes=["Kitchen", "LivingRoom"], ) assert not controller.step(action="RandomizeMaterials", inRoomTypes=["LivingRoom"]) assert not controller.step(action="RandomizeMaterials", inRoomTypes=["RoboTHOR"]) controller.reset(scene="FloorPlan_Train5_2") assert not controller.step( - action="RandomizeMaterials", inRoomTypes=["Kitchen", "LivingRoom"], + action="RandomizeMaterials", + inRoomTypes=["Kitchen", "LivingRoom"], ) assert not controller.step(action="RandomizeMaterials", inRoomTypes=["LivingRoom"]) assert controller.step(action="RandomizeMaterials", inRoomTypes=["RoboTHOR"]) controller.reset(scene="FloorPlan_Val3_2") assert not controller.step( - action="RandomizeMaterials", inRoomTypes=["Kitchen", "LivingRoom"], + action="RandomizeMaterials", + inRoomTypes=["Kitchen", "LivingRoom"], ) assert not controller.step(action="RandomizeMaterials", inRoomTypes=["LivingRoom"]) assert controller.step(action="RandomizeMaterials", inRoomTypes=["RoboTHOR"]) @@ -2143,12 +2102,8 @@ def test_invalid_arguments(controller): placeStationary=True, ) print("Err {0}".format(controller.last_event.metadata["lastActionSuccess"])) - assert not controller.last_event.metadata[ - "lastActionSuccess" - ], "Extra parameter 'z' in action" - assert controller.last_event.metadata[ - "errorMessage" - ], "errorMessage with invalid argument" + assert not controller.last_event.metadata["lastActionSuccess"], "Extra parameter 'z' in action" + assert controller.last_event.metadata["errorMessage"], "errorMessage with invalid argument" @pytest.mark.parametrize("controller", fifo) @@ -2176,9 +2131,7 @@ def test_segmentation_colors(controller): event.color_to_object_id[fridge_color] == "Fridge" ), "Fridge should have this color semantic seg" - event = controller.reset( - renderSemanticSegmentation=False, renderInstanceSegmentation=True - ) + event = controller.reset(renderSemanticSegmentation=False, renderInstanceSegmentation=True) fridge_color = event.object_id_to_color["Fridge"] assert ( event.color_to_object_id[fridge_color] == "Fridge" @@ -2195,9 +2148,7 @@ def test_move_hand(controller): h2 = controller.step(action="MoveHeldObject", ahead=0.1).metadata["heldObjectPose"] assert_near(h1["rotation"], h2["rotation"]) - assert ( - 0.1 - 1e-3 <= h2["localPosition"]["z"] - h1["localPosition"]["z"] <= 0.1 + 1e-3 - ) + assert 0.1 - 1e-3 <= h2["localPosition"]["z"] - h1["localPosition"]["z"] <= 0.1 + 1e-3 assert abs(h2["localPosition"]["y"] - h1["localPosition"]["y"]) < 1e-3 assert abs(h2["localPosition"]["x"] - h1["localPosition"]["x"]) < 1e-3 @@ -2207,20 +2158,14 @@ def test_move_hand(controller): objectId="SoapBottle|-00.84|+00.93|-03.76", forceAction=True, ).metadata["heldObjectPose"] - h2 = controller.step( - action="MoveHeldObject", ahead=0.1, right=0.1, up=0.1 - ).metadata["heldObjectPose"] + h2 = controller.step(action="MoveHeldObject", ahead=0.1, right=0.1, up=0.1).metadata[ + "heldObjectPose" + ] assert_near(h1["rotation"], h2["rotation"]) - assert ( - 0.1 - 1e-3 <= h2["localPosition"]["z"] - h1["localPosition"]["z"] <= 0.1 + 1e-3 - ) - assert ( - 0.1 - 1e-3 <= h2["localPosition"]["x"] - h1["localPosition"]["x"] <= 0.1 + 1e-3 - ) - assert ( - 0.1 - 1e-3 <= h2["localPosition"]["y"] - h1["localPosition"]["y"] <= 0.1 + 1e-3 - ) + assert 0.1 - 1e-3 <= h2["localPosition"]["z"] - h1["localPosition"]["z"] <= 0.1 + 1e-3 + assert 0.1 - 1e-3 <= h2["localPosition"]["x"] - h1["localPosition"]["x"] <= 0.1 + 1e-3 + assert 0.1 - 1e-3 <= h2["localPosition"]["y"] - h1["localPosition"]["y"] <= 0.1 + 1e-3 controller.reset() h1 = controller.step( @@ -2228,24 +2173,14 @@ def test_move_hand(controller): objectId="SoapBottle|-00.84|+00.93|-03.76", forceAction=True, ).metadata["heldObjectPose"] - h2 = controller.step( - action="MoveHeldObject", ahead=0.1, right=0.05, up=-0.1 - ).metadata["heldObjectPose"] + h2 = controller.step(action="MoveHeldObject", ahead=0.1, right=0.05, up=-0.1).metadata[ + "heldObjectPose" + ] assert_near(h1["rotation"], h2["rotation"]) - assert ( - 0.1 - 1e-3 <= h2["localPosition"]["z"] - h1["localPosition"]["z"] <= 0.1 + 1e-3 - ) - assert ( - 0.05 - 1e-3 - <= h2["localPosition"]["x"] - h1["localPosition"]["x"] - <= 0.05 + 1e-3 - ) - assert ( - -0.1 - 1e-3 - <= h2["localPosition"]["y"] - h1["localPosition"]["y"] - <= -0.1 + 1e-3 - ) + assert 0.1 - 1e-3 <= h2["localPosition"]["z"] - h1["localPosition"]["z"] <= 0.1 + 1e-3 + assert 0.05 - 1e-3 <= h2["localPosition"]["x"] - h1["localPosition"]["x"] <= 0.05 + 1e-3 + assert -0.1 - 1e-3 <= h2["localPosition"]["y"] - h1["localPosition"]["y"] <= -0.1 + 1e-3 @pytest.mark.parametrize("controller", fifo) @@ -2302,9 +2237,7 @@ def test_rotate_hand(controller): objectId="SoapBottle|-00.84|+00.93|-03.76", forceAction=True, ).metadata["heldObjectPose"] - h2 = controller.step(action="RotateHeldObject", roll=90, pitch=90, yaw=90).metadata[ - "hand" - ] + h2 = controller.step(action="RotateHeldObject", roll=90, pitch=90, yaw=90).metadata["hand"] assert_near(h1["position"], h2["position"]) assert_near(h1["rotation"], dict(x=0, y=180, z=0)) @@ -2319,9 +2252,9 @@ def test_rotate_hand(controller): objectId="SoapBottle|-00.84|+00.93|-03.76", forceAction=True, ).metadata["hand"] - h2 = controller.step( - action="RotateHeldObject", rotation=dict(x=90, y=180, z=0) - ).metadata["hand"] + h2 = controller.step(action="RotateHeldObject", rotation=dict(x=90, y=180, z=0)).metadata[ + "hand" + ] assert_near(h1["position"], h2["position"]) assert_near(h1["localRotation"], dict(x=0, y=0, z=0)) @@ -2330,32 +2263,34 @@ def test_rotate_hand(controller): def test_settle_physics(): from dictdiffer import diff + physicsSimulationParams = { - "autoSimulation": False, - "fixedDeltaTime": 0.01, - # run 30 simulations after action - "minSimulateTimeSeconds": 0.3 + "autoSimulation": False, + "fixedDeltaTime": 0.01, + # run 30 simulations after action + "minSimulateTimeSeconds": 0.3, } fifo_controller = build_controller( - server_class=FifoServer, - agentMode="arm", - physicsSimulationParams = physicsSimulationParams + server_class=FifoServer, agentMode="arm", physicsSimulationParams=physicsSimulationParams ) - first_objs = {o['objectId']: o for o in fifo_controller.last_event.metadata["objects"]} + first_objs = {o["objectId"]: o for o in fifo_controller.last_event.metadata["objects"]} - fifo_controller.reset( - agentMode="arm", - physicsSimulationParams = physicsSimulationParams - ) + fifo_controller.reset(agentMode="arm", physicsSimulationParams=physicsSimulationParams) diffs = [] - last_objs = {o['objectId']: o for o in fifo_controller.last_event.metadata["objects"]} + last_objs = {o["objectId"]: o for o in fifo_controller.last_event.metadata["objects"]} for object_id, object_metadata in first_objs.items(): - for d in (diff(object_metadata, last_objs.get(object_id, {}), absolute_tolerance=0.001, ignore=set(["receptacleObjectIds"]))): + for d in diff( + object_metadata, + last_objs.get(object_id, {}), + absolute_tolerance=0.001, + ignore=set(["receptacleObjectIds"]), + ): diffs.append((object_id, d)) assert diffs == [] + @pytest.mark.parametrize("controller", fifo_wsgi) def test_fill_liquid(controller): pot = next( @@ -2399,12 +2334,10 @@ def test_fill_liquid(controller): def test_timeout(): - kwargs = { - "server_timeout": 2.0 - } + kwargs = {"server_timeout": 2.0} for c in [ build_controller(server_class=WsgiServer, **kwargs), - build_controller(server_class=FifoServer, **kwargs) + build_controller(server_class=FifoServer, **kwargs), ]: c.step("Sleep", seconds=1) assert c.last_event.metadata["lastActionSuccess"] @@ -2415,4 +2348,3 @@ def test_timeout(): # Above crash should kill the unity process time.sleep(1.0) assert c.server.unity_proc.poll() is not None - diff --git a/ai2thor/tests/test_unity_procedural.py b/ai2thor/tests/test_unity_procedural.py index d244df2473..20dfe4b357 100644 --- a/ai2thor/tests/test_unity_procedural.py +++ b/ai2thor/tests/test_unity_procedural.py @@ -101,6 +101,7 @@ def create_pixel_diff_image(img, g_truth): "metadata": {"schema": "1.0.0"}, } + # TODO rendering is different for fifo and wsgi server @pytest.mark.parametrize("controller_args", fifo) def test_render_lit(controller_args): @@ -147,9 +148,7 @@ def test_render_lit(controller_args): controller.stop() - assert images_near( - evt.cv2img, ground_truth, max_mean_pixel_diff=52, debug_save=True - ) + assert images_near(evt.cv2img, ground_truth, max_mean_pixel_diff=52, debug_save=True) # @@ -215,11 +214,12 @@ def test_depth(controller_args): @pytest.mark.parametrize("controller_args", fifo) def test_determinism(controller_args): from dictdiffer import diff + controller_args.update( - physicsSimulationParams = { + physicsSimulationParams={ "autoSimulation": False, # default fixedDeltaTime is 0.02 so 10 simulations - "minSimulateTimeSeconds": 0.2 + "minSimulateTimeSeconds": 0.2, } ) # add apple '$' on top of chair and table '*' to the left @@ -233,22 +233,21 @@ def test_determinism(controller_args): 0 0 0 0 0 0 """ ) - house_template['objects']["$"] = { - "kinematic": False, - "assetId": "Apple_4", - "position": {"x": 0, "y": 2, "z": 0} + house_template["objects"]["$"] = { + "kinematic": False, + "assetId": "Apple_4", + "position": {"x": 0, "y": 2, "z": 0}, } - house_template['objects']["*"] = { + house_template["objects"]["*"] = { "assetId": "Dining_Table_16_2", "kinematic": False, - "rotation": { "axis": {"x": 0, "y": 1, "z": 0}, "degrees": 90} + "rotation": {"axis": {"x": 0, "y": 1, "z": 0}, "degrees": 90}, } object_ids = ["+", "$", "*"] - house_template['objects']['+']['kinematic'] = False - + house_template["objects"]["+"]["kinematic"] = False controller = build_controller(**controller_args) @@ -272,11 +271,15 @@ def test_determinism(controller_args): ) ) assert evt.metadata["lastActionSuccess"] - pos = {x['name']: {'position': x['position'], 'rotation': x['rotation']} for x in evt.metadata['objects'] if x["name"] in object_ids} + pos = { + x["name"]: {"position": x["position"], "rotation": x["rotation"]} + for x in evt.metadata["objects"] + if x["name"] in object_ids + } print(f"{pos}") object_positions.append(pos) if prev_pos: - + diffs = list(diff(pos, prev_pos, tolerance=0.00001)) print(diffs) - assert [] == diffs \ No newline at end of file + assert [] == diffs diff --git a/ai2thor/util/lock.py b/ai2thor/util/lock.py index ad785d15c9..2d1a411871 100644 --- a/ai2thor/util/lock.py +++ b/ai2thor/util/lock.py @@ -25,7 +25,6 @@ def flock(fd, op): def lockf(fd, operation, length=0, start=0, whence=0): return - else: import fcntl diff --git a/ai2thor/util/metrics.py b/ai2thor/util/metrics.py index c2ebcf8b20..fa6ad33dae 100644 --- a/ai2thor/util/metrics.py +++ b/ai2thor/util/metrics.py @@ -58,9 +58,7 @@ def compute_single_spl(path, shortest_path, successful_path): return spl -def get_shortest_path_to_object( - controller, object_id, initial_position, initial_rotation=None -): +def get_shortest_path_to_object(controller, object_id, initial_position, initial_rotation=None): """ Computes the shortest path to an object from an initial position using a controller :param controller: agent controller @@ -80,9 +78,7 @@ def get_shortest_path_to_object( if event.metadata["lastActionSuccess"]: return event.metadata["actionReturn"]["corners"] else: - raise ValueError( - "Unable to find shortest path for objectId '{}'".format(object_id) - ) + raise ValueError("Unable to find shortest path for objectId '{}'".format(object_id)) def get_shortest_path_to_object_type( @@ -123,9 +119,7 @@ def get_shortest_path_to_object_type( ) -def get_shortest_path_to_point( - controller, initial_position, target_position, allowed_error=None -): +def get_shortest_path_to_point(controller, initial_position, target_position, allowed_error=None): """ Computes the shortest path to a point from an initial position using an agent controller :param controller: agent controller diff --git a/ai2thor/util/scene_yaml_edit.py b/ai2thor/util/scene_yaml_edit.py index 7645d5fe7f..6a96656644 100755 --- a/ai2thor/util/scene_yaml_edit.py +++ b/ai2thor/util/scene_yaml_edit.py @@ -23,9 +23,7 @@ def updateNavMeshParamsForScene(scene_file_name): doc.dump_yaml() -def GetRoboSceneNames( - last_index, last_subIndex, nameTemplate, prefix_path="unity/Assets/Scenes" -): +def GetRoboSceneNames(last_index, last_subIndex, nameTemplate, prefix_path="unity/Assets/Scenes"): return [ "{}/FloorPlan_{}{}_{}.unity".format(prefix_path, nameTemplate, i, j) for i in range(1, last_index + 1) @@ -33,9 +31,7 @@ def GetRoboSceneNames( ] -def GetSceneNames( - start_index, last_index, nameTemplate="", prefix_path="unity/Assets/Scenes" -): +def GetSceneNames(start_index, last_index, nameTemplate="", prefix_path="unity/Assets/Scenes"): return [ "{}/FloorPlan{}{}_physics.unity".format(prefix_path, i, nameTemplate) for i in range(start_index, last_index + 1) diff --git a/ai2thor/util/trials.py b/ai2thor/util/trials.py index 17884a9987..5a2f84c63a 100644 --- a/ai2thor/util/trials.py +++ b/ai2thor/util/trials.py @@ -3,11 +3,9 @@ class TrialMetric(object): - def init_trials(self, num_trials, metadata): - ... + def init_trials(self, num_trials, metadata): ... - def update_with_trial(self, trial_index, metadata): - ... + def update_with_trial(self, trial_index, metadata): ... class ObjectPositionVarianceAverage(TrialMetric): @@ -27,9 +25,7 @@ def init_trials(self, num_trials, metadata): def update_with_trial(self, trial_index, metadata): objects = metadata["objects"] - object_pos_map = { - o["objectId"]: vec_to_np_array(o["position"]) for o in objects - } + object_pos_map = {o["objectId"]: vec_to_np_array(o["position"]) for o in objects} for object_index in range(len(self.object_ids)): object_id = self.object_ids[object_index] self.trials[trial_index][object_index] = object_pos_map[object_id] @@ -56,17 +52,13 @@ def trial_runner(controller, number, metric, compute_running_metric=False): for trial_index in range(number): try: - yield controller, metric.compute( - n=trial_index - ) if compute_running_metric else math.nan + yield controller, metric.compute(n=trial_index) if compute_running_metric else math.nan metric.update_with_trial(trial_index, controller.last_event.metadata) controller.reset() except RuntimeError as e: print( e, - "Last action status: {}".format( - controller.last_event.meatadata["actionSuccess"] - ), + "Last action status: {}".format(controller.last_event.meatadata["actionSuccess"]), controller.last_event.meatadata["errorMessage"], ) yield controller, metric.compute() diff --git a/ai2thor/video_controller.py b/ai2thor/video_controller.py index 16b8c9d680..e4196ecf9b 100644 --- a/ai2thor/video_controller.py +++ b/ai2thor/video_controller.py @@ -101,7 +101,7 @@ def ToggleCeiling(self): def _cdf(self, x, std_dev=0.5, mean=0.0): """Cumulative distribution function""" - return (1.0 + erf((x - mean) / sqrt(2.0 * std_dev ** 2))) / 2.0 + return (1.0 + erf((x - mean) / sqrt(2.0 * std_dev**2))) / 2.0 def _linear_to_smooth(self, curr_frame, total_frames, std_dev=0.5, min_val=3): # start at -3 STD on a normal gaussian, go to 3 STD on gaussian @@ -112,9 +112,7 @@ def _linear_to_smooth(self, curr_frame, total_frames, std_dev=0.5, min_val=3): # removes drifting return 1 - return self._cdf( - -min_val + 2 * min_val * (curr_frame / total_frames), std_dev=std_dev - ) + return self._cdf(-min_val + 2 * min_val * (curr_frame / total_frames), std_dev=std_dev) def _move(self, actionName, moveMagnitude, frames, smoothAnimation, agentId=None): """Yields a generator full of move commands to move the agent incrementally. @@ -123,13 +121,9 @@ def _move(self, actionName, moveMagnitude, frames, smoothAnimation, agentId=None for i in range(frames): # smoothAnimation = False => linear animation if smoothAnimation: - next_moveMag = ( - self._linear_to_smooth(i + 1, frames, std_dev=1) * moveMagnitude - ) + next_moveMag = self._linear_to_smooth(i + 1, frames, std_dev=1) * moveMagnitude if agentId is None: - yield self.step( - action=actionName, moveMagnitude=next_moveMag - last_moveMag - ) + yield self.step(action=actionName, moveMagnitude=next_moveMag - last_moveMag) else: yield self.step( action=actionName, @@ -139,9 +133,7 @@ def _move(self, actionName, moveMagnitude, frames, smoothAnimation, agentId=None last_moveMag = next_moveMag else: if agentId is None: - yield self.step( - action=actionName, moveMagnitude=moveMagnitude / frames - ) + yield self.step(action=actionName, moveMagnitude=moveMagnitude / frames) else: yield self.step( action=actionName, @@ -168,8 +160,7 @@ def _rotate(self, direction, rotateDegrees, frames, smoothAnimation, agentId=Non if smoothAnimation: yield self.step( action="TeleportFull", - rotation=y0 - + rotateDegrees * self._linear_to_smooth(i + 1, frames, std_dev=1), + rotation=y0 + rotateDegrees * self._linear_to_smooth(i + 1, frames, std_dev=1), **p, ) else: @@ -180,40 +171,24 @@ def _rotate(self, direction, rotateDegrees, frames, smoothAnimation, agentId=Non ) def MoveAhead(self, moveMagnitude=1, frames=60, smoothAnimation=True, agentId=None): - return self._move( - "MoveAhead", moveMagnitude, frames, smoothAnimation, agentId=agentId - ) + return self._move("MoveAhead", moveMagnitude, frames, smoothAnimation, agentId=agentId) def MoveBack(self, moveMagnitude=1, frames=60, smoothAnimation=True, agentId=None): - return self._move( - "MoveBack", moveMagnitude, frames, smoothAnimation, agentId=agentId - ) + return self._move("MoveBack", moveMagnitude, frames, smoothAnimation, agentId=agentId) def MoveLeft(self, moveMagnitude=1, frames=60, smoothAnimation=True, agentId=None): - return self._move( - "MoveLeft", moveMagnitude, frames, smoothAnimation, agentId=agentId - ) + return self._move("MoveLeft", moveMagnitude, frames, smoothAnimation, agentId=agentId) def MoveRight(self, moveMagnitude=1, frames=60, smoothAnimation=True, agentId=None): - return self._move( - "MoveRight", moveMagnitude, frames, smoothAnimation, agentId=agentId - ) + return self._move("MoveRight", moveMagnitude, frames, smoothAnimation, agentId=agentId) - def RotateRight( - self, rotateDegrees=90, frames=60, smoothAnimation=True, agentId=None - ): + def RotateRight(self, rotateDegrees=90, frames=60, smoothAnimation=True, agentId=None): # do incremental teleporting - return self._rotate( - "right", rotateDegrees, frames, smoothAnimation, agentId=agentId - ) + return self._rotate("right", rotateDegrees, frames, smoothAnimation, agentId=agentId) - def RotateLeft( - self, rotateDegrees=90, frames=60, smoothAnimation=True, agentId=None - ): + def RotateLeft(self, rotateDegrees=90, frames=60, smoothAnimation=True, agentId=None): # do incremental teleporting - return self._rotate( - "left", rotateDegrees, frames, smoothAnimation, agentId=agentId - ) + return self._rotate("left", rotateDegrees, frames, smoothAnimation, agentId=agentId) def OrbitCameraAnimation( self, @@ -230,9 +205,7 @@ def OrbitCameraAnimation( Example: https://www.youtube.com/watch?v=KcELPpdN770&feature=youtu.be&t=14""" degrees = frames * orbit_degrees_per_frame - rot0 = self.last_event.metadata["thirdPartyCameras"][0]["rotation"][ - "y" - ] # starting angle + rot0 = self.last_event.metadata["thirdPartyCameras"][0]["rotation"]["y"] # starting angle for frame in range(frames): yAngle = rot0 + degrees * (frame + 1) / frames yield self.step( diff --git a/ai2thor/wsgi_server.py b/ai2thor/wsgi_server.py index 591835e802..d901289e04 100644 --- a/ai2thor/wsgi_server.py +++ b/ai2thor/wsgi_server.py @@ -40,8 +40,8 @@ def queue_get(que, unity_proc=None, timeout: Optional[float] = 100.0): max_attempts = ( float("inf") - if timeout is None or timeout == float("inf") else - max(int(math.ceil(timeout / queue_get_timeout_per_try)), 1) + if timeout is None or timeout == float("inf") + else max(int(math.ceil(timeout / queue_get_timeout_per_try)), 1) ) while True: try: @@ -130,9 +130,7 @@ def __init__(self, data, boundary): headers[k.strip()] = v.strip() ctype, ct_opts = werkzeug.http.parse_options_header(headers["Content-Type"]) - cdisp, cd_opts = werkzeug.http.parse_options_header( - headers["Content-disposition"] - ) + cdisp, cd_opts = werkzeug.http.parse_options_header(headers["Content-disposition"]) assert cdisp == "form-data" if "filename" in cd_opts: @@ -169,18 +167,14 @@ def __init__( app = Flask( __name__, template_folder=os.path.realpath( - os.path.join( - os.path.dirname(os.path.abspath(__file__)), "..", "templates" - ) + os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "templates") ), ) self.request_queue = Queue(maxsize=1) self.response_queue = Queue(maxsize=1) self.app = app - self.app.config.update( - PROPAGATE_EXCEPTIONS=False, JSONIFY_PRETTYPRINT_REGULAR=False - ) + self.app.config.update(PROPAGATE_EXCEPTIONS=False, JSONIFY_PRETTYPRINT_REGULAR=False) self.port = port self.last_rate_timestamp = time.time() self.frame_counter = 0 @@ -201,7 +195,7 @@ def __init__( height=height, timeout=timeout, depth_format=depth_format, - add_depth_noise=add_depth_noise + add_depth_noise=add_depth_noise, ) @app.route("/ping", methods=["get"]) @@ -220,10 +214,7 @@ def train(): ) metadata = json.loads(form.form["metadata"][0]) # backwards compatibility - if ( - "actionReturns" in form.form - and len(form.form["actionReturns"][0]) > 0 - ): + if "actionReturns" in form.form and len(form.form["actionReturns"][0]) > 0: action_returns = json.loads(form.form["actionReturns"][0]) token = form.form["token"][0] else: @@ -261,9 +252,7 @@ def train(): else: self.sequence_id = next_action["sequenceId"] - resp = make_response( - json.dumps(next_action, cls=ai2thor.server.NumpyAwareEncoder) - ) + resp = make_response(json.dumps(next_action, cls=ai2thor.server.NumpyAwareEncoder)) return resp @@ -281,7 +270,7 @@ def receive(self, timeout: Optional[float] = None): return queue_get( self.request_queue, unity_proc=self.unity_proc, - timeout=self.timeout if timeout is None else timeout + timeout=self.timeout if timeout is None else timeout, ) def send(self, action): diff --git a/arm_test/arm_counter_30fps_fixed_update.py b/arm_test/arm_counter_30fps_fixed_update.py index ca0585f4b3..fe4ebea086 100644 --- a/arm_test/arm_counter_30fps_fixed_update.py +++ b/arm_test/arm_counter_30fps_fixed_update.py @@ -35,9 +35,7 @@ returnToStart=False, handCameraSpace=False, ) -c.step( - action="MoveArmBase", disableRendering=False, y=0.9, speed=2, returnToStart=False -) +c.step(action="MoveArmBase", disableRendering=False, y=0.9, speed=2, returnToStart=False) pose = {"x": -1.0, "y": 0.9009995460510254, "z": 1, "rotation": 135, "horizon": 0} c.step( diff --git a/arm_test/arm_counter_30fps_fixed_update_random_sleep.py b/arm_test/arm_counter_30fps_fixed_update_random_sleep.py index 92dc355d96..9c2ea4f962 100644 --- a/arm_test/arm_counter_30fps_fixed_update_random_sleep.py +++ b/arm_test/arm_counter_30fps_fixed_update_random_sleep.py @@ -37,9 +37,7 @@ returnToStart=False, handCameraSpace=False, ) -c.step( - action="MoveArmBase", disableRendering=False, y=0.9, speed=2, returnToStart=False -) +c.step(action="MoveArmBase", disableRendering=False, y=0.9, speed=2, returnToStart=False) pose = {"x": -1.0, "y": 0.9009995460510254, "z": 1, "rotation": 135, "horizon": 0} c.step( diff --git a/arm_test/arm_counter_30fps_simulate.py b/arm_test/arm_counter_30fps_simulate.py index 1469074d55..5759e3c6ce 100644 --- a/arm_test/arm_counter_30fps_simulate.py +++ b/arm_test/arm_counter_30fps_simulate.py @@ -34,9 +34,7 @@ returnToStart=False, handCameraSpace=False, ) -c.step( - action="MoveArmBase", disableRendering=False, y=0.9, speed=2, returnToStart=False -) +c.step(action="MoveArmBase", disableRendering=False, y=0.9, speed=2, returnToStart=False) pose = {"x": -1.0, "y": 0.9009995460510254, "z": 1, "rotation": 135, "horizon": 0} c.step( diff --git a/arm_test/arm_stuck_test_wait_frame.py b/arm_test/arm_stuck_test_wait_frame.py index a3092c002c..c534c871a6 100644 --- a/arm_test/arm_stuck_test_wait_frame.py +++ b/arm_test/arm_stuck_test_wait_frame.py @@ -37,9 +37,7 @@ ] standard_pose() -execute_actions( - actions, disableRendering=False, waitForFixedUpdate=False, returnToStart=True -) +execute_actions(actions, disableRendering=False, waitForFixedUpdate=False, returnToStart=True) event = arm_test.base.controller.step( "MoveArmBase", y=0.49074136446614885, diff --git a/arm_test/base.py b/arm_test/base.py index 1fe97e15ba..2fdaa39c79 100644 --- a/arm_test/base.py +++ b/arm_test/base.py @@ -36,9 +36,7 @@ def upload_video(data): s3 = boto3.resource("s3") acl = "public-read" - key = os.path.join( - sys.argv[0].split("/")[-1].split(".")[0], str(uuid.uuid4()) + ".webm" - ) + key = os.path.join(sys.argv[0].split("/")[-1].split(".")[0], str(uuid.uuid4()) + ".webm") print( "Video is available at: https://ai2-thor-exproom-arm-test.s3-us-west-2.amazonaws.com/%s" % key @@ -59,12 +57,7 @@ def write_video(frames): if not args.record_video: return temp_file = ( - str(time.time()) - + "-" - + str(random.randint(0, 2 ** 32)) - + "-" - + str(os.getpid()) - + ".webm" + str(time.time()) + "-" + str(random.randint(0, 2**32)) + "-" + str(os.getpid()) + ".webm" ) video = cv2.VideoWriter( temp_file, @@ -131,9 +124,7 @@ def execute_actions(actions, **kwargs): controller.step(a) print("success: %s" % controller.last_event.metadata["lastActionSuccess"]) print("return: %s" % controller.last_event.metadata["actionReturn"]) - print( - "position: %s" % (controller.last_event.metadata["arm"]["handSphereCenter"]) - ) + print("position: %s" % (controller.last_event.metadata["arm"]["handSphereCenter"])) for j in controller.last_event.metadata["arm"]["joints"]: rot = " ".join(map(lambda x: str(j["rotation"][x]), ["x", "y", "z", "w"])) print("%s %s" % (j["name"], rot)) diff --git a/arm_test/check_determinism_different_machines.py b/arm_test/check_determinism_different_machines.py index 5a86283ebf..1e82ac3bd6 100644 --- a/arm_test/check_determinism_different_machines.py +++ b/arm_test/check_determinism_different_machines.py @@ -42,22 +42,16 @@ "restrictMovement": False, # "waitForFixedUpdate": False, // deprecated "returnToStart": True, - "speed": 1 + "speed": 1, } -ADDITONAL_MOVEMENT_ARGS = { - "disableRendering": True, - "returnToStart": True, - "speed": 1 - } +ADDITONAL_MOVEMENT_ARGS = {"disableRendering": True, "returnToStart": True, "speed": 1} -ADITIONAL_NEW_MOVEMENT_ARGS= { - "returnToStart": True, - "speed": 1, - "physicsSimulationParams": { - "autoSimulation": False - } - } +ADITIONAL_NEW_MOVEMENT_ARGS = { + "returnToStart": True, + "speed": 1, + "physicsSimulationParams": {"autoSimulation": False}, +} MoveArm = "MoveArm" @@ -68,27 +62,19 @@ ADITIONAL_ARM_ARGS_BY_ACTION = { - - "MoveArmNew": { - "restrictMovement": False, - **ADITIONAL_NEW_MOVEMENT_ARGS - }, + "MoveArmNew": {"restrictMovement": False, **ADITIONAL_NEW_MOVEMENT_ARGS}, "MoveArmBaseNew": ADITIONAL_NEW_MOVEMENT_ARGS, "RotateAgentNew": ADITIONAL_NEW_MOVEMENT_ARGS, "MoveAheadNew": ADITIONAL_NEW_MOVEMENT_ARGS, "MoveAgentNew": ADITIONAL_NEW_MOVEMENT_ARGS, - - "MoveArm": { - "restrictMovement": False, - **ADDITONAL_MOVEMENT_ARGS - }, + "MoveArm": {"restrictMovement": False, **ADDITONAL_MOVEMENT_ARGS}, "MoveArmBase": ADDITONAL_MOVEMENT_ARGS, "RotateAgent": ADDITONAL_MOVEMENT_ARGS, "MoveAhead": ADDITONAL_MOVEMENT_ARGS, - "MoveAgent": ADDITONAL_MOVEMENT_ARGS - + "MoveAgent": ADDITONAL_MOVEMENT_ARGS, } + def actionName(action): # return action if not new_actions: @@ -96,6 +82,7 @@ def actionName(action): else: return f"{action}{new_action_suffix}" + MOVE_CONSTANT = 0.05 @@ -135,21 +122,13 @@ def execute_command(controller, command, action_dict_addition_by_action): elif command == "d": action_details = dict(action="DropMidLevelHand", add_extra_args=True) elif command == "mm": - action_details = dict( - action=actionName(MoveAgent), - ahead=0.2, - add_extra_args=True - ) + action_details = dict(action=actionName(MoveAgent), ahead=0.2, add_extra_args=True) elif command == "rr": - action_details = dict( - action= actionName(RotateAgent), degrees=45, add_extra_args=True - ) + action_details = dict(action=actionName(RotateAgent), degrees=45, add_extra_args=True) elif command == "ll": - action_details = dict( - action=actionName(RotateAgent), degrees=-45, add_extra_args=True - ) + action_details = dict(action=actionName(RotateAgent), degrees=-45, add_extra_args=True) elif command == "m": action_details = dict(action=actionName(MoveAhead), add_extra_args=True) @@ -171,10 +150,8 @@ def execute_command(controller, command, action_dict_addition_by_action): if command in ["w", "z", "s", "a", "3", "4"]: action_details = dict( action=actionName(MoveArm), - position=dict( - x=base_position["x"], y=base_position["y"], z=base_position["z"] - ), - add_extra_args=True + position=dict(x=base_position["x"], y=base_position["y"], z=base_position["z"]), + add_extra_args=True, ) elif command in ["u", "j"]: @@ -184,20 +161,16 @@ def execute_command(controller, command, action_dict_addition_by_action): base_position["h"] = 0 action_details = dict( - action=actionName(MoveArmBase), - y=base_position["h"], - add_extra_args=True + action=actionName(MoveArmBase), y=base_position["h"], add_extra_args=True ) - if 'add_extra_args' in action_details and action_details['add_extra_args']: - del action_details['add_extra_args'] - action_dict_addition = action_dict_addition_by_action[action_details['action']] + if "add_extra_args" in action_details and action_details["add_extra_args"]: + del action_details["add_extra_args"] + action_dict_addition = action_dict_addition_by_action[action_details["action"]] action_details = dict(**action_details, **action_dict_addition) - if 'action' in action_details: + if "action" in action_details: # print(f"Calling action: {action_details['action']} with {action_details}") - controller.step( - **action_details - ) + controller.step(**action_details) return action_details @@ -293,7 +266,7 @@ def random_tests(): z=initial_location["z"], rotation=dict(x=0, y=initial_rotation, z=0), horizon=10, - standing=True + standing=True, ) initial_pose = dict( action="TeleportFull", @@ -302,7 +275,7 @@ def random_tests(): z=initial_location["z"], rotation=dict(x=0, y=initial_rotation, z=0), horizon=10, - standing=True + standing=True, ) controller.step("PausePhysicsAutoSim") all_commands = [] @@ -355,7 +328,7 @@ def determinism_test(all_tests, test_index=None): # only do this if an object is picked up passed_count = 0 tests = all_tests.items() - if test_index is not None: + if test_index is not None: tests = [list(tests)[test_index]] for k, test_point in tests: start = time.time() @@ -375,7 +348,7 @@ def determinism_test(all_tests, test_index=None): z=initial_location["z"], rotation=dict(x=0, y=initial_rotation, z=0), horizon=10, - standing=True + standing=True, ) controller.step("PausePhysicsAutoSim") for cmd in all_commands: @@ -406,9 +379,9 @@ def determinism_test(all_tests, test_index=None): all_dict = json.load(f) parser = argparse.ArgumentParser( - prog='Arm Determinism Tests', - description='Testing arm determinism') - parser.add_argument('-i', '--index', type=int) + prog="Arm Determinism Tests", description="Testing arm determinism" + ) + parser.add_argument("-i", "--index", type=int) args = parser.parse_args() diff --git a/arm_test/check_determinism_event_collision_different_machines.py b/arm_test/check_determinism_event_collision_different_machines.py index ffdc8aeeb9..4465586687 100644 --- a/arm_test/check_determinism_event_collision_different_machines.py +++ b/arm_test/check_determinism_event_collision_different_machines.py @@ -82,14 +82,10 @@ def execute_command(controller, command, action_dict_addition): if "moveSpeed" in action_dict_addition: action_dict_addition["speed"] = action_dict_addition["moveSpeed"] controller.step( - action="MoveContinuous", - direction=dict(x=0.0, y=0.0, z=0.2), - **action_dict_addition + action="MoveContinuous", direction=dict(x=0.0, y=0.0, z=0.2), **action_dict_addition ) action_details = dict( - action="MoveContinuous", - direction=dict(x=0.0, y=0.0, z=0.2), - **action_dict_addition + action="MoveContinuous", direction=dict(x=0.0, y=0.0, z=0.2), **action_dict_addition ) elif command == "rr": @@ -98,15 +94,11 @@ def execute_command(controller, command, action_dict_addition): if "moveSpeed" in action_dict_addition: action_dict_addition["speed"] = action_dict_addition["moveSpeed"] controller.step(action="RotateContinuous", degrees=45, **action_dict_addition) - action_details = dict( - action="RotateContinuous", degrees=45, **action_dict_addition - ) + action_details = dict(action="RotateContinuous", degrees=45, **action_dict_addition) elif command == "ll": action_dict_addition = copy.copy(action_dict_addition) controller.step(action="RotateContinuous", degrees=-45, **action_dict_addition) - action_details = dict( - action="RotateContinuous", degrees=-45, **action_dict_addition - ) + action_details = dict(action="RotateContinuous", degrees=-45, **action_dict_addition) elif command == "m": controller.step(action="MoveAhead", **action_dict_addition) action_details = dict(action="MoveAhead", **action_dict_addition) @@ -129,19 +121,15 @@ def execute_command(controller, command, action_dict_addition): controller.step( action="MoveMidLevelArm", - position=dict( - x=base_position["x"], y=base_position["y"], z=base_position["z"] - ), + position=dict(x=base_position["x"], y=base_position["y"], z=base_position["z"]), handCameraSpace=False, - **action_dict_addition + **action_dict_addition, ) action_details = dict( action="MoveMidLevelArm", - position=dict( - x=base_position["x"], y=base_position["y"], z=base_position["z"] - ), + position=dict(x=base_position["x"], y=base_position["y"], z=base_position["z"]), handCameraSpace=False, - **action_dict_addition + **action_dict_addition, ) elif command in ["u", "j"]: @@ -150,12 +138,8 @@ def execute_command(controller, command, action_dict_addition): elif base_position["h"] < 0: base_position["h"] = 0 - controller.step( - action="MoveArmBase", y=base_position["h"], **action_dict_addition - ) - action_details = dict( - action="MoveArmBase", y=base_position["h"], **action_dict_addition - ) + controller.step(action="MoveArmBase", y=base_position["h"], **action_dict_addition) + action_details = dict(action="MoveArmBase", y=base_position["h"], **action_dict_addition) return action_details diff --git a/fpin_tutorial.py b/fpin_tutorial.py index 629864a30c..bf67949575 100644 --- a/fpin_tutorial.py +++ b/fpin_tutorial.py @@ -7,79 +7,74 @@ def fpin_tutorial( - house_path, - run_in_editor = False, - platform=None, - local_build=False, + house_path, + run_in_editor=False, + platform=None, + local_build=False, commit_id=None, - objaverse_asset_id =None, - objaverse_dir=None + objaverse_asset_id=None, + objaverse_dir=None, ): if not run_in_editor: - build_args = dict( - commit_id=commit_id, - server_class=ai2thor.fifo_server.FifoServer, - ) - if local_build: - del build_args["commit_id"] - build_args["local_build"] = True - else: + build_args = dict( + commit_id=commit_id, + server_class=ai2thor.fifo_server.FifoServer, + ) + if local_build: + del build_args["commit_id"] + build_args["local_build"] = True + else: build_args = dict( start_unity=False, port=8200, server_class=ai2thor.wsgi_server.WsgiServer, ) - - # Arguments to Fpin agent's Initialize + # Arguments to Fpin agent's Initialize agentInitializationParams = dict( - bodyAsset= {"assetId": "Toaster_5"}, + bodyAsset={"assetId": "Toaster_5"}, originOffsetX=0.0, originOffsetZ=0.0, - colliderScaleRatio={"x":1, "y":1, "z": 1}, + colliderScaleRatio={"x": 1, "y": 1, "z": 1}, useAbsoluteSize=False, - useVisibleColliderBase=True + useVisibleColliderBase=True, ) # Initialization params init_params = dict( - # local_executable_path="unity/builds/thor-OSXIntel64-local/thor-OSXIntel64-local.app/Contents/MacOS/AI2-THOR", + # local_executable_path="unity/builds/thor-OSXIntel64-local/thor-OSXIntel64-local.app/Contents/MacOS/AI2-THOR", # local_build=True, - platform=platform, scene="Procedural", gridSize=0.25, width=300, height=300, - agentMode="fpin", visibilityScheme="Distance", renderInstanceSegmentation=True, renderDepth=True, - # New parameter to pass to agent's initializer agentInitializationParams=agentInitializationParams, - **build_args + **build_args, ) # Load house with open(house_path, "r") as f: house = json.load(f) - print('Controller args: ') + print("Controller args: ") print(init_params) # Build controller, Initialize will be called here - controller = ai2thor.controller.Controller( - **init_params - ) + controller = ai2thor.controller.Controller(**init_params) - print(f"Init action success: {controller.last_event.metadata['lastActionSuccess']} error: {controller.last_event.metadata['errorMessage']}") + print( + f"Init action success: {controller.last_event.metadata['lastActionSuccess']} error: {controller.last_event.metadata['errorMessage']}" + ) # Get the fpin box bounds, vector3 with the box sides lenght box_body_sides = controller.last_event.metadata["agent"]["fpinColliderSize"] print(f"box_body_sides: {box_body_sides}") - # Compute the desired capsule for the navmesh def get_nav_mesh_config_from_box(box_body_sides, nav_mesh_id, min_side_as_radius=False): # This can be changed to fit specific needs @@ -92,12 +87,13 @@ def get_nav_mesh_config_from_box(box_body_sides, nav_mesh_id, min_side_as_radius return { "id": navMeshOverEstimateId, - "agentRadius": capsuleUnderEstimateRadius if min_side_as_radius else capsuleOverEstimateRadius, + "agentRadius": ( + capsuleUnderEstimateRadius if min_side_as_radius else capsuleOverEstimateRadius + ), "agentHeight": capsuleHeight, } - - # Navmesh ids use integers, you can pass to GetShortestPath or actions of the type to compute on that particular navmesh + # Navmesh ids use integers, you can pass to GetShortestPath or actions of the type to compute on that particular navmesh navMeshOverEstimateId = 0 navMeshUnderEstimateId = 1 @@ -105,7 +101,11 @@ def get_nav_mesh_config_from_box(box_body_sides, nav_mesh_id, min_side_as_radius house["metadata"]["navMeshes"] = [ # The overestimated navmesh makes RandomlyPlaceAgentOnNavMesh # get_nav_mesh_config_from_box(box_body_sides= box_body_sides, nav_mesh_id= navMeshOverEstimateId, min_side_as_radius= False), - get_nav_mesh_config_from_box(box_body_sides= box_body_sides, nav_mesh_id= navMeshUnderEstimateId, min_side_as_radius= True) + get_nav_mesh_config_from_box( + box_body_sides=box_body_sides, + nav_mesh_id=navMeshUnderEstimateId, + min_side_as_radius=True, + ) ] print(f"navmeshes: { house['metadata']['navMeshes']}") @@ -122,15 +122,13 @@ def get_nav_mesh_config_from_box(box_body_sides, nav_mesh_id, min_side_as_radius # Teleport using new RandomlyPlaceAgentOnNavMesh evt = controller.step( action="RandomlyPlaceAgentOnNavMesh", - n = 200 # Number of sampled points in Navmesh defaults to 200 + n=200, # Number of sampled points in Navmesh defaults to 200 ) print( f"Action {controller.last_action['action']} success: {evt.metadata['lastActionSuccess']} Error: {evt.metadata['errorMessage']}" ) - - # Teleport agent using Teleport full # Get a valid position, for house procthor_train_1.json this is a valid one @@ -140,98 +138,64 @@ def get_nav_mesh_config_from_box(box_body_sides, nav_mesh_id, min_side_as_radius evt = controller.step( action="TeleportFull", - x=position['x'], - y=position['y'], - z=position['z'], + x=position["x"], + y=position["y"], + z=position["z"], rotation=rotation, horizon=agent["horizon"], - standing=agent["standing"] + standing=agent["standing"], ) print( f"Action {controller.last_action['action']} success: {evt.metadata['lastActionSuccess']} Error: {evt.metadata['errorMessage']}" ) - # Move - controller.step( - action = "MoveAhead", - moveMagnitude = 0.25 - ) - controller.step( - action = "MoveRight", - moveMagnitude = 0.25 - ) + # Move + controller.step(action="MoveAhead", moveMagnitude=0.25) + controller.step(action="MoveRight", moveMagnitude=0.25) # Move Diagonally - controller.step( - action = "MoveAgent", - ahead = 0.25, - right = 0.25, - speed = 1 - ) + controller.step(action="MoveAgent", ahead=0.25, right=0.25, speed=1) # Moves diagonally 0.25 - controller.step( - action = "MoveAgent", - ahead = 0.15, - right = 0.2, - speed = 1 - ) + controller.step(action="MoveAgent", ahead=0.15, right=0.2, speed=1) # Whatever rotateStepDegrees is from initialize, defualt 90 - controller.step( - action = "RotateRight" - ) - + controller.step(action="RotateRight") + # + clockwise - controller.step( - action = "RotateAgent", - degrees = 35 - ) - # - counter-clockwise - controller.step( - action = "RotateAgent", - degrees = -35 - ) - + controller.step(action="RotateAgent", degrees=35) + # - counter-clockwise + controller.step(action="RotateAgent", degrees=-35) + print( f"Action {controller.last_action['action']} success: {evt.metadata['lastActionSuccess']} Error: {evt.metadata['errorMessage']}" ) - ## Change Body! # default change to stretch robot body = {"assetId": "StretchBotSimObj"} # body = {"assetId": "Apple_1"} # For objaverse assets loaded in unity if objaverse_asset_id != None and objaverse_dir != None: - body = dict( - dynamicAsset = { - "id": objaverse_asset_id, - "dir": os.path.abspath(objaverse_dir) - } - ) + body = dict(dynamicAsset={"id": objaverse_asset_id, "dir": os.path.abspath(objaverse_dir)}) # Also alternative if you load the asset data from python of a json model you can load via # bodyAsset = dict(asset = ), - - # Uses exact same parameters as agentInitializationParams sent to Initialize + # Uses exact same parameters as agentInitializationParams sent to Initialize bodyParams = dict( bodyAsset=body, originOffsetX=0.0, originOffsetZ=0.0, - colliderScaleRatio={"x":1, "y":1, "z": 1}, + colliderScaleRatio={"x": 1, "y": 1, "z": 1}, useAbsoluteSize=False, - useVisibleColliderBase=False + useVisibleColliderBase=False, ) ### Currently working on this bug, so works for some object not for others # Call InitializeBody with flattened parameters if False: - evt = controller.step( - action = "InitializeBody", - **bodyParams - ) + evt = controller.step(action="InitializeBody", **bodyParams) print( f"Action {controller.last_action['action']} success: {evt.metadata['lastActionSuccess']} Error: {evt.metadata['errorMessage']}" ) @@ -239,7 +203,11 @@ def get_nav_mesh_config_from_box(box_body_sides, nav_mesh_id, min_side_as_radius # Create new navmesh, you don't need to do this if you call CreateHouse just setting house["metadata"]["navMeshes"] will be fastest box_body_sides = evt.metadata["agent"]["fpinColliderSize"] print(f"box_body_sides: {box_body_sides}") - navmesh_config = get_nav_mesh_config_from_box(box_body_sides= box_body_sides, nav_mesh_id= navMeshOverEstimateId, min_side_as_radius= False) + navmesh_config = get_nav_mesh_config_from_box( + box_body_sides=box_body_sides, + nav_mesh_id=navMeshOverEstimateId, + min_side_as_radius=False, + ) print(f"navmeshes: {navmesh_config}") print(navmesh_config) @@ -247,47 +215,43 @@ def get_nav_mesh_config_from_box(box_body_sides, nav_mesh_id, min_side_as_radius action="OverwriteNavMeshes", # action = "ReBakeNavMeshes", # navMeshConfigs=[navmesh_config] - navMeshConfigs = [navmesh_config] - + navMeshConfigs=[navmesh_config], ) return # Reset the scene and pass the agentInitializationParams and other desired initparams agane - evt = controller.reset(house, agentInitializationParams = bodyParams) + evt = controller.reset(house, agentInitializationParams=bodyParams) box_body_sides = controller.last_event.metadata["agent"]["fpinColliderSize"] - navmesh_config = get_nav_mesh_config_from_box(box_body_sides= box_body_sides, nav_mesh_id= navMeshOverEstimateId, min_side_as_radius= False) + navmesh_config = get_nav_mesh_config_from_box( + box_body_sides=box_body_sides, nav_mesh_id=navMeshOverEstimateId, min_side_as_radius=False + ) # Rebake Navmeshes - controller.step( - action="OverwriteNavMeshes", - navMeshConfigs = [navmesh_config] - - ) + controller.step(action="OverwriteNavMeshes", navMeshConfigs=[navmesh_config]) print( f"Action {controller.last_action['action']} success: {evt.metadata['lastActionSuccess']} Error: {evt.metadata['errorMessage']}" ) - #Teleport + # Teleport evt = controller.step( action="TeleportFull", - x=position['x'], - y=position['y'], - z=position['z'], + x=position["x"], + y=position["y"], + z=position["z"], rotation=rotation, horizon=agent["horizon"], standing=agent["standing"], - forceAction=True + forceAction=True, ) - - print( f"Action {controller.last_action['action']} success: {evt.metadata['lastActionSuccess']} Error: {evt.metadata['errorMessage']}" ) - # + # # input() + if __name__ == "__main__": parser = argparse.ArgumentParser() @@ -303,13 +267,9 @@ def get_nav_mesh_config_from_box(box_body_sides, nav_mesh_id, min_side_as_radius type=str, default=None, ) - parser.add_argument( - "--local_build", action="store_true", help="Uses the local build." - ) + parser.add_argument("--local_build", action="store_true", help="Uses the local build.") - parser.add_argument( - "--editor", action="store_true", help="Runs in editor." - ) + parser.add_argument("--editor", action="store_true", help="Runs in editor.") parser.add_argument( "--objaverse_dir", @@ -323,15 +283,14 @@ def get_nav_mesh_config_from_box(box_body_sides, nav_mesh_id, min_side_as_radius default=None, ) - args = parser.parse_args(sys.argv[1:]) fpin_tutorial( - house_path=args.house_path, - run_in_editor=args.editor, - local_build=args.local_build, - commit_id=args.commit_id, - platform=args.platform, - objaverse_asset_id=args.objaverse_asset_id, - objaverse_dir=args.objaverse_dir - ) #platform="CloudRendering") - # input() \ No newline at end of file + house_path=args.house_path, + run_in_editor=args.editor, + local_build=args.local_build, + commit_id=args.commit_id, + platform=args.platform, + objaverse_asset_id=args.objaverse_asset_id, + objaverse_dir=args.objaverse_dir, + ) # platform="CloudRendering") + # input() diff --git a/scripts/objaverse_expand.py b/scripts/objaverse_expand.py index 8d2a65d451..c1e91ac580 100644 --- a/scripts/objaverse_expand.py +++ b/scripts/objaverse_expand.py @@ -4,9 +4,11 @@ import compress_pickle import json + def normalize_texture_path(obj_dir, texture_path): return os.path.join(os.path.abspath(obj_dir), os.path.basename(texture_path)) + def expand_objaverse(directory, ids): id_set = {} if ids != "": @@ -14,27 +16,30 @@ def expand_objaverse(directory, ids): print(f"selected ids: {id_set}") for obj_file in glob.glob(os.path.join(directory, "*", "*.pkl.gz")): obj_dir = os.path.dirname(obj_file) - obj_id = os.path.basename(obj_dir) - if not id_set or obj_id in id_set: + obj_id = os.path.basename(obj_dir) + if not id_set or obj_id in id_set: obj = compress_pickle.load(obj_file) obj["albedoTexturePath"] = normalize_texture_path(obj_dir, obj["albedoTexturePath"]) obj["normalTexturePath"] = normalize_texture_path(obj_dir, obj["normalTexturePath"]) obj["emissionTexturePath"] = normalize_texture_path(obj_dir, obj["emissionTexturePath"]) - print(f'new paths: {obj["albedoTexturePath"]} {obj["normalTexturePath"]} {obj["emissionTexturePath"]}') + print( + f'new paths: {obj["albedoTexturePath"]} {obj["normalTexturePath"]} {obj["emissionTexturePath"]}' + ) out_obj = os.path.join(obj_dir, f"{obj_id}.json") print(out_obj) with open(out_obj, "w") as f: json.dump(obj, f) + if __name__ == "__main__": # 0a0a8274693445a6b533dce7f97f747c parser = argparse.ArgumentParser() - parser.add_argument('directory') - parser.add_argument( + parser.add_argument("directory") + parser.add_argument( "--ids", help="Comma separated list of ids to convert", type=str, default="", ) args = parser.parse_args() - expand_objaverse(args.directory, args.ids) \ No newline at end of file + expand_objaverse(args.directory, args.ids) diff --git a/scripts/update_private.py b/scripts/update_private.py index b07fb7ae80..1497694fa1 100755 --- a/scripts/update_private.py +++ b/scripts/update_private.py @@ -7,7 +7,8 @@ private_dir = "" private_repo_url = "" -class Repo(): + +class Repo: def __init__( self, url: str, @@ -24,7 +25,7 @@ def __init__( self.commit_id = commit_id self.branch = branch self.delete_before_checkout = delete_before_checkout - + def current_branch(self): git_dir = os.path.join(self.base_dir, ".git") return ( @@ -61,6 +62,7 @@ def checkout_branch(self, remote="origin"): os.chdir(cwd) + """ Script that maintains the Private directory checkout - intended to be run immediately after switching branches in the parent ai2thor project @@ -73,9 +75,7 @@ def checkout_branch(self, remote="origin"): private_dir = sys.argv[1] private_repo_url = sys.argv[2] if not os.path.isdir(private_dir) and os.path.exists(private_dir): - raise Exception( - f"Private directory {private_dir} is not a directory - please remove" - ) + raise Exception(f"Private directory {private_dir} is not a directory - please remove") else: - repo = Repo(url = private_repo_url, target_dir = private_dir, delete_before_checkout=True) + repo = Repo(url=private_repo_url, target_dir=private_dir, delete_before_checkout=True) repo.checkout_branch() diff --git a/setup.py b/setup.py index 5538ab5baf..ff928d10a4 100644 --- a/setup.py +++ b/setup.py @@ -12,14 +12,12 @@ VERSION = __version__ + def _read_reqs(relpath): - fullpath = os.path.join(os.path.dirname(__file__), relpath) - with open(fullpath) as f: - return [ - s.strip() - for s in f.readlines() - if (s.strip() and not s.startswith("#")) - ] + fullpath = os.path.join(os.path.dirname(__file__), relpath) + with open(fullpath) as f: + return [s.strip() for s in f.readlines() if (s.strip() and not s.startswith("#"))] + REQUIREMENTS = _read_reqs("requirements.txt") REQUIREMENTS_TEST = _read_reqs("requirements-dev.txt") @@ -59,4 +57,3 @@ def _read_reqs(relpath): scripts=["scripts/ai2thor-xorg"], include_package_data=False, ) - diff --git a/tasks.py b/tasks.py index 58a22f9e62..ee8839a098 100644 --- a/tasks.py +++ b/tasks.py @@ -67,9 +67,7 @@ def add_files(zipf, start_dir, exclude_ext=()): continue arcname = os.path.relpath(fn, start_dir) - if arcname.split("/")[0].endswith( - "_BackUpThisFolder_ButDontShipItWithYourGame" - ): + if arcname.split("/")[0].endswith("_BackUpThisFolder_ButDontShipItWithYourGame"): # print("skipping %s" % arcname) continue # print("adding %s" % arcname) @@ -106,19 +104,17 @@ def push_build(build_archive_name, zip_data, include_private_scenes): ChecksumSHA256=b64encode(sha.digest()).decode("ascii"), ) logger.info("pushing sha256 %s" % (sha256_key,)) - s3.Object(bucket, sha256_key).put( - Body=sha.hexdigest(), ACL=acl, ContentType="text/plain" - ) + s3.Object(bucket, sha256_key).put(Body=sha.hexdigest(), ACL=acl, ContentType="text/plain") except botocore.exceptions.ClientError: - logger.error("caught error uploading archive %s: %s" % (build_archive_name, traceback.format_exc())) + logger.error( + "caught error uploading archive %s: %s" % (build_archive_name, traceback.format_exc()) + ) logger.info("pushed build %s to %s" % (bucket, build_archive_name)) def _webgl_local_build_path(prefix, source_dir="builds"): - return os.path.join( - os.getcwd(), "unity/{}/thor-{}-WebGL/".format(source_dir, prefix) - ) + return os.path.join(os.getcwd(), "unity/{}/thor-{}-WebGL/".format(source_dir, prefix)) def _unity_version(): @@ -135,18 +131,10 @@ def _unity_playback_engines_path(): standalone_path = None if sys.platform.startswith("darwin"): - unity_hub_path = ( - "/Applications/Unity/Hub/Editor/{}/PlaybackEngines".format( - unity_version - ) - ) + unity_hub_path = "/Applications/Unity/Hub/Editor/{}/PlaybackEngines".format(unity_version) # /Applications/Unity/2019.4.20f1/Unity.app/Contents/MacOS - standalone_path = ( - "/Applications/Unity/{}/PlaybackEngines".format( - unity_version - ) - ) + standalone_path = "/Applications/Unity/{}/PlaybackEngines".format(unity_version) elif "win" in sys.platform: raise ValueError("Windows not supported yet, verify PlaybackEnginesPath") unity_hub_path = "C:/PROGRA~1/Unity/Hub/Editor/{}/Editor/Data/PlaybackEngines".format( @@ -166,22 +154,19 @@ def _unity_playback_engines_path(): return unity_path + def _unity_path(): unity_version = _unity_version() standalone_path = None if sys.platform.startswith("darwin"): - unity_hub_path = ( - "/Applications/Unity/Hub/Editor/{}/Unity.app/Contents/MacOS/Unity".format( - unity_version - ) + unity_hub_path = "/Applications/Unity/Hub/Editor/{}/Unity.app/Contents/MacOS/Unity".format( + unity_version ) # /Applications/Unity/2019.4.20f1/Unity.app/Contents/MacOS - standalone_path = ( - "/Applications/Unity/{}/Unity.app/Contents/MacOS/Unity".format( - unity_version - ) + standalone_path = "/Applications/Unity/{}/Unity.app/Contents/MacOS/Unity".format( + unity_version ) # standalone_path = ( # "/Applications/Unity-{}/Unity.app/Contents/MacOS/Unity".format( @@ -189,9 +174,7 @@ def _unity_path(): # ) # ) elif "win" in sys.platform: - unity_hub_path = "C:/PROGRA~1/Unity/Hub/Editor/{}/Editor/Unity.exe".format( - unity_version - ) + unity_hub_path = "C:/PROGRA~1/Unity/Hub/Editor/{}/Editor/Unity.exe".format(unity_version) # TODO: Verify windows unity standalone path standalone_path = "C:/PROGRA~1/{}/Editor/Unity.exe".format(unity_version) elif sys.platform.startswith("linux"): @@ -248,9 +231,7 @@ def _build( elapsed = time.time() - start if elapsed > timeout: - logger.error( - f"Timeout occurred when running command:\n{command}\nKilling the process." - ) + logger.error(f"Timeout occurred when running command:\n{command}\nKilling the process.") os.kill(process.pid, signal.SIGKILL) os.waitpid(-1, os.WNOHANG) return False @@ -316,9 +297,7 @@ def class_dataset_images_for_scene(scene_name): for o in event.metadata["objects"]: if o["receptacle"] and o["receptacleObjectIds"] and o["openable"]: print("opening %s" % o["objectId"]) - env.step( - dict(action="OpenObject", objectId=o["objectId"], forceAction=True) - ) + env.step(dict(action="OpenObject", objectId=o["objectId"], forceAction=True)) event = env.step(dict(action="GetReachablePositions", gridSize=0.25)) @@ -337,9 +316,7 @@ def class_dataset_images_for_scene(scene_name): ) ) exclude_colors.update( - set( - map(tuple, np.unique(event.instance_segmentation_frame[-1], axis=0)) - ) + set(map(tuple, np.unique(event.instance_segmentation_frame[-1], axis=0))) ) exclude_colors.update( set( @@ -416,9 +393,7 @@ def class_dataset_images_for_scene(scene_name): for o in event.metadata["objects"]: if o["receptacle"] and o["receptacleObjectIds"] and o["openable"]: print("opening %s" % o["objectId"]) - env.step( - dict(action="OpenObject", objectId=o["objectId"], forceAction=True) - ) + env.step(dict(action="OpenObject", objectId=o["objectId"], forceAction=True)) for vol in visible_object_locations: point = vol["point"] @@ -462,9 +437,7 @@ def class_dataset_images_for_scene(scene_name): # print("start x %s start_y %s end_x %s end y %s" % (start_x, start_y, end_x, end_y)) print("storing %s " % object_id) img = event.cv2img[start_y:end_y, start_x:end_x, :] - dst = cv2.resize( - img, (target_size, target_size), interpolation=cv2.INTER_LANCZOS4 - ) + dst = cv2.resize(img, (target_size, target_size), interpolation=cv2.INTER_LANCZOS4) object_type = object_id.split("|")[0].lower() target_dir = os.path.join("images", scene_name, object_type) @@ -513,14 +486,14 @@ def local_build_test(context, prefix="local", arch="OSXIntel64"): @task(iterable=["scenes"]) -def local_build( - context, prefix="local", arch="OSXIntel64", scenes=None, scripts_only=False -): +def local_build(context, prefix="local", arch="OSXIntel64", scenes=None, scripts_only=False): import ai2thor.controller build = ai2thor.build.Build(arch, prefix, False) env = dict() - if os.path.isdir("unity/Assets/Private/Scenes") or os.path.isdir("Assets/Resources/ai2thor-objaverse/NoveltyTHOR_Assets/Scenes"): + if os.path.isdir("unity/Assets/Private/Scenes") or os.path.isdir( + "Assets/Resources/ai2thor-objaverse/NoveltyTHOR_Assets/Scenes" + ): env["INCLUDE_PRIVATE_SCENES"] = "true" build_dir = os.path.join("builds", build.name) @@ -528,9 +501,7 @@ def local_build( env["BUILD_SCRIPTS_ONLY"] = "true" if scenes: - env["BUILD_SCENES"] = ",".join( - map(ai2thor.controller.Controller.normalize_scene, scenes) - ) + env["BUILD_SCENES"] = ",".join(map(ai2thor.controller.Controller.normalize_scene, scenes)) if _build("unity", arch, build_dir, build.name, env=env): print("Build Successful") @@ -672,9 +643,7 @@ class YamlUnity3dTag(yaml.SafeLoader): def let_through(self, node): return self.construct_mapping(node) - YamlUnity3dTag.add_constructor( - "tag:unity3d.com,2011:47", YamlUnity3dTag.let_through - ) + YamlUnity3dTag.add_constructor("tag:unity3d.com,2011:47", YamlUnity3dTag.let_through) qs = yaml.load( open("unity/ProjectSettings/QualitySettings.asset").read(), @@ -695,20 +664,14 @@ def let_through(self, node): def git_commit_comment(): - comment = ( - subprocess.check_output("git log -n 1 --format=%B", shell=True) - .decode("utf8") - .strip() - ) + comment = subprocess.check_output("git log -n 1 --format=%B", shell=True).decode("utf8").strip() return comment def git_commit_id(): commit_id = ( - subprocess.check_output("git log -n 1 --format=%H", shell=True) - .decode("ascii") - .strip() + subprocess.check_output("git log -n 1 --format=%H", shell=True).decode("ascii").strip() ) return commit_id @@ -732,9 +695,9 @@ def push_pip_commit(context): pip_name = os.path.basename(g) logger.info("pushing pip file %s" % g) with open(g, "rb") as f: - s3.Object( - ai2thor.build.PYPI_S3_BUCKET, os.path.join("ai2thor", pip_name) - ).put(Body=f, ACL=acl) + s3.Object(ai2thor.build.PYPI_S3_BUCKET, os.path.join("ai2thor", pip_name)).put( + Body=f, ACL=acl + ) @task @@ -810,11 +773,7 @@ def build_pip(context, version): if ( (next_maj == current_maj + 1) or (next_maj == current_maj and next_min == current_min + 1) - or ( - next_maj == current_maj - and next_min == current_min - and next_sub >= current_sub + 1 - ) + or (next_maj == current_maj and next_min == current_min and next_sub >= current_sub + 1) ): if os.path.isdir("dist"): shutil.rmtree("dist") @@ -831,9 +790,7 @@ def build_pip(context, version): fi.write("__version__ = '%s'\n" % (version)) subprocess.check_call("python setup.py clean --all", shell=True) - subprocess.check_call( - "python setup.py sdist bdist_wheel --universal", shell=True - ) + subprocess.check_call("python setup.py sdist bdist_wheel --universal", shell=True) else: raise Exception( @@ -873,9 +830,7 @@ def build_log_push(build_info, include_private_scenes): bucket = ai2thor.build.PRIVATE_S3_BUCKET acl = "private" - s3.Object(bucket, build_log_key).put( - Body=build_log, ACL=acl, ContentType="text/plain" - ) + s3.Object(bucket, build_log_key).put(Body=build_log, ACL=acl, ContentType="text/plain") def archive_push(unity_path, build_path, build_dir, build_info, include_private_scenes): @@ -966,13 +921,9 @@ def link_build_cache(root_dir, arch, branch): # -c uses MacOS clonefile if sys.platform.startswith("darwin"): - subprocess.check_call( - "cp -a -c %s %s" % (main_cache_dir, branch_cache_dir), shell=True - ) + subprocess.check_call("cp -a -c %s %s" % (main_cache_dir, branch_cache_dir), shell=True) else: - subprocess.check_call( - "cp -a %s %s" % (main_cache_dir, branch_cache_dir), shell=True - ) + subprocess.check_call("cp -a %s %s" % (main_cache_dir, branch_cache_dir), shell=True) logger.info("copying main cache complete for %s" % encoded_branch) branch_library_cache_dir = os.path.join(branch_cache_dir, "Library") @@ -1073,9 +1024,7 @@ def ci_merge_push_pytest_results(context, commit_id): s3_obj.bucket_name, s3_obj.key, ) - logger.info( - "ci_merge_push_pytest_results pytest before url check code change logging works" - ) + logger.info("ci_merge_push_pytest_results pytest before url check code change logging works") logger.info("pytest url %s" % s3_pytest_url) logger.info("s3 obj is valid: {}".format(s3_obj)) @@ -1104,9 +1053,7 @@ def ci_pytest(branch, commit_id): start_time = time.time() - proc = subprocess.run( - "pytest", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE - ) + proc = subprocess.run("pytest", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = dict( success=proc.returncode == 0, @@ -1121,16 +1068,17 @@ def ci_pytest(branch, commit_id): f"finished pytest for {branch} {commit_id} in {time.time() - start_time:.2f} seconds" ) -# Type hints break build server's invoke version + +# Type hints break build server's invoke version @task def ci_build( context, - commit_id = None, # Optional[str] - branch = None, # Optional[str] - skip_pip = False, # bool - novelty_thor_scenes = False, - skip_delete_tmp_dir = False, # bool - cloudrendering_first = False + commit_id=None, # Optional[str] + branch=None, # Optional[str] + skip_pip=False, # bool + novelty_thor_scenes=False, + skip_delete_tmp_dir=False, # bool + cloudrendering_first=False, ): assert (commit_id is None) == ( branch is None @@ -1146,12 +1094,11 @@ def ci_build( if is_travis_build: # a deploy key is used on the build server and an .ssh/config entry has been added # to point to the deploy key caclled ai2thor-private-github - private_url = "git@ai2thor-private-github:allenai/ai2thor-private.git" + private_url = "git@ai2thor-private-github:allenai/ai2thor-private.git" novelty_thor_url = "git@ai2thor-objaverse-github:allenai/ai2thor-objaverse.git" else: private_url = "https://github.com/allenai/ai2thor-private" - novelty_thor_url ="https://github.com/allenai/ai2thor-objaverse" - + novelty_thor_url = "https://github.com/allenai/ai2thor-objaverse" private_repos = [ scripts.update_private.Repo( @@ -1169,17 +1116,17 @@ def ci_build( if novelty_thor_scenes: logger.info("Including a NoveltyThor scenes and making it a private build") - private_repos.append( - novelty_thor_repo - ) + private_repos.append(novelty_thor_repo) else: # Needs to be here so we overwrite any existing NoveltyTHOR repo private_repos.append( scripts.update_private.Repo( url=novelty_thor_url, - target_dir=os.path.join(base_dir, "unity", "Assets", "Resources", "ai2thor-objaverse"), + target_dir=os.path.join( + base_dir, "unity", "Assets", "Resources", "ai2thor-objaverse" + ), delete_before_checkout=is_travis_build, - commit_id="066485f29d7021ac732bed57758dea4b9d481c40", # Initial commit, empty repo. + commit_id="066485f29d7021ac732bed57758dea4b9d481c40", # Initial commit, empty repo. ) ) @@ -1196,13 +1143,11 @@ def ci_build( "tag": None, "id": None, } - + novelty_thor_add_branches = ["new_cam_adjust"] if is_travis_build and build and build["branch"] in novelty_thor_add_branches: novelty_thor_scenes = True - private_repos.append( - novelty_thor_repo - ) + private_repos.append(novelty_thor_repo) skip_branches = ["vids", "video", "erick/cloudrendering", "it_vr"] if build and build["branch"] not in skip_branches: @@ -1211,17 +1156,13 @@ def ci_build( logger.info(f"pending build for {build['branch']} {build['commit_id']}") clean(private_repos=private_repos) subprocess.check_call("git fetch", shell=True) - subprocess.check_call( - "git checkout %s --" % build["branch"], shell=True - ) + subprocess.check_call("git checkout %s --" % build["branch"], shell=True) logger.info(f" After checkout") - subprocess.check_call( - "git checkout -qf %s" % build["commit_id"], shell=True - ) + subprocess.check_call("git checkout -qf %s" % build["commit_id"], shell=True) private_scene_options = [novelty_thor_scenes] - build_archs = ["OSXIntel64"] #, "Linux64"] + build_archs = ["OSXIntel64"] # , "Linux64"] # CloudRendering only supported with 2020.3.25 # should change this in the future to automatically install @@ -1235,9 +1176,7 @@ def ci_build( has_any_build_failed = False for include_private_scenes in private_scene_options: for arch in build_archs: - logger.info( - f"processing {arch} {build['branch']} {build['commit_id']}" - ) + logger.info(f"processing {arch} {build['branch']} {build['commit_id']}") temp_dir = arch_temp_dirs[arch] = os.path.join( os.environ["HOME"], "tmp/unity-%s-%s-%s-%s" @@ -1264,24 +1203,20 @@ def ci_build( releases_dir=rdir, ) if commit_build.exists(): - logger.info( - f"found build for commit {build['commit_id']} {arch}" - ) + logger.info(f"found build for commit {build['commit_id']} {arch}") # download the build so that we can run the tests if sys.platform.startswith("darwin"): if arch == "OSXIntel64": commit_build.download() else: - + if arch in ["CloudRendering", "OSXIntel64"]: # In Linux the OSX build cache is used for Unity Tests as cloud rendering fails commit_build.download() else: # this is done here so that when a tag build request arrives and the commit_id has already # been built, we avoid bootstrapping the cache since we short circuited on the line above - link_build_cache( - root_dir=temp_dir, arch=arch, branch=build["branch"] - ) + link_build_cache(root_dir=temp_dir, arch=arch, branch=build["branch"]) build_success = ci_build_arch( root_dir=temp_dir, @@ -1289,13 +1224,11 @@ def ci_build( commit_id=build["commit_id"], include_private_scenes=include_private_scenes, immediately_fail_and_push_log=has_any_build_failed, - timeout=60 * 60 + timeout=60 * 60, # Don't bother trying another build if one has already failed ) - has_any_build_failed = ( - has_any_build_failed or not build_success - ) + has_any_build_failed = has_any_build_failed or not build_success if build_success: logger.info( f"Build success detected for {arch} {build['commit_id']}" @@ -1307,9 +1240,7 @@ def ci_build( # the project and we can run the unit tests # waiting for all builds to complete before starting tests for arch in build_archs: - lock_file_path = os.path.join( - arch_temp_dirs[arch], "unity/Temp/UnityLockfile" - ) + lock_file_path = os.path.join(arch_temp_dirs[arch], "unity/Temp/UnityLockfile") if os.path.isfile(lock_file_path): logger.info(f"attempting to lock {lock_file_path}") lock_file = os.open(lock_file_path, os.O_RDWR) @@ -1324,8 +1255,10 @@ def ci_build( if build["tag"] is None: # its possible that the cache doesn't get linked if the builds # succeeded during an earlier run - - pytest_platform = "OSXIntel64" if sys.platform.startswith("darwin") else "CloudRendering" + + pytest_platform = ( + "OSXIntel64" if sys.platform.startswith("darwin") else "CloudRendering" + ) # Weirdly even in Linux you can run utf tests using OSX build cache, but not CloudRendering utf_test_platform = "OSXIntel64" @@ -1339,7 +1272,9 @@ def ci_build( os.path.join(arch_temp_dirs[pytest_platform], "unity/builds"), "unity/builds", ) - print(f"Symlink from `unity/builds` to `{os.path.join(arch_temp_dirs[pytest_platform], 'unity/builds')}`") + print( + f"Symlink from `unity/builds` to `{os.path.join(arch_temp_dirs[pytest_platform], 'unity/builds')}`" + ) os.makedirs("tmp", exist_ok=True) # using threading here instead of multiprocessing since we must use the start_method of spawn, which # causes the tasks.py to get reloaded, which may be different on a branch from main @@ -1370,8 +1305,7 @@ def ci_build( for p in procs: if p: logger.info( - "joining proc %s for %s %s" - % (p, build["branch"], build["commit_id"]) + "joining proc %s for %s %s" % (p, build["branch"], build["commit_id"]) ) p.join() @@ -1391,17 +1325,13 @@ def ci_build( if is_travis_build: for i in range(12): b = travis_build(build["id"]) - logger.info( - "build state for %s: %s" % (build["id"], b["state"]) - ) + logger.info("build state for %s: %s" % (build["id"], b["state"])) if b["state"] != "started": break time.sleep(10) - logger.info( - "build complete %s %s" % (build["branch"], build["commit_id"]) - ) + logger.info("build complete %s %s" % (build["branch"], build["commit_id"])) fcntl.flock(lock_f, fcntl.LOCK_UN) @@ -1428,13 +1358,9 @@ def install_cloudrendering_engine(context, force=False): if os.path.isdir(full_dir): if force: shutil.rmtree(full_dir) - logger.info( - "CloudRendering engine already installed - removing due to force" - ) + logger.info("CloudRendering engine already installed - removing due to force") else: - logger.info( - "skipping installation - CloudRendering engine already installed" - ) + logger.info("skipping installation - CloudRendering engine already installed") return print("packages/CloudRendering-%s.zip" % _unity_version()) @@ -1457,9 +1383,7 @@ def ci_build_webgl(context, commit_id): arch = "WebGL" set_gi_cache_folder(arch) link_build_cache(os.getcwd(), arch, branch) - webgl_build_deploy_demo( - context, verbose=True, content_addressable=False, force=True - ) + webgl_build_deploy_demo(context, verbose=True, content_addressable=False, force=True) logger.info("finished webgl build deploy %s %s" % (branch, commit_id)) update_webgl_autodeploy_commit_id(commit_id) @@ -1563,9 +1487,7 @@ def poll_ci_build(context): start_datetime = datetime.datetime.utcnow() hours_before_timeout = 2 - print( - f"WAITING FOR BUILDS TO COMPLETE ({hours_before_timeout} hours before timeout)" - ) + print(f"WAITING FOR BUILDS TO COMPLETE ({hours_before_timeout} hours before timeout)") start_time = time.time() last_emit_time = 0 for i in range(360 * hours_before_timeout): @@ -1617,9 +1539,7 @@ def poll_ci_build(context): f"\nBuild DOES NOT exist for arch {plat}, expected log url: {commit_build.log_url}" ) else: - print( - f"\nBuild DOES exist for arch {plat}, log url: {commit_build.log_url}" - ) + print(f"\nBuild DOES exist for arch {plat}, log url: {commit_build.log_url}") if any_failures: print(f"\nERROR: BUILD FAILURES DETECTED") @@ -1677,9 +1597,7 @@ def build(context, local=False): if include_private_scenes: env["INCLUDE_PRIVATE_SCENES"] = "true" unity_path = "unity" - build_name = ai2thor.build.build_name( - plat.name(), version, include_private_scenes - ) + build_name = ai2thor.build.build_name(plat.name(), version, include_private_scenes) build_dir = os.path.join("builds", build_name) build_path = build_dir + ".zip" build_info = builds[plat.name()] = {} @@ -1834,9 +1752,7 @@ def get_depth( save_image_per_frame=True, ) else: - env = ai2thor.controller.Controller( - width=600, height=600, local_build=local_build - ) + env = ai2thor.controller.Controller(width=600, height=600, local_build=local_build) if scene is not None: env.reset(scene) @@ -1858,9 +1774,7 @@ def get_depth( from ai2thor.interact import InteractiveControllerPrompt if scene is not None: - teleport_arg = dict( - action="TeleportFull", y=0.9010001, rotation=dict(x=0, y=rotation, z=0) - ) + teleport_arg = dict(action="TeleportFull", y=0.9010001, rotation=dict(x=0, y=rotation, z=0)) if teleport is not None: teleport = [float(pos) for pos in teleport.split(",")] @@ -1916,9 +1830,7 @@ def get_depth( @task -def inspect_depth( - ctx, directory, all=False, indices=None, jet=False, under_score=False -): +def inspect_depth(ctx, directory, all=False, indices=None, jet=False, under_score=False): import numpy as np import cv2 import glob @@ -1960,15 +1872,11 @@ def sort_key_function(name): mn = np.min(raw_depth) mx = np.max(raw_depth) print("min depth value: {}, max depth: {}".format(mn, mx)) - norm = (((raw_depth - mn).astype(np.float32) / (mx - mn)) * 255.0).astype( - np.uint8 - ) + norm = (((raw_depth - mn).astype(np.float32) / (mx - mn)) * 255.0).astype(np.uint8) img = cv2.applyColorMap(norm, cv2.COLORMAP_JET) else: - grayscale = ( - 255.0 / raw_depth.max() * (raw_depth - raw_depth.min()) - ).astype(np.uint8) + grayscale = (255.0 / raw_depth.max() * (raw_depth - raw_depth.min())).astype(np.uint8) print("max {} min {}".format(raw_depth.max(), raw_depth.min())) img = grayscale @@ -1987,9 +1895,7 @@ def inspect_pixel(event, x, y, flags, param): @task -def real_2_sim( - ctx, source_dir, index, scene, output_dir, rotation=0, local_build=False, jet=False -): +def real_2_sim(ctx, source_dir, index, scene, output_dir, rotation=0, local_build=False, jet=False): import cv2 from ai2thor.util.transforms import transform_real_2_sim @@ -2077,9 +1983,7 @@ def imshow_components(labels): indices_top_left = np.where(labels == labels[0][0]) indices_top_right = np.where(labels == labels[0][img_size[1] - 1]) indices_bottom_left = np.where(labels == labels[img_size[0] - 1][0]) - indices_bottom_right = np.where( - labels == labels[img_size[0] - 1][img_size[1] - 1] - ) + indices_bottom_right = np.where(labels == labels[img_size[0] - 1][img_size[1] - 1]) indices = [ indices_top_left, @@ -2156,10 +2060,7 @@ def check_visible_objects_closed_receptacles(ctx, start_scene, end_scene): ) ) - if ( - visibility_object_id is None - and obj["objectType"] in visibility_object_types - ): + if visibility_object_id is None and obj["objectType"] in visibility_object_types: visibility_object_id = obj["objectId"] if visibility_object_id is None: @@ -2189,9 +2090,7 @@ def check_visible_objects_closed_receptacles(ctx, start_scene, end_scene): ) ) - replace_success = controller.last_event.metadata[ - "lastActionSuccess" - ] + replace_success = controller.last_event.metadata["lastActionSuccess"] if replace_success: if ( @@ -2219,9 +2118,7 @@ def list_objects_with_metadata(bucket): continuation_token = None while True: if continuation_token: - objects = s3c.list_objects_v2( - Bucket=bucket, ContinuationToken=continuation_token - ) + objects = s3c.list_objects_v2(Bucket=bucket, ContinuationToken=continuation_token) else: objects = s3c.list_objects_v2(Bucket=bucket) @@ -2292,11 +2189,7 @@ def upload_file(f_path, key): if ext in content_encoding: kwargs["ContentEncoding"] = content_encoding[ext] - if ( - not force - and key in current_objects - and etag == current_objects[key]["ETag"] - ): + if not force and key in current_objects and etag == current_objects[key]["ETag"]: if verbose: print("ETag match - skipping %s" % key) return @@ -2372,9 +2265,7 @@ def webgl_build_deploy_demo(ctx, verbose=False, force=False, content_addressable content_addressable=content_addressable, ) - webgl_deploy( - ctx, source_dir="builds/demo", target_dir="demo", verbose=verbose, force=force - ) + webgl_deploy(ctx, source_dir="builds/demo", target_dir="demo", verbose=verbose, force=force) if verbose: print("Deployed selected scenes to bucket's 'demo' directory") @@ -2384,13 +2275,9 @@ def webgl_build_deploy_demo(ctx, verbose=False, force=False, content_addressable living_rooms = [f"FloorPlan{200 + i}_physics" for i in range(1, 31)] bedrooms = [f"FloorPlan{300 + i}_physics" for i in range(1, 31)] bathrooms = [f"FloorPlan{400 + i}_physics" for i in range(1, 31)] - robothor_train = [ - f"FloorPlan_Train{i}_{j}" for i in range(1, 13) for j in range(1, 6) - ] + robothor_train = [f"FloorPlan_Train{i}_{j}" for i in range(1, 13) for j in range(1, 6)] robothor_val = [f"FloorPlan_Val{i}_{j}" for i in range(1, 4) for j in range(1, 6)] - scenes = ( - kitchens + living_rooms + bedrooms + bathrooms + robothor_train + robothor_val - ) + scenes = kitchens + living_rooms + bedrooms + bathrooms + robothor_train + robothor_val webgl_build( ctx, @@ -2446,9 +2333,7 @@ def webgl_deploy_all(ctx, verbose=False, individual_rooms=False): build_dir = "builds/{}".format(target_s3_dir) webgl_build(ctx, scenes=floorPlanName, directory=build_dir) - webgl_deploy( - ctx, source_dir=build_dir, target_dir=target_s3_dir, verbose=verbose - ) + webgl_deploy(ctx, source_dir=build_dir, target_dir=target_s3_dir, verbose=verbose) else: webgl_build(ctx, room_ranges=range_str, directory=build_dir) @@ -2480,10 +2365,7 @@ def webgl_s3_deploy( if all: flatten = lambda l: [item for sublist in l for item in sublist] room_numbers = flatten( - [ - [i for i in range(room_range[0], room_range[1])] - for key, room_range in rooms.items() - ] + [[i for i in range(room_range[0], room_range[1])] for key, room_range in rooms.items()] ) else: room_numbers = [s.strip() for s in scenes.split(",")] @@ -2498,9 +2380,7 @@ def webgl_s3_deploy( target_s3_dir = "{}/{}".format(target_dir, floor_plan_name) build_dir = "builds/{}".format(target_s3_dir) - webgl_build( - ctx, scenes=floor_plan_name, directory=build_dir, crowdsource_build=True - ) + webgl_build(ctx, scenes=floor_plan_name, directory=build_dir, crowdsource_build=True) if verbose: print("Deploying room '{}'...".format(floor_plan_name)) if not deploy_skip: @@ -2534,9 +2414,7 @@ def webgl_site_deploy( shutil.rmtree(output_dir) # os.mkdir(output_dir) - ignore_func = lambda d, files: [ - f for f in files if isfile(join(d, f)) and f.endswith(".meta") - ] + ignore_func = lambda d, files: [f for f in files if isfile(join(d, f)) and f.endswith(".meta")] if unity_build_dir != "": shutil.copytree(unity_build_dir, output_dir, ignore=ignore_func) @@ -2563,9 +2441,7 @@ def mock_client_request(context): import requests import cv2 - r = requests.post( - "http://127.0.0.1:9200/step", json=dict(action="MoveAhead", sequenceId=1) - ) + r = requests.post("http://127.0.0.1:9200/step", json=dict(action="MoveAhead", sequenceId=1)) payload = msgpack.unpackb(r.content, raw=False) metadata = payload["metadata"]["agents"][0] image = np.frombuffer(payload["frames"][0], dtype=np.uint8).reshape( @@ -2681,9 +2557,7 @@ def get_points(contoller, object_type, scene): print("Getting points in scene: '{}'...: ".format(scene)) controller.reset(scene) event = controller.step( - dict( - action="ObjectTypeToObjectIds", objectType=object_type.replace(" ", "") - ) + dict(action="ObjectTypeToObjectIds", objectType=object_type.replace(" ", "")) ) object_ids = event.metadata["actionReturn"] @@ -2694,13 +2568,11 @@ def get_points(contoller, object_type, scene): objects_types_in_scene.add(object_type) object_id = object_ids[0] - event_reachable = controller.step( - dict(action="GetReachablePositions", gridSize=0.25) - ) + event_reachable = controller.step(dict(action="GetReachablePositions", gridSize=0.25)) - target_position = controller.step( - action="GetObjectPosition", objectId=object_id - ).metadata["actionReturn"] + target_position = controller.step(action="GetObjectPosition", objectId=object_id).metadata[ + "actionReturn" + ] reachable_positions = event_reachable.metadata["actionReturn"] @@ -2721,8 +2593,7 @@ def filter_points(selected_points, point_set, minimum_distance): [ p for p in point_set - if sqr_dist(p, selected) - <= minimum_distance * minimum_distance + if sqr_dist(p, selected) <= minimum_distance * minimum_distance ] ) point_set = point_set.difference(remove_set) @@ -2849,8 +2720,7 @@ def key_sort_func(scene_name): objects = [] for objectType in targets: if filter_file is None or ( - objectType in scene_object_filter - and scene in scene_object_filter[objectType] + objectType in scene_object_filter and scene in scene_object_filter[objectType] ): dataset[scene][objectType] = [] obj = get_points(controller, objectType, scene) @@ -2859,9 +2729,7 @@ def key_sort_func(scene_name): dataset_flat = dataset_flat + objects if intermediate_directory != ".": - with open( - os.path.join(intermediate_directory, "{}.json".format(scene)), "w" - ) as f: + with open(os.path.join(intermediate_directory, "{}.json".format(scene)), "w") as f: json.dump(objects, f, indent=4) with open(os.path.join(intermediate_directory, output), "w") as f: @@ -2912,9 +2780,7 @@ def shortest_path_to_object( agentMode="bot", visibilityDistance=visibility_distance, ) - path = metrics.get_shortest_path_to_object_type( - controller, object, p, {"x": 0, "y": 0, "z": 0} - ) + path = metrics.get_shortest_path_to_object_type(controller, object, p, {"x": 0, "y": 0, "z": 0}) minimum_path_length = metrics.path_distance(path) print("Path: {}".format(path)) @@ -3001,9 +2867,7 @@ def filter_dataset(ctx, filename, output_filename, ids=False): @task -def fix_dataset_object_types( - ctx, input_file, output_file, editor_mode=False, local_build=False -): +def fix_dataset_object_types(ctx, input_file, output_file, editor_mode=False, local_build=False): import ai2thor.controller with open(input_file, "r") as f: @@ -3049,9 +2913,7 @@ def fix_dataset_object_types( @task -def test_dataset( - ctx, filename, scenes=None, objects=None, editor_mode=False, local_build=False -): +def test_dataset(ctx, filename, scenes=None, objects=None, editor_mode=False, local_build=False): import ai2thor.controller import ai2thor.util.metrics as metrics @@ -3081,9 +2943,7 @@ def test_dataset( if objects is not None: object_set = set(objects.split(",")) print("Filtering {}".format(object_set)) - filtered_dataset = [ - d for d in filtered_dataset if d["object_type"] in object_set - ] + filtered_dataset = [d for d in filtered_dataset if d["object_type"] in object_set] current_scene = None current_object = None point_counter = 0 @@ -3171,9 +3031,7 @@ def visualize_shortest_paths( dataset_filtered = [d for d in dataset if d["scene"] in scene_f_set] if object_types is not None: object_f_set = set(object_types.split(",")) - dataset_filtered = [ - d for d in dataset_filtered if d["object_type"] in object_f_set - ] + dataset_filtered = [d for d in dataset_filtered if d["object_type"] in object_f_set] print("Running for {} points...".format(len(dataset_filtered))) index = 0 @@ -3187,8 +3045,7 @@ def visualize_shortest_paths( previous_index = index controller.reset(current_scene) while ( - current_scene == datapoint["scene"] - and current_object == datapoint["object_type"] + current_scene == datapoint["scene"] and current_object == datapoint["object_type"] ): index += 1 if index > len(dataset_filtered) - 1: @@ -3202,9 +3059,7 @@ def visualize_shortest_paths( failed[key] = [] - print( - "Points for '{}' in scene '{}'...".format(current_object, current_scene) - ) + print("Points for '{}' in scene '{}'...".format(current_object, current_scene)) evt = controller.step( action="AddThirdPartyCamera", rotation=dict(x=90, y=0, z=0), @@ -3215,9 +3070,7 @@ def visualize_shortest_paths( sc = dataset_filtered[previous_index]["scene"] obj_type = dataset_filtered[previous_index]["object_type"] - positions = [ - d["initial_position"] for d in dataset_filtered[previous_index:index] - ] + positions = [d["initial_position"] for d in dataset_filtered[previous_index:index]] # print("{} : {} : {}".format(sc, obj_type, positions)) evt = controller.step( action="VisualizeShortestPaths", @@ -3316,9 +3169,7 @@ def key_sort_func(scene_name): for datapoint in filter_dataset: missing_datapoints_by_scene[datapoint["scene"]].append(datapoint) - partial_dataset_filenames = sorted( - glob.glob("{}/FloorPlan_*.png".format(dataset_dir)) - ) + partial_dataset_filenames = sorted(glob.glob("{}/FloorPlan_*.png".format(dataset_dir))) print("Datas") difficulty_order_map = {"easy": 0, "medium": 1, "hard": 2} @@ -3331,12 +3182,8 @@ def key_sort_func(scene_name): final_dataset = [] for scene in scenes: for object_type in targets: - arr = [ - p for p in partial_dataset[scene] if p["object_type"] == object_type - ] + [ - p - for p in missing_datapoints_by_scene[scene] - if p["object_type"] == object_type + arr = [p for p in partial_dataset[scene] if p["object_type"] == object_type] + [ + p for p in missing_datapoints_by_scene[scene] if p["object_type"] == object_type ] final_dataset = final_dataset + sorted( arr, @@ -3398,10 +3245,7 @@ def resort_dataset(ctx, dataset_path, output_path, editor_mode=False, local_buil new_dataset = [] while index < len(dataset): previous_index = index - while ( - current_scene == datapoint["scene"] - and current_object == datapoint["object_type"] - ): + while current_scene == datapoint["scene"] and current_object == datapoint["object_type"]: index += 1 if index > len(dataset) - 1: break @@ -3559,9 +3403,7 @@ def reachable_pos(ctx, scene, editor_mode=False, local_build=False): @task -def get_physics_determinism( - ctx, scene="FloorPlan1_physics", agent_mode="arm", n=100, samples=100 -): +def get_physics_determinism(ctx, scene="FloorPlan1_physics", agent_mode="arm", n=100, samples=100): import ai2thor.controller import random @@ -3608,11 +3450,7 @@ def act(controller, actions, n): controller, num_trials, ObjectPositionVarianceAverage() ): act(controller, actions, n) - print( - " actions: '{}', object_position_variance_average: {} ".format( - action_name, metric - ) - ) + print(" actions: '{}', object_position_variance_average: {} ".format(action_name, metric)) @task @@ -3651,8 +3489,7 @@ def generate_pypi_index(context): def ci_test_utf(branch, commit_id, base_dir): logger.info( - "running Unity Test framework testRunner for %s %s %s" - % (branch, commit_id, base_dir) + "running Unity Test framework testRunner for %s %s %s" % (branch, commit_id, base_dir) ) results_path, results_logfile = test_utf(base_dir) @@ -3722,13 +3559,21 @@ def format_cs(context): # Now run dotnet-format as it allows more configuration options (e.g. curly brace with no new line). # The following message will get emitted, this can safely be ignored # "Warnings were encountered while loading the workspace. Set the verbosity option to the 'diagnostic' level to log warnings" - + print(f"\nRunning dotnet-format on {proj}") subprocess.check_call( f".dotnet/dotnet tool run dotnet-format {proj} -w -s --verbosity diagnostic", shell=True, ) + # For some reason if you don't run this twice because of using csharpier some files + # remain with formating errors i.e. DebugInputField.cs (with whitespace changes) + print(f"\nRunning dotnet-format again on {proj}") + subprocess.check_call( + f".dotnet/dotnet tool run dotnet-format {proj} -w -s --verbosity diagnostic", + shell=True, + ) + @task def install_dotnet_tool(context, tool: str, force=False): @@ -3790,18 +3635,14 @@ def format_py(context): @task -def install_unity_hub( - context, target_dir=os.path.join(os.path.expanduser("~"), "local/bin") -): +def install_unity_hub(context, target_dir=os.path.join(os.path.expanduser("~"), "local/bin")): import stat import requests if not sys.platform.startswith("linux"): raise Exception("Installation only support for Linux") - res = requests.get( - "https://public-cdn.cloud.unity3d.com/hub/prod/UnityHub.AppImage" - ) + res = requests.get("https://public-cdn.cloud.unity3d.com/hub/prod/UnityHub.AppImage") res.raise_for_status() os.makedirs(target_dir, exist_ok=True) @@ -3829,9 +3670,7 @@ def install_unity_editor(context, version=None, changeset=None): unity_hub_path = None if sys.platform.startswith("linux"): - unity_hub_path = os.path.join( - os.path.expanduser("~"), "local/bin/UnityHub.AppImage" - ) + unity_hub_path = os.path.join(os.path.expanduser("~"), "local/bin/UnityHub.AppImage") elif sys.platform.startswith("darwin"): unity_hub_path = "/Applications/Unity\ Hub.app/Contents/MacOS/Unity\ Hub --" else: @@ -3871,24 +3710,17 @@ def generate_unity_alf(context): # with manual activation https://docs.unity3d.com/Manual/ManualActivationGuide.html alf_path = "Unity_v%s.alf" % _unity_version() - subprocess.run( - "%s -batchmode -createManualActivationFile" % _unity_path(), shell=True - ) + subprocess.run("%s -batchmode -createManualActivationFile" % _unity_path(), shell=True) assert os.path.isfile(alf_path), "ALF not found at %s" % alf_path - print( - "ALF created at %s. Activate license at: https://license.unity3d.com/manual" - % alf_path - ) + print("ALF created at %s. Activate license at: https://license.unity3d.com/manual" % alf_path) @task def activate_unity_license(context, ulf_path): assert os.path.isfile(ulf_path), "License file '%s' not found" % ulf_path - subprocess.run( - '%s -batchmode -manualLicenseFile "%s"' % (_unity_path(), ulf_path), shell=True - ) + subprocess.run('%s -batchmode -manualLicenseFile "%s"' % (_unity_path(), ulf_path), shell=True) def test_utf(base_dir=None): @@ -3968,9 +3800,7 @@ def test_{methodname}(self): test_record_data = " pass" if test_records: test_record_data = "\n".join(test_records) - encoded_class_name = re.sub( - r"[^a-zA-Z0-9_]", "_", re.sub("_", "__", class_name) - ) + encoded_class_name = re.sub(r"[^a-zA-Z0-9_]", "_", re.sub("_", "__", class_name)) class_data.append( f""" class {encoded_class_name}: @@ -4173,9 +4003,7 @@ def test_render(ctx, editor_mode=False, local_build=False): if img is not None: print(f"img r {img[0][0][0]} g {img[0][0][1]} b {img[0][0][2]}") - print( - f"evt frame r {evt.cv2img[0][0][0]} g {evt.cv2img[0][0][1]} b {evt.cv2img[0][0][2]}" - ) + print(f"evt frame r {evt.cv2img[0][0][0]} g {evt.cv2img[0][0][1]} b {evt.cv2img[0][0][2]}") cv2.namedWindow("image") @@ -4278,9 +4106,7 @@ def walls_to_floor_poly(walls): "empty": wall["empty"] if "empty" in wall else False, "polygon": wall_to_poly(wall), } - for (wall, wall_indx) in zip( - room["walls"], range(0, len(room["walls"])) - ) + for (wall, wall_indx) in zip(room["walls"], range(0, len(room["walls"]))) ] for (room, room_i) in zip(obj["rooms"], range(len(obj["rooms"]))) ] @@ -4461,8 +4287,7 @@ def get_benchmark_title(benchmark, default_title=""): benchmarks = [load_benchmark_filename(filename) for filename in benchmark_filenames] benchmark_titles = [ - get_benchmark_title(b, "") - for (i, b) in zip(range(0, len(benchmarks)), benchmarks) + get_benchmark_title(b, "") for (i, b) in zip(range(0, len(benchmarks)), benchmarks) ] if plot_titles is not None: @@ -4488,10 +4313,7 @@ def get_benchmark_title(benchmark, default_title=""): ) all_data = reduce( list.__add__, - [ - [(x, [y[action] for y in b]) for action in all_data[0][1][0]] - for (x, b) in all_data - ], + [[(x, [y[action] for y in b]) for action in all_data[0][1][0]] for (x, b) in all_data], ) keys = [k for (k, y) in all_data] @@ -4668,9 +4490,7 @@ def run_benchmark_from_s3_config(ctx): client = boto3.client("s3") - response = client.list_objects_v2( - Bucket=BENCHMARKING_S3_BUCKET, Prefix="benchmark_jobs/" - ) + response = client.list_objects_v2(Bucket=BENCHMARKING_S3_BUCKET, Prefix="benchmark_jobs/") s3 = boto3.resource("s3", region_name="us-west-2") benchmark_runs = [] @@ -4688,9 +4508,7 @@ def run_benchmark_from_s3_config(ctx): BENCHMARKING_S3_BUCKET, f"procedural_houses/{procedural_house}", ) - house_json = json.loads( - house_obj.get()["Body"].read().decode("utf-8") - ) + house_json = json.loads(house_obj.get()["Body"].read().decode("utf-8")) if "id" not in house_json: house_json["id"] = procedural_house.split(".")[0] procedural_houses_transformed.append(house_json) @@ -4750,9 +4568,7 @@ def run_benchmark_from_local_config( if house_from_s3: client = boto3.client("s3") - response = client.list_objects_v2( - Bucket=BENCHMARKING_S3_BUCKET, Prefix="benchmark_jobs/" - ) + response = client.list_objects_v2(Bucket=BENCHMARKING_S3_BUCKET, Prefix="benchmark_jobs/") s3 = boto3.resource("s3", region_name="us-west-2") benchmark_runs = [] key = config_path @@ -4779,9 +4595,7 @@ def run_benchmark_from_local_config( BENCHMARKING_S3_BUCKET, f"procedural_houses/{procedural_house}", ) - house_json = json.loads( - house_obj.get()["Body"].read().decode("utf-8") - ) + house_json = json.loads(house_obj.get()["Body"].read().decode("utf-8")) if "id" not in house_json: house_json["id"] = procedural_house.split(".")[0] procedural_houses_transformed.append(house_json) @@ -4796,15 +4610,12 @@ def run_benchmark_from_local_config( benchmark_run_config["init_params"]["commit_id"] = None benchmark_run_config["init_params"]["local_build"] = True del benchmark_run_config["init_params"]["platform"] - - + # benchmark_run_config['verbose'] = True action_groups = copy.deepcopy(benchmark_run_config["action_groups"]) del benchmark_run_config["action_groups"] - benchmark_runs.append( - (UnityActionBenchmarkRunner(**benchmark_run_config), action_groups) - ) + benchmark_runs.append((UnityActionBenchmarkRunner(**benchmark_run_config), action_groups)) benchmark_results = [] for benchmark_runner, action_group in benchmark_runs: benchmark_result = benchmark_runner.benchmark(action_group) @@ -4842,16 +4653,12 @@ def add_daily_benchmark_config(ctx, benchmark_config_filename): # validate(benchmark_config, schema=benchmarking_config_schema) try: logger.info(f"Pushing benchmark config '{benchmark_config_basename}'") - s3.Object( - BENCHMARKING_S3_BUCKET, f"benchmark_jobs/{benchmark_config_basename}" - ).put( + s3.Object(BENCHMARKING_S3_BUCKET, f"benchmark_jobs/{benchmark_config_basename}").put( Body=json.dumps(benchmark_config, indent=4), ContentType="application/json", ) except botocore.exceptions.ClientError as e: - logger.error( - f"Caught error uploading archive '{benchmark_config_basename}': {e}" - ) + logger.error(f"Caught error uploading archive '{benchmark_config_basename}': {e}") @task diff --git a/unity/Assets/Editor/Build.cs b/unity/Assets/Editor/Build.cs index 29c6313c23..388b3c377f 100644 --- a/unity/Assets/Editor/Build.cs +++ b/unity/Assets/Editor/Build.cs @@ -1,22 +1,32 @@ -using UnityEditor; using System; -using System.IO; -using UnityEngine; using System.Collections.Generic; +using System.IO; using System.Linq; +using UnityEditor; +using UnityEditor.Build.Reporting; using UnityEditor.Rendering; +using UnityEngine; using UnityEngine.Rendering; -using UnityEditor.Build.Reporting; - -public class Build { +public class Build +{ // Since CloudRendering uses a different version of Unity (2020.2) vs production (2019.4), GraphicsSettings and ProjectSettings - // must be copied over from the Standalone platform. As well, continuing to use this ensures that settings made for + // must be copied over from the Standalone platform. As well, continuing to use this ensures that settings made for // the Standalone platform get used for CloudRendering - static void InitializeCloudRendering() { - PlayerSettings.SetApiCompatibilityLevel(BuildTargetGroup.CloudRendering, PlayerSettings.GetApiCompatibilityLevel(BuildTargetGroup.Standalone)); - var graphicsTiers = new List(){GraphicsTier.Tier1, GraphicsTier.Tier2, GraphicsTier.Tier3}; - foreach (var graphicsTier in graphicsTiers) { + static void InitializeCloudRendering() + { + PlayerSettings.SetApiCompatibilityLevel( + BuildTargetGroup.CloudRendering, + PlayerSettings.GetApiCompatibilityLevel(BuildTargetGroup.Standalone) + ); + var graphicsTiers = new List() + { + GraphicsTier.Tier1, + GraphicsTier.Tier2, + GraphicsTier.Tier3 + }; + foreach (var graphicsTier in graphicsTiers) + { EditorGraphicsSettings.SetTierSettings( BuildTargetGroup.CloudRendering, graphicsTier, @@ -25,62 +35,87 @@ static void InitializeCloudRendering() { } } - static void OSXIntel64() { - build(GetBuildName(), BuildTargetGroup.Standalone, BuildTarget.StandaloneOSX); + static void OSXIntel64() + { + build(GetBuildName(), BuildTargetGroup.Standalone, BuildTarget.StandaloneOSX); } - static string GetBuildName() { + static string GetBuildName() + { return Environment.GetEnvironmentVariable("UNITY_BUILD_NAME"); } - static void Linux64() { + static void Linux64() + { build(GetBuildName(), BuildTargetGroup.Standalone, BuildTarget.StandaloneLinux64); } - static void CloudRendering() { + static void CloudRendering() + { InitializeCloudRendering(); build(GetBuildName(), BuildTargetGroup.CloudRendering, BuildTarget.CloudRendering); } - static void WebGL() { + static void WebGL() + { // USIM_USE_... scripting defines are required // to disable the native PNG and JPEG encoders present in the simulation capture package // if these defines are not provide the WebGL build will fail - build(GetBuildName(), BuildTargetGroup.WebGL, BuildTarget.WebGL, new string[]{"USIM_USE_BUILTIN_JPG_ENCODER", "USIM_USE_BUILTIN_PNG_ENCODER"}); + build( + GetBuildName(), + BuildTargetGroup.WebGL, + BuildTarget.WebGL, + new string[] { "USIM_USE_BUILTIN_JPG_ENCODER", "USIM_USE_BUILTIN_PNG_ENCODER" } + ); } - static void StandaloneWindows64() { + static void StandaloneWindows64() + { build(GetBuildName(), BuildTargetGroup.Standalone, BuildTarget.StandaloneWindows64); } - static void buildResourceAssetJson() { + static void buildResourceAssetJson() + { ResourceAssetManager manager = new ResourceAssetManager(); manager.BuildCatalog(); } - static void build(string buildName, BuildTargetGroup targetGroup, BuildTarget target, string[] extraScriptingDefines=null) { + static void build( + string buildName, + BuildTargetGroup targetGroup, + BuildTarget target, + string[] extraScriptingDefines = null + ) + { buildResourceAssetJson(); var defines = GetDefineSymbolsFromEnv(); - if (defines != "") { - PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, GetDefineSymbolsFromEnv()); + if (defines != "") + { + PlayerSettings.SetScriptingDefineSymbolsForGroup( + targetGroup, + GetDefineSymbolsFromEnv() + ); } List scenes = GetScenes(); - foreach (string scene in scenes) { + foreach (string scene in scenes) + { Debug.Log("Adding Scene " + scene); } - // zip + compresslevel=1 && LZ4 is faster by about 30 seconds + // zip + compresslevel=1 && LZ4 is faster by about 30 seconds // (and results in smaller .zip files) than - // zip + compresslevel=6 (default) && uncomprsesed asset bundles + // zip + compresslevel=6 (default) && uncomprsesed asset bundles BuildOptions options = BuildOptions.StrictMode | BuildOptions.CompressWithLz4; - if (ScriptsOnly()) { + if (ScriptsOnly()) + { options |= BuildOptions.Development | BuildOptions.BuildScriptsOnly; } Debug.Log("Build options " + options); BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions(); - if (extraScriptingDefines != null) { + if (extraScriptingDefines != null) + { buildPlayerOptions.extraScriptingDefines = extraScriptingDefines; } buildPlayerOptions.scenes = scenes.ToArray(); @@ -90,43 +125,58 @@ static void build(string buildName, BuildTargetGroup targetGroup, BuildTarget ta EditorUserBuildSettings.SwitchActiveBuildTarget(targetGroup, target); BuildReport report = BuildPipeline.BuildPlayer(buildPlayerOptions); BuildSummary summary = report.summary; - } - private static List GetScenes() { + private static List GetScenes() + { List envScenes = GetScenesFromEnv(); - if (envScenes.Count > 0) { + if (envScenes.Count > 0) + { return envScenes; - } else { + } + else + { return GetAllScenePaths(); } } - private static List GetAllScenePaths() { + private static List GetAllScenePaths() + { List files = new List(); List scenes = new List(); files.AddRange(Directory.GetFiles("Assets/Scenes/")); - if (IncludePrivateScenes()) { + if (IncludePrivateScenes()) + { files.AddRange(Directory.GetFiles("Assets/Private/Scenes/")); - files.AddRange(Directory.GetFiles("Assets/Resources/ai2thor-objaverse/NoveltyTHOR_Assets/Scenes")); + files.AddRange( + Directory.GetFiles("Assets/Resources/ai2thor-objaverse/NoveltyTHOR_Assets/Scenes") + ); } files.AddRange(Directory.GetFiles("Assets/Scenes/Procedural")); files.AddRange(Directory.GetFiles("Assets/Scenes/Procedural/ArchitecTHOR")); - files.AddRange(Directory.GetFiles("Assets/Standard Assets/Characters/FirstPersonCharacter/StretchCalibration/Scenes")); - - foreach (string f in files) { + files.AddRange( + Directory.GetFiles( + "Assets/Standard Assets/Characters/FirstPersonCharacter/StretchCalibration/Scenes" + ) + ); + + foreach (string f in files) + { // ignore entryway scenes in build since these are not yet complete - if (f.Contains("FloorPlan5") && !f.EndsWith("FloorPlan5_physics.unity")) { + if (f.Contains("FloorPlan5") && !f.EndsWith("FloorPlan5_physics.unity")) + { continue; } - if (f.EndsWith("_Screenshot.unity")) { + if (f.EndsWith("_Screenshot.unity")) + { continue; } - if (f.EndsWith(".unity")) { + if (f.EndsWith(".unity")) + { scenes.Add(f); } } @@ -137,34 +187,47 @@ private static List GetAllScenePaths() { return scenes; //.Where(x => x.Contains("Procedural.unity") || x.Contains("Procedural.unity")).ToList(); //.Where(x => x.Contains("FloorPlan1_") || x.Contains("Procedural")).ToList(); } - private static List GetScenesFromEnv() { - if (Environment.GetEnvironmentVariables().Contains(("BUILD_SCENES"))) { - return Environment.GetEnvironmentVariable("BUILD_SCENES").Split(',').Select( - x => "Assets/Scenes/" + x + ".unity" - ).ToList(); - } else { + private static List GetScenesFromEnv() + { + if (Environment.GetEnvironmentVariables().Contains(("BUILD_SCENES"))) + { + return Environment + .GetEnvironmentVariable("BUILD_SCENES") + .Split(',') + .Select(x => "Assets/Scenes/" + x + ".unity") + .ToList(); + } + else + { return new List(); } } - private static bool GetBoolEnvVariable(string key, bool defaultValue = false) { + private static bool GetBoolEnvVariable(string key, bool defaultValue = false) + { string value = Environment.GetEnvironmentVariable(key); - if (value != null) { + if (value != null) + { return value.ToLower() == "true"; - } else { + } + else + { return defaultValue; } } - private static bool ScriptsOnly() { + private static bool ScriptsOnly() + { return GetBoolEnvVariable("BUILD_SCRIPTS_ONLY"); } - private static bool IncludePrivateScenes() { + private static bool IncludePrivateScenes() + { return GetBoolEnvVariable("INCLUDE_PRIVATE_SCENES"); } - private static string GetDefineSymbolsFromEnv() { + private static string GetDefineSymbolsFromEnv() + { return Environment.GetEnvironmentVariable("DEFINES"); } } diff --git a/unity/Assets/Editor/CabinetEditor.cs b/unity/Assets/Editor/CabinetEditor.cs index 147f7d5069..f2aa41edea 100644 --- a/unity/Assets/Editor/CabinetEditor.cs +++ b/unity/Assets/Editor/CabinetEditor.cs @@ -1,25 +1,32 @@ -using UnityEngine; -using UnityEditor; +using System; using System.Collections.Generic; -using System; +using UnityEditor; +using UnityEngine; [CustomEditor(typeof(Cabinet))] -public class CabinetEditor : Editor { - public override void OnInspectorGUI() { +public class CabinetEditor : Editor +{ + public override void OnInspectorGUI() + { Cabinet c = (Cabinet)target; - if (!Application.isPlaying) { + if (!Application.isPlaying) + { c.Animate = EditorGUILayout.Toggle("Animate", c.Animate); bool open = EditorGUILayout.Toggle("Open", c.Open); - if (open != c.Open) { + if (open != c.Open) + { c.Open = open; EditorUtility.SetDirty(c); } } - if (c.ParentObj == null) { + if (c.ParentObj == null) + { GUI.color = Color.red; - } else { + } + else + { GUI.color = Color.grey; } EditorGUILayout.BeginVertical(EditorStyles.helpBox); @@ -28,50 +35,94 @@ public override void OnInspectorGUI() { c.ParentObj = (SimObj)EditorGUILayout.ObjectField(c.ParentObj, typeof(SimObj), true); EditorGUILayout.EndVertical(); - GUI.color = Color.grey; EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUI.color = Color.white; EditorGUILayout.LabelField("Transforms:", EditorStyles.miniLabel); c.OpenStyle = (CabinetOpenStyle)EditorGUILayout.EnumPopup("Open Style", c.OpenStyle); - switch (c.OpenStyle) { + switch (c.OpenStyle) + { case CabinetOpenStyle.DoubleDoors: - c.LeftDoor = (Transform)EditorGUILayout.ObjectField("Left door", c.LeftDoor, typeof(Transform), true); - c.RightDoor = (Transform)EditorGUILayout.ObjectField("Right door", c.RightDoor, typeof(Transform), true); - c.OpenAngleLeft = EditorGUILayout.Vector3Field("Open Angle (Left)", c.OpenAngleLeft); - c.ClosedAngleLeft = EditorGUILayout.Vector3Field("Closed Angle (Left)", c.ClosedAngleLeft); - c.OpenAngleRight = EditorGUILayout.Vector3Field("Open Angle (Right)", c.OpenAngleRight); - c.ClosedAngleRight = EditorGUILayout.Vector3Field("Closed Angle (Right)", c.ClosedAngleRight); + c.LeftDoor = (Transform) + EditorGUILayout.ObjectField("Left door", c.LeftDoor, typeof(Transform), true); + c.RightDoor = (Transform) + EditorGUILayout.ObjectField("Right door", c.RightDoor, typeof(Transform), true); + c.OpenAngleLeft = EditorGUILayout.Vector3Field( + "Open Angle (Left)", + c.OpenAngleLeft + ); + c.ClosedAngleLeft = EditorGUILayout.Vector3Field( + "Closed Angle (Left)", + c.ClosedAngleLeft + ); + c.OpenAngleRight = EditorGUILayout.Vector3Field( + "Open Angle (Right)", + c.OpenAngleRight + ); + c.ClosedAngleRight = EditorGUILayout.Vector3Field( + "Closed Angle (Right)", + c.ClosedAngleRight + ); break; case CabinetOpenStyle.SingleDoorLeft: - c.LeftDoor = (Transform)EditorGUILayout.ObjectField("Left door", c.LeftDoor, typeof(Transform), true); + c.LeftDoor = (Transform) + EditorGUILayout.ObjectField("Left door", c.LeftDoor, typeof(Transform), true); // c.RightDoor = null; c.OpenAngleLeft = EditorGUILayout.Vector3Field("Open Angle", c.OpenAngleLeft); c.ClosedAngleLeft = EditorGUILayout.Vector3Field("Closed Angle", c.ClosedAngleLeft); break; case CabinetOpenStyle.SingleDoorRight: - c.RightDoor = (Transform)EditorGUILayout.ObjectField("Right door", c.RightDoor, typeof(Transform), true); + c.RightDoor = (Transform) + EditorGUILayout.ObjectField("Right door", c.RightDoor, typeof(Transform), true); // c.LeftDoor = null; c.OpenAngleRight = EditorGUILayout.Vector3Field("Open Angle", c.OpenAngleRight); - c.ClosedAngleRight = EditorGUILayout.Vector3Field("Closed Angle", c.ClosedAngleRight); + c.ClosedAngleRight = EditorGUILayout.Vector3Field( + "Closed Angle", + c.ClosedAngleRight + ); break; case CabinetOpenStyle.Drawer: - c.DrawerDoor = (Transform)EditorGUILayout.ObjectField("Drawer", c.DrawerDoor, typeof(Transform), true); - c.OpenLocalPosition = EditorGUILayout.Vector3Field("Open Position (local)", c.OpenLocalPosition); - c.ClosedLocalPosition = EditorGUILayout.Vector3Field("Closed Position (local)", c.ClosedLocalPosition); + c.DrawerDoor = (Transform) + EditorGUILayout.ObjectField("Drawer", c.DrawerDoor, typeof(Transform), true); + c.OpenLocalPosition = EditorGUILayout.Vector3Field( + "Open Position (local)", + c.OpenLocalPosition + ); + c.ClosedLocalPosition = EditorGUILayout.Vector3Field( + "Closed Position (local)", + c.ClosedLocalPosition + ); // visibility collider needs to change scale and position if drawer is open or closed - c.VisCollider = (Transform)EditorGUILayout.ObjectField("Visibility Collider", c.VisCollider, typeof(Transform), true); + c.VisCollider = (Transform) + EditorGUILayout.ObjectField( + "Visibility Collider", + c.VisCollider, + typeof(Transform), + true + ); // open position and scale for the visibility collider, set this manually in editor - c.OpenVisColPosition = EditorGUILayout.Vector3Field("Visibility Collider Open Position (local)", c.OpenVisColPosition); - c.OpenVisColScale = EditorGUILayout.Vector3Field("Visibility Collider Open Scale (local)", c.OpenVisColScale); + c.OpenVisColPosition = EditorGUILayout.Vector3Field( + "Visibility Collider Open Position (local)", + c.OpenVisColPosition + ); + c.OpenVisColScale = EditorGUILayout.Vector3Field( + "Visibility Collider Open Scale (local)", + c.OpenVisColScale + ); // closed position and scale for visibility collider, set this manually in editor - c.ClosedVisColPosition = EditorGUILayout.Vector3Field("Visibility Collider Closed Position (local)", c.ClosedVisColPosition); - c.ClosedVisColScale = EditorGUILayout.Vector3Field("Visibility Collider Closed Scale (local)", c.ClosedVisColScale); + c.ClosedVisColPosition = EditorGUILayout.Vector3Field( + "Visibility Collider Closed Position (local)", + c.ClosedVisColPosition + ); + c.ClosedVisColScale = EditorGUILayout.Vector3Field( + "Visibility Collider Closed Scale (local)", + c.ClosedVisColScale + ); break; } @@ -82,11 +133,14 @@ public override void OnInspectorGUI() { GUI.color = Color.white; EditorGUILayout.LabelField("Utilities:", EditorStyles.miniLabel); - if (c.OpenStyle == CabinetOpenStyle.Drawer) { - if (GUILayout.Button("Set drawer open position")) { + if (c.OpenStyle == CabinetOpenStyle.Drawer) + { + if (GUILayout.Button("Set drawer open position")) + { c.OpenLocalPosition = c.DrawerDoor.localPosition; } - if (GUILayout.Button("Set drawer closed position")) { + if (GUILayout.Button("Set drawer closed position")) + { c.ClosedLocalPosition = c.DrawerDoor.localPosition; } @@ -114,31 +168,40 @@ public override void OnInspectorGUI() { */ } - if (c.ParentObj != null && c.ParentObj.Animator == null) { - if (GUILayout.Button("Add animation controller to parent SimObj")) { + if (c.ParentObj != null && c.ParentObj.Animator == null) + { + if (GUILayout.Button("Add animation controller to parent SimObj")) + { Animator a = c.ParentObj.GetComponent(); - if (a == null) { + if (a == null) + { a = c.ParentObj.gameObject.AddComponent(); } - a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; + a.runtimeAnimatorController = + Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; } } - if (GUILayout.Button("Set ALL pivots to UP")) { + if (GUILayout.Button("Set ALL pivots to UP")) + { SetAllPivotsToUp(); } - if (GUILayout.Button("Set ALL cabinet pivots to bottom-center")) { + if (GUILayout.Button("Set ALL cabinet pivots to bottom-center")) + { SetAllPivotsBottomCenter(); } - if (GUILayout.Button("Create cabinet from top-level door")) { + if (GUILayout.Button("Create cabinet from top-level door")) + { CreateCabinetFromBase(c); } - if (GUILayout.Button("Create ALL cabinets from top-level door")) { + if (GUILayout.Button("Create ALL cabinets from top-level door")) + { Cabinet[] cabinets = GameObject.FindObjectsOfType(); - foreach (Cabinet cabinet in cabinets) { + foreach (Cabinet cabinet in cabinets) + { CreateCabinetFromBase(cabinet); } } @@ -146,41 +209,52 @@ public override void OnInspectorGUI() { EditorGUILayout.EndVertical(); } - public void SetAllPivotsBottomCenter() { + public void SetAllPivotsBottomCenter() + { Cabinet[] cabinets = GameObject.FindObjectsOfType(); - foreach (Cabinet cabinet in cabinets) { + foreach (Cabinet cabinet in cabinets) + { // if (cabinet.OpenStyle != CabinetOpenStyle.Drawer) { - try { - if (cabinet.ParentObj != null) { + try + { + if (cabinet.ParentObj != null) + { Receptacle r = cabinet.ParentObj.GetComponent(); Transform pivot = r.Pivots[0]; Collider vCollider = r.VisibilityCollider; - pivot.transform.position = vCollider.bounds.center + (Vector3.down * vCollider.bounds.extents.y); + pivot.transform.position = + vCollider.bounds.center + (Vector3.down * vCollider.bounds.extents.y); } //} - } catch (Exception e) { + } + catch (Exception e) + { Debug.Log("Error in cabinet " + cabinet.name + ": " + e.ToString()); } } } - public void SetAllPivotsToUp() { + public void SetAllPivotsToUp() + { Cabinet[] cabinets = GameObject.FindObjectsOfType(); - foreach (Cabinet cabinet in cabinets) { - if (cabinet.ParentObj != null) { + foreach (Cabinet cabinet in cabinets) + { + if (cabinet.ParentObj != null) + { Receptacle r = cabinet.ParentObj.GetComponent(); Transform pivot = r.Pivots[0]; Transform tempParent = pivot.parent; Transform child = null; - if (pivot.childCount > 0) { + if (pivot.childCount > 0) + { child = pivot.GetChild(0); child.parent = null; - } pivot.parent = null; pivot.up = Vector3.up; pivot.localScale = Vector3.one; - if (child != null) { + if (child != null) + { child.parent = pivot; } pivot.parent = tempParent; @@ -188,9 +262,11 @@ public void SetAllPivotsToUp() { } } - public void CreateCabinetFromBase(Cabinet c) { + public void CreateCabinetFromBase(Cabinet c) + { SimObj parentObj = c.GetComponent(); - if (parentObj == null) { + if (parentObj == null) + { parentObj = c.gameObject.AddComponent(); } parentObj.Type = SimObjType.Cabinet; @@ -204,9 +280,11 @@ public void CreateCabinetFromBase(Cabinet c) { BoxCollider doorBc = null; // drawers and cabinets are very different so handle drawers here - if (c.OpenStyle == CabinetOpenStyle.Drawer) { + if (c.OpenStyle == CabinetOpenStyle.Drawer) + { Transform drawerObj = null; - if (c.DrawerDoor == null) { + if (c.DrawerDoor == null) + { c.DrawerDoor = c.transform; } drawerObj = CopyDoor(c.DrawerDoor, baseObj.transform); @@ -238,7 +316,8 @@ public void CreateCabinetFromBase(Cabinet c) { pivotObj.transform.localRotation = Quaternion.identity; // add pivot to receptacle Receptacle r = c.GetComponent(); - if (r == null) { + if (r == null) + { r = c.gameObject.AddComponent(); } r.Pivots = new Transform[] { pivotObj.transform }; @@ -251,19 +330,24 @@ public void CreateCabinetFromBase(Cabinet c) { newC.transform.localScale = Vector3.one; Animator a = newC.ParentObj.GetComponent(); - if (a == null) { + if (a == null) + { a = newC.ParentObj.gameObject.AddComponent(); } - a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; - - } else { + a.runtimeAnimatorController = + Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; + } + else + { // create a door object under the base that's a copy of the top-level object Transform leftDoorObj = null; Transform rightDoorObj = null; - switch (c.OpenStyle) { + switch (c.OpenStyle) + { case CabinetOpenStyle.SingleDoorLeft: - if (c.LeftDoor == null) { + if (c.LeftDoor == null) + { c.LeftDoor = c.transform; } leftDoorObj = CopyDoor(c.LeftDoor, baseObj.transform); @@ -272,7 +356,8 @@ public void CreateCabinetFromBase(Cabinet c) { break; case CabinetOpenStyle.SingleDoorRight: - if (c.RightDoor == null) { + if (c.RightDoor == null) + { c.RightDoor = c.transform; } rightDoorObj = CopyDoor(c.RightDoor, baseObj.transform); @@ -282,14 +367,17 @@ public void CreateCabinetFromBase(Cabinet c) { case CabinetOpenStyle.DoubleDoors: // one of these objects is going to be a copy, the other will be the real thing - if (c.LeftDoor == c.transform) { + if (c.LeftDoor == c.transform) + { // copy the left door, parent the right door leftDoorObj = CopyDoor(c.LeftDoor, baseObj.transform); doorBc = leftDoorObj.GetComponent(); rightDoorObj = c.RightDoor; rightDoorObj.transform.parent = baseObj.transform; cabineObj = leftDoorObj.gameObject; - } else { + } + else + { // copy the right door, parent the left door rightDoorObj = CopyDoor(c.RightDoor, baseObj.transform); doorBc = rightDoorObj.GetComponent(); @@ -324,7 +412,8 @@ public void CreateCabinetFromBase(Cabinet c) { pivotObj.transform.localRotation = Quaternion.identity; // add pivot to receptacle Receptacle r = c.GetComponent(); - if (r == null) { + if (r == null) + { r = c.gameObject.AddComponent(); } r.Pivots = new Transform[] { pivotObj.transform }; @@ -337,14 +426,17 @@ public void CreateCabinetFromBase(Cabinet c) { newC.transform.localScale = Vector3.one; Animator a = newC.ParentObj.GetComponent(); - if (a == null) { + if (a == null) + { a = newC.ParentObj.gameObject.AddComponent(); } - a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; + a.runtimeAnimatorController = + Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; } } - public Transform CopyDoor(Transform doorTransform, Transform baseObj) { + public Transform CopyDoor(Transform doorTransform, Transform baseObj) + { GameObject doorCopy = new GameObject("Door"); doorCopy.transform.parent = baseObj; doorCopy.transform.position = doorTransform.position; @@ -359,19 +451,22 @@ public Transform CopyDoor(Transform doorTransform, Transform baseObj) { GameObject.DestroyImmediate(cmf); GameObject.DestroyImmediate(cmr); BoxCollider bc = doorTransform.GetComponent(); - if (bc != null) { + if (bc != null) + { GameObject.DestroyImmediate(bc); } doorCopy.AddComponent(); // copy all child transforms (handles) List childTransforms = new List(); - foreach (Transform child in doorTransform) { + foreach (Transform child in doorTransform) + { childTransforms.Add(child); } - foreach (Transform child in childTransforms) { + foreach (Transform child in childTransforms) + { child.parent = doorCopy.transform; } return doorCopy.transform; } -} \ No newline at end of file +} diff --git a/unity/Assets/Editor/ConvertableEditor.cs b/unity/Assets/Editor/ConvertableEditor.cs index 54c73d30c8..430de8dcb3 100644 --- a/unity/Assets/Editor/ConvertableEditor.cs +++ b/unity/Assets/Editor/ConvertableEditor.cs @@ -1,23 +1,28 @@ -using UnityEngine; -using UnityEditor; -using System; +using System; using System.Collections.Generic; +using UnityEditor; +using UnityEngine; [CustomEditor(typeof(Convertable))] -public class ConvertableEditor : Editor { - public override void OnInspectorGUI() { +public class ConvertableEditor : Editor +{ + public override void OnInspectorGUI() + { Convertable c = (Convertable)target; GUI.color = Color.grey; - if (c.CurrentState < 0) { + if (c.CurrentState < 0) + { GUI.color = Color.red; } Animator a = c.GetComponent(); - if (a == null) { + if (a == null) + { a = c.gameObject.AddComponent(); - a.runtimeAnimatorController = Resources.Load("StateAnimController") as RuntimeAnimatorController; + a.runtimeAnimatorController = + Resources.Load("StateAnimController") as RuntimeAnimatorController; } EditorGUILayout.BeginVertical(EditorStyles.helpBox); @@ -28,7 +33,8 @@ public override void OnInspectorGUI() { c.EditorState = EditorGUILayout.IntSlider("Editor State", c.EditorState + 1, 1, 4) - 1; EditorGUILayout.LabelField("Current state: " + (c.CurrentState + 1).ToString()); - if (c.States == null || c.States.Length < 2) { + if (c.States == null || c.States.Length < 2) + { c.States = new SimObjState[2]; c.States[0] = new SimObjState(); c.States[1] = new SimObjState(); @@ -36,48 +42,61 @@ public override void OnInspectorGUI() { } // name all state objects for their state - foreach (SimObjState state in c.States) { - if (state.Obj != null) { + foreach (SimObjState state in c.States) + { + if (state.Obj != null) + { // state.Obj.name = state.Type.ToString (); } } List availableItems = new List(); Transform baseTransform = c.transform.Find("Base"); - if (baseTransform == null) { + if (baseTransform == null) + { GUI.color = Color.red; EditorGUILayout.LabelField("MUST HAVE BASE OBJECT!"); - } else { - foreach (Transform child in baseTransform) { + } + else + { + foreach (Transform child in baseTransform) + { availableItems.Add(child.gameObject); } List choicesList = new List(); - foreach (GameObject availableItem in availableItems) { + foreach (GameObject availableItem in availableItems) + { choicesList.Add(availableItem.name); } string[] choices = choicesList.ToArray(); int stateIndex = 0; - foreach (SimObjState state in c.States) { + foreach (SimObjState state in c.States) + { GUI.color = Color.white; - if (stateIndex == c.CurrentState) { + if (stateIndex == c.CurrentState) + { GUI.color = Color.Lerp(Color.white, Color.green, 0.5f); } EditorGUILayout.BeginVertical(EditorStyles.helpBox); EditorGUILayout.LabelField("State " + (stateIndex + 1).ToString()); state.Type = (SimObjType)EditorGUILayout.EnumPopup("Type", state.Type); int stateObjIndex = 0; - if (state.Obj != null) { - for (int i = 0; i < choices.Length; i++) { - if (state.Obj.name.Equals(choices[i])) { + if (state.Obj != null) + { + for (int i = 0; i < choices.Length; i++) + { + if (state.Obj.name.Equals(choices[i])) + { stateObjIndex = i; break; } } } stateObjIndex = EditorGUILayout.Popup("Object", stateObjIndex, choices); - if (availableItems.Count > 0) { + if (availableItems.Count > 0) + { state.Obj = availableItems[stateObjIndex]; } EditorGUILayout.EndVertical(); @@ -86,12 +105,12 @@ public override void OnInspectorGUI() { } EditorGUILayout.EndVertical(); - GUI.color = Color.grey; EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUI.color = Color.white; EditorGUILayout.LabelField("Utilities:", EditorStyles.miniLabel); - if (baseTransform.childCount == 0 && GUILayout.Button("Create sub-type objects from base")) { + if (baseTransform.childCount == 0 && GUILayout.Button("Create sub-type objects from base")) + { GameObject newBaseObj = new GameObject("Base"); newBaseObj.transform.parent = baseTransform.parent; newBaseObj.transform.position = baseTransform.position; @@ -112,4 +131,4 @@ public override void OnInspectorGUI() { EditorUtility.SetDirty(c.gameObject); EditorUtility.SetDirty(c); } -} \ No newline at end of file +} diff --git a/unity/Assets/Editor/ExpRoomEditor.cs b/unity/Assets/Editor/ExpRoomEditor.cs index 5d62d2c2dd..d70f8eed5c 100644 --- a/unity/Assets/Editor/ExpRoomEditor.cs +++ b/unity/Assets/Editor/ExpRoomEditor.cs @@ -2,18 +2,19 @@ using System.Collections; using System.Collections.Generic; using System.Linq; +using System.Security.Cryptography; using UnityEditor; using UnityEngine; -using System.Security.Cryptography; - -public class ExpRoomEditor : EditorWindow { +public class ExpRoomEditor : EditorWindow +{ Vector2 scroll; - List <(SimObjPhysics, string)> sopAndPrefabTuples = null; + List<(SimObjPhysics, string)> sopAndPrefabTuples = null; [MenuItem("ExpRoom/Add all pickupable prefabs to AvailableObjects")] - static void AddPickupableToAvailableObjects() { + static void AddPickupableToAvailableObjects() + { GameObject availableObjectsGameObject = GameObject.Find("AvailableObjects"); AddAllPrefabsAsOnlyChildrenOfObject( parent: availableObjectsGameObject, @@ -24,7 +25,8 @@ static void AddPickupableToAvailableObjects() { } [MenuItem("ExpRoom/Add all pickupable receptacle prefabs to AvailableContainers")] - static void AddPickupableReceptaclesToAvailableContainers() { + static void AddPickupableReceptaclesToAvailableContainers() + { GameObject availableContainersGameObject = GameObject.Find("AvailableContainers"); AddAllPrefabsAsOnlyChildrenOfObject( parent: availableContainersGameObject, @@ -35,8 +37,9 @@ static void AddPickupableReceptaclesToAvailableContainers() { } [MenuItem("ExpRoom/Interactively add all pickupable prefabs to AvailableObjects")] - static void Init() { - ExpRoomEditor window = (ExpRoomEditor) EditorWindow.GetWindow(typeof(ExpRoomEditor)); + static void Init() + { + ExpRoomEditor window = (ExpRoomEditor)EditorWindow.GetWindow(typeof(ExpRoomEditor)); window.Show(); window.position = new Rect(20, 80, 400, 300); } @@ -45,12 +48,15 @@ static void Init() { [MenuItem("ExpRoom/Add all pickupable prefabs to AvailableObjects", true)] [MenuItem("ExpRoom/Add all pickupable receptacle prefabs to AvailableContainers", true)] [MenuItem("ExpRoom/Interactively add all pickupable prefabs to AvailableObjects", true)] - static bool HideMenuIfNotInExpRoom() { + static bool HideMenuIfNotInExpRoom() + { //Debug.Log(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name); - return UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "FloorPlan_ExpRoom"; + return UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + == "FloorPlan_ExpRoom"; } - void OnGUI() { + void OnGUI() + { GUILayout.Space(3); int oldValue = GUI.skin.window.padding.bottom; GUI.skin.window.padding.bottom = -20; @@ -59,7 +65,8 @@ void OnGUI() { windowRect.width -= 7; GUI.skin.window.padding.bottom = oldValue; - if (GUILayout.Button("Find all pickupable")) { + if (GUILayout.Button("Find all pickupable")) + { GameObject availableObjectsGameObject = GameObject.Find("AvailableObjects"); sopAndPrefabTuples = AddAllPrefabsAsOnlyChildrenOfObject( parent: availableObjectsGameObject, @@ -68,21 +75,26 @@ void OnGUI() { ); } - if (sopAndPrefabTuples != null) { - if (sopAndPrefabTuples.Count == 0) { + if (sopAndPrefabTuples != null) + { + if (sopAndPrefabTuples.Count == 0) + { GUILayout.Label("No pickupable objects found"); - } else { + } + else + { GUILayout.Label("The following prefabs were found:"); scroll = GUILayout.BeginScrollView(scroll); - - foreach ((SimObjPhysics, string) sopAndPath in sopAndPrefabTuples) { + foreach ((SimObjPhysics, string) sopAndPath in sopAndPrefabTuples) + { SimObjPhysics sop = sopAndPath.Item1; string path = sopAndPath.Item2; GUILayout.BeginHorizontal(); GUILayout.Label(path, GUILayout.Width(4 * position.width / 8)); GUILayout.Label(sop.Type.ToString(), GUILayout.Width(3 * position.width / 8)); - if (GUILayout.Button("Select", GUILayout.Width(position.width / 8 - 2))) { + if (GUILayout.Button("Select", GUILayout.Width(position.width / 8 - 2))) + { Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(path); } GUILayout.EndHorizontal(); @@ -92,10 +104,13 @@ void OnGUI() { } } - public static void OpenBoxFlapsMore(SimObjPhysics sop) { + public static void OpenBoxFlapsMore(SimObjPhysics sop) + { CanOpen_Object coo = sop.GetComponent(); - if (coo) { - for (int i = 0; i < coo.MovingParts.Length; i++) { + if (coo) + { + for (int i = 0; i < coo.MovingParts.Length; i++) + { GameObject part = coo.MovingParts[i]; Vector3 openRot = coo.openPositions[i]; Vector3 closeRot = coo.closedPositions[i]; @@ -105,20 +120,23 @@ public static void OpenBoxFlapsMore(SimObjPhysics sop) { float angle = Quaternion.Angle(openRotQ, closeRotQ); float newAngle = angle; - while (newAngle < 180f) { - newAngle += 30f; + while (newAngle < 180f) + { + newAngle += 30f; } part.transform.rotation = Quaternion.Euler( (openRot - closeRot) * (newAngle / angle) + closeRot ); // Debug.Log($"Open = {openRot}, closed = {closeRot}, Euler = {(openRot - closeRot) * (newAngle / angle) + openRot}"); - Debug.Log($"Part = {part}, angle {angle}, new angle {newAngle}, true angle {Quaternion.Angle(openRotQ, part.transform.rotation)}"); + Debug.Log( + $"Part = {part}, angle {angle}, new angle {newAngle}, true angle {Quaternion.Angle(openRotQ, part.transform.rotation)}" + ); } } } - public static void FixBoundingBox(SimObjPhysics sop) { - + public static void FixBoundingBox(SimObjPhysics sop) + { Vector3 startPos = sop.transform.position; Quaternion startRot = sop.transform.rotation; @@ -132,8 +150,10 @@ public static void FixBoundingBox(SimObjPhysics sop) { Physics.SyncTransforms(); Bounds objBounds = UtilityFunctions.CreateEmptyBounds(); - foreach (Collider c in sop.GetComponentsInChildren()) { - if (c.enabled && !c.isTrigger) { + foreach (Collider c in sop.GetComponentsInChildren()) + { + if (c.enabled && !c.isTrigger) + { objBounds.Encapsulate(c.bounds); } } @@ -142,7 +162,8 @@ public static void FixBoundingBox(SimObjPhysics sop) { bbox.center = objBounds.center; bbox.size = 2 * objBounds.extents; - foreach (Transform child in sop.transform) { + foreach (Transform child in sop.transform) + { child.position = child.position - bbox.center; } bbox.transform.position = Vector3.zero; @@ -152,23 +173,29 @@ public static void FixBoundingBox(SimObjPhysics sop) { sop.transform.rotation = startRot; } - public static string CreateSHA256Hash(string path) { + public static string CreateSHA256Hash(string path) + { SHA256 hasher = SHA256.Create(); - using (System.IO.FileStream fs = System.IO.File.OpenRead(path)) { + using (System.IO.FileStream fs = System.IO.File.OpenRead(path)) + { return string.Join("", hasher.ComputeHash(fs).Select(b => b.ToString("x2")).ToArray()); } } - public static string[] GetAllPrefabs() { - return AssetDatabase.GetAllAssetPaths().Where( - s => s.Contains(".prefab") + public static string[] GetAllPrefabs() + { + return AssetDatabase + .GetAllAssetPaths() + .Where(s => + s.Contains(".prefab") && !s.Contains("Custom Project") && !s.Contains("Assets/Resources/") && !s.Contains("PhysicsTestPrefabs") && !s.Contains("(Old)") - // && s.Contains("Assets/Physics/SimObjsPhysics") && - ).ToArray(); + // && s.Contains("Assets/Physics/SimObjsPhysics") && + ) + .ToArray(); } public static List<(SimObjPhysics, string)> AddAllPrefabsAsOnlyChildrenOfObject( @@ -176,59 +203,74 @@ public static string[] GetAllPrefabs() { bool onlyPickupable, bool onlyReceptacles, string tag = "" - ) { - List <(SimObjPhysics, string)> sopAndPrefabTuples = new List <(SimObjPhysics, string)>(); + ) + { + List<(SimObjPhysics, string)> sopAndPrefabTuples = new List<(SimObjPhysics, string)>(); string[] allPrefabs = GetAllPrefabs(); int numAdded = 0; - foreach (string prefab in allPrefabs) { + foreach (string prefab in allPrefabs) + { GameObject go = null; - try { + try + { Debug.Log($"Checking {prefab}"); - go = (GameObject) AssetDatabase.LoadMainAssetAtPath(prefab); + go = (GameObject)AssetDatabase.LoadMainAssetAtPath(prefab); SimObjPhysics sop = go.GetComponent(); // if (sop != null && sop.Type.ToString() == "Box" && sop.GetComponent()) { - if (sop != null) { + if (sop != null) + { bool pickupable = sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup; - bool isReceptacle = Array.IndexOf( - sop.SecondaryProperties, - SimObjSecondaryProperty.Receptacle - ) > -1 && sop.ReceptacleTriggerBoxes != null; - if ( - (pickupable || !onlyPickupable) - && (isReceptacle || !onlyReceptacles) - ) { + bool isReceptacle = + Array.IndexOf(sop.SecondaryProperties, SimObjSecondaryProperty.Receptacle) + > -1 + && sop.ReceptacleTriggerBoxes != null; + if ((pickupable || !onlyPickupable) && (isReceptacle || !onlyReceptacles)) + { sopAndPrefabTuples.Add((go.GetComponent(), prefab)); numAdded += 1; } } - } catch { - try { - if (go) { + } + catch + { + try + { + if (go) + { DestroyImmediate(go); } - } catch {} + } + catch { } Debug.LogWarning($"Prefab {prefab} failed to load."); } } - sopAndPrefabTuples = sopAndPrefabTuples.OrderBy( - sopAndPath => ( - sopAndPath.Item1.Type.ToString(), - int.Parse("0" + new string( - sopAndPath.Item1.name - .Split('/') - .Last() - .Where(c => char.IsDigit(c)) - .ToArray())) + sopAndPrefabTuples = sopAndPrefabTuples + .OrderBy(sopAndPath => + ( + sopAndPath.Item1.Type.ToString(), + int.Parse( + "0" + + new string( + sopAndPath + .Item1.name.Split('/') + .Last() + .Where(c => char.IsDigit(c)) + .ToArray() + ) + ) + ) ) - ).ToList(); + .ToList(); Debug.Log( $"Found {allPrefabs.Length} total prefabs of which {sopAndPrefabTuples.Count} were SimObjPhysics satisfying" - + $"onlyPickupable=={onlyPickupable} and onlyReceptacles=={onlyReceptacles}." + + $"onlyPickupable=={onlyPickupable} and onlyReceptacles=={onlyReceptacles}." ); - UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene()); + UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty( + UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene() + ); // Note that you cannot (unfortunately) combine the two below loops into // a single loop as doing something like @@ -238,27 +280,32 @@ public static string[] GetAllPrefabs() { // Will actually miss a large number of children because the way that looping through // parent.transform works (deleting while iterating results in missing elements). List toDestroy = new List(); - foreach (Transform child in parent.transform) { + foreach (Transform child in parent.transform) + { toDestroy.Add(child.gameObject); } - foreach (GameObject child in toDestroy) { + foreach (GameObject child in toDestroy) + { Debug.Log($"Attempting to destroy {child.gameObject}"); DestroyImmediate(child); } - if (tag != "") { + if (tag != "") + { tag = $"_{tag}"; } - for (int i = 0; i < sopAndPrefabTuples.Count; i++) { + for (int i = 0; i < sopAndPrefabTuples.Count; i++) + { SimObjPhysics sop = sopAndPrefabTuples[i].Item1; string path = sopAndPrefabTuples[i].Item2; string hash = CreateSHA256Hash(path).Substring(0, 8); - GameObject go = (GameObject) PrefabUtility.InstantiatePrefab(sop.gameObject); + GameObject go = (GameObject)PrefabUtility.InstantiatePrefab(sop.gameObject); SimObjPhysics newSop = go.GetComponent(); - if (onlyReceptacles && sop.Type.ToString() == "Box") { + if (onlyReceptacles && sop.Type.ToString() == "Box") + { OpenBoxFlapsMore(newSop); } @@ -275,98 +322,97 @@ public static string[] GetAllPrefabs() { return sopAndPrefabTuples; } -// [MenuItem("ExpRoom/Fix All Moveable Object Prefabs")] -// public static void FixAllMoveableObjectPrefabs() { -// string[] allPrefabGUIDs = AssetDatabase.FindAssets("t:Prefab"); -// -// List toFixGOs = new List(); -// List toFixPrefabPaths = new List(); -// Dictionary sopTypeToMovementType = new Dictionary(); -// -// foreach (string guid in allPrefabGUIDs) { -// string prefab = AssetDatabase.GUIDToAssetPath(guid); -// GameObject go = null; -// try { -// go = AssetDatabase.LoadAssetAtPath(prefab); -// SimObjPhysics sop = go.GetComponent(); -// -// if (sop != null) { -// CanOpen_Object coo = go.GetComponentInChildren(); -// if (coo != null) { -// Debug.Log($"Checking {prefab}"); -// if (coo.movementType != CanOpen_Object.MovementType.Invalid) { -// if (!sopTypeToMovementType.ContainsKey(sop.Type)) { -// sopTypeToMovementType[sop.Type] = coo.movementType; -// } -// if (sopTypeToMovementType[sop.Type] != coo.movementType) { -// throw new Exception($"Found two different movement types for {sop.Type}."); -// } -// } else { -// toFixGOs.Add(go); -// toFixPrefabPaths.Add(prefab); -// } -// } -// } -// } catch { -// Debug.LogWarning($"Prefab {prefab} failed to load."); -// } -// } -// -// if (!sopTypeToMovementType.ContainsKey(SimObjType.ScreenFrame)) { -// sopTypeToMovementType[SimObjType.ScreenFrame] = CanOpen_Object.MovementType.Scale; -// } -// if (!sopTypeToMovementType.ContainsKey(SimObjType.Blinds)) { -// sopTypeToMovementType[SimObjType.Blinds] = CanOpen_Object.MovementType.Scale; -// } -// -// foreach (SimObjType sopType in sopTypeToMovementType.Keys) { -// Debug.Log($"{sopType} has movement type {sopTypeToMovementType[sopType]}"); -// } -// -// foreach (string path in toFixPrefabPaths) { -// using (var editingScope = new PrefabUtility.EditPrefabContentsScope(path)) { -// GameObject go = editingScope.prefabContentsRoot; -// SimObjPhysics sop = go.GetComponentInChildren(); -// CanOpen_Object coo = go.GetComponentInChildren(); -// -// if (!sopTypeToMovementType.ContainsKey(sop.Type)) { -// Debug.LogError($"No movement type found for {sop.Type}."); -// continue; -// } -// Debug.Log($"{go} does not have a valid movement type. Setting based on object type to {sopTypeToMovementType[sop.Type]}"); -// coo.movementType = sopTypeToMovementType[sop.Type]; -// } -// } -// -// -// // Loop through each scene -// Dictionary> sceneToSopsThatNeedFix = new Dictionary>(); -// foreach (string scenePath in Build.GetAllScenePaths()) { -// UnityEditor.SceneManagement.EditorSceneManager.OpenScene(scenePath); -// sceneToSopsThatNeedFix[scenePath] = new List(); -// -// // Update game objects in the scene -// foreach (SimObjPhysics sop in FindObjectsOfType()) { -// CanOpen_Object coo = sop.GetComponentInChildren(); -// if (coo != null) { -// if (coo.movementType == CanOpen_Object.MovementType.Invalid) { -// Debug.Log($"Found invalid movement type for {sop.name} in {scenePath}"); -// sceneToSopsThatNeedFix[scenePath].Add(sop.name); -// } -// } -// } -// } -// -// // Print out scenes and sops that need fix -// foreach (string scenePath in sceneToSopsThatNeedFix.Keys) { -// if (sceneToSopsThatNeedFix[scenePath].Count > 0) { -// Debug.Log($"Scene {scenePath} has {sceneToSopsThatNeedFix[scenePath].Count} sops that need fix:"); -// foreach (string sopName in sceneToSopsThatNeedFix[scenePath]) { -// Debug.Log($" {sopName}"); -// } -// } -// } -// -// } - -} \ No newline at end of file + // [MenuItem("ExpRoom/Fix All Moveable Object Prefabs")] + // public static void FixAllMoveableObjectPrefabs() { + // string[] allPrefabGUIDs = AssetDatabase.FindAssets("t:Prefab"); + // + // List toFixGOs = new List(); + // List toFixPrefabPaths = new List(); + // Dictionary sopTypeToMovementType = new Dictionary(); + // + // foreach (string guid in allPrefabGUIDs) { + // string prefab = AssetDatabase.GUIDToAssetPath(guid); + // GameObject go = null; + // try { + // go = AssetDatabase.LoadAssetAtPath(prefab); + // SimObjPhysics sop = go.GetComponent(); + // + // if (sop != null) { + // CanOpen_Object coo = go.GetComponentInChildren(); + // if (coo != null) { + // Debug.Log($"Checking {prefab}"); + // if (coo.movementType != CanOpen_Object.MovementType.Invalid) { + // if (!sopTypeToMovementType.ContainsKey(sop.Type)) { + // sopTypeToMovementType[sop.Type] = coo.movementType; + // } + // if (sopTypeToMovementType[sop.Type] != coo.movementType) { + // throw new Exception($"Found two different movement types for {sop.Type}."); + // } + // } else { + // toFixGOs.Add(go); + // toFixPrefabPaths.Add(prefab); + // } + // } + // } + // } catch { + // Debug.LogWarning($"Prefab {prefab} failed to load."); + // } + // } + // + // if (!sopTypeToMovementType.ContainsKey(SimObjType.ScreenFrame)) { + // sopTypeToMovementType[SimObjType.ScreenFrame] = CanOpen_Object.MovementType.Scale; + // } + // if (!sopTypeToMovementType.ContainsKey(SimObjType.Blinds)) { + // sopTypeToMovementType[SimObjType.Blinds] = CanOpen_Object.MovementType.Scale; + // } + // + // foreach (SimObjType sopType in sopTypeToMovementType.Keys) { + // Debug.Log($"{sopType} has movement type {sopTypeToMovementType[sopType]}"); + // } + // + // foreach (string path in toFixPrefabPaths) { + // using (var editingScope = new PrefabUtility.EditPrefabContentsScope(path)) { + // GameObject go = editingScope.prefabContentsRoot; + // SimObjPhysics sop = go.GetComponentInChildren(); + // CanOpen_Object coo = go.GetComponentInChildren(); + // + // if (!sopTypeToMovementType.ContainsKey(sop.Type)) { + // Debug.LogError($"No movement type found for {sop.Type}."); + // continue; + // } + // Debug.Log($"{go} does not have a valid movement type. Setting based on object type to {sopTypeToMovementType[sop.Type]}"); + // coo.movementType = sopTypeToMovementType[sop.Type]; + // } + // } + // + // + // // Loop through each scene + // Dictionary> sceneToSopsThatNeedFix = new Dictionary>(); + // foreach (string scenePath in Build.GetAllScenePaths()) { + // UnityEditor.SceneManagement.EditorSceneManager.OpenScene(scenePath); + // sceneToSopsThatNeedFix[scenePath] = new List(); + // + // // Update game objects in the scene + // foreach (SimObjPhysics sop in FindObjectsOfType()) { + // CanOpen_Object coo = sop.GetComponentInChildren(); + // if (coo != null) { + // if (coo.movementType == CanOpen_Object.MovementType.Invalid) { + // Debug.Log($"Found invalid movement type for {sop.name} in {scenePath}"); + // sceneToSopsThatNeedFix[scenePath].Add(sop.name); + // } + // } + // } + // } + // + // // Print out scenes and sops that need fix + // foreach (string scenePath in sceneToSopsThatNeedFix.Keys) { + // if (sceneToSopsThatNeedFix[scenePath].Count > 0) { + // Debug.Log($"Scene {scenePath} has {sceneToSopsThatNeedFix[scenePath].Count} sops that need fix:"); + // foreach (string sopName in sceneToSopsThatNeedFix[scenePath]) { + // Debug.Log($" {sopName}"); + // } + // } + // } + // + // } +} diff --git a/unity/Assets/Editor/Instant Screenshot/ScreenshotTaker.cs b/unity/Assets/Editor/Instant Screenshot/ScreenshotTaker.cs index 962410aeb1..7ae334f6b4 100644 --- a/unity/Assets/Editor/Instant Screenshot/ScreenshotTaker.cs +++ b/unity/Assets/Editor/Instant Screenshot/ScreenshotTaker.cs @@ -2,10 +2,9 @@ using UnityEditor; using UnityEngine; - [ExecuteInEditMode] -public class Screenshot : EditorWindow { - +public class Screenshot : EditorWindow +{ int resWidth = Screen.width * 4; int resHeight = Screen.height * 4; @@ -20,7 +19,8 @@ public class Screenshot : EditorWindow { // Add menu item named "My Window" to the Window menu [MenuItem("Tools/Saad Khawaja/Instant High-Res Screenshot")] - public static void ShowWindow() { + public static void ShowWindow() + { // Show existing window instance. If one doesn't exist, make one. EditorWindow editorWindow = EditorWindow.GetWindow(typeof(Screenshot)); editorWindow.autoRepaintOnSceneChange = true; @@ -31,8 +31,8 @@ public static void ShowWindow() { float lastTime; - - void OnGUI() { + void OnGUI() + { EditorGUILayout.LabelField("Resolution", EditorStyles.boldLabel); resWidth = EditorGUILayout.IntField("Width", resWidth); resHeight = EditorGUILayout.IntField("Height", resHeight); @@ -41,13 +41,14 @@ void OnGUI() { scale = EditorGUILayout.IntSlider("Scale", scale, 1, 15); - EditorGUILayout.HelpBox("The default mode of screenshot is crop - so choose a proper width and height. The scale is a factor " + - "to multiply or enlarge the renders without loosing quality.", MessageType.None); - + EditorGUILayout.HelpBox( + "The default mode of screenshot is crop - so choose a proper width and height. The scale is a factor " + + "to multiply or enlarge the renders without loosing quality.", + MessageType.None + ); EditorGUILayout.Space(); - GUILayout.Label("Save Path", EditorStyles.boldLabel); EditorGUILayout.BeginHorizontal(); @@ -57,61 +58,71 @@ void OnGUI() { EditorGUILayout.EndHorizontal(); - EditorGUILayout.HelpBox("Choose the folder in which to save the screenshots ", MessageType.None); + EditorGUILayout.HelpBox( + "Choose the folder in which to save the screenshots ", + MessageType.None + ); EditorGUILayout.Space(); - - // isTransparent = EditorGUILayout.Toggle(isTransparent,"Transparent Background"); GUILayout.Label("Select Camera", EditorStyles.boldLabel); - myCamera = EditorGUILayout.ObjectField(myCamera, typeof(Camera), true, null) as Camera; - - if (myCamera == null) { + if (myCamera == null) + { myCamera = Camera.main; } isTransparent = EditorGUILayout.Toggle("Transparent Background", isTransparent); - - EditorGUILayout.HelpBox("Choose the camera of which to capture the render. You can make the background transparent using the transparency option.", MessageType.None); + EditorGUILayout.HelpBox( + "Choose the camera of which to capture the render. You can make the background transparent using the transparency option.", + MessageType.None + ); EditorGUILayout.Space(); EditorGUILayout.BeginVertical(); EditorGUILayout.LabelField("Default Options", EditorStyles.boldLabel); - - if (GUILayout.Button("Set To Screen Size")) { + if (GUILayout.Button("Set To Screen Size")) + { resHeight = (int)Handles.GetMainGameViewSize().y; resWidth = (int)Handles.GetMainGameViewSize().x; - } - - if (GUILayout.Button("Default Size")) { + if (GUILayout.Button("Default Size")) + { resHeight = 1440; resWidth = 2560; scale = 1; } - - EditorGUILayout.EndVertical(); EditorGUILayout.Space(); - EditorGUILayout.LabelField("Screenshot will be taken at " + resWidth * scale + " x " + resHeight * scale + " px", EditorStyles.boldLabel); - - if (GUILayout.Button("Take Screenshot", GUILayout.MinHeight(60))) { - if (path == "") { - path = EditorUtility.SaveFolderPanel("Path to Save Images", path, Application.dataPath); + EditorGUILayout.LabelField( + "Screenshot will be taken at " + resWidth * scale + " x " + resHeight * scale + " px", + EditorStyles.boldLabel + ); + + if (GUILayout.Button("Take Screenshot", GUILayout.MinHeight(60))) + { + if (path == "") + { + path = EditorUtility.SaveFolderPanel( + "Path to Save Images", + path, + Application.dataPath + ); Debug.Log("Path Set"); TakeHiResShot(); - } else { + } + else + { TakeHiResShot(); } } @@ -119,26 +130,35 @@ void OnGUI() { EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); - if (GUILayout.Button("Open Last Screenshot", GUILayout.MaxWidth(160), GUILayout.MinHeight(40))) { - if (lastScreenshot != "") { + if ( + GUILayout.Button( + "Open Last Screenshot", + GUILayout.MaxWidth(160), + GUILayout.MinHeight(40) + ) + ) + { + if (lastScreenshot != "") + { Application.OpenURL("file://" + lastScreenshot); Debug.Log("Opening File " + lastScreenshot); } } - if (GUILayout.Button("Open Folder", GUILayout.MaxWidth(100), GUILayout.MinHeight(40))) { - + if (GUILayout.Button("Open Folder", GUILayout.MaxWidth(100), GUILayout.MinHeight(40))) + { Application.OpenURL("file://" + path); } - if (GUILayout.Button("More Assets", GUILayout.MaxWidth(100), GUILayout.MinHeight(40))) { + if (GUILayout.Button("More Assets", GUILayout.MaxWidth(100), GUILayout.MinHeight(40))) + { Application.OpenURL("https://www.assetstore.unity3d.com/en/#!/publisher/5951"); } EditorGUILayout.EndHorizontal(); - - if (takeHiResShot) { + if (takeHiResShot) + { int resWidthN = resWidth * scale; int resHeightN = resHeight * scale; RenderTexture rt = new RenderTexture(resWidthN, resHeightN, 24); @@ -150,7 +170,6 @@ void OnGUI() { else tFormat = TextureFormat.RGB24; - Texture2D screenShot = new Texture2D(resWidthN, resHeightN, tFormat, false); myCamera.Render(); RenderTexture.active = rt; @@ -166,37 +185,34 @@ void OnGUI() { takeHiResShot = false; } - EditorGUILayout.HelpBox("In case of any error, make sure you have Unity Pro as the plugin requires Unity Pro to work.", MessageType.Info); - - + EditorGUILayout.HelpBox( + "In case of any error, make sure you have Unity Pro as the plugin requires Unity Pro to work.", + MessageType.Info + ); } - - private bool takeHiResShot = false; public string lastScreenshot = ""; - - public string ScreenShotName(int width, int height) { - + public string ScreenShotName(int width, int height) + { string strPath = ""; strPath = string.Format( "{0}/screen_{1}x{2}_{3}.png", path, - width, height, - System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss")); + width, + height, + System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ); lastScreenshot = strPath; return strPath; } - - - public void TakeHiResShot() { + public void TakeHiResShot() + { Debug.Log("Taking Screenshot"); takeHiResShot = true; } - } - diff --git a/unity/Assets/Editor/NormalsVisualizer.cs b/unity/Assets/Editor/NormalsVisualizer.cs index 3d6497e3d4..262d805ccc 100644 --- a/unity/Assets/Editor/NormalsVisualizer.cs +++ b/unity/Assets/Editor/NormalsVisualizer.cs @@ -2,29 +2,33 @@ using UnityEngine; [CustomEditor(typeof(MeshFilter))] -public class NormalsVisualizer : Editor { - - private const string EDITOR_PREF_KEY = "_normals_length"; - private const string EDITOR_PREF_KEY_SHOW = "_normals_show"; - private Mesh mesh; - private MeshFilter mf; - private Vector3[] verts; - private Vector3[] normals; - private float normalsLength = 1f; +public class NormalsVisualizer : Editor +{ + private const string EDITOR_PREF_KEY = "_normals_length"; + private const string EDITOR_PREF_KEY_SHOW = "_normals_show"; + private Mesh mesh; + private MeshFilter mf; + private Vector3[] verts; + private Vector3[] normals; + private float normalsLength = 1f; private bool showNormals = false; - private void OnEnable() { - mf = target as MeshFilter; - if (mf != null) { + private void OnEnable() + { + mf = target as MeshFilter; + if (mf != null) + { mesh = mf.sharedMesh; } normalsLength = EditorPrefs.GetFloat(EDITOR_PREF_KEY); showNormals = EditorPrefs.GetBool(EDITOR_PREF_KEY_SHOW); } - private void OnSceneGUI() { - if (mesh == null || !showNormals) { + private void OnSceneGUI() + { + if (mesh == null || !showNormals) + { return; } @@ -33,20 +37,23 @@ private void OnSceneGUI() { verts = mesh.vertices; normals = mesh.normals; int len = mesh.vertexCount; - - for (int i = 0; i < len; i++) { + + for (int i = 0; i < len; i++) + { Handles.DrawLine(verts[i], verts[i] + normals[i] * normalsLength, 4.0f); } } - public override void OnInspectorGUI() { + public override void OnInspectorGUI() + { base.OnInspectorGUI(); EditorGUI.BeginChangeCheck(); normalsLength = EditorGUILayout.FloatField("Normals length", normalsLength); showNormals = EditorGUILayout.Toggle("Show normals", showNormals); - if (EditorGUI.EndChangeCheck()) { + if (EditorGUI.EndChangeCheck()) + { EditorPrefs.SetFloat(EDITOR_PREF_KEY, normalsLength); EditorPrefs.SetBool(EDITOR_PREF_KEY_SHOW, showNormals); } } -} \ No newline at end of file +} diff --git a/unity/Assets/Editor/PhysicsSettler.cs b/unity/Assets/Editor/PhysicsSettler.cs index 1f5f9a57aa..1299a25e2b 100644 --- a/unity/Assets/Editor/PhysicsSettler.cs +++ b/unity/Assets/Editor/PhysicsSettler.cs @@ -1,11 +1,12 @@ -using UnityEngine; -using UnityEditor; -// using System; +// using System; using System.Collections.Generic; +using UnityEditor; +using UnityEngine; // This causes the class' static constructor to be called on load and on starting playmode [InitializeOnLoad] -class PhysicsSettler { +class PhysicsSettler +{ // only ever register once static bool registered = false; @@ -25,8 +26,10 @@ class PhysicsSettler { static float activeTime = 0f; // this is the static constructor called by [InitializeOnLoad] - static PhysicsSettler() { - if (!registered) { + static PhysicsSettler() + { + if (!registered) + { // hook into the editor update EditorApplication.update += Update; @@ -36,46 +39,58 @@ static PhysicsSettler() { } } - // let users turn on + // let users turn on [MenuItem("GameMenu/Settle Physics")] - static void Activate() { - if (!active) { + static void Activate() + { + if (!active) + { active = true; List filter = new List(); Rigidbody[] arrayOfAllRB = Object.FindObjectsOfType(); - foreach (Rigidbody rb in arrayOfAllRB) { + foreach (Rigidbody rb in arrayOfAllRB) + { // first make sure it' a sim object - if (rb.GetComponentInParent()) { + if (rb.GetComponentInParent()) + { // ok now make sure that the sim object is moveable or pickupable SimObjPhysics sop = rb.GetComponentInParent(); - if (sop.PrimaryProperty == SimObjPrimaryProperty.Moveable || sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup) { - if (!rb.GetComponent()) { + if ( + sop.PrimaryProperty == SimObjPrimaryProperty.Moveable + || sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup + ) + { + if (!rb.GetComponent()) + { // don't add object if it's in an object specific receptacle-so things like towels and toilet paper that are mounted by default if (sop.transform.parent.name != "AttachPoint") filter.Add(rb); } } - IgnoreCollision[] ignoreCollisionObjects = sop.GetComponentsInChildren(); - foreach (IgnoreCollision ic in ignoreCollisionObjects) { + IgnoreCollision[] ignoreCollisionObjects = + sop.GetComponentsInChildren(); + foreach (IgnoreCollision ic in ignoreCollisionObjects) + { ic.SetupIgnoreCollision(); } } } // Normally avoid Find functions, but this is editor time and only happens once - workList = filter.ToArray();// Object.FindObjectsOfType(); + workList = filter.ToArray(); // Object.FindObjectsOfType(); // we will need to ensure autoSimulation is off to manually tick physics cachedAutoSimulation = Physics.autoSimulation; activeTime = 0f; // make sure that all rigidbodies are awake so they will actively settle against changed geometry. - foreach (Rigidbody body in workList) { + foreach (Rigidbody body in workList) + { body.isKinematic = false; body.WakeUp(); } @@ -84,47 +99,64 @@ static void Activate() { // grey out the menu item while we are settling physics [MenuItem("GameMenu/Settle Physics", true)] - static bool checkMenu() { + static bool checkMenu() + { return !active; } - static void Update() { - if (active) { + static void Update() + { + if (active) + { activeTime += Time.deltaTime; // make sure we are not autosimulating Physics.autoSimulation = false; - // see if all our + // see if all our bool allSleeping = true; - foreach (Rigidbody body in workList) { - if (body != null) { + foreach (Rigidbody body in workList) + { + if (body != null) + { allSleeping &= body.IsSleeping(); } } - if (allSleeping || activeTime >= timeToSettle) { + if (allSleeping || activeTime >= timeToSettle) + { Physics.autoSimulation = cachedAutoSimulation; active = false; - } else { + } + else + { PhysicsSceneManager.PhysicsSimulateTHOR(0.01f); } } } - static void OnSceneGUI(SceneView sceneView) { - if (active) { + static void OnSceneGUI(SceneView sceneView) + { + if (active) + { Handles.BeginGUI(); Color cacheColor = GUI.color; GUI.color = Color.red; GUILayout.Label("Simulating Physics.", GUI.skin.box, GUILayout.Width(200)); - GUILayout.Label(string.Format("Time Remaining: {0:F2}", (timeToSettle - activeTime)), GUI.skin.box, GUILayout.Width(200)); + GUILayout.Label( + string.Format("Time Remaining: {0:F2}", (timeToSettle - activeTime)), + GUI.skin.box, + GUILayout.Width(200) + ); Handles.EndGUI(); - foreach (Rigidbody body in workList) { - if (body != null) { + foreach (Rigidbody body in workList) + { + if (body != null) + { bool isSleeping = body.IsSleeping(); - if (!isSleeping) { + if (!isSleeping) + { GUI.color = Color.green; Handles.Label(body.transform.position, "SIMULATING"); } diff --git a/unity/Assets/Editor/ReceptacleEditor.cs b/unity/Assets/Editor/ReceptacleEditor.cs index 9178633134..6883431696 100644 --- a/unity/Assets/Editor/ReceptacleEditor.cs +++ b/unity/Assets/Editor/ReceptacleEditor.cs @@ -1,26 +1,35 @@ -using UnityEngine; -using UnityEditor; -using System; +using System; using System.Collections.Generic; +using UnityEditor; +using UnityEngine; [CustomEditor(typeof(Receptacle))] -public class ReceptacleEditor : Editor { - public override void OnInspectorGUI() { +public class ReceptacleEditor : Editor +{ + public override void OnInspectorGUI() + { Receptacle r = (Receptacle)target; GUI.color = Color.grey; EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUI.color = Color.white; EditorGUILayout.LabelField("Visibility Collider:", EditorStyles.miniLabel); - if (r.VisibilityCollider == null) { + if (r.VisibilityCollider == null) + { GUI.color = Color.Lerp(Color.red, Color.white, 0.5f); - EditorGUILayout.TextArea("You must define a visibility collider.\n" + - "If the item does not close, this should be the main collider.\n" + - "If the item closes, it should be a collider that is obscured when it is closed.", EditorStyles.miniLabel); + EditorGUILayout.TextArea( + "You must define a visibility collider.\n" + + "If the item does not close, this should be the main collider.\n" + + "If the item closes, it should be a collider that is obscured when it is closed.", + EditorStyles.miniLabel + ); CheckForDragDropColliders(r); - } else { - r.VisibilityCollider = (Collider)EditorGUILayout.ObjectField(r.VisibilityCollider, typeof(Collider), false); + } + else + { + r.VisibilityCollider = (Collider) + EditorGUILayout.ObjectField(r.VisibilityCollider, typeof(Collider), false); } EditorGUILayout.EndVertical(); @@ -32,43 +41,60 @@ public override void OnInspectorGUI() { EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUI.color = Color.white; EditorGUILayout.LabelField("Pivots:", EditorStyles.miniLabel); - if (r.Pivots == null) { + if (r.Pivots == null) + { r.Pivots = new Transform[0]; } - if (r.Pivots.Length == 0) { + if (r.Pivots.Length == 0) + { GUI.color = Color.Lerp(Color.red, Color.white, 0.5f); EditorGUILayout.LabelField("Receptacle has no pivots!"); - } else { + } + else + { int deletedPivotIndex = -1; // check for null objects in the pivot list - for (int i = 0; i < r.Pivots.Length; i++) { - if (r.Pivots[i] == null) { + for (int i = 0; i < r.Pivots.Length; i++) + { + if (r.Pivots[i] == null) + { deletedPivotIndex = i; break; } } - if (deletedPivotIndex < 0) { + if (deletedPivotIndex < 0) + { EditorGUILayout.BeginHorizontal(); - for (int i = 0; i < r.Pivots.Length; i++) { + for (int i = 0; i < r.Pivots.Length; i++) + { GUI.color = Color.white; string pivotDesc = r.Pivots[i].name; string itemDesc = string.Empty; - if (r.Pivots[i].childCount > 0) { + if (r.Pivots[i].childCount > 0) + { GUI.color = Color.Lerp(Color.green, Color.white, 0.5f); - if (r.Pivots[i].childCount > 1) { + if (r.Pivots[i].childCount > 1) + { GUI.color = Color.Lerp(Color.red, Color.white, 0.5f); itemDesc = "Too many items under pivot!"; - } else { + } + else + { SimObj o = r.Pivots[i].GetChild(0).GetComponent(); - if (o == null) { + if (o == null) + { GUI.color = Color.Lerp(Color.red, Color.white, 0.5f); itemDesc = "Contained item is NOT a SimObj!"; - } else { + } + else + { itemDesc = r.Pivots[i].GetChild(0).name; } } - } else { + } + else + { GUI.color = Color.white; itemDesc = "Empty\n(Drag-drop SimObj here to add to pivot)"; } @@ -77,21 +103,25 @@ public override void OnInspectorGUI() { EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); - for (int i = 0; i < r.Pivots.Length; i++) { + for (int i = 0; i < r.Pivots.Length; i++) + { CheckForClearAndDelete(r, i, ref deletedPivotIndex); } EditorGUILayout.EndHorizontal(); } - if (deletedPivotIndex >= 0) { + if (deletedPivotIndex >= 0) + { // remove the pivot from the array List newPivotList = new List(r.Pivots); newPivotList.RemoveAt(deletedPivotIndex); r.Pivots = newPivotList.ToArray(); } } - if (GUILayout.Button("Set pivots to UP")) { - foreach (Transform pivot in r.Pivots) { + if (GUILayout.Button("Set pivots to UP")) + { + foreach (Transform pivot in r.Pivots) + { Transform tempParent = pivot.parent; pivot.parent = null; pivot.up = Vector3.up; @@ -107,51 +137,64 @@ public override void OnInspectorGUI() { GUI.color = Color.white; EditorGUILayout.LabelField("Mess item:", EditorStyles.miniLabel); r.MessItem = (GameObject)EditorGUILayout.ObjectField(r.MessItem, typeof(GameObject), false); - if (r.MessItem != null) { - if (!r.MessItem.transform.IsChildOf(r.transform)) { + if (r.MessItem != null) + { + if (!r.MessItem.transform.IsChildOf(r.transform)) + { r.MessItem = null; - } else { + } + else + { r.IsClean = GUILayout.Toggle(r.IsClean, "Is clean"); } } EditorGUILayout.EndVertical(); } - void CheckForClearAndDelete(Receptacle r, int index, ref int deletedPivotIndex) { + void CheckForClearAndDelete(Receptacle r, int index, ref int deletedPivotIndex) + { EditorGUILayout.BeginVertical(); - Rect deleteArea = GUILayoutUtility.GetRect( - 100.0f, - 25.0f); + Rect deleteArea = GUILayoutUtility.GetRect(100.0f, 25.0f); GUI.color = Color.Lerp(Color.grey, Color.yellow, 0.5f); - if (GUI.Button(deleteArea, "Delete pivot")) { - if (EditorUtility.DisplayDialog("Delete pivot", "Are you sure you want to delete pivot?", "Yes", "Cancel")) { + if (GUI.Button(deleteArea, "Delete pivot")) + { + if ( + EditorUtility.DisplayDialog( + "Delete pivot", + "Are you sure you want to delete pivot?", + "Yes", + "Cancel" + ) + ) + { deletedPivotIndex = index; } } - Rect removeArea = GUILayoutUtility.GetRect( - 100.0f, - 25.0f); - if (r.Pivots[index].childCount > 0) { + Rect removeArea = GUILayoutUtility.GetRect(100.0f, 25.0f); + if (r.Pivots[index].childCount > 0) + { GUI.color = Color.white; - } else { + } + else + { GUI.color = Color.grey; } - if (GUI.Button(removeArea, "Clear pivot") && r.Pivots[index].transform.childCount > 0) { + if (GUI.Button(removeArea, "Clear pivot") && r.Pivots[index].transform.childCount > 0) + { Transform item = r.Pivots[index].GetChild(0); SimUtil.TakeItem(item.GetComponent()); } EditorGUILayout.EndVertical(); - } - void CheckForDragDropColliders(Receptacle r) { + void CheckForDragDropColliders(Receptacle r) + { Event evt = Event.current; - Rect dropArea = GUILayoutUtility.GetRect( - 100.0f, - 100.0f); + Rect dropArea = GUILayoutUtility.GetRect(100.0f, 100.0f); GUI.Box(dropArea, "Drag-drop visibility collider here", EditorStyles.helpBox); - switch (evt.type) { + switch (evt.type) + { case EventType.DragUpdated: case EventType.DragPerform: if (!dropArea.Contains(evt.mousePosition)) @@ -159,10 +202,12 @@ void CheckForDragDropColliders(Receptacle r) { DragAndDrop.visualMode = DragAndDropVisualMode.Generic; - if (evt.type == EventType.DragPerform) { + if (evt.type == EventType.DragPerform) + { DragAndDrop.AcceptDrag(); - foreach (UnityEngine.Object draggedItem in DragAndDrop.objectReferences) { + foreach (UnityEngine.Object draggedItem in DragAndDrop.objectReferences) + { TryToSetVisibilityCollider(r, draggedItem); } } @@ -170,40 +215,44 @@ void CheckForDragDropColliders(Receptacle r) { } } - void TryToSetVisibilityCollider(Receptacle r, UnityEngine.Object potentialCollider) { + void TryToSetVisibilityCollider(Receptacle r, UnityEngine.Object potentialCollider) + { GameObject coGo = (GameObject)potentialCollider; - if (coGo == null) { + if (coGo == null) + { Debug.Log("Couldn't cast to gameobject, not adding"); return; } Collider c = coGo.GetComponent(); - if (c == null) { + if (c == null) + { Debug.Log("No collider attached, not adding"); return; } - if (!c.transform.IsChildOf(r.transform) && coGo != r.gameObject) { - Debug.Log("Visibility collider must be the receptacle or a child of the receptacle, not adding"); + if (!c.transform.IsChildOf(r.transform) && coGo != r.gameObject) + { + Debug.Log( + "Visibility collider must be the receptacle or a child of the receptacle, not adding" + ); } r.VisibilityCollider = c; } - void CheckForDragDropItems(Receptacle r, Transform pivot, string pivotDesc, string itemDesc) { + void CheckForDragDropItems(Receptacle r, Transform pivot, string pivotDesc, string itemDesc) + { Event evt = Event.current; EditorGUILayout.BeginVertical(); - Rect labelArea = GUILayoutUtility.GetRect( - 100.0f, - 20.0f); + Rect labelArea = GUILayoutUtility.GetRect(100.0f, 20.0f); GUI.Button(labelArea, pivotDesc, EditorStyles.toolbarButton); - Rect dropArea = GUILayoutUtility.GetRect( - 100.0f, - 100.0f); + Rect dropArea = GUILayoutUtility.GetRect(100.0f, 100.0f); GUI.Box(dropArea, itemDesc, EditorStyles.helpBox); EditorGUILayout.EndVertical(); - switch (evt.type) { + switch (evt.type) + { case EventType.DragUpdated: case EventType.DragPerform: if (!dropArea.Contains(evt.mousePosition)) @@ -211,10 +260,12 @@ void CheckForDragDropItems(Receptacle r, Transform pivot, string pivotDesc, stri DragAndDrop.visualMode = DragAndDropVisualMode.Generic; - if (evt.type == EventType.DragPerform) { + if (evt.type == EventType.DragPerform) + { DragAndDrop.AcceptDrag(); - foreach (UnityEngine.Object draggedItem in DragAndDrop.objectReferences) { + foreach (UnityEngine.Object draggedItem in DragAndDrop.objectReferences) + { TryToAddItem(draggedItem, pivot, r); } } @@ -222,36 +273,45 @@ void CheckForDragDropItems(Receptacle r, Transform pivot, string pivotDesc, stri } } - void TryToAddItem(UnityEngine.Object item, Transform pivot, Receptacle r) { - if (pivot.childCount > 0) { + void TryToAddItem(UnityEngine.Object item, Transform pivot, Receptacle r) + { + if (pivot.childCount > 0) + { Debug.Log("Pivot is already filled, not adding item"); return; } - if (EditorUtility.IsPersistent(r)) { + if (EditorUtility.IsPersistent(r)) + { Debug.Log("Can't add items to a recepticle when not in scene, not adding"); return; } GameObject itemGo = null; - try { + try + { itemGo = (GameObject)item; - } catch (Exception e) { + } + catch (Exception e) + { Debug.Log(e); return; } - if (item == null) { + if (item == null) + { Debug.Log("Item was null, not adding"); return; } - if (itemGo == r.gameObject || itemGo.transform.IsChildOf(r.transform)) { + if (itemGo == r.gameObject || itemGo.transform.IsChildOf(r.transform)) + { Debug.Log("Can't add item to itself, not adding"); return; } - if (EditorUtility.IsPersistent(itemGo)) { + if (EditorUtility.IsPersistent(itemGo)) + { // instantiate the object Debug.Log("Instantiating " + itemGo.name + " and placing in the scene"); itemGo = GameObject.Instantiate(itemGo) as GameObject; @@ -259,15 +319,20 @@ void TryToAddItem(UnityEngine.Object item, Transform pivot, Receptacle r) { } SimObj o = itemGo.GetComponent(); - if (o == null) { + if (o == null) + { Debug.Log("Item was not a SimObj, not adding"); return; } - for (int i = 0; i < r.Pivots.Length; i++) { - if (r.Pivots[i].childCount > 0) { - foreach (Transform c in r.Pivots[i]) { - if (c == itemGo.transform) { + for (int i = 0; i < r.Pivots.Length; i++) + { + if (r.Pivots[i].childCount > 0) + { + foreach (Transform c in r.Pivots[i]) + { + if (c == itemGo.transform) + { Debug.Log("Item is already in a pivot, not adding"); return; } @@ -281,13 +346,15 @@ void TryToAddItem(UnityEngine.Object item, Transform pivot, Receptacle r) { // don't scale the item } - void CheckForDragDropPivots(Receptacle r) { + void CheckForDragDropPivots(Receptacle r) + { Event evt = Event.current; EditorGUILayout.LabelField(""); Rect dropArea = GUILayoutUtility.GetRect(0.0f, 35.0f, GUILayout.ExpandWidth(true)); GUI.Box(dropArea, "Drag-drop transforms here to add pivots", EditorStyles.helpBox); - switch (evt.type) { + switch (evt.type) + { case EventType.DragUpdated: case EventType.DragPerform: if (!dropArea.Contains(evt.mousePosition)) @@ -295,10 +362,12 @@ void CheckForDragDropPivots(Receptacle r) { DragAndDrop.visualMode = DragAndDropVisualMode.Generic; - if (evt.type == EventType.DragPerform) { + if (evt.type == EventType.DragPerform) + { DragAndDrop.AcceptDrag(); - foreach (UnityEngine.Object draggedTransform in DragAndDrop.objectReferences) { + foreach (UnityEngine.Object draggedTransform in DragAndDrop.objectReferences) + { TryToAddPivot(draggedTransform, r); } } @@ -306,28 +375,36 @@ void CheckForDragDropPivots(Receptacle r) { } } - void TryToAddPivot(UnityEngine.Object potentialPivot, Receptacle r) { + void TryToAddPivot(UnityEngine.Object potentialPivot, Receptacle r) + { GameObject pivot = null; - try { + try + { pivot = (GameObject)potentialPivot; - } catch (Exception e) { + } + catch (Exception e) + { // if we can't cast, forget it Debug.Log(e); return; } - if (pivot == null) { + if (pivot == null) + { Debug.Log("Pivot is null, not accepting"); return; } - if (!pivot.transform.IsChildOf(r.transform)) { + if (!pivot.transform.IsChildOf(r.transform)) + { Debug.Log("Pivot is not a child of receptcale, not accepting"); return; } - for (int i = 0; i < r.Pivots.Length; i++) { - if (r.Pivots[i] == pivot.transform) { + for (int i = 0; i < r.Pivots.Length; i++) + { + if (r.Pivots[i] == pivot.transform) + { Debug.Log("Pivot is already in list, not accepting"); return; } @@ -337,4 +414,4 @@ void TryToAddPivot(UnityEngine.Object potentialPivot, Receptacle r) { Array.Resize(ref r.Pivots, r.Pivots.Length + 1); r.Pivots[r.Pivots.Length - 1] = pivot.transform; } -} \ No newline at end of file +} diff --git a/unity/Assets/Editor/ReceptacleTriggerBoxEditor.cs b/unity/Assets/Editor/ReceptacleTriggerBoxEditor.cs index 98dae5a4e6..793eed26a3 100644 --- a/unity/Assets/Editor/ReceptacleTriggerBoxEditor.cs +++ b/unity/Assets/Editor/ReceptacleTriggerBoxEditor.cs @@ -1,20 +1,27 @@ -using UnityEngine; -using UnityEditor; using System; using System.Collections.Generic; using System.Linq; +using UnityEditor; +using UnityEngine; -public class ReceptacleTriggerBoxEditor : EditorWindow { - +public class ReceptacleTriggerBoxEditor : EditorWindow +{ [MenuItem("Receptacles/Try create receptacle trigger box for object")] - public static void TryToAddReceptacleTriggerBoxFromSelected() { + public static void TryToAddReceptacleTriggerBoxFromSelected() + { GameObject obj = Selection.activeGameObject; SimObjPhysics sop = obj.GetComponent(); TryToAddReceptacleTriggerBox(sop); } - public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresMax = 0.075f, float worldOffset=-100f) { - if (sop == null) { + public static void TryToAddReceptacleTriggerBox( + SimObjPhysics sop, + float yThresMax = 0.075f, + float worldOffset = -100f + ) + { + if (sop == null) + { throw new NotImplementedException( $"Adding receptacle trigger box is only possible the active game object, has an associated SimObjPhysics script." ); @@ -25,18 +32,22 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM List tmpMeshColliders = new List(); List enabledColliders = new List(); - foreach (Collider c in sop.GetComponentsInChildren()) { - if (c.enabled) { + foreach (Collider c in sop.GetComponentsInChildren()) + { + if (c.enabled) + { enabledColliders.Add(c); c.enabled = false; } } - try { + try + { sop.transform.rotation = Quaternion.identity; sop.transform.position = new Vector3(worldOffset, worldOffset, worldOffset); sop.GetComponent().isKinematic = true; - foreach (MeshFilter mf in sop.GetComponentsInChildren()) { + foreach (MeshFilter mf in sop.GetComponentsInChildren()) + { GameObject tmpGo = new GameObject(); tmpGo.layer = LayerMask.NameToLayer("SimObjVisible"); tmpGo.transform.position = mf.gameObject.transform.position; @@ -74,35 +85,45 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM List> mat = new List>(); int n = 30; - for (int iX = 0; iX < n; iX++) { + for (int iX = 0; iX < n; iX++) + { float x = xMin + iX * (xMax - xMin) / (n - 1.0f); // Debug.Log($"x val: {x}"); var yVals = new List(); - for (int iZ = 0; iZ < n; iZ++) { + for (int iZ = 0; iZ < n; iZ++) + { float z = zMin + iZ * (zMax - zMin) / (n - 1.0f); // Debug.Log($"Pos: ({iX}, {iZ}), vals ({x}, {z})"); RaycastHit hit; - if (Physics.Raycast( - origin: new Vector3(x, yStart, z), - direction: new Vector3(0f, -1f, 0f), - hitInfo: out hit, - maxDistance: 10f, - layerMask: LayerMask.GetMask("SimObjVisible"), - queryTriggerInteraction: QueryTriggerInteraction.Ignore - )) { + if ( + Physics.Raycast( + origin: new Vector3(x, yStart, z), + direction: new Vector3(0f, -1f, 0f), + hitInfo: out hit, + maxDistance: 10f, + layerMask: LayerMask.GetMask("SimObjVisible"), + queryTriggerInteraction: QueryTriggerInteraction.Ignore + ) + ) + { // Debug.Log($"HITS {hit.point.y}"); // Debug.DrawLine(hit.point, hit.point + new Vector3(0f, 0.1f, 0f), Color.cyan, 15f); - if (Vector3.Angle(hit.normal, Vector3.up) < 30f) { + if (Vector3.Angle(hit.normal, Vector3.up) < 30f) + { yVals.Add(hit.point.y); Debug.Log(hit.point.y); - } else { + } + else + { yVals.Add(dummyY); } - } else { + } + else + { yVals.Add(dummyY); } } @@ -115,28 +136,33 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM Dictionary> groupToPos = new Dictionary>(); int nextGroup = 0; - for (int iX = 0; iX < n; iX++) { - for (int iZ = 0; iZ < n; iZ++) { + for (int iX = 0; iX < n; iX++) + { + for (int iZ = 0; iZ < n; iZ++) + { // Debug.Log($"Pos: ({iX}, {iZ})"); float curYVal = mat[iX][iZ]; // Debug.Log($"Cur Y: {curYVal}"); - if (curYVal == dummyY) { + if (curYVal == dummyY) + { posToGroup[(iX, iZ)] = -1; groupToMaxYVal[-1] = dummyY; groupToMinYVal[-1] = dummyY; continue; } - if (iX > 0) { + if (iX > 0) + { int group = posToGroup[(iX - 1, iZ)]; float otherMaxYVal = groupToMaxYVal[group]; float otherMinYVal = groupToMinYVal[group]; if ( - Mathf.Abs(curYVal - otherMaxYVal) < yThres && - Mathf.Abs(curYVal - otherMinYVal) < yThres - ) { + Mathf.Abs(curYVal - otherMaxYVal) < yThres + && Mathf.Abs(curYVal - otherMinYVal) < yThres + ) + { posToGroup[(iX, iZ)] = group; groupToPos[group].Add((iX, iZ)); groupToMaxYVal[group] = Mathf.Max(curYVal, otherMaxYVal); @@ -145,15 +171,17 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM } } - if (iZ > 0) { + if (iZ > 0) + { int group = posToGroup[(iX, iZ - 1)]; float otherMaxYVal = groupToMaxYVal[group]; float otherMinYVal = groupToMinYVal[group]; if ( - Mathf.Abs(curYVal - otherMaxYVal) < yThres && - Mathf.Abs(curYVal - otherMinYVal) < yThres - ) { + Mathf.Abs(curYVal - otherMaxYVal) < yThres + && Mathf.Abs(curYVal - otherMinYVal) < yThres + ) + { posToGroup[(iX, iZ)] = group; groupToPos[group].Add((iX, iZ)); groupToMaxYVal[group] = Mathf.Max(curYVal, otherMaxYVal); @@ -172,42 +200,51 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM } var groupToRectangles = new Dictionary>(); - foreach (int group in groupToPos.Keys) { + foreach (int group in groupToPos.Keys) + { var posSet = new HashSet<(int, int)>(groupToPos[group]); List<((int, int), (int, int))> rectangles = new List<((int, int), (int, int))>(); - while (posSet.Count > 0) { + while (posSet.Count > 0) + { (int, int) nextiXiZ = posSet.Min(); int startIX = nextiXiZ.Item1; int startIZ = nextiXiZ.Item2; int k = 1; - while (posSet.Contains((startIX + k, startIZ))) { + while (posSet.Contains((startIX + k, startIZ))) + { k++; } int endIX = startIX + k - 1; k = 1; - while (true) { + while (true) + { bool allContained = true; - for (int iX = startIX; iX <= endIX; iX++) { - if (!posSet.Contains((iX, startIZ + k))) { + for (int iX = startIX; iX <= endIX; iX++) + { + if (!posSet.Contains((iX, startIZ + k))) + { allContained = false; break; } } - if (!allContained) { + if (!allContained) + { break; } k++; } int endIZ = startIZ + k - 1; - for (int iX = startIX; iX <= endIX; iX++) { - for (int iZ = startIZ; iZ <= endIZ; iZ++) { + for (int iX = startIX; iX <= endIX; iX++) + { + for (int iZ = startIZ; iZ <= endIZ; iZ++) + { posSet.Remove((iX, iZ)); } } @@ -218,12 +255,22 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM } var vector3CornerLists = new List>(); - List colors = new List{Color.cyan, Color.yellow, Color.red, Color.magenta, Color.green, Color.blue}; + List colors = new List + { + Color.cyan, + Color.yellow, + Color.red, + Color.magenta, + Color.green, + Color.blue + }; int yar = -1; - foreach (int group in groupToRectangles.Keys) { + foreach (int group in groupToRectangles.Keys) + { float y = groupToMinYVal[group]; - foreach (((int, int), (int, int)) extents in groupToRectangles[group]) { + foreach (((int, int), (int, int)) extents in groupToRectangles[group]) + { yar++; (int, int) start = extents.Item1; (int, int) end = extents.Item2; @@ -231,10 +278,16 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM float startX = xMin + (start.Item1 - 0.5f) * (xMax - xMin) / (n - 1.0f); float endX = xMin + (end.Item1 + 0.5f) * (xMax - xMin) / (n - 1.0f); - float startZ = zMin + (start.Item2 - 0.5f) * (zMax - zMin) / (n - 1.0f); + float startZ = zMin + (start.Item2 - 0.5f) * (zMax - zMin) / (n - 1.0f); float endZ = zMin + (end.Item2 + 0.5f) * (zMax - zMin) / (n - 1.0f); - if (Math.Min(Math.Abs(start.Item1 - end.Item1), Math.Abs(start.Item2 - end.Item2)) <= 1) { + if ( + Math.Min( + Math.Abs(start.Item1 - end.Item1), + Math.Abs(start.Item2 - end.Item2) + ) <= 1 + ) + { continue; } @@ -256,10 +309,12 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM Transform t = sop.transform.Find("ReceptacleTriggerBoxes"); GameObject go = null; - if (t != null) { + if (t != null) + { DestroyImmediate(t.gameObject); } - if (t == null) { + if (t == null) + { go = new GameObject("ReceptacleTriggerBoxes"); go.transform.position = sop.transform.position; go.transform.parent = sop.transform; @@ -268,7 +323,8 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM int cornerListInd = 0; List boxGos = new List(); - foreach (List cornerList in vector3CornerLists) { + foreach (List cornerList in vector3CornerLists) + { Vector3 c0 = cornerList[0]; Vector3 c1 = cornerList[1]; Vector3 c2 = cornerList[2]; @@ -280,23 +336,30 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM rtb.transform.parent = go.transform; rtb.layer = LayerMask.NameToLayer("SimObjInvisible"); BoxCollider bc = rtb.AddComponent(); - bc.center = (c0 + c1 + c2 + c3) * 0.25f - rtb.transform.position + new Vector3(0f, rtbYSize / 2.0f, 0f); + bc.center = + (c0 + c1 + c2 + c3) * 0.25f + - rtb.transform.position + + new Vector3(0f, rtbYSize / 2.0f, 0f); bc.size = c2 - c0 + new Vector3(0f, rtbYSize, 0f); bc.isTrigger = true; } sop.ReceptacleTriggerBoxes = boxGos.ToArray(); - } finally { + } + finally + { sop.transform.position = oldPos; sop.transform.rotation = oldRot; sop.GetComponent().isKinematic = false; - foreach (MeshCollider tmc in tmpMeshColliders) { + foreach (MeshCollider tmc in tmpMeshColliders) + { DestroyImmediate(tmc.gameObject); } - foreach (Collider c in enabledColliders) { + foreach (Collider c in enabledColliders) + { c.enabled = true; } Physics.SyncTransforms(); } } -} \ No newline at end of file +} diff --git a/unity/Assets/Editor/SceneManagerEditor.cs b/unity/Assets/Editor/SceneManagerEditor.cs index b6f742f80e..adc5cf6ef7 100644 --- a/unity/Assets/Editor/SceneManagerEditor.cs +++ b/unity/Assets/Editor/SceneManagerEditor.cs @@ -1,23 +1,25 @@ -using UnityEngine; -using UnityEditor; +using System; using System.Collections.Generic; using System.Text.RegularExpressions; -using System; +using UnityEditor; +using UnityEngine; using UnityEngine.SceneManagement; [CustomEditor(typeof(SceneManager))] -public class SceneManagerEditor : Editor { - public BuildTarget[] Targets = new BuildTarget[] { +public class SceneManagerEditor : Editor +{ + public BuildTarget[] Targets = new BuildTarget[] + { #if UNITY_2017_3_OR_NEWER - BuildTarget.StandaloneOSX, + BuildTarget.StandaloneOSX, #else - BuildTarget.StandaloneOSXIntel, - BuildTarget.StandaloneOSXIntel64, + BuildTarget.StandaloneOSXIntel, + BuildTarget.StandaloneOSXIntel64, #endif - BuildTarget.StandaloneLinux64, - // BuildTarget.StandaloneLinux, - // BuildTarget.StandaloneLinuxUniversal, - BuildTarget.StandaloneWindows, + BuildTarget.StandaloneLinux64, + // BuildTarget.StandaloneLinux, + // BuildTarget.StandaloneLinuxUniversal, + BuildTarget.StandaloneWindows, BuildTarget.StandaloneWindows64, }; public SimObjType SelectionType; @@ -31,7 +33,8 @@ public class SceneManagerEditor : Editor { static string outputPath; static bool launchOnBuild = false; - public override void OnInspectorGUI() { + public override void OnInspectorGUI() + { SceneManager sm = (SceneManager)target; GUI.color = Color.white; @@ -41,48 +44,86 @@ public override void OnInspectorGUI() { GUI.color = Color.white; sm.SceneNumber = EditorGUILayout.IntField("Scene Number", sm.SceneNumber); sm.LocalSceneType = (SceneType)EditorGUILayout.EnumPopup("Scene Type", sm.LocalSceneType); - sm.LocalPhysicsMode = (ScenePhysicsMode)EditorGUILayout.EnumPopup("Physics Mode", sm.LocalPhysicsMode); - sm.AnimationMode = (SceneAnimationMode)EditorGUILayout.EnumPopup("Animation Mode", sm.AnimationMode); + sm.LocalPhysicsMode = (ScenePhysicsMode) + EditorGUILayout.EnumPopup("Physics Mode", sm.LocalPhysicsMode); + sm.AnimationMode = (SceneAnimationMode) + EditorGUILayout.EnumPopup("Animation Mode", sm.AnimationMode); EditorUtility.SetDirty(sm.gameObject); EditorUtility.SetDirty(sm); - if (!Application.isPlaying) { - UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene()); + if (!Application.isPlaying) + { + UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty( + UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene() + ); } - sm.FPSControllerPrefab = (GameObject)EditorGUILayout.ObjectField("FPS controller prefab:", sm.FPSControllerPrefab, typeof(GameObject), false); + sm.FPSControllerPrefab = (GameObject) + EditorGUILayout.ObjectField( + "FPS controller prefab:", + sm.FPSControllerPrefab, + typeof(GameObject), + false + ); EditorGUILayout.LabelField("Actions:", EditorStyles.miniLabel); - if (GUILayout.Button("Check for required object types", GUILayout.MaxWidth(300))) { + if (GUILayout.Button("Check for required object types", GUILayout.MaxWidth(300))) + { TypesNotFound = sm.CheckSceneForRequiredTypes(); ShowRequiredTypeCheckResult = true; } - if (ShowRequiredTypeCheckResult) { - if (TypesNotFound != null && TypesNotFound.Length > 0) { + if (ShowRequiredTypeCheckResult) + { + if (TypesNotFound != null && TypesNotFound.Length > 0) + { GUI.color = Color.Lerp(Color.red, Color.white, 0.5f); - EditorGUILayout.LabelField("The following required types were NOT found:", EditorStyles.boldLabel); - for (int i = 0; i < TypesNotFound.Length; i++) { - EditorGUILayout.LabelField(" - " + TypesNotFound[i].ToString(), EditorStyles.miniLabel); + EditorGUILayout.LabelField( + "The following required types were NOT found:", + EditorStyles.boldLabel + ); + for (int i = 0; i < TypesNotFound.Length; i++) + { + EditorGUILayout.LabelField( + " - " + TypesNotFound[i].ToString(), + EditorStyles.miniLabel + ); } - } else { + } + else + { GUI.color = Color.Lerp(Color.green, Color.white, 0.5f); - EditorGUILayout.LabelField("All required types were found!", EditorStyles.boldLabel); + EditorGUILayout.LabelField( + "All required types were found!", + EditorStyles.boldLabel + ); } - if (GUILayout.Button("OK", GUILayout.MaxWidth(125))) { + if (GUILayout.Button("OK", GUILayout.MaxWidth(125))) + { ShowRequiredTypeCheckResult = false; } } GUI.color = Color.white; - if (GUILayout.Button("Gather SimObjs and assign object IDs", GUILayout.MaxWidth(300))) { + if (GUILayout.Button("Gather SimObjs and assign object IDs", GUILayout.MaxWidth(300))) + { sm.GatherSimObjsInScene(); } - if (GUILayout.Button("Gather objects under parent folders", GUILayout.MaxWidth(300))) { + if (GUILayout.Button("Gather objects under parent folders", GUILayout.MaxWidth(300))) + { sm.GatherObjectsUnderParents(); } /*if (GUILayout.Button ("Set up FPS controller", GUILayout.MaxWidth(300))) { - sm.SetUpFPSController (); - }*/ - if (GUILayout.Button("Replace generics with platonic objects", GUILayout.MaxWidth(300))) { - if (EditorUtility.DisplayDialog("Confirm replace", "Are you SURE you want to do this?", "Yes", "Cancel")) { + sm.SetUpFPSController (); + }*/ + if (GUILayout.Button("Replace generics with platonic objects", GUILayout.MaxWidth(300))) + { + if ( + EditorUtility.DisplayDialog( + "Confirm replace", + "Are you SURE you want to do this?", + "Yes", + "Cancel" + ) + ) + { sm.ReplaceGenerics(); sm.GatherSimObjsInScene(); } @@ -95,40 +136,57 @@ public override void OnInspectorGUI() { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Objects in scene:", EditorStyles.miniLabel); - if (GUILayout.Button("Show / Hide", EditorStyles.toolbarButton, GUILayout.MaxWidth(125))) { + if (GUILayout.Button("Show / Hide", EditorStyles.toolbarButton, GUILayout.MaxWidth(125))) + { ShowSceneObjects = !ShowSceneObjects; } EditorGUILayout.EndHorizontal(); - if (ShowSceneObjects) { - if (sm.ObjectsInScene.Count == 0) { + if (ShowSceneObjects) + { + if (sm.ObjectsInScene.Count == 0) + { GUI.color = Color.Lerp(Color.white, Color.red, 0.5f); EditorGUILayout.LabelField("(None found)"); - } else { + } + else + { HashSet objectIDsSoFar = new HashSet(); - for (int i = 0; i < sm.ObjectsInScene.Count; i++) { - if (sm.ObjectsInScene[i] == null) { + for (int i = 0; i < sm.ObjectsInScene.Count; i++) + { + if (sm.ObjectsInScene[i] == null) + { Debug.Log("Found null items in sm objects list, returning"); sm.ObjectsInScene.Clear(); break; } - if (!string.IsNullOrEmpty(sm.ObjectsInScene[i].Error)) { + if (!string.IsNullOrEmpty(sm.ObjectsInScene[i].Error)) + { GUI.color = Color.Lerp(Color.red, Color.white, 0.5f); - } else { + } + else + { GUI.color = Color.white; } string buttonText = string.Empty; - if (!SimUtil.IsObjectIDValid(sm.ObjectsInScene[i].ObjectID)) { + if (!SimUtil.IsObjectIDValid(sm.ObjectsInScene[i].ObjectID)) + { buttonText = sm.ObjectsInScene[i].Type.ToString() + ": (No ID)"; - } else { - if (!objectIDsSoFar.Add(sm.ObjectsInScene[i].ObjectID)) { + } + else + { + if (!objectIDsSoFar.Add(sm.ObjectsInScene[i].ObjectID)) + { GUI.color = Color.Lerp(Color.red, Color.white, 0.5f); buttonText = "ERROR: DUPLICATE ID! " + sm.ObjectsInScene[i].ObjectID; - } else { + } + else + { buttonText = sm.ObjectsInScene[i].ObjectID; } } - if (GUILayout.Button(buttonText, EditorStyles.miniButton)) { + if (GUILayout.Button(buttonText, EditorStyles.miniButton)) + { UnityEditor.Selection.activeGameObject = sm.ObjectsInScene[i].gameObject; } } @@ -140,67 +198,93 @@ public override void OnInspectorGUI() { EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUI.color = Color.white; EditorGUILayout.LabelField("Item placement:", EditorStyles.miniLabel); - if (GUILayout.Button("Auto-assign navmesh layers", GUILayout.MaxWidth(300))) { + if (GUILayout.Button("Auto-assign navmesh layers", GUILayout.MaxWidth(300))) + { sm.AutoStructureNavigation(); } EditorGUILayout.EndVertical(); - GUI.color = Color.white; EditorGUILayout.LabelField("Build Options", EditorStyles.miniLabel); GUI.color = Color.grey; EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUI.color = Color.white; /*if (!showBuildOptions) { - if (GUILayout.Button ("Show", EditorStyles.miniButton)) { - showBuildOptions = true; - } - } else if (GUILayout.Button ("Hide", EditorStyles.miniButton)) { - showBuildOptions = false; - }*/ + if (GUILayout.Button ("Show", EditorStyles.miniButton)) { + showBuildOptions = true; + } + } else if (GUILayout.Button ("Hide", EditorStyles.miniButton)) { + showBuildOptions = false; + }*/ string scenePath = string.Empty; string buildName = string.Empty; #if UNITY_2017_3_OR_NEWER BuildTarget buildTarget = BuildTarget.StandaloneOSX; #else - BuildTarget buildTarget = BuildTarget.StandaloneOSXIntel; + BuildTarget buildTarget = BuildTarget.StandaloneOSXIntel; #endif - if (showBuildOptions) { + if (showBuildOptions) + { // figure out what scene we want to build List dropdownOptions = new List(); - foreach (UnityEngine.Object scene in sm.Scenes) { + foreach (UnityEngine.Object scene in sm.Scenes) + { dropdownOptions.Add(scene.name); } dropdownOptions.Sort(new NaturalStringComparer()); - sceneSelection = EditorGUILayout.Popup("Scene to build", sceneSelection, dropdownOptions.ToArray()); + sceneSelection = EditorGUILayout.Popup( + "Scene to build", + sceneSelection, + dropdownOptions.ToArray() + ); string sceneToBuild = dropdownOptions[sceneSelection]; EditorGUILayout.BeginHorizontal(); - if (string.IsNullOrEmpty(outputPath)) { - if (string.IsNullOrEmpty(SimUtil.DefaultBuildDirectory)) { + if (string.IsNullOrEmpty(outputPath)) + { + if (string.IsNullOrEmpty(SimUtil.DefaultBuildDirectory)) + { outputPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); - } else { + } + else + { outputPath = SimUtil.DefaultBuildDirectory; } } outputPath = EditorGUILayout.TextField("Output Path", outputPath); - if (GUILayout.Button("Choose...")) { - outputPath = EditorUtility.OpenFolderPanel("Scene output path", outputPath, string.Empty); + if (GUILayout.Button("Choose...")) + { + outputPath = EditorUtility.OpenFolderPanel( + "Scene output path", + outputPath, + string.Empty + ); } EditorGUILayout.EndHorizontal(); launchOnBuild = EditorGUILayout.Toggle("Launch on build", launchOnBuild); GUI.color = Color.yellow; - foreach (BuildTarget bt in Targets) { - if (GUILayout.Button("BUILD -> " + bt.ToString())) { - if (string.IsNullOrEmpty(outputPath) || !System.IO.Directory.Exists(outputPath)) { - EditorUtility.DisplayDialog("Invalid output path!", "Select a valid scene output path", "OK"); - } else { - foreach (UnityEngine.Object sceneObject in sm.Scenes) { - if (sceneObject.name == sceneToBuild) { + foreach (BuildTarget bt in Targets) + { + if (GUILayout.Button("BUILD -> " + bt.ToString())) + { + if (string.IsNullOrEmpty(outputPath) || !System.IO.Directory.Exists(outputPath)) + { + EditorUtility.DisplayDialog( + "Invalid output path!", + "Select a valid scene output path", + "OK" + ); + } + else + { + foreach (UnityEngine.Object sceneObject in sm.Scenes) + { + if (sceneObject.name == sceneToBuild) + { scenePath = AssetDatabase.GetAssetPath(sceneObject); buildName = sceneObject.name.Replace(".unity", ""); } @@ -212,35 +296,47 @@ public override void OnInspectorGUI() { EditorGUILayout.EndVertical(); - if (!string.IsNullOrEmpty(scenePath)) { + if (!string.IsNullOrEmpty(scenePath)) + { SimUtil.BuildScene(scenePath, buildName, outputPath, buildTarget, launchOnBuild); return; } } } -public class NaturalStringComparer : IComparer { - private static readonly Regex _re = new Regex(@"(?<=\D)(?=\d)|(?<=\d)(?=\D)", RegexOptions.Compiled); +public class NaturalStringComparer : IComparer +{ + private static readonly Regex _re = new Regex( + @"(?<=\D)(?=\d)|(?<=\d)(?=\D)", + RegexOptions.Compiled + ); - public int Compare(string x, string y) { + public int Compare(string x, string y) + { x = x.ToLower(); y = y.ToLower(); - if (string.Compare(x, 0, y, 0, Math.Min(x.Length, y.Length)) == 0) { - if (x.Length == y.Length) return 0; + if (string.Compare(x, 0, y, 0, Math.Min(x.Length, y.Length)) == 0) + { + if (x.Length == y.Length) + return 0; return x.Length < y.Length ? -1 : 1; } var a = _re.Split(x); var b = _re.Split(y); int i = 0; - while (true) { + while (true) + { int r = PartCompare(a[i], b[i]); - if (r != 0) return r; + if (r != 0) + return r; ++i; } } - private static int PartCompare(string x, string y) { - int a, b; + private static int PartCompare(string x, string y) + { + int a, + b; if (int.TryParse(x, out a) && int.TryParse(y, out b)) return a.CompareTo(b); return x.CompareTo(y); diff --git a/unity/Assets/Editor/SimObjEditor.cs b/unity/Assets/Editor/SimObjEditor.cs index 526e619482..7c96d42050 100644 --- a/unity/Assets/Editor/SimObjEditor.cs +++ b/unity/Assets/Editor/SimObjEditor.cs @@ -1,88 +1,128 @@ -using UnityEngine; +using System.Collections.Generic; using UnityEditor; -using System.Collections.Generic; +using UnityEngine; [CustomEditor(typeof(SimObj))] -public class SimObjectEditor : Editor { - void OnSceneGUI() { +public class SimObjectEditor : Editor +{ + void OnSceneGUI() + { SimObj simObj = (SimObj)target; - if (SimUtil.ShowIDs) { + if (SimUtil.ShowIDs) + { Handles.color = Color.white; - Handles.Label((simObj.transform.position + Vector3.up * 0.1f), simObj.Type.ToString() + " : " + simObj.ObjectID.ToString(), EditorStyles.miniButton); + Handles.Label( + (simObj.transform.position + Vector3.up * 0.1f), + simObj.Type.ToString() + " : " + simObj.ObjectID.ToString(), + EditorStyles.miniButton + ); } - if (SimUtil.ShowBasePivots) { + if (SimUtil.ShowBasePivots) + { Handles.color = Color.white; // this was originally Handles.CircleCap, which is obsolete, had to add the EventType.Repaint parameter in upgrading to new CircleHandleCap implementation // not sure if the event type should be EventType.Repaint or EventType.Layout, but if Repaint isn't working change it to Layout - Handles.CircleHandleCap(0, simObj.transform.position, Quaternion.Euler(-90f, 0f, 0f), 1f, EventType.Repaint); + Handles.CircleHandleCap( + 0, + simObj.transform.position, + Quaternion.Euler(-90f, 0f, 0f), + 1f, + EventType.Repaint + ); } } - public override void OnInspectorGUI() { + public override void OnInspectorGUI() + { SimObj simObj = (SimObj)target; GUI.color = Color.grey; EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUI.color = Color.white; EditorGUILayout.LabelField("Properties:", EditorStyles.miniLabel); - if (!EditorUtility.IsPersistent(simObj)) { - if (!SimUtil.IsObjectIDValid(simObj.ObjectID)) { + if (!EditorUtility.IsPersistent(simObj)) + { + if (!SimUtil.IsObjectIDValid(simObj.ObjectID)) + { GUI.color = Color.Lerp(Color.yellow, Color.white, 0.5f); - EditorGUILayout.LabelField("This object has no Object ID. Use SceneManager to gather / generate SimObj IDs."); - } else { + EditorGUILayout.LabelField( + "This object has no Object ID. Use SceneManager to gather / generate SimObj IDs." + ); + } + else + { GUI.color = Color.white; EditorGUILayout.TextField("Object ID:", simObj.ObjectID.ToString()); } } GUI.color = Color.white; simObj.Type = (SimObjType)EditorGUILayout.EnumPopup("Object type:", simObj.Type); - simObj.Manipulation = (SimObjManipType)EditorGUILayout.EnumPopup("Manipulation type:", simObj.Manipulation); - simObj.UseCustomBounds = EditorGUILayout.Toggle("Use custom bounds", simObj.UseCustomBounds); - if (!EditorUtility.IsPersistent(simObj)) { + simObj.Manipulation = (SimObjManipType) + EditorGUILayout.EnumPopup("Manipulation type:", simObj.Manipulation); + simObj.UseCustomBounds = EditorGUILayout.Toggle( + "Use custom bounds", + simObj.UseCustomBounds + ); + if (!EditorUtility.IsPersistent(simObj)) + { EditorGUILayout.Toggle("Is a receptacle", simObj.IsReceptacle); EditorGUILayout.Toggle("Is animated", simObj.IsAnimated); EditorGUILayout.Toggle("Is animating now", simObj.IsAnimating); } - if (simObj.UseCustomBounds) { + if (simObj.UseCustomBounds) + { GUI.color = Color.grey; EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUI.color = Color.white; EditorGUILayout.LabelField("Bounds dimensions:", EditorStyles.miniLabel); - simObj.BoundsTransform = (Transform)EditorGUILayout.ObjectField(simObj.BoundsTransform, typeof(Transform), true); + simObj.BoundsTransform = (Transform) + EditorGUILayout.ObjectField(simObj.BoundsTransform, typeof(Transform), true); EditorGUILayout.EndVertical(); } - if (Application.isPlaying) { - if (GUILayout.Button("Put back in original position")) { + if (Application.isPlaying) + { + if (GUILayout.Button("Put back in original position")) + { SimUtil.PutItemBackInStartupPosition(simObj); } } EditorGUILayout.EndVertical(); - if (!string.IsNullOrEmpty(simObj.Error)) { + if (!string.IsNullOrEmpty(simObj.Error)) + { GUI.color = Color.Lerp(Color.white, Color.red, 0.5f); EditorGUILayout.BeginVertical(EditorStyles.helpBox); EditorGUILayout.LabelField("Error: " + simObj.Error); EditorGUILayout.EndVertical(); } - if (!Application.isPlaying && !EditorUtility.IsPersistent(simObj)) { + if (!Application.isPlaying && !EditorUtility.IsPersistent(simObj)) + { GUI.color = Color.grey; EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUI.color = Color.white; EditorGUILayout.LabelField("Utilities:", EditorStyles.miniLabel); bool showBasePivots = GUILayout.Toggle(SimUtil.ShowBasePivots, "Show base pivots"); bool showIDs = GUILayout.Toggle(SimUtil.ShowIDs, "Show ID labels"); - bool showCustomBounds = GUILayout.Toggle(SimUtil.ShowCustomBounds, "Show custom bounds"); - bool showObjectVisibility = GUILayout.Toggle(SimUtil.ShowObjectVisibility, "Show object visibility"); - - if (GUILayout.Button("Set up base transform")) { + bool showCustomBounds = GUILayout.Toggle( + SimUtil.ShowCustomBounds, + "Show custom bounds" + ); + bool showObjectVisibility = GUILayout.Toggle( + SimUtil.ShowObjectVisibility, + "Show object visibility" + ); + + if (GUILayout.Button("Set up base transform")) + { GameObject newBaseObject = new GameObject("Base"); newBaseObject.transform.position = simObj.transform.position; newBaseObject.transform.rotation = simObj.transform.rotation; newBaseObject.transform.localScale = simObj.transform.localScale; MeshRenderer r = simObj.GetComponent(); - if (r != null) { + if (r != null) + { MeshRenderer rc = newBaseObject.AddComponent(); rc.sharedMaterials = r.sharedMaterials; MeshFilter mc = newBaseObject.AddComponent(); @@ -93,17 +133,20 @@ public override void OnInspectorGUI() { GameObject.DestroyImmediate(m); BoxCollider c = simObj.GetComponent(); - if (c != null) { + if (c != null) + { GameObject.DestroyImmediate(c); newBaseObject.AddComponent(); } // create a base object and parent everything under it List children = new List(); - foreach (Transform t in simObj.transform) { + foreach (Transform t in simObj.transform) + { children.Add(t); } - foreach (Transform t in children) { + foreach (Transform t in children) + { t.parent = newBaseObject.transform; } @@ -118,13 +161,17 @@ public override void OnInspectorGUI() { UnityEditor.Selection.activeGameObject = newBaseObject; simObj.RefreshColliders(); - } else { + } + else + { // create a base object and parent everything under it List children = new List(); - foreach (Transform t in simObj.transform) { + foreach (Transform t in simObj.transform) + { children.Add(t); } - foreach (Transform t in children) { + foreach (Transform t in children) + { t.parent = newBaseObject.transform; } simObj.transform.localScale = Vector3.one; @@ -134,11 +181,15 @@ public override void OnInspectorGUI() { newBaseObject.tag = SimUtil.SimObjTag; } } - if (GUILayout.Button("Fix base rotation/scale")) { + if (GUILayout.Button("Fix base rotation/scale")) + { Transform baseObj = simObj.transform.Find("Base"); - if (baseObj == null) { + if (baseObj == null) + { Debug.LogError("No base object found, not adjusting"); - } else { + } + else + { baseObj.transform.parent = null; simObj.transform.localScale = Vector3.one; simObj.transform.localRotation = Quaternion.identity; @@ -149,10 +200,13 @@ public override void OnInspectorGUI() { UnityEditor.EditorUtility.SetDirty(simObj); - if (showBasePivots != SimUtil.ShowBasePivots + if ( + showBasePivots != SimUtil.ShowBasePivots || showIDs != SimUtil.ShowIDs || showCustomBounds != SimUtil.ShowCustomBounds - || showObjectVisibility != SimUtil.ShowObjectVisibility) { + || showObjectVisibility != SimUtil.ShowObjectVisibility + ) + { SimUtil.ShowBasePivots = showBasePivots; SimUtil.ShowIDs = showIDs; SimUtil.ShowCustomBounds = showCustomBounds; @@ -163,4 +217,4 @@ public override void OnInspectorGUI() { } } } -} \ No newline at end of file +} diff --git a/unity/Assets/Editor/TestCabinetVisibilityEditor.cs b/unity/Assets/Editor/TestCabinetVisibilityEditor.cs index e2717de47c..d8157fcf9e 100644 --- a/unity/Assets/Editor/TestCabinetVisibilityEditor.cs +++ b/unity/Assets/Editor/TestCabinetVisibilityEditor.cs @@ -1,18 +1,23 @@ -using UnityEngine; +using System.Collections; using UnityEditor; -using System.Collections; +using UnityEngine; [CustomEditor(typeof(TestCabinetVisibility))] -public class TestCabinetVisibilityEditor : Editor { - public override void OnInspectorGUI() { +public class TestCabinetVisibilityEditor : Editor +{ + public override void OnInspectorGUI() + { DrawDefaultInspector(); TestCabinetVisibility t = (TestCabinetVisibility)target; - if (!Application.isPlaying) { - if (GUILayout.Button("Next position")) { + if (!Application.isPlaying) + { + if (GUILayout.Button("Next position")) + { t.ProblemIndex++; - if (t.ProblemIndex >= t.ProblemCabinets.Count) { + if (t.ProblemIndex >= t.ProblemCabinets.Count) + { t.ProblemIndex = 0; } float headingAngle = t.ProblemHeadingAngles[t.ProblemIndex]; diff --git a/unity/Assets/Physics/SimObjsPhysics/Custom Project Objects/Hide And Seek Objects/ExperimentScene/Screen/Screen_Adjust_Script.cs b/unity/Assets/Physics/SimObjsPhysics/Custom Project Objects/Hide And Seek Objects/ExperimentScene/Screen/Screen_Adjust_Script.cs index eefab4dddd..63c6178d1b 100644 --- a/unity/Assets/Physics/SimObjsPhysics/Custom Project Objects/Hide And Seek Objects/ExperimentScene/Screen/Screen_Adjust_Script.cs +++ b/unity/Assets/Physics/SimObjsPhysics/Custom Project Objects/Hide And Seek Objects/ExperimentScene/Screen/Screen_Adjust_Script.cs @@ -12,14 +12,20 @@ public class Screen_Adjust_Script : MonoBehaviour { [Range(0f, 2f)] public float spacing = 1; + [Range(-1f, 1f)] public float topShift = 0; + [Range(-1f, 1f)] public float bottomShift = 0; + [Range(-1f, 1f)] public float widthShift = 0; - float spacingPrev, topShiftPrev, bottomShiftPrev, widthShiftPrev; + float spacingPrev, + topShiftPrev, + bottomShiftPrev, + widthShiftPrev; int stableVisPoints = 4; @@ -27,7 +33,11 @@ void Start() { if (PrefabUtility.GetCorrespondingObjectFromSource(gameObject) != null) { - PrefabUtility.UnpackPrefabInstance(transform.gameObject, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction); + PrefabUtility.UnpackPrefabInstance( + transform.gameObject, + PrefabUnpackMode.Completely, + InteractionMode.AutomatedAction + ); } spacingPrev = spacing + 0.000001f; @@ -38,22 +48,45 @@ void Start() // Update is called once per frame void Update() - { - if (spacing != spacingPrev || topShift != topShiftPrev || bottomShift != bottomShiftPrev || widthShift != widthShiftPrev) + { + if ( + spacing != spacingPrev + || topShift != topShiftPrev + || bottomShift != bottomShiftPrev + || widthShift != widthShiftPrev + ) { // Zero out rotation for entirety of operation, for simplicity Quaternion rotationSaver = transform.rotation; transform.rotation = Quaternion.identity; Transform screenObject = transform.Find("screen_reference"); - Transform sheetObject = transform.Find("screen_reference").transform.Find("screen_sheet"); - - Transform leftBaseJoint = screenObject.Find("screen_master_jnt").Find("screen_pillar_l_base_jnt"); - Transform rightBaseJoint = screenObject.Find("screen_master_jnt").Find("screen_pillar_r_base_jnt"); - Transform leftBottomJoint = screenObject.Find("screen_master_jnt").Find("screen_pillar_l_base_jnt").Find("screen_pillar_l_bottom_jnt"); - Transform rightBottomJoint = screenObject.Find("screen_master_jnt").Find("screen_pillar_r_base_jnt").Find("screen_pillar_r_bottom_jnt"); - Transform leftTopJoint = screenObject.Find("screen_master_jnt").Find("screen_pillar_l_base_jnt").Find("screen_pillar_l_top_jnt"); - Transform rightTopJoint = screenObject.Find("screen_master_jnt").Find("screen_pillar_r_base_jnt").Find("screen_pillar_r_top_jnt"); + Transform sheetObject = transform + .Find("screen_reference") + .transform.Find("screen_sheet"); + + Transform leftBaseJoint = screenObject + .Find("screen_master_jnt") + .Find("screen_pillar_l_base_jnt"); + Transform rightBaseJoint = screenObject + .Find("screen_master_jnt") + .Find("screen_pillar_r_base_jnt"); + Transform leftBottomJoint = screenObject + .Find("screen_master_jnt") + .Find("screen_pillar_l_base_jnt") + .Find("screen_pillar_l_bottom_jnt"); + Transform rightBottomJoint = screenObject + .Find("screen_master_jnt") + .Find("screen_pillar_r_base_jnt") + .Find("screen_pillar_r_bottom_jnt"); + Transform leftTopJoint = screenObject + .Find("screen_master_jnt") + .Find("screen_pillar_l_base_jnt") + .Find("screen_pillar_l_top_jnt"); + Transform rightTopJoint = screenObject + .Find("screen_master_jnt") + .Find("screen_pillar_r_base_jnt") + .Find("screen_pillar_r_top_jnt"); float pillarToSheetVisPointBuffer = 0.05f; @@ -66,15 +99,28 @@ void Update() rightTopJoint.position += rightTopJoint.forward * (topShift - topShiftPrev); // Adjust colliders - float colHeight = Vector3.Distance(leftBaseJoint.position, leftTopJoint.position); - BoxCollider colL = screenObject.Find("Colliders").Find("Col_l2").GetComponent(); - BoxCollider colR = screenObject.Find("Colliders").Find("Col_r2").GetComponent(); - - colL.center = ((leftTopJoint.position + leftBaseJoint.position) / 2) - colL.transform.position; + float colHeight = Vector3.Distance( + leftBaseJoint.position, + leftTopJoint.position + ); + BoxCollider colL = screenObject + .Find("Colliders") + .Find("Col_l2") + .GetComponent(); + BoxCollider colR = screenObject + .Find("Colliders") + .Find("Col_r2") + .GetComponent(); + + colL.center = + ((leftTopJoint.position + leftBaseJoint.position) / 2) + - colL.transform.position; colL.center -= new Vector3(0, 0, colL.center.z); colL.size = new Vector3(0.05f, colHeight, 0.05f); - colR.center = ((rightTopJoint.position + rightBaseJoint.position) / 2) - colR.transform.position; + colR.center = + ((rightTopJoint.position + rightBaseJoint.position) / 2) + - colR.transform.position; colR.center -= new Vector3(0, 0, colR.center.z); colR.size = new Vector3(0.05f, colHeight, 0.05f); } @@ -82,12 +128,17 @@ void Update() if (bottomShift != bottomShiftPrev) { // Adjust joints - leftBottomJoint.position += leftBottomJoint.forward * (bottomShift - bottomShiftPrev); - rightBottomJoint.position += rightBottomJoint.forward * (bottomShift - bottomShiftPrev); + leftBottomJoint.position += + leftBottomJoint.forward * (bottomShift - bottomShiftPrev); + rightBottomJoint.position += + rightBottomJoint.forward * (bottomShift - bottomShiftPrev); } // Adjust sheet collider - BoxCollider colSheet = sheetObject.Find("Colliders").Find("Col_s").transform.GetComponent(); + BoxCollider colSheet = sheetObject + .Find("Colliders") + .Find("Col_s") + .transform.GetComponent(); Bounds newBounds = newSheetBounds(colSheet, leftTopJoint, rightBottomJoint); @@ -124,12 +175,19 @@ void Update() // Adjust sheet collider Transform colCenter = sheetObject.Find("Colliders").Find("Col_s").transform; - colCenter.GetComponent().size += transform.right * 2 * (widthShift - widthShiftPrev); + colCenter.GetComponent().size += + transform.right * 2 * (widthShift - widthShiftPrev); // Adjust left pillar base-vispoints Transform[] visPointsLeft = new Transform[2]; - visPointsLeft[0] = screenObject.Find("VisibilityPoints").Find("vPoint_stable_1").transform; - visPointsLeft[1] = screenObject.Find("VisibilityPoints").Find("vPoint_stable_2").transform; + visPointsLeft[0] = screenObject + .Find("VisibilityPoints") + .Find("vPoint_stable_1") + .transform; + visPointsLeft[1] = screenObject + .Find("VisibilityPoints") + .Find("vPoint_stable_2") + .transform; foreach (Transform transform in visPointsLeft) { @@ -138,8 +196,14 @@ void Update() // Adjust right pillar base-vispoints Transform[] visPointsRight = new Transform[2]; - visPointsRight[0] = screenObject.Find("VisibilityPoints").Find("vPoint_stable_3").transform; - visPointsRight[1] = screenObject.Find("VisibilityPoints").Find("vPoint_stable_4").transform; + visPointsRight[0] = screenObject + .Find("VisibilityPoints") + .Find("vPoint_stable_3") + .transform; + visPointsRight[1] = screenObject + .Find("VisibilityPoints") + .Find("vPoint_stable_4") + .transform; foreach (Transform transform in visPointsRight) { @@ -149,34 +213,56 @@ void Update() // Define vispoint adjustment inputs float pillarHeight = Vector3.Distance(rightBaseJoint.position, rightTopJoint.position); - float sheetWidth = Vector3.Distance(rightBottomJoint.position, leftBottomJoint.position) - pillarToSheetVisPointBuffer * 2; + float sheetWidth = + Vector3.Distance(rightBottomJoint.position, leftBottomJoint.position) + - pillarToSheetVisPointBuffer * 2; float sheetHeight = Vector3.Distance(rightBottomJoint.position, rightTopJoint.position); int sheetWidthVisCount = (int)Mathf.Floor(2 + (sheetWidth * 3)); int sheetHeightVisCount = (int)Mathf.Floor(2 + (sheetHeight * 3)); // Use first existing vispoint as reference - GameObject visPointObject = screenObject.Find("VisibilityPoints").GetChild(0).gameObject; + GameObject visPointObject = screenObject + .Find("VisibilityPoints") + .GetChild(0) + .gameObject; // Delete previous dynamic pillar vispoints int prevVisPoints = screenObject.Find("VisibilityPoints").childCount; for (int i = stableVisPoints; i < prevVisPoints; i++) { - DestroyImmediate(screenObject.Find("VisibilityPoints").GetChild(stableVisPoints).gameObject); + DestroyImmediate( + screenObject.Find("VisibilityPoints").GetChild(stableVisPoints).gameObject + ); } // Define pillar vispoints array Vector3[] pillarVisPoints = new Vector3[2 * (sheetHeightVisCount - 1)]; for (int i = 0; i < sheetHeightVisCount - 1; i++) { - pillarVisPoints[i] = rightBaseJoint.TransformPoint(rightBottomJoint.TransformDirection(0, 0, (i + 1) * pillarHeight / (sheetHeightVisCount - 1))); - pillarVisPoints[i + sheetHeightVisCount - 1] = leftBaseJoint.TransformPoint(leftBottomJoint.TransformDirection(0, 0, (i + 1) * pillarHeight / (sheetHeightVisCount - 1))); + pillarVisPoints[i] = rightBaseJoint.TransformPoint( + rightBottomJoint.TransformDirection( + 0, + 0, + (i + 1) * pillarHeight / (sheetHeightVisCount - 1) + ) + ); + pillarVisPoints[i + sheetHeightVisCount - 1] = leftBaseJoint.TransformPoint( + leftBottomJoint.TransformDirection( + 0, + 0, + (i + 1) * pillarHeight / (sheetHeightVisCount - 1) + ) + ); } // Generate pillar vispoints for (int i = 0; i < pillarVisPoints.Length; i++) { - GameObject newVisPoint = Instantiate(visPointObject, screenObject.Find("VisibilityPoints")); + GameObject newVisPoint = Instantiate( + visPointObject, + screenObject.Find("VisibilityPoints") + ); newVisPoint.name = ("vPoint_dynamic_" + (i + 1)); newVisPoint.transform.position = pillarVisPoints[i]; } @@ -187,18 +273,31 @@ void Update() { for (int j = 0; j < sheetWidthVisCount; j++) { - sheetVisPoints[i * sheetWidthVisCount + j] = rightBottomJoint.TransformPoint(new Vector3(pillarToSheetVisPointBuffer + (sheetWidth / (sheetWidthVisCount - 1)) * j, 0, 0.05f * sheetHeight + (0.9f * sheetHeight / (sheetHeightVisCount - 1)) * i)); + sheetVisPoints[i * sheetWidthVisCount + j] = rightBottomJoint.TransformPoint( + new Vector3( + pillarToSheetVisPointBuffer + + (sheetWidth / (sheetWidthVisCount - 1)) * j, + 0, + 0.05f * sheetHeight + + (0.9f * sheetHeight / (sheetHeightVisCount - 1)) * i + ) + ); // Debug.Log("Vispoint " + (i * sheetWidthVisCount + j + 1) + " has coordinates " + sheetVisPoints[i * sheetWidthVisCount + j]); } } - + // Delete any excess vispoints for sheet int prevSheetVisPoints = sheetObject.Find("VisibilityPoints").childCount; if (sheetVisPoints.Length < prevSheetVisPoints) { for (int i = 0; i < prevSheetVisPoints - sheetVisPoints.Length; i++) { - DestroyImmediate(sheetObject.Find("VisibilityPoints").GetChild(sheetVisPoints.Length).gameObject); + DestroyImmediate( + sheetObject + .Find("VisibilityPoints") + .GetChild(sheetVisPoints.Length) + .gameObject + ); } } @@ -208,15 +307,18 @@ void Update() // Repurpose existing vispoints if (i < sheetObject.Find("VisibilityPoints").childCount) { - - sheetObject.Find("VisibilityPoints").transform.GetChild(i).name = "vPoint_dynamic_" + (i + 1); - sheetObject.Find("VisibilityPoints").transform.GetChild(i).transform.position = sheetVisPoints[i]; + sheetObject.Find("VisibilityPoints").transform.GetChild(i).name = + "vPoint_dynamic_" + (i + 1); + sheetObject.Find("VisibilityPoints").transform.GetChild(i).transform.position = + sheetVisPoints[i]; } - // Generate more vispoints if needed else { - GameObject newVisPoint = Instantiate(visPointObject, sheetObject.Find("VisibilityPoints")); + GameObject newVisPoint = Instantiate( + visPointObject, + sheetObject.Find("VisibilityPoints") + ); newVisPoint.name = ("vPoint_dynamic_" + (i + 1)); newVisPoint.transform.position = sheetVisPoints[i]; } @@ -227,7 +329,11 @@ void Update() screenObject.Find("mesh").GetComponent().BakeMesh(screenSnapshot); for (int i = 0; i < transform.Find("mesh").childCount; i++) { - transform.Find("mesh").GetChild(i).localPosition = new Vector3(0, 0, spacing * (i / (transform.Find("mesh").childCount - 1) - 0.5f)); + transform.Find("mesh").GetChild(i).localPosition = new Vector3( + 0, + 0, + spacing * (i / (transform.Find("mesh").childCount - 1) - 0.5f) + ); transform.Find("mesh").GetChild(i).GetComponent().mesh = screenSnapshot; } @@ -242,7 +348,8 @@ void Update() // If it's a sub-gameobject... if (transform.GetChild(i).GetComponent() != null) { - transform.GetChild(i).Find("mesh").GetComponent().mesh = sheetSnapshot; + transform.GetChild(i).Find("mesh").GetComponent().mesh = + sheetSnapshot; // Add to the list in the meantime childGameObjects.Add(transform.GetChild(i)); @@ -258,7 +365,6 @@ void Update() int currentchildGameObject = 0; foreach (Transform subObjectMesh in transform.Find("mesh")) { - Instantiate(screenObject.Find("Colliders"), subObjectMesh); Instantiate(screenObject.Find("VisibilityPoints"), subObjectMesh); Instantiate(screenObject.Find("screen_sheet"), subObjectMesh); @@ -276,43 +382,56 @@ void Update() DestroyImmediate(currentMetadataGroup.gameObject); } - else if (currentMetadataGroup.name == "VisibilityPoints(Clone)") { while (currentMetadataGroup.childCount != 0) { - currentMetadataGroup.GetChild(0).SetParent(transform.Find("VisibilityPoints")); + currentMetadataGroup + .GetChild(0) + .SetParent(transform.Find("VisibilityPoints")); } DestroyImmediate(currentMetadataGroup.gameObject); } - // For sub-SimObjects (move VisPoints and Colliders part of metadata from the first to the second...) else { deleteCollidersAndVisPoints(childGameObjects[currentchildGameObject]); - while (currentMetadataGroup.childCount != 0) { - currentSubObjectMetadataGroup = currentMetadataGroup.GetChild(0); // If it's a collider group... // Debug.Log(currentMetadataGroup.GetChild(0).name); if (currentSubObjectMetadataGroup.name == "Colliders") { - - Debug.Log("Adding colliders from " + currentMetadataGroup + " to " + childGameObjects[currentchildGameObject].Find("Colliders") + " which is a child of " + childGameObjects[currentchildGameObject]); + Debug.Log( + "Adding colliders from " + + currentMetadataGroup + + " to " + + childGameObjects[currentchildGameObject].Find("Colliders") + + " which is a child of " + + childGameObjects[currentchildGameObject] + ); while (currentSubObjectMetadataGroup.childCount != 0) { - Debug.Log("Moving " + currentSubObjectMetadataGroup.GetChild(0) + " to proper spot, which is " + childGameObjects[currentchildGameObject].Find("Colliders")); + Debug.Log( + "Moving " + + currentSubObjectMetadataGroup.GetChild(0) + + " to proper spot, which is " + + childGameObjects[currentchildGameObject] + .Find("Colliders") + ); // DestroyImmediate(currentSubObjectMetadataGroup.GetChild(0).gameObject); - currentSubObjectMetadataGroup.GetChild(0).SetParent(childGameObjects[currentchildGameObject].Find("Colliders")); - + currentSubObjectMetadataGroup + .GetChild(0) + .SetParent( + childGameObjects[currentchildGameObject] + .Find("Colliders") + ); } } - // If it's a visiblity point group... else if (currentSubObjectMetadataGroup.name == "VisibilityPoints") { @@ -320,7 +439,12 @@ void Update() { // Debug.Log("Moving " + currentSubObjectMetadataGroup.GetChild(0) + " to proper spot."); // DestroyImmediate(currentSubObjectMetadataGroup.GetChild(0).gameObject); - currentSubObjectMetadataGroup.GetChild(0).SetParent(childGameObjects[currentchildGameObject].Find("VisibilityPoints")); + currentSubObjectMetadataGroup + .GetChild(0) + .SetParent( + childGameObjects[currentchildGameObject] + .Find("VisibilityPoints") + ); } } @@ -339,10 +463,13 @@ void Update() // Move subobjects to their correct places for (int i = 0; i < childGameObjects.Count; i++) { - childGameObjects[i].localPosition = new Vector3(0, 0, spacing * (i / (transform.Find("mesh").childCount - 1) - 0.5f)); + childGameObjects[i].localPosition = new Vector3( + 0, + 0, + spacing * (i / (transform.Find("mesh").childCount - 1) - 0.5f) + ); } - /// Run SimObjPhysics Setup // screenObject.GetComponent().ContextSetUpSimObjPhysics(); // sheetObject.GetComponent().ContextSetUpSimObjPhysics(); @@ -352,7 +479,7 @@ void Update() { childGameObject.GetComponent().ContextSetUpSimObjPhysics(); } - + // Restore initial rotation transform.rotation = rotationSaver; diff --git a/unity/Assets/PlaceableSurfaceEditorReset.cs b/unity/Assets/PlaceableSurfaceEditorReset.cs index ca85249967..d27abb248a 100644 --- a/unity/Assets/PlaceableSurfaceEditorReset.cs +++ b/unity/Assets/PlaceableSurfaceEditorReset.cs @@ -1,7 +1,7 @@ using System.Collections; using System.Collections.Generic; -using UnityEngine; using UnityEditor; +using UnityEngine; #if UNITY_EDITOR [ExecuteInEditMode] @@ -9,37 +9,41 @@ public class PlaceableSurfaceEditorReset : MonoBehaviour { public Dictionary assetToAssetPath = new Dictionary(); - public void GetAllSimObjPrefabs() + public void GetAllSimObjPrefabs() { assetToAssetPath.Clear(); //var assetsOfSimObjectType = new List(); string[] guids = AssetDatabase.FindAssets("t:prefab"); - for (int i = 0; i < guids.Length; i++) + for (int i = 0; i < guids.Length; i++) + { + string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]); + string assetName = assetPath.Substring( + assetPath.LastIndexOf("/") + 1, + assetPath.Length - (assetPath.LastIndexOf("/") + 1) - ".prefab".Length + ); + + // skip all these prefabs + if ( + assetPath.Contains("Scene Setup Prefabs") + || assetPath.Contains("Entryway Objects") + || assetPath.Contains("Custom Project Objects") + ) { - string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]); - string assetName = assetPath.Substring( - assetPath.LastIndexOf("/") + 1, - assetPath.Length - (assetPath.LastIndexOf("/") + 1) - ".prefab".Length - ); - - // skip all these prefabs - if (assetPath.Contains("Scene Setup Prefabs") || assetPath.Contains("Entryway Objects") || assetPath.Contains("Custom Project Objects")) - { - continue; - } - - GameObject asset = AssetDatabase.LoadAssetAtPath(assetPath); - if (asset != null && asset.GetComponent()) { + continue; + } - SimObjPhysics sop = asset.GetComponent(); - assetToAssetPath.Add(asset, assetPath); - } + GameObject asset = AssetDatabase.LoadAssetAtPath(assetPath); + if (asset != null && asset.GetComponent()) + { + SimObjPhysics sop = asset.GetComponent(); + assetToAssetPath.Add(asset, assetPath); } + } } - public void ToggleOffPlaceableSurface () + public void ToggleOffPlaceableSurface() { GetAllSimObjPrefabs(); @@ -54,17 +58,19 @@ public void ToggleOffPlaceableSurface () MeshRenderer[] renderers; renderers = contentRoot.GetComponentsInChildren(); - bool shouldSave = false; //just in case something doesn't have a renderer? - if(renderers.Length > 0) + if (renderers.Length > 0) { foreach (MeshRenderer mr in renderers) { - if(mr.sharedMaterial != null) + if (mr.sharedMaterial != null) { - if(mr.sharedMaterial.ToString() == "Placeable_Surface_Mat (UnityEngine.Material)") + if ( + mr.sharedMaterial.ToString() + == "Placeable_Surface_Mat (UnityEngine.Material)" + ) { mr.enabled = false; shouldSave = true; @@ -72,18 +78,16 @@ public void ToggleOffPlaceableSurface () } } } - - if(shouldSave) - PrefabUtility.SaveAsPrefabAsset(contentRoot, assetPath); + if (shouldSave) + PrefabUtility.SaveAsPrefabAsset(contentRoot, assetPath); } PrefabUtility.UnloadPrefabContents(contentRoot); } - } - public void ToggleOnPlaceableSurface () + public void ToggleOnPlaceableSurface() { GetAllSimObjPrefabs(); @@ -98,17 +102,19 @@ public void ToggleOnPlaceableSurface () MeshRenderer[] renderers; renderers = contentRoot.GetComponentsInChildren(); - bool shouldSave = false; //just in case something doesn't have a renderer? - if(renderers.Length > 0) + if (renderers.Length > 0) { foreach (MeshRenderer mr in renderers) { - if(mr.sharedMaterial != null) + if (mr.sharedMaterial != null) { - if(mr.sharedMaterial.ToString() == "Placeable_Surface_Mat (UnityEngine.Material)") + if ( + mr.sharedMaterial.ToString() + == "Placeable_Surface_Mat (UnityEngine.Material)" + ) { mr.enabled = true; shouldSave = true; @@ -116,36 +122,34 @@ public void ToggleOnPlaceableSurface () } } } - - if(shouldSave) - PrefabUtility.SaveAsPrefabAsset(contentRoot, assetPath); + if (shouldSave) + PrefabUtility.SaveAsPrefabAsset(contentRoot, assetPath); } PrefabUtility.UnloadPrefabContents(contentRoot); } - } - [CustomEditor (typeof(PlaceableSurfaceEditorReset))] + + [CustomEditor(typeof(PlaceableSurfaceEditorReset))] public class PlaceableSurfaceEditorThing : Editor { - public override void OnInspectorGUI () + public override void OnInspectorGUI() { DrawDefaultInspector(); PlaceableSurfaceEditorReset myScript = (PlaceableSurfaceEditorReset)target; - if(GUILayout.Button("Toggle Off Placeable Surface in Prefab Assets")) + if (GUILayout.Button("Toggle Off Placeable Surface in Prefab Assets")) { myScript.ToggleOffPlaceableSurface(); } - if(GUILayout.Button("Toggle ON Placeable Surface in Prefab Assets")) + if (GUILayout.Button("Toggle ON Placeable Surface in Prefab Assets")) { myScript.ToggleOnPlaceableSurface(); } } } - } -#endif \ No newline at end of file +#endif diff --git a/unity/Assets/PrefabAssetIdAssigner.cs b/unity/Assets/PrefabAssetIdAssigner.cs index f196ab400c..8104e9eb63 100644 --- a/unity/Assets/PrefabAssetIdAssigner.cs +++ b/unity/Assets/PrefabAssetIdAssigner.cs @@ -1,11 +1,11 @@ using System.Collections; using System.Collections.Generic; -using UnityEngine; using UnityEditor; +using UnityEngine; /////////HOW TO USE/////////// /* -put the sim object type in the `SimObjectType` string field in this component on +put the sim object type in the `SimObjectType` string field in this component on `PrefabAssetIdAssigner` in the Asset_Id_Assign scene Then hit the button to load all prefabs in the project that are sim objects of that type @@ -21,14 +21,14 @@ public class PrefabAssetIdAssigner : MonoBehaviour public string SimObjectType; public Dictionary assetToAssetPath = new Dictionary(); - public void GetAllPrefabsOfType() + public void GetAllPrefabsOfType() { assetToAssetPath.Clear(); //var assetsOfSimObjectType = new List(); string[] guids = AssetDatabase.FindAssets("t:prefab"); - for (int i = 0; i < guids.Length; i++) + for (int i = 0; i < guids.Length; i++) { string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]); string assetName = assetPath.Substring( @@ -37,18 +37,18 @@ public void GetAllPrefabsOfType() ); // skip all these prefabs - if (assetPath.Contains("Scene Setup Prefabs") || assetPath.Contains("Entryway Objects")) + if (assetPath.Contains("Scene Setup Prefabs") || assetPath.Contains("Entryway Objects")) { continue; } GameObject asset = AssetDatabase.LoadAssetAtPath(assetPath); - if (asset != null && asset.GetComponent()) { - + if (asset != null && asset.GetComponent()) + { SimObjPhysics sop = asset.GetComponent(); //only add the type specified - if(sop.Type.ToString() == SimObjectType) - assetToAssetPath.Add(asset, assetPath); + if (sop.Type.ToString() == SimObjectType) + assetToAssetPath.Add(asset, assetPath); } } } @@ -60,7 +60,7 @@ public void GetAllPrefabs() //var assetsOfSimObjectType = new List(); string[] guids = AssetDatabase.FindAssets("t:prefab"); - for (int i = 0; i < guids.Length; i++) + for (int i = 0; i < guids.Length; i++) { string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]); string assetName = assetPath.Substring( @@ -69,17 +69,19 @@ public void GetAllPrefabs() ); // skip all these prefabs - if (assetPath.Contains("Scene Setup Prefabs") || - assetPath.Contains("Entryway Objects") || - assetPath.Contains("SceneSetupPrefabs") || - assetPath.Contains("EntrywayObjects")) + if ( + assetPath.Contains("Scene Setup Prefabs") + || assetPath.Contains("Entryway Objects") + || assetPath.Contains("SceneSetupPrefabs") + || assetPath.Contains("EntrywayObjects") + ) { continue; } GameObject asset = AssetDatabase.LoadAssetAtPath(assetPath); - if (asset != null && asset.GetComponent()) { - + if (asset != null && asset.GetComponent()) + { SimObjPhysics sop = asset.GetComponent(); assetToAssetPath.Add(asset, assetPath); } @@ -89,7 +91,7 @@ public void GetAllPrefabs() public void AssignIds() { GetAllPrefabsOfType(); - foreach (KeyValuePair go in assetToAssetPath) + foreach (KeyValuePair go in assetToAssetPath) { GameObject assetRoot = go.Key; string assetPath = go.Value; @@ -107,7 +109,7 @@ public void AssignIds() public void AssignIdsToAll() { GetAllPrefabs(); - foreach (KeyValuePair go in assetToAssetPath) + foreach (KeyValuePair go in assetToAssetPath) { GameObject assetRoot = go.Key; string assetPath = go.Value; @@ -123,10 +125,10 @@ public void AssignIdsToAll() } } -[CustomEditor (typeof(PrefabAssetIdAssigner))] +[CustomEditor(typeof(PrefabAssetIdAssigner))] public class AssetIdAssigner : Editor { - public override void OnInspectorGUI () + public override void OnInspectorGUI() { DrawDefaultInspector(); PrefabAssetIdAssigner myScript = (PrefabAssetIdAssigner)target; @@ -135,16 +137,16 @@ public override void OnInspectorGUI () // myScript.GetAllPrefabsOfType(); // } - if(GUILayout.Button("Assign Prefab Name as assetID to All Prefabs Gotten Of Type")) + if (GUILayout.Button("Assign Prefab Name as assetID to All Prefabs Gotten Of Type")) { myScript.AssignIds(); } - if(GUILayout.Button("Assign Prefab Name as assetID to All Prefabs")) + if (GUILayout.Button("Assign Prefab Name as assetID to All Prefabs")) { myScript.AssignIdsToAll(); } } } -#endif \ No newline at end of file +#endif diff --git a/unity/Assets/Scripts/ActionDispatcher.cs b/unity/Assets/Scripts/ActionDispatcher.cs index 22a5e7624e..966ca60a67 100644 --- a/unity/Assets/Scripts/ActionDispatcher.cs +++ b/unity/Assets/Scripts/ActionDispatcher.cs @@ -1,13 +1,11 @@ - -using System.Reflection; +using System; using System.Collections; using System.Collections.Generic; -using System; using System.Linq; -using UnityEngine; -using Newtonsoft.Json.Linq; +using System.Reflection; using System.Threading; - +using Newtonsoft.Json.Linq; +using UnityEngine; public class ActionFinished { public bool success; @@ -20,17 +18,24 @@ public class ActionFinished { // TODO: Remove when backcompat actions are gone public bool isDummy; - public ActionFinished() {} + public ActionFinished() { } - public ActionFinished(bool success = true, object actionReturn = null, string errorMessage = "", bool toEmitState = false, ServerActionErrorCode errorCode = 0, bool isDummy = false) { + public ActionFinished( + bool success = true, + object actionReturn = null, + string errorMessage = "", + bool toEmitState = false, + ServerActionErrorCode errorCode = 0, + bool isDummy = false + ) { this.success = success; this.actionReturn = actionReturn; this.errorMessage = errorMessage; this.toEmitState = toEmitState; this.errorCode = errorCode; this.isDummy = isDummy; - } - + } + public ActionFinished(ActionFinished toCopy) { this.success = toCopy.success; this.actionReturn = toCopy.actionReturn; @@ -40,11 +45,13 @@ public ActionFinished(ActionFinished toCopy) { this.isDummy = toCopy.isDummy; } - public static ActionFinished Success = new ActionFinished() { success = true} ; - public static ActionFinished Fail = new ActionFinished() { success = false} ; - + public static ActionFinished Success = new ActionFinished() { success = true }; + public static ActionFinished Fail = new ActionFinished() { success = false }; - public static ActionFinished SuccessToEmitState = new ActionFinished() { success = true, toEmitState = true} ; + public static ActionFinished SuccessToEmitState = new ActionFinished() { + success = true, + toEmitState = true + }; public IEnumerator GetEnumerator() { yield return this; @@ -58,17 +65,17 @@ public IEnumerator GetEnumerator() { // } // } - public interface ActionInvokable { - void Complete(ActionFinished actionFinished); - Coroutine StartCoroutine(System.Collections.IEnumerator routine); - } +public interface ActionInvokable { + void Complete(ActionFinished actionFinished); + Coroutine StartCoroutine(System.Collections.IEnumerator routine); +} /* - The ActionDispatcher takes a dynamic object with an 'action' property and - maps this to a method. Matching is performed using the parameter names. + The ActionDispatcher takes a dynamic object with an 'action' property and + maps this to a method. Matching is performed using the parameter names. In the case of method overloading, the best match is returned based on the number of matched named parameters. For a method to qualify for dispatching - it must be public and have a return type of void. The following method + it must be public and have a return type of void. The following method definitions are permitted: public void MoveAhead() @@ -90,7 +97,7 @@ public void ObjectVisible(int x, int y, bool foo) The reason for the aforementioned restrictions is twofold, we pass the arguments to Unity serialized using json. This restricts the types that can be passed to - C# as well even if we serialized using a different format, Python does not + C# as well even if we serialized using a different format, Python does not have all the same primitives, such as 'short'. Second, we allow actions to be invoked from the Python side using keyword args which don't preserve order. @@ -101,7 +108,7 @@ confusion and should be avoided. Ambiguous Actions - The following method signatures are not permitted since they can create ambiguity as + The following method signatures are not permitted since they can create ambiguity as to which method to dispatch to: case 1: @@ -110,7 +117,7 @@ public void Teleport(ServerAction) public void Teleport(float x, float y, float z) reason: Mixing ServerAction methods and non-server action methods creates ambiguity - if one param is omitted from the (x,y,z) method. You could default back to + if one param is omitted from the (x,y,z) method. You could default back to ServerAction method, but you can't be sure that is what the user intended. case 2: @@ -133,22 +140,26 @@ public void LookUp(float degrees, bool forceThing=false) This is similar to case #2, but the methods are spread across two classes. The way to resolve this is to define the following methods: Subclass - public override void LookUp(float degrees) + public override void LookUp(float degrees) public void LookUp(float degrees, bool forceThing) - Within the override method, the author can dispatch to LookUp with a default + Within the override method, the author can dispatch to LookUp with a default value for forceThing. */ public static class ActionDispatcher { - private static Dictionary>> allMethodDispatchTable = new Dictionary>>(); - private static Dictionary methodCache = new Dictionary(); + private static Dictionary>> allMethodDispatchTable = + new Dictionary>>(); + private static Dictionary methodCache = + new Dictionary(); // look through all methods on a target type and attempt to get the MethodInfo // any ambiguous method will throw an exception. This is used during testing. public static List FindAmbiguousActions(Type targetType) { List actions = new List(); - System.Reflection.MethodInfo[] allMethods = targetType.GetMethods(BindingFlags.Public | BindingFlags.Instance); + System.Reflection.MethodInfo[] allMethods = targetType.GetMethods( + BindingFlags.Public | BindingFlags.Instance + ); HashSet methodNames = new HashSet(); foreach (var method in allMethods) { methodNames.Add(method.Name); @@ -169,8 +180,14 @@ public static List FindAmbiguousActions(Type targetType) { private static MethodInfo[] getMethods(Type targetType) { if (!methodCache.ContainsKey(targetType)) { var methods = new List(); - foreach (MethodInfo mi in targetType.GetMethods(BindingFlags.Public | BindingFlags.Instance)) { - if (mi.ReturnType == typeof(void) || mi.ReturnType == typeof(ActionFinished) || mi.ReturnType == typeof(IEnumerator)) { + foreach ( + MethodInfo mi in targetType.GetMethods(BindingFlags.Public | BindingFlags.Instance) + ) { + if ( + mi.ReturnType == typeof(void) + || mi.ReturnType == typeof(ActionFinished) + || mi.ReturnType == typeof(IEnumerator) + ) { methods.Add(mi); } } @@ -197,7 +214,10 @@ public static Dictionary> FindMethodVariableNameConflicts(T for (int j = i + 1; j < allMethods.Length; j++) { MethodInfo methodIn = allMethods[j]; ParameterInfo[] methodInParams = allMethods[j].GetParameters(); - if (methodIn.Name == methodOut.Name && methodOutParams.Length == methodInParams.Length) { + if ( + methodIn.Name == methodOut.Name + && methodOutParams.Length == methodInParams.Length + ) { bool allVariableNamesMatch = true; bool allParamsMatch = true; for (int k = 0; k < methodInParams.Length; k++) { @@ -230,7 +250,9 @@ private static Dictionary> getMethodDispatchTable(Type } private static List getCandidateMethods(Type targetType, string action) { - Dictionary> methodDispatchTable = getMethodDispatchTable(targetType); + Dictionary> methodDispatchTable = getMethodDispatchTable( + targetType + ); if (!methodDispatchTable.ContainsKey(action)) { List methods = new List(); @@ -265,27 +287,37 @@ private static List getCandidateMethods(Type targetType, string acti } } - if (sourceParams.Length > targetParams.Length && !sourceParams[minCommon].HasDefaultValue) { + if ( + sourceParams.Length > targetParams.Length + && !sourceParams[minCommon].HasDefaultValue + ) { signatureMatch = false; - } else if (targetParams.Length > sourceParams.Length && !targetParams[minCommon].HasDefaultValue) { + } else if ( + targetParams.Length > sourceParams.Length + && !targetParams[minCommon].HasDefaultValue + ) { signatureMatch = false; } // if the method is more specific and the parameters match // we will dispatch to this method instead of the base type if (signatureMatch) { - - // this happens if one method has a trailing optional value and all + // this happens if one method has a trailing optional value and all // other parameter types match if (targetParams.Length != sourceParams.Length) { // TODO: This designation is based on ordered argument call assumption, which is not true for DynamicServerActions // which are always passed as named arguments, order does not matter, Ambiguity should be determined on actual call // not on method signatures - throw new AmbiguousActionException("Signature match found in the same class"); + throw new AmbiguousActionException( + "Signature match found in the same class" + ); } replaced = true; - if (hierarchy.IndexOf(mi.DeclaringType) < hierarchy.IndexOf(methods[j].DeclaringType)) { + if ( + hierarchy.IndexOf(mi.DeclaringType) + < hierarchy.IndexOf(methods[j].DeclaringType) + ) { methods[j] = mi; } } @@ -309,40 +341,52 @@ private static List getCandidateMethods(Type targetType, string acti return methodDispatchTable[action]; } - public static MethodInfo getDispatchMethod(Type targetType, DynamicServerAction dynamicServerAction) { - - List actionMethods = getCandidateMethods(targetType, dynamicServerAction.action); + public static MethodInfo getDispatchMethod( + Type targetType, + DynamicServerAction dynamicServerAction + ) { + List actionMethods = getCandidateMethods( + targetType, + dynamicServerAction.action + ); MethodInfo matchedMethod = null; - int bestMatchCount = -1; // we do this so that + int bestMatchCount = -1; // we do this so that // Debug.Log($"getDispatch method -- targettype {targetType}, methods {string.Join("/n", actionMethods.Select(m => $"method: {m.Name} in class '{m.DeclaringType}' with params {$"{string.Join(", ", m.GetParameters().Select(p => $"{p.ParameterType} {p.Name}"))}"}"))}"); // This is where the the actual matching occurs. The matching is done strictly based on // variable names. In the future, this could be modified to include type information from - // the inbound JSON object by mapping JSON types to csharp primitive types + // the inbound JSON object by mapping JSON types to csharp primitive types // (i.e. number -> [short, float, int], bool -> bool, string -> string, dict -> object, list -> list) foreach (var method in actionMethods) { int matchCount = 0; ParameterInfo[] mParams = method.GetParameters(); - - var childmostType = actionMethods.Aggregate(method.DeclaringType, (acc, m) => m.DeclaringType.IsSubclassOf(acc) ? m.DeclaringType : acc); - var childMostTypeMethods = actionMethods.Where(m => m.DeclaringType.Equals(childmostType)).Select(m => (method: m, parameters: m.GetParameters())); + var childmostType = actionMethods.Aggregate( + method.DeclaringType, + (acc, m) => m.DeclaringType.IsSubclassOf(acc) ? m.DeclaringType : acc + ); + var childMostTypeMethods = actionMethods + .Where(m => m.DeclaringType.Equals(childmostType)) + .Select(m => (method: m, parameters: m.GetParameters())); // mixing a ServerAction action with non-server action creates an ambiguous situation // if one parameter is missing from the overloaded method its not clear whether the caller // intended to call the ServerAction action or was simply missing on of the parameters for the overloaded // variant - var serverActionMethods = childMostTypeMethods - .Where(m => m.parameters.Length == 1 && m.parameters[0].ParameterType == typeof(ServerAction)); + var serverActionMethods = childMostTypeMethods.Where(m => + m.parameters.Length == 1 && m.parameters[0].ParameterType == typeof(ServerAction) + ); - // Throw the exception only if there are more than one methods at the same childmost class level, + // Throw the exception only if there are more than one methods at the same childmost class level, // if not, the child most method will be chosen so there is no ambiguity if (serverActionMethods.Count() > 0 && childMostTypeMethods.Count() > 1) { - throw new AmbiguousActionException($"Mixing a ServerAction method with overloaded methods is not permitted. Ambiguous methods: {string.Join(" | ", serverActionMethods.Select(m => $"method: {m.method.Name} in class '{m.method.DeclaringType}' with params {$"{string.Join(", ", m.parameters.Select(p => $"{p.ParameterType} {p.Name}"))}"}"))}"); + throw new AmbiguousActionException( + $"Mixing a ServerAction method with overloaded methods is not permitted. Ambiguous methods: {string.Join(" | ", serverActionMethods.Select(m => $"method: {m.method.Name} in class '{m.method.DeclaringType}' with params {$"{string.Join(", ", m.parameters.Select(p => $"{p.ParameterType} {p.Name}"))}"}"))}" + ); } // if (actionMethods.Count > 1 && mParams.Length == 1 && mParams[0].ParameterType == typeof(ServerAction)) { - + // throw new AmbiguousActionException("Mixing a ServerAction method with overloaded methods is not permitted"); // } @@ -350,7 +394,11 @@ public static MethodInfo getDispatchMethod(Type targetType, DynamicServerAction // this is also necessary, to allow Initialize to be // called in the AgentManager and an Agent, since we // pass a ServerAction through - if (matchedMethod == null && mParams.Length == 1 && mParams[0].ParameterType == typeof(ServerAction)) { + if ( + matchedMethod == null + && mParams.Length == 1 + && mParams[0].ParameterType == typeof(ServerAction) + ) { matchedMethod = method; } else { foreach (var p in method.GetParameters()) { @@ -360,16 +408,24 @@ public static MethodInfo getDispatchMethod(Type targetType, DynamicServerAction } } - var isSubclassOfBestMatchDeclaringType = matchedMethod != null && matchedMethod.DeclaringType.IsAssignableFrom(method.DeclaringType); - + var isSubclassOfBestMatchDeclaringType = + matchedMethod != null + && matchedMethod.DeclaringType.IsAssignableFrom(method.DeclaringType); + // preference is given to the method that matches all parameters for a method // even if another method has the same matchCount (but has more parameters) // unless is declared in a subclass in which it's given preference - if (matchCount > bestMatchCount || (matchCount == bestMatchCount && isSubclassOfBestMatchDeclaringType && matchedMethod.DeclaringType != method.DeclaringType)) { - + if ( + matchCount > bestMatchCount + || ( + matchCount == bestMatchCount + && isSubclassOfBestMatchDeclaringType + && matchedMethod.DeclaringType != method.DeclaringType + ) + ) { // TODO: decide if this check should be added, or we want whatever method ranked top by 'MethodParamComparer' to be chosen (based on param number and default params) // if (matchedMethod.DeclaringType == method.DeclaringType) { - // // if matchcount is the same between any two methods and same level of inheritance hierarchy throw ambiguous exeption, since no method + // // if matchcount is the same between any two methods and same level of inheritance hierarchy throw ambiguous exeption, since no method // // is clearly prefered // throw new AmbiguousActionException($"Ambiguous call. Cannot distinguish between actions '{method.Name}' at class level '{method.DeclaringType}'"); // } @@ -381,20 +437,25 @@ public static MethodInfo getDispatchMethod(Type targetType, DynamicServerAction return matchedMethod; } - public static IEnumerable getMatchingMethodOverwrites(Type targetType, DynamicServerAction dynamicServerAction) { + public static IEnumerable getMatchingMethodOverwrites( + Type targetType, + DynamicServerAction dynamicServerAction + ) { return getCandidateMethods(targetType, dynamicServerAction.action) - .Select( - method => ( + .Select(method => + ( method, count: method - .GetParameters().Count(param => dynamicServerAction.ContainsKey(param.Name)) + .GetParameters() + .Count(param => dynamicServerAction.ContainsKey(param.Name)) ) ) .OrderByDescending(tuple => tuple.count) .Select((tuple) => tuple.method); } - public static void Dispatch(T target, DynamicServerAction dynamicServerAction) where T : ActionInvokable { + public static void Dispatch(T target, DynamicServerAction dynamicServerAction) + where T : ActionInvokable { MethodInfo method = getDispatchMethod(target.GetType(), dynamicServerAction); if (method == null) { @@ -409,15 +470,22 @@ public static void Dispatch(T target, DynamicServerAction dynamicServerAction var addPhysicsSimulationParams = physicsSimulationParams == null; // If it's passed in the action or was set globally - var usePhysicsSimulationParams = physicsSimulationParams != null || PhysicsSceneManager.defaultPhysicsSimulationParams != null; + var usePhysicsSimulationParams = + physicsSimulationParams != null + || PhysicsSceneManager.defaultPhysicsSimulationParams != null; // Default simulation params if physicsSimulationParams is null and if default is null create the default (backcompat when it's not passed to init) - physicsSimulationParams ??= PhysicsSceneManager.defaultPhysicsSimulationParams ?? new PhysicsSimulationParams(); + physicsSimulationParams ??= + PhysicsSceneManager.defaultPhysicsSimulationParams ?? new PhysicsSimulationParams(); // Set static variable so actions can access it PhysicsSceneManager.SetPhysicsSimulationParams(physicsSimulationParams); if ( - usePhysicsSimulationParams && addPhysicsSimulationParams && - (typeof(IEnumerator) == method.ReturnType || method.ReturnType == typeof(ActionFinished)) + usePhysicsSimulationParams + && addPhysicsSimulationParams + && ( + typeof(IEnumerator) == method.ReturnType + || method.ReturnType == typeof(ActionFinished) + ) ) { // New action types always pass down physicsSim params if interface has them if (paramDict.ContainsKey(DynamicServerAction.physicsSimulationParamsVariable)) { @@ -435,18 +503,17 @@ public static void Dispatch(T target, DynamicServerAction dynamicServerAction .Where(argName => !paramDict.ContainsKey(argName)) .ToList(); if (invalidArgs.Count > 0) { - Func paramToString = - (ParameterInfo param) => - $"{param.ParameterType.Name} {param.Name}{(param.HasDefaultValue ? " = " + param.DefaultValue : "")}"; - var matchingMethodOverWrites = getMatchingMethodOverwrites(target.GetType(), dynamicServerAction).Select( - m => - $"{m.ReturnType.Name} {m.Name}(" + - string.Join(", ", - m.GetParameters() - .Select(paramToString) - ) - + ")" - ); + Func paramToString = (ParameterInfo param) => + $"{param.ParameterType.Name} {param.Name}{(param.HasDefaultValue ? " = " + param.DefaultValue : "")}"; + var matchingMethodOverWrites = getMatchingMethodOverwrites( + target.GetType(), + dynamicServerAction + ) + .Select(m => + $"{m.ReturnType.Name} {m.Name}(" + + string.Join(", ", m.GetParameters().Select(paramToString)) + + ")" + ); throw new InvalidArgumentsException( dynamicServerAction.ArgumentKeys(), @@ -459,7 +526,9 @@ public static void Dispatch(T target, DynamicServerAction dynamicServerAction System.Reflection.ParameterInfo pi = methodParams[i]; if (dynamicServerAction.ContainsKey(pi.Name)) { try { - arguments[i] = dynamicServerAction.GetValue(pi.Name).ToObject(pi.ParameterType); + arguments[i] = dynamicServerAction + .GetValue(pi.Name) + .ToObject(pi.ParameterType); } catch (ArgumentException ex) { throw new ToObjectArgumentActionException( parameterName: pi.Name, @@ -486,11 +555,10 @@ public static void Dispatch(T target, DynamicServerAction dynamicServerAction IEnumerator action = null; object methodReturn; - // TODO: deprecated actions called in the old way that return void + // TODO: deprecated actions called in the old way that return void if (!usePhysicsSimulationParams && method.ReturnType == typeof(void)) { method.Invoke(target, arguments); - } - else { + } else { // Only IEnumerators return functions can be run in a coroutine var runAsCoroutine = false; @@ -498,37 +566,37 @@ public static void Dispatch(T target, DynamicServerAction dynamicServerAction methodReturn = method.Invoke(target, arguments); action = methodReturn as IEnumerator; runAsCoroutine = physicsSimulationParams.autoSimulation; - } - else if (method.ReturnType == typeof(ActionFinished)) { - action = ActionFinishedDelayActionWrapper( + } else if (method.ReturnType == typeof(ActionFinished)) { + action = ActionFinishedDelayActionWrapper( () => method.Invoke(target, arguments) as ActionFinished ); } - // TODO: when legacy actions are gone remove branch - else { - action = ActionFinishedDelayActionWrapper( - () => { - method.Invoke(target, arguments); - // TODO: deprecated void action returns dummy ActionFinished - return new ActionFinished() { isDummy = true }; - } - ); + // TODO: when legacy actions are gone remove branch + else { + action = ActionFinishedDelayActionWrapper(() => { + method.Invoke(target, arguments); + // TODO: deprecated void action returns dummy ActionFinished + return new ActionFinished() { isDummy = true }; + }); } - if (!runAsCoroutine) { + if (!runAsCoroutine) { // Blocking var actionFinished = PhysicsSceneManager.RunSimulatePhysicsForAction( - action, + action, physicsSimulationParams ); // Complete callback at action end, implementation should do any state changes target.Complete(actionFinished); - - } - else { + } else { // "Async" will run after unity's frame update - target.StartCoroutine(PhysicsSceneManager.RunActionForCoroutine(target, action, physicsSimulationParams)); + target.StartCoroutine( + PhysicsSceneManager.RunActionForCoroutine( + target, + action, + physicsSimulationParams + ) + ); } - } } @@ -541,10 +609,7 @@ public static IEnumerator ActionFinishedDelayActionWrapper(Func } } - - public class MethodParamComparer : IComparer { - public int Compare(MethodInfo a, MethodInfo b) { int requiredParamCountA = requiredParamCount(a); int requiredParamCountB = requiredParamCount(b); @@ -569,20 +634,20 @@ private static int requiredParamCount(MethodInfo method) { return count; } - } - [Serializable] public class InvalidActionException : Exception { } public class InvalidActionCallWithPhysicsSimulationParams : Exception { - public InvalidActionCallWithPhysicsSimulationParams(string message): base(message) { } - } + public InvalidActionCallWithPhysicsSimulationParams(string message) + : base(message) { } +} [Serializable] public class AmbiguousActionException : Exception { - public AmbiguousActionException(string message) : base(message) { } + public AmbiguousActionException(string message) + : base(message) { } } [Serializable] @@ -608,6 +673,7 @@ ArgumentException ex [Serializable] public class MissingArgumentsActionException : Exception { public List ArgumentNames; + public MissingArgumentsActionException(List argumentNames) { this.ArgumentNames = argumentNames; } @@ -619,12 +685,13 @@ public class InvalidArgumentsException : Exception { public IEnumerable InvalidArgumentNames; public IEnumerable ParameterNames; public IEnumerable PossibleOverwrites; + public InvalidArgumentsException( - IEnumerable argumentNames, - IEnumerable invalidArgumentNames, - IEnumerable parameterNames = null, - IEnumerable possibleOverwrites = null - ) { + IEnumerable argumentNames, + IEnumerable invalidArgumentNames, + IEnumerable parameterNames = null, + IEnumerable possibleOverwrites = null + ) { this.ArgumentNames = argumentNames; this.InvalidArgumentNames = invalidArgumentNames; this.ParameterNames = parameterNames ?? new List(); @@ -634,5 +701,6 @@ public InvalidArgumentsException( [Serializable] public class MissingActionFinishedException : Exception { - public MissingActionFinishedException(string message = ""): base(message) { } + public MissingActionFinishedException(string message = "") + : base(message) { } } diff --git a/unity/Assets/Scripts/AgentManager.cs b/unity/Assets/Scripts/AgentManager.cs index 5a10f70bf2..6dc119e148 100644 --- a/unity/Assets/Scripts/AgentManager.cs +++ b/unity/Assets/Scripts/AgentManager.cs @@ -1,35 +1,34 @@ using System; using System.Collections; - using System.Collections.Generic; -using UnityEngine; -using UnityStandardAssets.Characters.FirstPerson; using System.IO; -using System.Net.Sockets; +using System.Linq; using System.Net; -using MessagePack.Resolvers; -using MessagePack.Formatters; +using System.Net.Sockets; +using System.Reflection; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; using MessagePack; +using MessagePack.Formatters; +using MessagePack.Resolvers; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -using System.Threading; -using UnityEngine.Rendering; +using Thor.Procedural.Data; +using UnityEngine; using UnityEngine.Experimental.Rendering; +using UnityEngine.Networking; +using UnityEngine.Rendering; +using UnityEngine.Rendering.PostProcessing; +using UnityStandardAssets.Characters.FirstPerson; +using UnityStandardAssets.ImageEffects; #if PLATFORM_CLOUD_RENDERING using Unity.Simulation; using UnityEditor; using UnityEngine.CloudRendering; #endif -using UnityEngine.Networking; -using System.Linq; -using UnityEngine.Rendering.PostProcessing; -using UnityStandardAssets.ImageEffects; -using Thor.Procedural.Data; -using System.Runtime.InteropServices; public class AgentManager : MonoBehaviour, ActionInvokable { public List agents = new List(); @@ -53,24 +52,45 @@ public class AgentManager : MonoBehaviour, ActionInvokable { private bool renderNormalsImage; private bool renderFlowImage; private Socket sock = null; + [SerializeField] public List thirdPartyCameras = new List(); - private Color[] agentColors = new Color[] { Color.blue, Color.yellow, Color.green, Color.red, Color.magenta, Color.grey }; + private Color[] agentColors = new Color[] + { + Color.blue, + Color.yellow, + Color.green, + Color.red, + Color.magenta, + Color.grey + }; public int actionDuration = 3; public BaseFPSAgentController primaryAgent; - public PhysicsSceneManager physicsSceneManager { - get; - private set; - } + public PhysicsSceneManager physicsSceneManager { get; private set; } private FifoServer.Client fifoClient = null; - private enum serverTypes { WSGI, FIFO }; + + private enum serverTypes { + WSGI, + FIFO + }; + private serverTypes serverType; private AgentState agentManagerState = AgentState.Emit; private bool fastActionEmit = true; // it is public to be accessible from the debug input field. - public HashSet agentManagerActions = new HashSet { "Reset", "Initialize", "AddThirdPartyCamera", "UpdateMainCamera", "UpdateThirdPartyCamera", "ChangeResolution", "CoordinateFromRaycastThirdPartyCamera", "ChangeQuality" }; - public HashSet errorAllowedActions = new HashSet { "Reset" }; + public HashSet agentManagerActions = new HashSet + { + "Reset", + "Initialize", + "AddThirdPartyCamera", + "UpdateMainCamera", + "UpdateThirdPartyCamera", + "ChangeResolution", + "CoordinateFromRaycastThirdPartyCamera", + "ChangeQuality" + }; + public HashSet errorAllowedActions = new HashSet { "Reset" }; public bool doResetMaterials = false; public bool doResetColors = false; @@ -80,7 +100,6 @@ private enum serverTypes { WSGI, FIFO }; public const float MIN_FOV = 0; public string agentMode; - public Bounds sceneBounds = UtilityFunctions.CreateEmptyBounds(); public Bounds SceneBounds { get { @@ -89,14 +108,16 @@ public Bounds SceneBounds { } return sceneBounds; } - set { - sceneBounds = value; - } + set { sceneBounds = value; } } void Awake() { - - tex = new Texture2D(UnityEngine.Screen.width, UnityEngine.Screen.height, TextureFormat.RGB24, false); + tex = new Texture2D( + UnityEngine.Screen.width, + UnityEngine.Screen.height, + TextureFormat.RGB24, + false + ); readPixelsRect = new Rect(0, 0, UnityEngine.Screen.width, UnityEngine.Screen.height); #if !UNITY_WEBGL @@ -104,7 +125,7 @@ void Awake() { // https://forum.unity.com/threads/rendering-without-using-requestanimationframe-for-the-main-loop.373331/ Application.targetFrameRate = 3000; #else - Debug.unityLogger.logEnabled = Debug.isDebugBuild; + Debug.unityLogger.logEnabled = Debug.isDebugBuild; #endif QualitySettings.vSyncCount = 0; @@ -113,7 +134,11 @@ void Awake() { serverSideScreenshot = LoadBoolVariable(serverSideScreenshot, "SERVER_SIDE_SCREENSHOT"); // serverSideScreenshot = true; robosimsClientToken = LoadStringVariable(robosimsClientToken, "CLIENT_TOKEN"); - serverType = (serverTypes)Enum.Parse(typeof(serverTypes), LoadStringVariable(serverTypes.WSGI.ToString(), "SERVER_TYPE").ToUpper()); + serverType = (serverTypes) + Enum.Parse( + typeof(serverTypes), + LoadStringVariable(serverTypes.WSGI.ToString(), "SERVER_TYPE").ToUpper() + ); if (serverType == serverTypes.FIFO) { string serverPipePath = LoadStringVariable(null, "FIFO_SERVER_PIPE_PATH"); string clientPipePath = LoadStringVariable(null, "FIFO_CLIENT_PIPE_PATH"); @@ -121,7 +146,6 @@ void Awake() { // TODO: Create dir if not exists if (string.IsNullOrEmpty(serverPipePath)) { serverPipePath = "fifo_pipe/server.pipe"; - } if (string.IsNullOrEmpty(clientPipePath)) { clientPipePath = "fifo_pipe/client.pipe"; @@ -130,15 +154,14 @@ void Awake() { Debug.Log("creating fifo server: " + serverPipePath); Debug.Log("client fifo path: " + clientPipePath); this.fifoClient = FifoServer.Client.GetInstance(serverPipePath, clientPipePath); - } - #if UNITY_EDITOR +#if UNITY_EDITOR if (serverType == serverTypes.WSGI) { serverSideScreenshot = true; print("---ServerSideScreenshot enabled"); } - #endif +#endif bool trainPhase = true; trainPhase = LoadBoolVariable(trainPhase, "TRAIN_PHASE"); @@ -148,39 +171,41 @@ void Awake() { string prefix = trainPhase ? "TRAIN_" : "TEST_"; actionDuration = LoadIntVariable(actionDuration, prefix + "ACTION_LENGTH"); - } void Start() { // default primary agent's agentController type to "PhysicsRemoteFPSAgentController" initializePrimaryAgent(); // primaryAgent.stand - #if PLATFORM_CLOUD_RENDERING +#if PLATFORM_CLOUD_RENDERING // must wrap this in PLATFORM_CLOUDRENDERING // needed to ensure that the com.unity.simulation.capture package // gets initialized var instance = Manager.Instance; Camera camera = this.primaryAgent.gameObject.GetComponentInChildren(); camera.targetTexture = createRenderTexture(Screen.width, Screen.height); - #endif +#endif primaryAgent.actionDuration = this.actionDuration; // this.agents.Add (primaryAgent); - physicsSceneManager = GameObject.Find("PhysicsSceneManager").GetComponent(); + physicsSceneManager = GameObject + .Find("PhysicsSceneManager") + .GetComponent(); // auto set agentMode to default for the web demo #if UNITY_WEBGL physicsSceneManager.UnpausePhysicsAutoSim(); primaryAgent.InitializeBody(null); JavaScriptInterface jsInterface = primaryAgent.GetComponent(); - if (jsInterface != null) { + if (jsInterface != null) + { jsInterface.enabled = true; } #endif StartCoroutine(EmitFrame()); } - public void Complete(ActionFinished result) { + public void Complete(ActionFinished result) { this.activeAgent().Complete(result); } @@ -233,8 +258,7 @@ public void Initialize(ServerAction action) { // TODO make calll using ProcessControlCommand var initp = action.dynamicServerAction.ToObject(); - - // TODO Decide if we want to run it + // TODO Decide if we want to run it // var jsonResolver = new ShouldSerializeContractResolver(); // var json = Newtonsoft.Json.JsonConvert.SerializeObject( // new Dictionary() { {"args", initp} }, @@ -244,25 +268,29 @@ public void Initialize(ServerAction action) { // ContractResolver = jsonResolver // } // ); - + // // var clone = action.dynamicServerAction.jObject.DeepClone().ToObject(); // // clone["action"] = "BackwardsCompatibleInitialize"; // var actionCopy = new DynamicServerAction(json); // actionCopy.jObject.Add(new JProperty("action", "BackwardsCompatibleInitialize")); // primaryAgent.ProcessControlCommand(actionCopy); - + var fpin = primaryAgent as FpinAgentController; var actionFinished = fpin.BackwardsCompatibleInitialize(initp); - Debug.Log($"BackwardsCompatibleInitialize of AgentController. lastActionSuccess: {actionFinished.success}, errorMessage: {actionFinished.errorMessage} actionReturn: {actionFinished.actionReturn}, agentState: {primaryAgent.agentState}"); + Debug.Log( + $"BackwardsCompatibleInitialize of AgentController. lastActionSuccess: {actionFinished.success}, errorMessage: {actionFinished.errorMessage} actionReturn: {actionFinished.actionReturn}, agentState: {primaryAgent.agentState}" + ); if (!actionFinished.success) { - primaryAgent.actionFinished(false, $"Error running 'BackwardsCompatibleInitialize' failed with error: {actionFinished.errorMessage}"); + primaryAgent.actionFinished( + false, + $"Error running 'BackwardsCompatibleInitialize' failed with error: {actionFinished.errorMessage}" + ); return; } // if (actiongF) // actionFinished. - } else { var error = $"Invalid agentMode {action.agentMode}"; Debug.Log(error); @@ -274,7 +302,8 @@ public void Initialize(ServerAction action) { if (action.massThreshold.Value > 0.0) { SetUpMassThreshold(action.massThreshold.Value); } else { - var error = $"massThreshold must have nonzero value - invalid value: {action.massThreshold.Value}"; + var error = + $"massThreshold must have nonzero value - invalid value: {action.massThreshold.Value}"; Debug.Log(error); primaryAgent.actionFinished(false, error); return; @@ -286,11 +315,13 @@ public void Initialize(ServerAction action) { // Allows to segment specific agent initialization params and move away from bloated ServerAction class primaryAgent.ProcessControlCommand( // action.dynamicServerAction.agentInitializationParams ?? action.dynamicServerAction - !action.dynamicServerAction.HasAgentInitializationParams() ? - action.dynamicServerAction : - action.dynamicServerAction.agentInitializationParams + !action.dynamicServerAction.HasAgentInitializationParams() + ? action.dynamicServerAction + : action.dynamicServerAction.agentInitializationParams + ); + Debug.Log( + $"Initialize of AgentController. lastActionSuccess: {primaryAgent.lastActionSuccess}, errorMessage: {primaryAgent.errorMessage}, actionReturn: {primaryAgent.actionReturn}, agentState: {primaryAgent.agentState}" ); - Debug.Log($"Initialize of AgentController. lastActionSuccess: {primaryAgent.lastActionSuccess}, errorMessage: {primaryAgent.errorMessage}, actionReturn: {primaryAgent.actionReturn}, agentState: {primaryAgent.agentState}"); Time.fixedDeltaTime = action.fixedDeltaTime.GetValueOrDefault(Time.fixedDeltaTime); if (action.targetFrameRate > 0) { Application.targetFrameRate = action.targetFrameRate; @@ -300,12 +331,15 @@ public void Initialize(ServerAction action) { this.renderSemanticSegmentation = action.renderSemanticSegmentation; this.renderDepthImage = action.renderDepthImage; this.renderNormalsImage = action.renderNormalsImage; - this.renderInstanceSegmentation = this.initializedInstanceSeg = action.renderInstanceSegmentation; + this.renderInstanceSegmentation = this.initializedInstanceSeg = + action.renderInstanceSegmentation; this.renderFlowImage = action.renderFlowImage; this.fastActionEmit = action.fastActionEmit; - + PhysicsSceneManager.SetDefaultSimulationParams(action.defaultPhysicsSimulationParams); - Time.fixedDeltaTime = (action.defaultPhysicsSimulationParams?.fixedDeltaTime).GetValueOrDefault(Time.fixedDeltaTime); + Time.fixedDeltaTime = ( + action.defaultPhysicsSimulationParams?.fixedDeltaTime + ).GetValueOrDefault(Time.fixedDeltaTime); // we default Physics.autoSimulation to False in the built Player, but // set ServerAction.autoSimulation = True for backwards compatibility. Keeping // this value False allows the user complete control of all Physics Simulation @@ -314,7 +348,8 @@ public void Initialize(ServerAction action) { Physics.autoSyncTransforms = Physics.autoSimulation; if (action.alwaysReturnVisibleRange) { - ((PhysicsRemoteFPSAgentController)primaryAgent).alwaysReturnVisibleRange = action.alwaysReturnVisibleRange; + ((PhysicsRemoteFPSAgentController)primaryAgent).alwaysReturnVisibleRange = + action.alwaysReturnVisibleRange; } //if multi agent requested, add duplicates of primary agent now @@ -376,8 +411,13 @@ public void SetUpFpinController(ServerAction action) { primaryAgent = createAgentType(typeof(FpinAgentController), baseAgentComponent); } - private BaseFPSAgentController createAgentType(Type agentType, BaseAgentComponent agentComponent) { - BaseFPSAgentController agent = Activator.CreateInstance(agentType, new object[] { agentComponent, this }) as BaseFPSAgentController; + private BaseFPSAgentController createAgentType( + Type agentType, + BaseAgentComponent agentComponent + ) { + BaseFPSAgentController agent = + Activator.CreateInstance(agentType, new object[] { agentComponent, this }) + as BaseFPSAgentController; this.agents.Add(agent); return agent; } @@ -386,7 +426,9 @@ private void SetUpArmController(bool midLevelArm) { this.agents.Clear(); BaseAgentComponent baseAgentComponent = GameObject.FindObjectOfType(); primaryAgent = createAgentType(typeof(KinovaArmAgentController), baseAgentComponent); - var handObj = primaryAgent.transform.FirstChildOrDefault((x) => x.name == "robot_arm_rig_gripper"); + var handObj = primaryAgent.transform.FirstChildOrDefault( + (x) => x.name == "robot_arm_rig_gripper" + ); handObj.gameObject.SetActive(true); } @@ -411,13 +453,24 @@ private void addAgents(ServerAction action) { // primary agent floating in space, then generates the house, then teleports the primary agent. // this will need a rework to make multi agent work as GetReachablePositions is used to position additional // agents, which won't work if we initialize the agent(s) before the scene exists - if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name.StartsWith("Procedural")) { - throw new NotImplementedException($"Procedural scenes only support a single agent currently."); + if ( + UnityEngine + .SceneManagement.SceneManager.GetActiveScene() + .name.StartsWith("Procedural") + ) { + throw new NotImplementedException( + $"Procedural scenes only support a single agent currently." + ); } Physics.SyncTransforms(); Vector3[] reachablePositions = primaryAgent.getReachablePositions(2.0f); - for (int i = 1; i < action.agentCount && this.agents.Count < Math.Min(agentColors.Length, action.agentCount); i++) { + for ( + int i = 1; + i < action.agentCount + && this.agents.Count < Math.Min(agentColors.Length, action.agentCount); + i++ + ) { action.x = reachablePositions[i + 4].x; action.y = reachablePositions[i + 4].y; action.z = reachablePositions[i + 4].z; @@ -455,7 +508,11 @@ public void RotateAgentsByRotatingUniverse(float rotation) { superObject.transform.position = this.agents[0].transform.position; List topLevelObjects = new List(); - foreach (GameObject go in UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects()) { + foreach ( + GameObject go in UnityEngine + .SceneManagement.SceneManager.GetActiveScene() + .GetRootGameObjects() + ) { topLevelObjects.Add(go); go.transform.SetParent(superObject.transform); } @@ -472,16 +529,23 @@ public void RotateAgentsByRotatingUniverse(float rotation) { ResetSceneBounds(); } - public void registerAsThirdPartyCamera(Camera camera) { this.thirdPartyCameras.Add(camera); - #if PLATFORM_CLOUD_RENDERING - camera.targetTexture = createRenderTexture(this.primaryAgent.m_Camera.pixelWidth, this.primaryAgent.m_Camera.targetTexture.height); - #endif +#if PLATFORM_CLOUD_RENDERING + camera.targetTexture = createRenderTexture( + this.primaryAgent.m_Camera.pixelWidth, + this.primaryAgent.m_Camera.targetTexture.height + ); +#endif } // If fov is <= min or > max, return defaultVal, else return fov - private float ClampFieldOfView(float fov, float defaultVal = 90f, float min = 0f, float max = 180f) { + private float ClampFieldOfView( + float fov, + float defaultVal = 90f, + float min = 0f, + float max = 180f + ) { return (fov <= min || fov > max) ? defaultVal : fov; } @@ -495,11 +559,13 @@ public void updateThirdPartyCameraImageSynthesis(bool status) { if (status) { foreach (var camera in this.thirdPartyCameras) { GameObject gameObject = camera.gameObject; - var imageSynthesis = gameObject.GetComponentInChildren() as ImageSynthesis; + var imageSynthesis = + gameObject.GetComponentInChildren() as ImageSynthesis; if (imageSynthesis == null) { gameObject.AddComponent(typeof(ImageSynthesis)); } - imageSynthesis = gameObject.GetComponentInChildren() as ImageSynthesis; + imageSynthesis = + gameObject.GetComponentInChildren() as ImageSynthesis; imageSynthesis.enabled = status; } } @@ -522,9 +588,9 @@ private void updateCameraProperties( ) { if (orthographic != true && orthographicSize != null) { throw new InvalidOperationException( - $"orthographicSize(: {orthographicSize}) can only be set when orthographic=True.\n" + - "Otherwise, we use assume perspective camera setting." + - "Hint: call .step(..., orthographic=True)." + $"orthographicSize(: {orthographicSize}) can only be set when orthographic=True.\n" + + "Otherwise, we use assume perspective camera setting." + + "Hint: call .step(..., orthographic=True)." ); } @@ -585,7 +651,6 @@ private void updateCameraProperties( if (nearClippingPlane != null) { camera.nearClipPlane = (float)nearClippingPlane; } - //default to primary agent's near clip plane value else { camera.nearClipPlane = this.primaryAgent.m_Camera.nearClipPlane; @@ -594,7 +659,6 @@ private void updateCameraProperties( if (farClippingPlane != null) { camera.farClipPlane = (float)farClippingPlane; } - //default to primary agent's far clip plane value else { camera.farClipPlane = this.primaryAgent.m_Camera.farClipPlane; @@ -610,7 +674,9 @@ private void updateCameraProperties( camera.clearFlags = CameraClearFlags.SolidColor; camera.backgroundColor = color; } else { - throw new ArgumentException($"Invalid skyboxColor: {skyboxColor}! Cannot be parsed as an HTML color."); + throw new ArgumentException( + $"Invalid skyboxColor: {skyboxColor}! Cannot be parsed as an HTML color." + ); } } @@ -632,7 +698,9 @@ private void updateCameraProperties( private void assertFovInBounds(float fov) { if (fov <= MIN_FOV || fov >= MAX_FOV) { - throw new ArgumentOutOfRangeException($"fieldOfView: {fov} must be in {MIN_FOV} < fieldOfView > {MIN_FOV}."); + throw new ArgumentOutOfRangeException( + $"fieldOfView: {fov} must be in {MIN_FOV} < fieldOfView > {MIN_FOV}." + ); } } @@ -644,13 +712,19 @@ public void updateAntiAliasing(PostProcessLayer postProcessLayer, string antiAli postProcessLayer.enabled = true; switch (antiAliasing) { case "fxaa": - postProcessLayer.antialiasingMode = PostProcessLayer.Antialiasing.FastApproximateAntialiasing; + postProcessLayer.antialiasingMode = PostProcessLayer + .Antialiasing + .FastApproximateAntialiasing; break; case "smaa": - postProcessLayer.antialiasingMode = PostProcessLayer.Antialiasing.SubpixelMorphologicalAntialiasing; + postProcessLayer.antialiasingMode = PostProcessLayer + .Antialiasing + .SubpixelMorphologicalAntialiasing; break; case "taa": - postProcessLayer.antialiasingMode = PostProcessLayer.Antialiasing.TemporalAntialiasing; + postProcessLayer.antialiasingMode = PostProcessLayer + .Antialiasing + .TemporalAntialiasing; break; default: throw new InvalidOperationException( @@ -678,19 +752,29 @@ public void AddThirdPartyCamera( // adds error if fieldOfView is out of bounds assertFovInBounds(fov: fieldOfView); - GameObject gameObject = GameObject.Instantiate(Resources.Load("ThirdPartyCameraTemplate")) as GameObject; + GameObject gameObject = + GameObject.Instantiate(Resources.Load("ThirdPartyCameraTemplate")) as GameObject; gameObject.name = "ThirdPartyCamera" + thirdPartyCameras.Count; Camera camera = gameObject.GetComponentInChildren(); // set up returned image camera.cullingMask = ~LayerMask.GetMask("PlaceableSurface"); - if (renderDepthImage || renderSemanticSegmentation || renderInstanceSegmentation || renderNormalsImage || renderFlowImage) { + if ( + renderDepthImage + || renderSemanticSegmentation + || renderInstanceSegmentation + || renderNormalsImage + || renderFlowImage + ) { gameObject.AddComponent(typeof(ImageSynthesis)); } - - #if PLATFORM_CLOUD_RENDERING - camera.targetTexture = createRenderTexture(this.primaryAgent.m_Camera.pixelWidth, this.primaryAgent.m_Camera.targetTexture.height); - #endif + +#if PLATFORM_CLOUD_RENDERING + camera.targetTexture = createRenderTexture( + this.primaryAgent.m_Camera.pixelWidth, + this.primaryAgent.m_Camera.targetTexture.height + ); +#endif thirdPartyCameras.Add(camera); updateCameraProperties( @@ -711,10 +795,7 @@ public void AddThirdPartyCamera( } // helper that can be used when converting Dictionary to a Vector3. - private Vector3 parseOptionalVector3( - OptionalVector3 optionalVector3, - Vector3 defaultsOnNull - ) { + private Vector3 parseOptionalVector3(OptionalVector3 optionalVector3, Vector3 defaultsOnNull) { if (optionalVector3 == null) { return defaultsOnNull; } @@ -740,7 +821,7 @@ public OptionalVector3(float? x = null, float? y = null, float? z = null) { //allows repositioning and changing of values of agent's primary camera //note this does not support changing the main camera of multiple agents beyond the primary for now - public void UpdateMainCamera ( + public void UpdateMainCamera( OptionalVector3 position = null, OptionalVector3 rotation = null, float? fieldOfView = null, @@ -766,8 +847,14 @@ public void UpdateMainCamera ( Vector3 oldPosition = agentMainCam.transform.localPosition; Vector3 oldRotation = agentMainCam.transform.localEulerAngles; - Vector3 targetPosition = parseOptionalVector3(optionalVector3: position, defaultsOnNull: oldPosition); - Vector3 targetRotation = parseOptionalVector3(optionalVector3: rotation, defaultsOnNull: oldRotation); + Vector3 targetPosition = parseOptionalVector3( + optionalVector3: position, + defaultsOnNull: oldPosition + ); + Vector3 targetRotation = parseOptionalVector3( + optionalVector3: rotation, + defaultsOnNull: oldRotation + ); updateCameraProperties( camera: agentMainCam, position: targetPosition, @@ -827,8 +914,14 @@ public void UpdateThirdPartyCamera( oldRotation = thirdPartyCamera.transform.eulerAngles; } - Vector3 targetPosition = parseOptionalVector3(optionalVector3: position, defaultsOnNull: oldPosition); - Vector3 targetRotation = parseOptionalVector3(optionalVector3: rotation, defaultsOnNull: oldRotation); + Vector3 targetPosition = parseOptionalVector3( + optionalVector3: position, + defaultsOnNull: oldPosition + ); + Vector3 targetRotation = parseOptionalVector3( + optionalVector3: rotation, + defaultsOnNull: oldRotation + ); updateCameraProperties( camera: thirdPartyCamera, position: targetPosition, @@ -848,24 +941,34 @@ public void UpdateThirdPartyCamera( private void addAgent(ServerAction action) { Vector3 clonePosition = new Vector3(action.x, action.y, action.z); - BaseAgentComponent componentClone = UnityEngine.Object.Instantiate(primaryAgent.baseAgentComponent); + BaseAgentComponent componentClone = UnityEngine.Object.Instantiate( + primaryAgent.baseAgentComponent + ); var agent = createAgentType(primaryAgent.GetType(), componentClone); agent.IsVisible = action.makeAgentsVisible; agent.actionDuration = this.actionDuration; // clone.m_Camera.targetDisplay = this.agents.Count; componentClone.transform.position = clonePosition; UpdateAgentColor(agent, agentColors[this.agents.Count]); - + #if PLATFORM_CLOUD_RENDERING - agent.m_Camera.targetTexture = createRenderTexture(this.primaryAgent.m_Camera.targetTexture.width, this.primaryAgent.m_Camera.targetTexture.height); -#endif + agent.m_Camera.targetTexture = createRenderTexture( + this.primaryAgent.m_Camera.targetTexture.width, + this.primaryAgent.m_Camera.targetTexture.height + ); +#endif agent.ProcessControlCommand(action.dynamicServerAction); } private Vector3 agentStartPosition(BaseFPSAgentController agent) { - Transform t = agent.transform; - Vector3[] castDirections = new Vector3[] { t.forward, t.forward * -1, t.right, t.right * -1 }; + Vector3[] castDirections = new Vector3[] + { + t.forward, + t.forward * -1, + t.right, + t.right * -1 + }; RaycastHit maxHit = new RaycastHit(); Vector3 maxDirection = Vector3.zero; @@ -875,32 +978,31 @@ private Vector3 agentStartPosition(BaseFPSAgentController agent) { Vector3 p1 = t.position + charContr.center + Vector3.up * -charContr.height * 0.5f; Vector3 p2 = p1 + Vector3.up * charContr.height; foreach (Vector3 d in castDirections) { - if (Physics.CapsuleCast(p1, p2, charContr.radius, d, out hit)) { if (hit.distance > maxHit.distance) { maxHit = hit; maxDirection = d; } - } } if (maxHit.distance > (charContr.radius * 5)) { return t.position + (maxDirection * (charContr.radius * 4)); - } return Vector3.zero; } public void UpdateAgentColor(BaseFPSAgentController agent, Color color) { - foreach (MeshRenderer r in agent.gameObject.GetComponentsInChildren() as MeshRenderer[]) { + foreach ( + MeshRenderer r in agent.gameObject.GetComponentsInChildren() + as MeshRenderer[] + ) { foreach (Material m in r.materials) { if (m.name.Contains("Agent_Color_Mat")) { m.color = color; } } - } } @@ -915,7 +1017,9 @@ public IEnumerator ResetCoroutine(ServerAction response) { yield return null; if (string.IsNullOrEmpty(response.sceneName)) { - UnityEngine.SceneManagement.SceneManager.LoadScene(UnityEngine.SceneManagement.SceneManager.GetActiveScene().name); + UnityEngine.SceneManagement.SceneManager.LoadScene( + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + ); } else { UnityEngine.SceneManagement.SceneManager.LoadScene(response.sceneName); } @@ -955,31 +1059,39 @@ public bool SwitchScene(string sceneName) { // And if we need to capture a new frame private void Update() { - physicsSceneManager.isSceneAtRest = true;// assume the scene is at rest by default + physicsSceneManager.isSceneAtRest = true; // assume the scene is at rest by default } - - private void captureScreenAsync(List> payload, string key, Camera camera) { + private void captureScreenAsync( + List> payload, + string key, + Camera camera + ) { RenderTexture tt = camera.targetTexture; RenderTexture.active = tt; camera.Render(); - AsyncGPUReadback.Request(tt, 0, (request) => - { - if (!request.hasError) { - var data = request.GetData().ToArray(); - payload.Add(new KeyValuePair(key, data)); - } - else - { - Debug.Log("Request error: " + request.hasError); + AsyncGPUReadback.Request( + tt, + 0, + (request) => { + if (!request.hasError) { + var data = request.GetData().ToArray(); + payload.Add(new KeyValuePair(key, data)); + } else { + Debug.Log("Request error: " + request.hasError); + } } - }); + ); } private byte[] captureScreen() { - if (tex.height != UnityEngine.Screen.height || - tex.width != UnityEngine.Screen.width) { - tex = new Texture2D(UnityEngine.Screen.width, UnityEngine.Screen.height, TextureFormat.RGB24, false); + if (tex.height != UnityEngine.Screen.height || tex.width != UnityEngine.Screen.width) { + tex = new Texture2D( + UnityEngine.Screen.width, + UnityEngine.Screen.height, + TextureFormat.RGB24, + false + ); readPixelsRect = new Rect(0, 0, UnityEngine.Screen.width, UnityEngine.Screen.height); } tex.ReadPixels(readPixelsRect, 0, 0); @@ -987,7 +1099,6 @@ private byte[] captureScreen() { return tex.GetRawTextureData(); } - private void addThirdPartyCameraImage(List> payload, Camera camera) { #if PLATFORM_CLOUD_RENDERING captureScreenAsync(payload, "image-thirdParty-camera", camera); @@ -1000,7 +1111,6 @@ private void addThirdPartyCameraImage(List> payload private void addImage(List> payload, BaseFPSAgentController agent) { if (this.renderImage) { - #if PLATFORM_CLOUD_RENDERING captureScreenAsync(payload, "image", agent.m_Camera); #else @@ -1045,8 +1155,8 @@ public IEnumerator WaitOnResolutionChange(int width, int height) { if (Screen.width != width || Screen.height != height) { success = false; this.primaryAgent.errorMessage = ( - $"Screen resolution change failed, requested ({width}, {height}), actual ({Screen.width}, {Screen.height})." + - $" This is likely due to Unity not supporting the requested resolution and instead using the closest possible resolution." + $"Screen resolution change failed, requested ({width}, {height}), actual ({Screen.width}, {Screen.height})." + + $" This is likely due to Unity not supporting the requested resolution and instead using the closest possible resolution." ); } @@ -1062,27 +1172,30 @@ public void ChangeQuality(string quality) { break; } } - + this.primaryAgent.actionFinished(true); } - public void ChangeResolution(int x, int y) { Screen.SetResolution(width: x, height: y, false); - Debug.Log("current screen resolution pre change: " + Screen.width + " height" + Screen.height); + Debug.Log( + "current screen resolution pre change: " + Screen.width + " height" + Screen.height + ); #if PLATFORM_CLOUD_RENDERING - foreach (var agent in this.agents) { + foreach (var agent in this.agents) + { var rt = agent.m_Camera.targetTexture; rt.Release(); Destroy(rt); - agent.m_Camera.targetTexture = createRenderTexture(x, y); + agent.m_Camera.targetTexture = createRenderTexture(x, y); } - - foreach (var camera in this.thirdPartyCameras) { + + foreach (var camera in this.thirdPartyCameras) + { var rt = camera.targetTexture; rt.Release(); Destroy(rt); - camera.targetTexture = createRenderTexture(x, y); + camera.targetTexture = createRenderTexture(x, y); } #endif StartCoroutine(WaitOnResolutionChange(width: x, height: y)); @@ -1094,9 +1207,11 @@ private void addObjectImage( ref MetadataWrapper metadata ) { if (this.renderInstanceSegmentation || this.renderSemanticSegmentation) { - Debug.Log($"imageSynthesis null {agent.ImageSynthesis==null}"); + Debug.Log($"imageSynthesis null {agent.ImageSynthesis == null}"); if (!agent.ImageSynthesis.hasCapturePass("_id")) { - Debug.LogError("Object Image not available in imagesynthesis - returning empty image"); + Debug.LogError( + "Object Image not available in imagesynthesis - returning empty image" + ); } byte[] bytes = agent.ImageSynthesis.Encode("_id"); payload.Add(new KeyValuePair("image_ids", bytes)); @@ -1104,21 +1219,27 @@ ref MetadataWrapper metadata List colors = new List(); foreach (Color key in agent.ImageSynthesis.colorIds.Keys) { ColorId cid = new ColorId(); - cid.color = new ushort[] { - (ushort)Math.Round (key.r * 255), - (ushort)Math.Round (key.g * 255), - (ushort)Math.Round (key.b * 255) + cid.color = new ushort[] + { + (ushort)Math.Round(key.r * 255), + (ushort)Math.Round(key.g * 255), + (ushort)Math.Round(key.b * 255) }; cid.name = agent.ImageSynthesis.colorIds[key]; colors.Add(cid); } metadata.colors = colors.ToArray(); - } } - private void addImageSynthesisImage(List> payload, ImageSynthesis synth, bool flag, string captureName, string fieldName) { + private void addImageSynthesisImage( + List> payload, + ImageSynthesis synth, + bool flag, + string captureName, + string fieldName + ) { if (flag) { if (!synth.hasCapturePass(captureName)) { Debug.LogError(captureName + " not available - sending empty image"); @@ -1159,7 +1280,7 @@ bool shouldRenderImageSynthesis multiMeta.sequenceId = this.currentSequenceId; RenderTexture currentTexture = null; - + if (shouldRender) { currentTexture = RenderTexture.active; for (int i = 0; i < this.thirdPartyCameras.Count; i++) { @@ -1172,27 +1293,71 @@ bool shouldRenderImageSynthesis //agent relative third party camera metadata here //if the camera is a child of the base agent, then return local space values - if(camera.GetComponentInParent()) { - cMetadata.agentPositionRelativeThirdPartyCameraPosition = camera.gameObject.transform.localPosition; - cMetadata.agentPositionRelativeThirdPartyCameraRotation = camera.gameObject.transform.localEulerAngles; + if (camera.GetComponentInParent()) { + cMetadata.agentPositionRelativeThirdPartyCameraPosition = camera + .gameObject + .transform + .localPosition; + cMetadata.agentPositionRelativeThirdPartyCameraRotation = camera + .gameObject + .transform + .localEulerAngles; } else { //if this third party camera is not a child of the agent, then the agent relative coordinates //are the same as the world coordinates so - cMetadata.agentPositionRelativeThirdPartyCameraPosition = camera.gameObject.transform.position; - cMetadata.agentPositionRelativeThirdPartyCameraRotation = camera.gameObject.transform.eulerAngles; + cMetadata.agentPositionRelativeThirdPartyCameraPosition = camera + .gameObject + .transform + .position; + cMetadata.agentPositionRelativeThirdPartyCameraRotation = camera + .gameObject + .transform + .eulerAngles; } - + cMetadata.fieldOfView = camera.fieldOfView; cameraMetadata[i] = cMetadata; addThirdPartyCameraImage(renderPayload, camera); if (shouldRenderImageSynthesis) { - ImageSynthesis imageSynthesis = camera.gameObject.GetComponentInChildren() as ImageSynthesis; - addImageSynthesisImage(renderPayload, imageSynthesis, this.renderDepthImage, "_depth", "image_thirdParty_depth"); - addImageSynthesisImage(renderPayload, imageSynthesis, this.renderNormalsImage, "_normals", "image_thirdParty_normals"); - addImageSynthesisImage(renderPayload, imageSynthesis, this.renderInstanceSegmentation, "_id", "image_thirdParty_image_ids"); - addImageSynthesisImage(renderPayload, imageSynthesis, this.renderSemanticSegmentation, "_class", "image_thirdParty_classes"); - addImageSynthesisImage(renderPayload, imageSynthesis, this.renderSemanticSegmentation, "_flow", "image_thirdParty_flow");// XXX fix this in a bit + ImageSynthesis imageSynthesis = + camera.gameObject.GetComponentInChildren() + as ImageSynthesis; + addImageSynthesisImage( + renderPayload, + imageSynthesis, + this.renderDepthImage, + "_depth", + "image_thirdParty_depth" + ); + addImageSynthesisImage( + renderPayload, + imageSynthesis, + this.renderNormalsImage, + "_normals", + "image_thirdParty_normals" + ); + addImageSynthesisImage( + renderPayload, + imageSynthesis, + this.renderInstanceSegmentation, + "_id", + "image_thirdParty_image_ids" + ); + addImageSynthesisImage( + renderPayload, + imageSynthesis, + this.renderSemanticSegmentation, + "_class", + "image_thirdParty_classes" + ); + addImageSynthesisImage( + renderPayload, + imageSynthesis, + this.renderSemanticSegmentation, + "_flow", + "image_thirdParty_flow" + ); // XXX fix this in a bit } } } @@ -1206,15 +1371,39 @@ bool shouldRenderImageSynthesis metadata.agentId = i; // we don't need to render the agent's camera for the first agent - + if (shouldRender) { addImage(renderPayload, agent); if (shouldRenderImageSynthesis) { - addImageSynthesisImage(renderPayload, agent.imageSynthesis, this.renderDepthImage, "_depth", "image_depth"); - addImageSynthesisImage(renderPayload, agent.imageSynthesis, this.renderNormalsImage, "_normals", "image_normals"); + addImageSynthesisImage( + renderPayload, + agent.imageSynthesis, + this.renderDepthImage, + "_depth", + "image_depth" + ); + addImageSynthesisImage( + renderPayload, + agent.imageSynthesis, + this.renderNormalsImage, + "_normals", + "image_normals" + ); addObjectImage(renderPayload, agent, ref metadata); - addImageSynthesisImage(renderPayload, agent.imageSynthesis, this.renderSemanticSegmentation, "_class", "image_classes"); - addImageSynthesisImage(renderPayload, agent.imageSynthesis, this.renderFlowImage, "_flow", "image_flow"); + addImageSynthesisImage( + renderPayload, + agent.imageSynthesis, + this.renderSemanticSegmentation, + "_class", + "image_classes" + ); + addImageSynthesisImage( + renderPayload, + agent.imageSynthesis, + this.renderFlowImage, + "_flow", + "image_flow" + ); } metadata.thirdPartyCameras = cameraMetadata; } @@ -1247,12 +1436,18 @@ private bool canEmit() { break; } } - - return (this.agentManagerState == AgentState.Emit && emit) || this.agentManagerState == AgentState.Error; + + return (this.agentManagerState == AgentState.Emit && emit) + || this.agentManagerState == AgentState.Error; } private RenderTexture createRenderTexture(int width, int height) { - RenderTexture rt = new RenderTexture(width: width, height: height,depth:0, GraphicsFormat.R8G8B8A8_UNorm); + RenderTexture rt = new RenderTexture( + width: width, + height: height, + depth: 0, + GraphicsFormat.R8G8B8A8_UNorm + ); rt.antiAliasing = 4; if (rt.Create()) { Debug.Log(" created render texture with width= " + width + " height=" + height); @@ -1262,18 +1457,18 @@ private RenderTexture createRenderTexture(int width, int height) { Debug.LogError("Could not create a renderTexture"); return null; } - } public IEnumerator EmitFrame() { while (true) { - bool shouldRender = this.renderImage && serverSideScreenshot; bool shouldRenderImageSynthesis = shouldRender && this.renderImageSynthesis; if (renderImageSynthesisChanged) { foreach (BaseFPSAgentController agent in this.agents) { - foreach (ImageSynthesis ims in agent.gameObject.GetComponentsInChildren()) { + foreach ( + ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() + ) { if (ims.enabled) { ims.updateCameraStatuses(this.renderImageSynthesis); } @@ -1284,7 +1479,7 @@ public IEnumerator EmitFrame() { yield return new WaitForEndOfFrame(); frameCounter += 1; - + if (this.agentManagerState == AgentState.ActionComplete) { this.agentManagerState = AgentState.Emit; } @@ -1294,27 +1489,36 @@ public IEnumerator EmitFrame() { agent.agentState = AgentState.Emit; } } - + if (!this.canEmit()) { continue; } MultiAgentMetadata multiMeta = new MultiAgentMetadata(); - ThirdPartyCameraMetadata[] cameraMetadata = new ThirdPartyCameraMetadata[this.thirdPartyCameras.Count]; - List> renderPayload = new List>(); - createPayload(multiMeta, cameraMetadata, renderPayload, shouldRender, shouldRenderImageSynthesis); + ThirdPartyCameraMetadata[] cameraMetadata = new ThirdPartyCameraMetadata[ + this.thirdPartyCameras.Count + ]; + List> renderPayload = + new List>(); + createPayload( + multiMeta, + cameraMetadata, + renderPayload, + shouldRender, + shouldRenderImageSynthesis + ); #if UNITY_WEBGL - JavaScriptInterface jsInterface = this.primaryAgent.GetComponent(); - if (jsInterface != null) { - jsInterface.SendActionMetadata(serializeMetadataJson(multiMeta)); - } + JavaScriptInterface jsInterface = this.primaryAgent.GetComponent(); + if (jsInterface != null) + { + jsInterface.SendActionMetadata(serializeMetadataJson(multiMeta)); + } #endif - -// Tradeoff of faster unity editor vs python controller parity -// for faster editor add back || !UNITY_EDITOR below, and #if UNITY_EDITOR and break after socket -// creation failure -// Not running code below loses compatibility with python controlled editor + // Tradeoff of faster unity editor vs python controller parity + // for faster editor add back || !UNITY_EDITOR below, and #if UNITY_EDITOR and break after socket + // creation failure + // Not running code below loses compatibility with python controlled editor #if !UNITY_WEBGL if (serverType == serverTypes.WSGI) { WWWForm form = new WWWForm(); @@ -1325,22 +1529,27 @@ public IEnumerator EmitFrame() { } form.AddField("token", robosimsClientToken); - if (this.sock == null) { // Debug.Log("connecting to host: " + robosimsHost); IPAddress host = IPAddress.Parse(robosimsHost); IPEndPoint hostep = new IPEndPoint(host, robosimsPort); - this.sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + this.sock = new Socket( + AddressFamily.InterNetwork, + SocketType.Stream, + ProtocolType.Tcp + ); try { this.sock.Connect(hostep); } catch (SocketException e) { var msg = e.ToString(); Debug.Log("Socket exception: " + msg); -// TODO: change how payload creation is run in editor, it keeps creating the payload every -// frame create new controller state Emitted, to detect between ready to emit and already emitted -// remove back for python controller parity -#if UNITY_EDITOR - Debug.LogWarning("EmitFrame WILL STOP RUNNING. createPayload will not be called after every action. Possible environment mismatch. Use python server to match standalone environment."); + // TODO: change how payload creation is run in editor, it keeps creating the payload every + // frame create new controller state Emitted, to detect between ready to emit and already emitted + // remove back for python controller parity +#if UNITY_EDITOR + Debug.LogWarning( + "EmitFrame WILL STOP RUNNING. createPayload will not be called after every action. Possible environment mismatch. Use python server to match standalone environment." + ); break; #endif } @@ -1349,8 +1558,11 @@ public IEnumerator EmitFrame() { if (this.sock != null && this.sock.Connected) { byte[] rawData = form.data; - string request = "POST /train HTTP/1.1\r\n" + - "Content-Length: " + rawData.Length.ToString() + "\r\n"; + string request = + "POST /train HTTP/1.1\r\n" + + "Content-Length: " + + rawData.Length.ToString() + + "\r\n"; foreach (KeyValuePair entry in form.headers) { request += entry.Key + ": " + entry.Value + "\r\n"; @@ -1373,13 +1585,21 @@ public IEnumerator EmitFrame() { // read header while (true) { - int received = this.sock.Receive(headerBuffer, bytesReceived, headerBuffer.Length - bytesReceived, SocketFlags.None); + int received = this.sock.Receive( + headerBuffer, + bytesReceived, + headerBuffer.Length - bytesReceived, + SocketFlags.None + ); if (received == 0) { - Debug.LogError("0 bytes received attempting to read header - connection closed"); + Debug.LogError( + "0 bytes received attempting to read header - connection closed" + ); break; } - bytesReceived += received; ; + bytesReceived += received; + ; string headerMsg = Encoding.ASCII.GetString(headerBuffer, 0, bytesReceived); int offset = headerMsg.IndexOf("\r\n\r\n"); if (offset > 0) { @@ -1394,9 +1614,16 @@ public IEnumerator EmitFrame() { // read body while (bodyBytesReceived < contentLength) { // check for 0 bytes received - int received = this.sock.Receive(bodyBuffer, bodyBytesReceived, bodyBuffer.Length - bodyBytesReceived, SocketFlags.None); + int received = this.sock.Receive( + bodyBuffer, + bodyBytesReceived, + bodyBuffer.Length - bodyBytesReceived, + SocketFlags.None + ); if (received == 0) { - Debug.LogError("0 bytes received attempting to read body - connection closed"); + Debug.LogError( + "0 bytes received attempting to read body - connection closed" + ); break; } @@ -1408,23 +1635,36 @@ public IEnumerator EmitFrame() { ProcessControlCommand(msg); } } else if (serverType == serverTypes.FIFO) { + byte[] msgPackMetadata = + MessagePack.MessagePackSerializer.Serialize( + multiMeta, + MessagePack.Resolvers.ThorContractlessStandardResolver.Options + ); - byte[] msgPackMetadata = MessagePack.MessagePackSerializer.Serialize(multiMeta, - MessagePack.Resolvers.ThorContractlessStandardResolver.Options); - - #if UNITY_EDITOR - - Debug.Log("FIFO Timeout started. Trying to read from FIFO server..."); - var completed = Task.Run(() => this.fifoClient.SendMessage(FifoServer.FieldType.Metadata, msgPackMetadata)).Wait(2000); - Debug.Log("ReachedTimeout " + !completed); - if (!completed) { - Debug.Log("FIFO Timeout Reached. Start FIFO server first if remote control is needed."); - Debug.LogWarning("EmitFrame WILL STOP RUNNING. createPayload will not be called after every action. Possible environment mismatch. Use python server to match standalone environment."); - break; - } - #else - this.fifoClient.SendMessage(FifoServer.FieldType.Metadata, msgPackMetadata); - #endif +#if UNITY_EDITOR + + Debug.Log("FIFO Timeout started. Trying to read from FIFO server..."); + var completed = Task.Run( + () => + this.fifoClient.SendMessage( + FifoServer.FieldType.Metadata, + msgPackMetadata + ) + ) + .Wait(2000); + Debug.Log("ReachedTimeout " + !completed); + if (!completed) { + Debug.Log( + "FIFO Timeout Reached. Start FIFO server first if remote control is needed." + ); + Debug.LogWarning( + "EmitFrame WILL STOP RUNNING. createPayload will not be called after every action. Possible environment mismatch. Use python server to match standalone environment." + ); + break; + } +#else + this.fifoClient.SendMessage(FifoServer.FieldType.Metadata, msgPackMetadata); +#endif AsyncGPUReadback.WaitAllRequests(); foreach (var item in renderPayload) { @@ -1437,9 +1677,14 @@ public IEnumerator EmitFrame() { while (canEmit() && this.fastActionEmit) { MetadataPatch patch = this.activeAgent().generateMetadataPatch(); patch.agentId = this.activeAgentId; - msgPackMetadata = MessagePack.MessagePackSerializer.Serialize(patch, - MessagePack.Resolvers.ThorContractlessStandardResolver.Options); - this.fifoClient.SendMessage(FifoServer.FieldType.MetadataPatch, msgPackMetadata); + msgPackMetadata = MessagePack.MessagePackSerializer.Serialize( + patch, + MessagePack.Resolvers.ThorContractlessStandardResolver.Options + ); + this.fifoClient.SendMessage( + FifoServer.FieldType.MetadataPatch, + msgPackMetadata + ); this.fifoClient.SendEOM(); msg = this.fifoClient.ReceiveMessage(); ProcessControlCommand(msg); @@ -1459,16 +1704,9 @@ public IEnumerator EmitFrame() { //} #endif - - - - } - - } - // Uniform entry point for both the test runner and the python server for step dispatch calls public void ProcessControlCommand(DynamicServerAction controlCommand) { this.renderInstanceSegmentation = this.initializedInstanceSeg; @@ -1477,14 +1715,19 @@ public void ProcessControlCommand(DynamicServerAction controlCommand) { // the following are handled this way since they can be null this.renderImage = controlCommand.renderImage; - this.renderImageSynthesisChanged = this.renderImageSynthesis != controlCommand.renderImageSynthesis; + this.renderImageSynthesisChanged = + this.renderImageSynthesis != controlCommand.renderImageSynthesis; this.renderImageSynthesis = controlCommand.renderImageSynthesis; this.activeAgentId = controlCommand.agentId; - if (agentManagerState == AgentState.Error && !errorAllowedActions.Contains(controlCommand.action)) { + if ( + agentManagerState == AgentState.Error + && !errorAllowedActions.Contains(controlCommand.action) + ) { var activeAgent = this.activeAgent(); - activeAgent.errorMessage = $"Critical Error. No more actions can be run before calling 'reset'. Action that caused error: '{activeAgent.lastAction}'"; + activeAgent.errorMessage = + $"Critical Error. No more actions can be run before calling 'reset'. Action that caused error: '{activeAgent.lastAction}'"; return; } @@ -1504,10 +1747,11 @@ public void ProcessControlCommand(DynamicServerAction controlCommand) { this.renderInstanceSegmentation = true; } - if (this.renderDepthImage || - this.renderSemanticSegmentation || - this.renderInstanceSegmentation || - this.renderNormalsImage + if ( + this.renderDepthImage + || this.renderSemanticSegmentation + || this.renderInstanceSegmentation + || this.renderNormalsImage ) { updateImageSynthesis(true); updateThirdPartyCameraImageSynthesis(true); @@ -1580,13 +1824,11 @@ protected bool LoadBoolVariable(bool variable, string name) { public void SetCriticalErrorState() { this.agentManagerState = AgentState.Error; } - } [Serializable] [MessagePackObject(keyAsPropertyName: true)] public class MultiAgentMetadata { - public MetadataWrapper[] agents; public ThirdPartyCameraMetadata[] thirdPartyCameras; public int activeAgentId; @@ -1600,6 +1842,7 @@ public class ThirdPartyCameraMetadata { public Vector3 position; public Vector3 rotation; public float fieldOfView; + //note these should only be returned with values //if the third party camera is a child of the agent public Vector3 agentPositionRelativeThirdPartyCameraPosition; @@ -1659,6 +1902,7 @@ public class DroneObjectMetadata : ObjectMetadata { public float lastVelocity; public Vector3 launcherPosition; public bool isCaught; + public DroneObjectMetadata() { } } @@ -1928,14 +2172,19 @@ public class ArmMetadata { public class ArticulationArmMetadata { //additional metadata for each joint in the articulated arm (currently base, extend joint, and wrist) public ArticulationJointMetadata[] joints; + //currently we only support picking up one object for the articulation grabbing public List heldObjects; + //a list of all objects currently intersecting the hand sphere that can be possibly picked up public List pickupableObjects; + // a list of all objects in the hand sphere radius regardless of if they can be picked up (so large objects too) public List objectsInsideHandSphereRadius; + //center of the hand sphere in world coordinates public Vector3 handSphereCenter; + //radius of the hand sphere in world coordinates public float handSphereRadius; } @@ -1943,26 +2192,33 @@ public class ArticulationArmMetadata { //this should include the arm base, the extend joint, and wrist joint for now public class ArticulationJointMetadata { //string name of this joint - public string name; + public string name; + //position of this joint in the heirarchy of articulations - //grab this from ArticulatedArmController.cs joints array, the 0th element should be the lift so this + //grab this from ArticulatedArmController.cs joints array, the 0th element should be the lift so this //starts from the lift even though the entire articulation itself has the agent as the base public int jointHeirarchyPosition; + //position of this object in world coordinates public Vector3 position; + //position of this object relative to this object's immediate parent in the articulation heirarchy public Vector3 localPosition; + //position relative to the root, or the first joint in the the articulations heirarchy public Vector3 rootRelativePosition; + //rotation of this object in world coordinates public Vector4 rotation; + //rotation relative to this object's immediate parent in the articulation heirarchy public Vector4 localRotation; + //rotation relative to the root, or the first joint in the the articulations heirarchy public Vector4 rootRelativeRotation; + //height in world coordinates of the first joint in the articulations heirarchy, or the base (lift in this case) public float? armBaseHeight; - } [Serializable] @@ -1974,13 +2230,15 @@ public class ObjectTypeCount { [Serializable] [MessagePackObject(keyAsPropertyName: true)] public class ObjectPose { + public ObjectPose() + : this("", new Vector3(), new Vector3()) { } - public ObjectPose() : this("", new Vector3(), new Vector3()) { } public ObjectPose(string objectName, Vector3 position, Vector3 rotation) { this.objectName = objectName; this.position = position; this.rotation = rotation; } + public string objectName; public Vector3 position; public Vector3 rotation; @@ -2009,7 +2267,7 @@ public class SetObjectStates { [MessagePackObject(keyAsPropertyName: true)] public struct MetadataWrapper { public ObjectMetadata[] objects; - public bool isSceneAtRest;// set true if all objects in the scene are at rest (or very very close to 0 velocity) + public bool isSceneAtRest; // set true if all objects in the scene are at rest (or very very close to 0 velocity) public AgentMetadata agent; public HandMetadata heldObjectPose; public ArmMetadata arm; @@ -2051,10 +2309,9 @@ public struct MetadataWrapper { public Vector3[] actionVector3sReturn; public List visibleRange; public float currentTime; - public SceneBounds sceneBounds;// return coordinates of the scene's bounds (center, size, extents) + public SceneBounds sceneBounds; // return coordinates of the scene's bounds (center, size, extents) public object actionReturn; - } /* @@ -2063,51 +2320,44 @@ to dispatch to the appropriate action based on the passed in params. The properties(agentId, sequenceId, action) exist to encapsulate the key names. */ public class DynamicServerAction { - // These parameters are allowed to exist as both parameters to an Action and as global // paramaters. This also excludes them from the InvalidArgument logic used in the ActionDispatcher - public static readonly IReadOnlyCollection AllowedExtraneousParameters = new HashSet(){ - "sequenceId", - "renderImage", - "renderImageSynthesis", - "agentId", - "renderObjectImage", - "renderClassImage", - "renderNormalsImage", - "renderInstanceSegmentation", - "action", - physicsSimulationParamsVariable - }; + public static readonly IReadOnlyCollection AllowedExtraneousParameters = + new HashSet() + { + "sequenceId", + "renderImage", + "renderImageSynthesis", + "agentId", + "renderObjectImage", + "renderClassImage", + "renderNormalsImage", + "renderInstanceSegmentation", + "action", + physicsSimulationParamsVariable + }; public const string physicsSimulationParamsVariable = "physicsSimulationParams"; public const string agentInitializationParamsVariable = "agentInitializationParams"; - public JObject jObject { - get; - private set; - } + public JObject jObject { get; private set; } public int agentId { - get { - return this.GetValue("agentId", 0); - } + get { return this.GetValue("agentId", 0); } } public int sequenceId { - get { - return (int)this.GetValue("sequenceId", 0); - } + get { return (int)this.GetValue("sequenceId", 0); } } public string action { - get { - return this.jObject["action"].ToString(); - } + get { return this.jObject["action"].ToString(); } } public PhysicsSimulationParams physicsSimulationParams { get { - return this.jObject[physicsSimulationParamsVariable]?.ToObject(); + return this.jObject[physicsSimulationParamsVariable] + ?.ToObject(); } } @@ -2117,14 +2367,15 @@ public bool HasAgentInitializationParams() { public DynamicServerAction agentInitializationParams { get { - var dict = this.jObject[agentInitializationParamsVariable]?.ToObject>(); + var dict = this.jObject[agentInitializationParamsVariable] + ?.ToObject>(); dict ??= new Dictionary(); foreach (var extraneousParam in AllowedExtraneousParameters) { var parmaValue = this.GetValue(extraneousParam); if (parmaValue != null) { dict.Add( extraneousParam, - this.GetValue(extraneousParam)//?.ToObject() + this.GetValue(extraneousParam) //?.ToObject() ); } } @@ -2157,30 +2408,26 @@ public bool ContainsKey(string name) { } public bool renderInstanceSegmentation { - get { - return this.GetValue("renderInstanceSegmentation", false); - } + get { return this.GetValue("renderInstanceSegmentation", false); } } public bool renderImage { - get { - return this.GetValue("renderImage", true); - } + get { return this.GetValue("renderImage", true); } } public bool renderImageSynthesis { - get { - return this.GetValue("renderImageSynthesis", true); - } + get { return this.GetValue("renderImageSynthesis", true); } } public DynamicServerAction(Dictionary action) { var jsonResolver = new ShouldSerializeContractResolver(); - this.jObject = JObject.FromObject(action, - new Newtonsoft.Json.JsonSerializer() { - ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, - ContractResolver = jsonResolver - }); + this.jObject = JObject.FromObject( + action, + new Newtonsoft.Json.JsonSerializer() { + ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, + ContractResolver = jsonResolver + } + ); } public DynamicServerAction(JObject action) { @@ -2200,18 +2447,25 @@ public T ToObject() { } // this is primarily used when detecting invalid arguments - // if Initialize is ever changed we should refactor this since renderInstanceSegmentation is a + // if Initialize is ever changed we should refactor this since renderInstanceSegmentation is a // valid argument for Initialize as well as a global parameter public IEnumerable ArgumentKeys() { - return this.jObject.Properties().Select(p => p.Name).Where(argName => !AllowedExtraneousParameters.Contains(argName)).ToList(); + return this + .jObject.Properties() + .Select(p => p.Name) + .Where(argName => !AllowedExtraneousParameters.Contains(argName)) + .ToList(); } - public IEnumerable ArgumentKeysWithPhysicsSimulationProperies() { - return this.jObject - .Properties() + public IEnumerable ArgumentKeysWithPhysicsSimulationProperies() { + return this + .jObject.Properties() .Select(p => p.Name) - .Where(argName => !AllowedExtraneousParameters.Except(new HashSet { physicsSimulationParamsVariable }) - .Contains(argName)) + .Where(argName => + !AllowedExtraneousParameters + .Except(new HashSet { physicsSimulationParamsVariable }) + .Contains(argName) + ) .ToList(); } @@ -2227,7 +2481,7 @@ public void AddPhysicsSimulationParams(PhysicsSimulationParams physicsSimulation var token = JToken.FromObject(physicsSimulationParams); this.jObject.Add(new JProperty(physicsSimulationParamsVariable, token)); } - } +} [Serializable] public class CameraParameters { @@ -2286,7 +2540,7 @@ public class ServerAction { public Vector3 position; public Vector3 direction; public bool allowAgentsToIntersect = false; - public float handDistance;// used for max distance agent's hand can move + public float handDistance; // used for max distance agent's hand can move public List positions = null; public bool standing = true; public bool forceAction; @@ -2304,7 +2558,7 @@ public class ServerAction { public string sceneName; public bool rotateOnTeleport; public bool forceVisible; - public bool anywhere;// used for SpawnTargetCircle, GetSpawnCoordinatesAboveObject for if anywhere or only in agent view + public bool anywhere; // used for SpawnTargetCircle, GetSpawnCoordinatesAboveObject for if anywhere or only in agent view public bool randomizeOpen; public int randomSeed; public float moveMagnitude; @@ -2324,22 +2578,24 @@ public class ServerAction { public bool renderFlowImage; public float cameraY = 0.675f; public bool placeStationary = true; // when placing/spawning an object, do we spawn it stationary (kinematic true) or spawn and let physics resolve final position - // public string ssao = "default"; + + // public string ssao = "default"; public string fillLiquid; // string to indicate what kind of liquid this object should be filled with. Water, Coffee, Wine etc. public float TimeUntilRoomTemp; public bool allowDecayTemperature = true; // set to true if temperature should decay over time, set to false if temp changes should not decay, defaulted true - public string StateChange;// a string that specifies which state change to randomly toggle + public string StateChange; // a string that specifies which state change to randomly toggle public float timeStep = 0.01f; public float mass; public float drag; public float angularDrag; public ObjectTypeCount[] numDuplicatesOfType; // specify, by object Type, how many duplicates of that given object type to try and spawn + // use only the objectType class member to specify which receptacle objects should be excluded from the valid receptacles to spawn objects in public String[] excludedReceptacles; public ObjectPose[] objectPoses; public SetObjectStates SetObjectStates; - public float minDistance;// used in target circle spawning function - public float maxDistance;// used in target circle spawning function + public float minDistance; // used in target circle spawning function + public float maxDistance; // used in target circle spawning function public float noise; public ControllerInitialization controllerInitialization = null; public string agentMode = "default"; // mode of Agent, valid values are "default" "locobot" "drone", note certain modes are only compatible with certain controller types @@ -2348,7 +2604,7 @@ public class ServerAction { public int maxStepCount; public float rotateStepDegrees = 90.0f; // default rotation amount for RotateRight/RotateLeft actions - public float degrees;// for overriding the default degree amount in look up/lookdown/rotaterRight/rotateLeft + public float degrees; // for overriding the default degree amount in look up/lookdown/rotaterRight/rotateLeft public bool topView = false; @@ -2374,6 +2630,7 @@ public class ServerAction { public float scale; public string visibilityScheme = VisibilityScheme.Collider.ToString(); public bool fastActionEmit = true; + // this allows us to chain the dispatch between two separate // legacy action (e.g. AgentManager.Initialize and BaseFPSAgentController.Initialize) public DynamicServerAction dynamicServerAction; @@ -2405,7 +2662,7 @@ public class ServerAction { // for the arm to detect collisions and stop moving public float? massThreshold; - public PhysicsSimulationParams physicsSimulationParams; + public PhysicsSimulationParams physicsSimulationParams; public float maxUpwardLookAngle = 0.0f; public float maxDownwardLookAngle = 0.0f; @@ -2413,7 +2670,6 @@ public class ServerAction { public Dictionary thirdPartyCameraParameters; - public SimObjType ReceptableSimObjType() { if (string.IsNullOrEmpty(receptacleObjectType)) { return SimObjType.Undefined; @@ -2430,7 +2686,9 @@ public static VisibilityScheme GetVisibilitySchemeFromString(string visibilitySc #pragma warning disable 0168 catch (ArgumentException ex) { #pragma warning restore 0168 - Debug.LogError("Error parsing visibilityScheme: '" + visibilityScheme + "' defaulting to Collider"); + Debug.LogError( + "Error parsing visibilityScheme: '" + visibilityScheme + "' defaulting to Collider" + ); } return result; @@ -2446,6 +2704,7 @@ public SimObjType GetSimObjType() { } return (SimObjType)Enum.Parse(typeof(SimObjType), objectType); } + // allows this to be passed in as a dynamic which we then // cast back to itself public ServerAction ToObject() { @@ -2455,8 +2714,6 @@ public ServerAction ToObject() { public ServerAction ToObject(Type t) { return this; } - - } [Serializable] @@ -2500,8 +2757,8 @@ public class DebugSphere { public Color color; } - [Serializable] - [MessagePackObject(keyAsPropertyName: true)] +[Serializable] +[MessagePackObject(keyAsPropertyName: true)] public class Waypoint { public Vector3 position; public SerializableColor color; @@ -2574,7 +2831,8 @@ public class TypedVariable { } public class ShouldSerializeContractResolver : DefaultContractResolver { - public static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver(); + public static readonly ShouldSerializeContractResolver Instance = + new ShouldSerializeContractResolver(); protected override JsonProperty CreateProperty( MemberInfo member, @@ -2583,12 +2841,17 @@ MemberSerialization memberSerialization JsonProperty property = base.CreateProperty(member, memberSerialization); // exclude these properties to make serialization match JsonUtility - if (property.DeclaringType == typeof(Vector3) && - (property.PropertyName == "sqrMagnitude" || - property.PropertyName == "magnitude" || - property.PropertyName == "normalized") + if ( + property.DeclaringType == typeof(Vector3) + && ( + property.PropertyName == "sqrMagnitude" + || property.PropertyName == "magnitude" + || property.PropertyName == "normalized" + ) ) { - property.ShouldSerialize = instance => { return false; }; + property.ShouldSerialize = instance => { + return false; + }; return property; } else { return base.CreateProperty(member, memberSerialization); diff --git a/unity/Assets/Scripts/Arm.cs b/unity/Assets/Scripts/Arm.cs index ff462fc7dc..72579e6487 100644 --- a/unity/Assets/Scripts/Arm.cs +++ b/unity/Assets/Scripts/Arm.cs @@ -1,21 +1,18 @@ -using UnityEngine; using System.Collections; using System.Collections.Generic; +using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; public interface Arm { - // void ContinuousUpdate(); bool IsArmColliding(); + // bool ShouldHalt(); GameObject GetArmTarget(); ArmMetadata GenerateMetadata(); - - public Dictionary> heldObjects { - get; - } + public Dictionary> heldObjects { get; } IEnumerator moveArmRelative( PhysicsRemoteFPSAgentController controller, @@ -37,7 +34,6 @@ IEnumerator moveArmTarget( bool restrictTargetPosition ); - IEnumerator moveArmBase( PhysicsRemoteFPSAgentController controller, float height, @@ -68,5 +64,4 @@ bool returnToStartPositionIfFailed IEnumerator PickupObject(List objectIds); IEnumerator DropObject(); - } diff --git a/unity/Assets/Scripts/ArmAgentController.cs b/unity/Assets/Scripts/ArmAgentController.cs index 00d3e97eb8..5e3aea7317 100644 --- a/unity/Assets/Scripts/ArmAgentController.cs +++ b/unity/Assets/Scripts/ArmAgentController.cs @@ -1,17 +1,16 @@ +using System; using System.Collections; using System.Collections.Generic; -using UnityEngine; -using System; using System.Linq; +using System.Runtime.CompilerServices; using RandomExtensions; +using UnityEngine; using UnityEngine.AI; -using System.Runtime.CompilerServices; namespace UnityStandardAssets.Characters.FirstPerson { - public abstract class ArmAgentController : PhysicsRemoteFPSAgentController { - public ArmAgentController(BaseAgentComponent baseAgentComponent, AgentManager agentManager) : base(baseAgentComponent, agentManager) { - } + public ArmAgentController(BaseAgentComponent baseAgentComponent, AgentManager agentManager) + : base(baseAgentComponent, agentManager) { } protected abstract ArmController getArm(); @@ -19,13 +18,15 @@ public ArmAgentController(BaseAgentComponent baseAgentComponent, AgentManager ag Toggles the visibility of the magnet sphere at the end of the arm. */ public ActionFinished ToggleMagnetVisibility(bool? visible = null) { - MeshRenderer mr = GameObject.Find("MagnetRenderer").GetComponentInChildren(); + MeshRenderer mr = GameObject + .Find("MagnetRenderer") + .GetComponentInChildren(); if (visible.HasValue) { mr.enabled = visible.Value; } else { mr.enabled = !mr.enabled; } - return ActionFinished.Success; + return ActionFinished.Success; } public override void updateImageSynthesis(bool status) { @@ -39,7 +40,6 @@ public override void updateImageSynthesis(bool status) { agentManager.updateThirdPartyCameraImageSynthesis(status); } - /* This function is identical to `MoveArm` except that rather than giving a target position you instead give an "offset" w.r.t. @@ -104,13 +104,22 @@ public IEnumerator PickupObject(List objectIdCandidates = null) { return arm.PickupObject(objectIdCandidates); } - public override void PickupObject(float x, float y, bool forceAction = false, bool manualInteract = false) { + public override void PickupObject( + float x, + float y, + bool forceAction = false, + bool manualInteract = false + ) { throw new InvalidOperationException( "You are passing in iTHOR PickupObject parameters (x, y) to the arm agent!" ); } - public override void PickupObject(string objectId, bool forceAction = false, bool manualInteract = false) { + public override void PickupObject( + string objectId, + bool forceAction = false, + bool manualInteract = false + ) { throw new InvalidOperationException( "You are passing in iTHOR PickupObject parameters (objectId) to the arm agent!" ); @@ -177,7 +186,6 @@ public IEnumerator MoveAhead( ); } - public IEnumerator MoveBack( float? moveMagnitude = null, float speed = 1, @@ -296,7 +304,9 @@ public virtual IEnumerator MoveArmBase( ) { if (normalizedY && (y < 0f || y > 1f)) { // Checking for bounds when normalizedY == false is handled by arm.moveArmBase - throw new ArgumentOutOfRangeException($"y={y} value must be in [0, 1] when normalizedY=true."); + throw new ArgumentOutOfRangeException( + $"y={y} value must be in [0, 1] when normalizedY=true." + ); } var arm = getArm(); @@ -330,11 +340,7 @@ public virtual IEnumerator MoveArmBaseDown( float speed = 1, bool returnToStart = true ) { - return MoveArmBaseUp( - distance: -distance, - speed: speed, - returnToStart: returnToStart - ); + return MoveArmBaseUp(distance: -distance, speed: speed, returnToStart: returnToStart); } #if UNITY_EDITOR @@ -343,7 +349,8 @@ public void GetMidLevelArmCollisions() { var arm = getArm(); CollisionListener collisionListener = arm.GetComponentInChildren(); if (collisionListener != null) { - List> collisions = new List>(); + List> collisions = + new List>(); foreach (var sc in collisionListener.StaticCollisions()) { Dictionary element = new Dictionary(); if (sc.simObjPhysics != null) { diff --git a/unity/Assets/Scripts/ArmCollisionResolver.cs b/unity/Assets/Scripts/ArmCollisionResolver.cs index 8e6b377e24..00addb64c5 100644 --- a/unity/Assets/Scripts/ArmCollisionResolver.cs +++ b/unity/Assets/Scripts/ArmCollisionResolver.cs @@ -1,24 +1,25 @@ using System; using System.Collections.Generic; -using UnityEngine; using System.Linq; +using UnityEngine; public class ArmCollisionResolver : CollisionEventResolver { - public Collider bodyColliderIgnore; public GameObject bodyCollidersParent; // TODO: Abstract arm api so that this class doesn't need to be duplicated for ik arm protected Stretch_Robot_Arm_Controller arm; - new protected void Start() { + protected new void Start() { base.Start(); arm = this.GetComponent(); var collisionListener = this.GetComponentInParent(); } - public override StaticCollision resolveToStaticCollision(Collider externalCollider, HashSet internalColliders) { - + public override StaticCollision resolveToStaticCollision( + Collider externalCollider, + HashSet internalColliders + ) { if (externalCollider.transform.parent != null) { if (externalCollider.transform.parent.gameObject.Equals(bodyCollidersParent)) { // Collision with body @@ -28,26 +29,20 @@ public override StaticCollision resolveToStaticCollision(Collider externalCollid }; } } - + if (externalCollider.GetComponentInParent() != null) { - if (internalColliders.Count == 1 && internalColliders.First() == bodyColliderIgnore) { return null; - } - else { + } else { foreach (var objectColliderSet in arm.heldObjects.Values) { - if (objectColliderSet.Contains(externalCollider)) { // Held-Object collision with aram Debug.Log("-------- RESOLVED COLLISION WITH ARm"); - return new StaticCollision() { - gameObject = externalCollider.gameObject - }; + return new StaticCollision() { gameObject = externalCollider.gameObject }; } } } } return null; } - -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/ArmController.cs b/unity/Assets/Scripts/ArmController.cs index a98ac61e0f..7e9a725746 100644 --- a/unity/Assets/Scripts/ArmController.cs +++ b/unity/Assets/Scripts/ArmController.cs @@ -1,14 +1,11 @@ -using UnityEngine; using System; - using System.Collections; using System.Collections.Generic; -using UnityStandardAssets.Characters.FirstPerson; using System.Linq; +using UnityEngine; +using UnityStandardAssets.Characters.FirstPerson; public abstract class ArmController : MonoBehaviour, Arm, MovableContinuous { - - [SerializeField] public Transform FinalJoint; @@ -18,31 +15,31 @@ public abstract class ArmController : MonoBehaviour, Arm, MovableContinuous { [SerializeField] protected WhatIsInsideMagnetSphere magnetSphereComp; - [SerializeField] + [SerializeField] public SphereCollider magnetSphere = null; [SerializeField] protected GameObject MagnetRenderer = null; [SerializeField] - public CapsuleCollider[] ArmCapsuleColliders {get; protected set; } + public CapsuleCollider[] ArmCapsuleColliders { get; protected set; } [SerializeField] - public BoxCollider[] ArmBoxColliders {get; protected set; } + public BoxCollider[] ArmBoxColliders { get; protected set; } [SerializeField] - public CapsuleCollider agentCapsuleCollider {get; protected set; } = null; + public CapsuleCollider agentCapsuleCollider { get; protected set; } = null; [HideInInspector] public CollisionListener collisionListener; // [SerializeField] - public Dictionary> heldObjects { get; protected set; } = new Dictionary>(); + public Dictionary> heldObjects { get; protected set; } = + new Dictionary>(); protected bool ignoreHeldObjectToAgentCollisions = false; - protected virtual bool validArmTargetPosition(Vector3 targetWorldPosition) { return true; } @@ -63,22 +60,19 @@ public virtual ActionFinished FinishContinuousMove(BaseFPSAgentController contro bool actionSuccess = !this.ShouldHalt(); string errorMessage = this.GetHaltMessage(); - return new ActionFinished() { - success = actionSuccess, - errorMessage = errorMessage - }; + return new ActionFinished() { success = actionSuccess, errorMessage = errorMessage }; } // bool actionSuccess = !movable.ShouldHalt(); - // string errorMessage = movable.GetHaltMessage(); - // if (!actionSuccess) { - // setProp(moveTransform, resetProp); - // } - - // return new ActionFinished() { - // success = actionSuccess, - // errorMessage = errorMessage - // }; + // string errorMessage = movable.GetHaltMessage(); + // if (!actionSuccess) { + // setProp(moveTransform, resetProp); + // } + + // return new ActionFinished() { + // success = actionSuccess, + // errorMessage = errorMessage + // }; public abstract GameObject GetArmTarget(); public abstract ArmMetadata GenerateMetadata(); @@ -93,21 +87,29 @@ public Vector3 MagnetSphereWorldCenter() { public virtual string GetHaltMessage() { var staticCollisions = collisionListener?.StaticCollisions().ToList(); - // decide if we want to return to original property or last known property before collision - if (staticCollisions.Count > 0) { - var sc = staticCollisions[0]; - - // if we hit a sim object - if (sc.isSimObj) { - return "Collided with static/kinematic sim object: '" + sc.simObjPhysics.name + "', could not reach target: '" + armTarget + "'."; - } + // decide if we want to return to original property or last known property before collision + if (staticCollisions.Count > 0) { + var sc = staticCollisions[0]; + + // if we hit a sim object + if (sc.isSimObj) { + return "Collided with static/kinematic sim object: '" + + sc.simObjPhysics.name + + "', could not reach target: '" + + armTarget + + "'."; + } - // if we hit a structural object that isn't a sim object but still has static collision - if (!sc.isSimObj) { - return "Collided with static structure in scene: '" + sc.gameObject.name + "', could not reach target: '" + armTarget + "'."; - } + // if we hit a structural object that isn't a sim object but still has static collision + if (!sc.isSimObj) { + return "Collided with static structure in scene: '" + + sc.gameObject.name + + "', could not reach target: '" + + armTarget + + "'."; } - return ""; + } + return ""; } // public virtual ActionFinished FinishContinuousMove( @@ -124,11 +126,11 @@ public IEnumerator withLastStepCallback(IEnumerator steps) { lastStepCallback(); } - public HashSet currentArmCollisions() { - HashSet colliders = new HashSet(); + public HashSet currentArmCollisions() { + HashSet colliders = new HashSet(); - // add the AgentCapsule to the ArmCapsuleColliders for the capsule collider check - List capsules = new List(); + // add the AgentCapsule to the ArmCapsuleColliders for the capsule collider check + List capsules = new List(); capsules.AddRange(ArmCapsuleColliders); capsules.Add(agentCapsuleCollider); @@ -193,7 +195,13 @@ public HashSet currentArmCollisions() { point0: point0, point1: point1, radius: radius, - layerMask: LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"), + layerMask: LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ), queryTriggerInteraction: QueryTriggerInteraction.Ignore ); foreach (Collider col in cols) { @@ -210,7 +218,13 @@ public HashSet currentArmCollisions() { center: b.transform.TransformPoint(b.center), halfExtents: b.size / 2.0f, orientation: b.transform.rotation, - layerMask: LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"), + layerMask: LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ), queryTriggerInteraction: QueryTriggerInteraction.Ignore ); foreach (Collider col in cols) { @@ -220,7 +234,6 @@ public HashSet currentArmCollisions() { return colliders; } - public virtual IEnumerator moveArmRelative( PhysicsRemoteFPSAgentController controller, Vector3 offset, @@ -259,8 +272,6 @@ bool restrictTargetPosition ); } - - public virtual IEnumerator moveArmTarget( PhysicsRemoteFPSAgentController controller, Vector3 target, @@ -315,7 +326,6 @@ bool restrictTargetPosition ); } - public virtual IEnumerator moveArmBase( PhysicsRemoteFPSAgentController controller, float height, @@ -330,7 +340,8 @@ bool normalizedY CapsuleCollider cc = controller.GetComponent(); Vector3 capsuleWorldCenter = cc.transform.TransformPoint(cc.center); - float minY, maxY; + float minY, + maxY; getCapsuleMinMaxY(controller, out minY, out maxY); if (normalizedY) { @@ -338,12 +349,14 @@ bool normalizedY } if (height < minY || height > maxY) { - throw new ArgumentOutOfRangeException($"height={height} value must be in [{minY}, {maxY}]."); + throw new ArgumentOutOfRangeException( + $"height={height} value must be in [{minY}, {maxY}]." + ); } Vector3 target = new Vector3(this.transform.position.x, height, this.transform.position.z); return withLastStepCallback( - ContinuousMovement.move( + ContinuousMovement.move( movable: this, controller: controller, moveTransform: this.transform, @@ -356,7 +369,11 @@ bool normalizedY ); } - private void getCapsuleMinMaxY(PhysicsRemoteFPSAgentController controller, out float minY, out float maxY) { + private void getCapsuleMinMaxY( + PhysicsRemoteFPSAgentController controller, + out float minY, + out float maxY + ) { CapsuleCollider cc = controller.GetComponent(); Vector3 capsuleWorldCenter = cc.transform.TransformPoint(cc.center); @@ -376,7 +393,8 @@ bool returnToStartPositionIfFailed CapsuleCollider cc = controller.GetComponent(); Vector3 capsuleWorldCenter = cc.transform.TransformPoint(cc.center); - float minY, maxY; + float minY, + maxY; getCapsuleMinMaxY(controller, out minY, out maxY); float targetY = this.transform.position.y + distance; targetY = Mathf.Max(Mathf.Min(targetY, maxY), minY); @@ -417,7 +435,9 @@ public List WhatObjectsAreInsideMagnetSphereAsSOP(bool onlyPickup return magnetSphereComp.CurrentlyContainedSimObjects(onlyPickupable: onlyPickupable); } - public IEnumerator ReturnObjectsInMagnetAfterPhysicsUpdate(PhysicsRemoteFPSAgentController controller) { + public IEnumerator ReturnObjectsInMagnetAfterPhysicsUpdate( + PhysicsRemoteFPSAgentController controller + ) { yield return new WaitForFixedUpdate(); List listOfSOP = new List(); foreach (SimObjPhysics sop in this.WhatObjectsAreInsideMagnetSphereAsSOP(false)) { @@ -426,7 +446,7 @@ public IEnumerator ReturnObjectsInMagnetAfterPhysicsUpdate(PhysicsRemoteFPSAgent Debug.Log("objs: " + string.Join(", ", listOfSOP)); controller.actionFinished(true, listOfSOP); } - + private Dictionary getGameObjectToMultipliedScale( GameObject go, Vector3 currentScale, @@ -450,7 +470,7 @@ private Dictionary getGameObjectToMultipliedScale( return gameObjectToScale; } - public virtual IEnumerator PickupObject(List objectIds) { + public virtual IEnumerator PickupObject(List objectIds) { // var at = this.transform.InverseTransformPoint(armTarget.position) - new Vector3(0, 0, originToShoulderLength); // Debug.Log("Pickup " + at.magnitude); bool pickedUp = false; @@ -463,10 +483,11 @@ public virtual IEnumerator PickupObject(List objectIds) { } } - Dictionary gameObjectToMultipliedScale = getGameObjectToMultipliedScale( - go: sop.gameObject, - currentScale: new Vector3(1f, 1f, 1f) - ); + Dictionary gameObjectToMultipliedScale = + getGameObjectToMultipliedScale( + go: sop.gameObject, + currentScale: new Vector3(1f, 1f, 1f) + ); Rigidbody rb = sop.GetComponent(); rb.isKinematic = true; sop.transform.SetParent(pickupParent()); @@ -477,7 +498,7 @@ public virtual IEnumerator PickupObject(List objectIds) { CanOpen_Object coj = sop.gameObject.GetComponent(); // if an openable object receives OnTriggerEnter events - // the RigidBody can be switched to Kinematic false + // the RigidBody can be switched to Kinematic false coj.triggerEnabled = false; } @@ -520,7 +541,9 @@ public virtual IEnumerator PickupObject(List objectIds) { // TODO: Ignore all collisions between arm/held object colliders (for efficiency)! // Removed first loop because of wanting heldobject->arm collision events var colliders = this.GetComponentsInChildren(); - Debug.Log($"------- ignoreHeldObjectToAgentCollisions {ignoreHeldObjectToAgentCollisions}"); + Debug.Log( + $"------- ignoreHeldObjectToAgentCollisions {ignoreHeldObjectToAgentCollisions}" + ); if (ignoreHeldObjectToAgentCollisions) { foreach (Collider c0 in colliders) { foreach (Collider c1 in cols) { @@ -542,17 +565,14 @@ public virtual IEnumerator PickupObject(List objectIds) { if (!pickedUp) { errorMessage = ( objectIds != null - ? "No objects (specified by objectId) were valid to be picked up by the arm" - : "No objects were valid to be picked up by the arm" + ? "No objects (specified by objectId) were valid to be picked up by the arm" + : "No objects were valid to be picked up by the arm" ); } // note: how to handle cases where object breaks if it is shoved into another object? // make them all unbreakable? - yield return new ActionFinished() { - success = pickedUp, - errorMessage= errorMessage - }; + yield return new ActionFinished() { success = pickedUp, errorMessage = errorMessage }; } public virtual IEnumerator DropObject() { @@ -603,6 +623,4 @@ public void SetHandSphereRadius(float radius) { magnetSphere.transform.localPosition = new Vector3(0, 0, 0.01f + radius); MagnetRenderer.transform.localPosition = new Vector3(0, 0, 0.01f + radius); } - - } diff --git a/unity/Assets/Scripts/ArticulatedAgentController.cs b/unity/Assets/Scripts/ArticulatedAgentController.cs index 38fa4c8844..618ccb4f6a 100644 --- a/unity/Assets/Scripts/ArticulatedAgentController.cs +++ b/unity/Assets/Scripts/ArticulatedAgentController.cs @@ -1,16 +1,20 @@ +using System; using System.Collections; using System.Collections.Generic; -using UnityEngine; -using System; using System.Linq; using RandomExtensions; +using UnityEngine; using UnityEngine.AI; using UnityEngine.Rendering.PostProcessing; namespace UnityStandardAssets.Characters.FirstPerson { public partial class ArticulatedAgentController : ArmAgentController { - public ArticulatedAgentController(BaseAgentComponent baseAgentComponent, AgentManager agentManager) : base(baseAgentComponent, agentManager) { - } + public ArticulatedAgentController( + BaseAgentComponent baseAgentComponent, + AgentManager agentManager + ) + : base(baseAgentComponent, agentManager) { } + public ArticulatedAgentSolver agent; [SerializeField] @@ -82,7 +86,6 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { // fp_camera_2.fieldOfView = 90f; if (initializeAction != null) { - if (initializeAction.cameraNearPlane > 0) { m_Camera.nearClipPlane = initializeAction.cameraNearPlane; // fp_camera_2.nearClipPlane = initializeAction.cameraNearPlane; @@ -92,7 +95,6 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { m_Camera.farClipPlane = initializeAction.cameraFarPlane; // fp_camera_2.farClipPlane = initializeAction.cameraFarPlane; } - } // // fp_camera_2.fieldOfView = 75f; @@ -117,7 +119,9 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { // // StretchSolver.ManipulateStretchArm(); //get references to floor collider and physica material to change when moving arm - FloorCollider = this.gameObject.transform.Find("abFloorCollider").GetComponent(); + FloorCollider = this + .gameObject.transform.Find("abFloorCollider") + .GetComponent(); FloorColliderPhysicsMaterial = FloorCollider.material; getArmImplementation().ContinuousUpdate(Time.fixedDeltaTime); @@ -128,8 +132,8 @@ private ArticulatedArmController getArmImplementation() { ArticulatedArmController arm = GetComponentInChildren(); if (arm == null) { throw new InvalidOperationException( - "Agent does not havSe Stretch arm or is not enabled.\n" + - $"Make sure there is a '{typeof(ArticulatedArmController).Name}' component as a child of this agent." + "Agent does not havSe Stretch arm or is not enabled.\n" + + $"Make sure there is a '{typeof(ArticulatedArmController).Name}' component as a child of this agent." ); } return arm; @@ -147,10 +151,10 @@ public IEnumerator setFloorToHighFrictionAsLastStep(IEnumerator steps) { } public override IEnumerator MoveArmBaseUp( - float distance, - float speed = 1, - bool returnToStart = true - ) { + float distance, + float speed = 1, + bool returnToStart = true + ) { Debug.Log("MoveArmBaseUp from ArticulatedAgentController"); SetFloorColliderToHighFriction(); var arm = getArmImplementation(); @@ -166,11 +170,11 @@ public override IEnumerator MoveArmBaseUp( //with limits public IEnumerator MoveArmBaseUp( - float distance, - bool useLimits, - float speed = 1, - bool returnToStart = true - ) { + float distance, + bool useLimits, + float speed = 1, + bool returnToStart = true + ) { Debug.Log("MoveArmBaseUp from ArticulatedAgentController"); SetFloorColliderToHighFriction(); var arm = getArmImplementation(); @@ -189,7 +193,9 @@ public override IEnumerator MoveArmBaseDown( float speed = 1, bool returnToStart = true ) { - Debug.Log("MoveArmBaseDown from ArticulatedAgentController (pass negative distance to MoveArmBaseUp)"); + Debug.Log( + "MoveArmBaseDown from ArticulatedAgentController (pass negative distance to MoveArmBaseUp)" + ); return MoveArmBaseUp( distance: -distance, speed: speed, @@ -205,7 +211,9 @@ public IEnumerator MoveArmBaseDown( float speed = 1, bool returnToStart = true ) { - Debug.Log("MoveArmBaseDown from ArticulatedAgentController (pass negative distance to MoveArmBaseUp)"); + Debug.Log( + "MoveArmBaseDown from ArticulatedAgentController (pass negative distance to MoveArmBaseUp)" + ); return MoveArmBaseUp( distance: -distance, speed: speed, @@ -232,11 +240,7 @@ public override IEnumerator MoveArm( } //move arm overload with limits - public IEnumerator MoveArm( - Vector3 position, - bool useLimits, - float speed = 1 - ) { + public IEnumerator MoveArm(Vector3 position, bool useLimits, float speed = 1) { var arm = getArmImplementation(); SetFloorColliderToHighFriction(); return arm.moveArmTarget( @@ -262,7 +266,12 @@ public void SetFloorColliderToHighFriction() { //FloorColliderPhysicsMaterial.dynamicFriction = 1; } - public void TeleportFull(Vector3 position, Vector3 rotation, float? horizon = null, bool forceAction = false) { + public void TeleportFull( + Vector3 position, + Vector3 rotation, + float? horizon = null, + bool forceAction = false + ) { Debug.Log($"Original Position: {this.transform.position}"); if (horizon == null) { @@ -280,7 +289,9 @@ public void TeleportFull(Vector3 position, Vector3 rotation, float? horizon = nu Quaternion realRotationAsQuaternionBecauseYes = Quaternion.Euler(rotation); //teleport must be finished in a coroutine because synctransforms DoESNt WoRK for ArTIcuLAtIONBodies soooooo - StartCoroutine(TeleportThenWait(position, realRotationAsQuaternionBecauseYes, horizonf)); + StartCoroutine( + TeleportThenWait(position, realRotationAsQuaternionBecauseYes, horizonf) + ); } IEnumerator TeleportThenWait(Vector3 position, Quaternion rotation, float cameraHorizon) { @@ -303,7 +314,7 @@ public override void GetInteractablePoses( float[] horizons = null, bool[] standings = null, float? maxDistance = null, - int maxPoses = int.MaxValue // works like infinity + int maxPoses = int.MaxValue // works like infinity ) { getInteractablePosesAB( objectId: objectId, @@ -325,18 +336,23 @@ public void getInteractablePosesAB( float[] horizons = null, bool[] standings = null, float? maxDistance = null, - int maxPoses = int.MaxValue // works like infinity + int maxPoses = int.MaxValue // works like infinity ) { Debug.Log("Calling getInteractablePosesAB"); if (standings != null) { - errorMessage = "Articulation Agent does not support 'standings' for GetInteractablePoses"; + errorMessage = + "Articulation Agent does not support 'standings' for GetInteractablePoses"; throw new InvalidActionException(); } - Debug.Log($"Position of agent at start of getInteractablePosesAB: {this.transform.position}"); + Debug.Log( + $"Position of agent at start of getInteractablePosesAB: {this.transform.position}" + ); if (360 % rotateStepDegrees != 0 && rotations != null) { - throw new InvalidOperationException($"360 % rotateStepDegrees (360 % {rotateStepDegrees} != 0) must be 0, unless 'rotations: float[]' is overwritten."); + throw new InvalidOperationException( + $"360 % rotateStepDegrees (360 % {rotateStepDegrees} != 0) must be 0, unless 'rotations: float[]' is overwritten." + ); } if (maxPoses <= 0) { @@ -348,7 +364,9 @@ public void getInteractablePosesAB( if (maxDistance == null) { maxDistanceFloat = maxVisibleDistance; } else if ((float)maxDistance <= 0) { - throw new ArgumentOutOfRangeException("maxDistance must be >= 0 meters from the object."); + throw new ArgumentOutOfRangeException( + "maxDistance must be >= 0 meters from the object." + ); } else { maxDistanceFloat = (float)maxDistance; } @@ -379,12 +397,19 @@ public void getInteractablePosesAB( // if rotateStepDegrees=90 and offset=10, then the paths would be [10, 100, 190, 280] rotations = new float[(int)Math.Round(360 / rotateStepDegrees)]; int i = 0; - for (float rotation = offset; rotation < 360 + offset; rotation += rotateStepDegrees) { + for ( + float rotation = offset; + rotation < 360 + offset; + rotation += rotateStepDegrees + ) { rotations[i++] = rotation; } } - SimObjPhysics theObject = getInteractableSimObjectFromId(objectId: objectId, forceAction: true); + SimObjPhysics theObject = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: true + ); // populate the positions by those that are reachable if (positions == null) { @@ -400,9 +425,14 @@ public void getInteractablePosesAB( objectBounds.Encapsulate(vp.position); } float fudgeFactor = objectBounds.extents.magnitude; - List filteredPositions = positions.Where( - p => (Vector3.Distance(a: p, b: theObject.transform.position) <= maxDistanceFloat + fudgeFactor + gridSize) - ).ToList(); + List filteredPositions = positions + .Where(p => + ( + Vector3.Distance(a: p, b: theObject.transform.position) + <= maxDistanceFloat + fudgeFactor + gridSize + ) + ) + .ToList(); // save current agent pose Vector3 oldPosition = transform.position; @@ -411,17 +441,19 @@ public void getInteractablePosesAB( //now put all this into a coroutine to actually teleport and do the visibility checks on a delay //since TeleportRoot needs to sync with a waitForFixedUpdate - StartCoroutine(TeleportThenWaitThenCheckInteractable( - filteredPositions: filteredPositions, - horizons: horizons, - rotations: rotations, - theObject: theObject, - maxDistanceFloat: maxDistanceFloat, - maxPoses: maxPoses, - oldPosition: oldPosition, - oldHorizon: oldHorizon, - oldRotation: oldRotation - )); + StartCoroutine( + TeleportThenWaitThenCheckInteractable( + filteredPositions: filteredPositions, + horizons: horizons, + rotations: rotations, + theObject: theObject, + maxDistanceFloat: maxDistanceFloat, + maxPoses: maxPoses, + oldPosition: oldPosition, + oldHorizon: oldHorizon, + oldRotation: oldRotation + ) + ); } IEnumerator TeleportThenWaitThenCheckInteractable( @@ -433,10 +465,11 @@ IEnumerator TeleportThenWaitThenCheckInteractable( int maxPoses, Vector3 oldPosition, Vector3 oldHorizon, - Quaternion oldRotation) { - + Quaternion oldRotation + ) { // set each key to store a list - List> validAgentPoses = new List>(); + List> validAgentPoses = + new List>(); bool stopEarly = false; foreach (float horizon in horizons) { @@ -451,8 +484,14 @@ IEnumerator TeleportThenWaitThenCheckInteractable( foreach (Vector3 position in filteredPositions) { Debug.Log("////////////////////"); Debug.Log($"position Before SetTransform: {transform.position}"); - Debug.Log($"Passing in position to SetTransform: Vector3 {position}, Vector3? {(Vector3?)position}"); - SetTransform(transform: transform, position: (Vector3?)position, rotation: (Quaternion?)Quaternion.Euler(rotationVector)); + Debug.Log( + $"Passing in position to SetTransform: Vector3 {position}, Vector3? {(Vector3?)position}" + ); + SetTransform( + transform: transform, + position: (Vector3?)position, + rotation: (Quaternion?)Quaternion.Euler(rotationVector) + ); yield return new WaitForFixedUpdate(); Debug.Log($"Position After SetTransform(): {transform.position}"); Debug.Log("////////////////////"); @@ -460,13 +499,15 @@ IEnumerator TeleportThenWaitThenCheckInteractable( // Each of these values is directly compatible with TeleportFull // and should be used with .step(action='TeleportFull', **interactable_positions[0]) if (objectIsCurrentlyVisible(theObject, maxDistanceFloat)) { - validAgentPoses.Add(new Dictionary { - ["x"] = position.x, - ["y"] = position.y, - ["z"] = position.z, - ["rotation"] = rotation, - ["horizon"] = horizon - }); + validAgentPoses.Add( + new Dictionary { + ["x"] = position.x, + ["y"] = position.y, + ["z"] = position.z, + ["rotation"] = rotation, + ["horizon"] = horizon + } + ); if (validAgentPoses.Count >= maxPoses) { stopEarly = true; @@ -475,17 +516,30 @@ IEnumerator TeleportThenWaitThenCheckInteractable( #if UNITY_EDITOR // In the editor, draw lines indicating from where the object was visible. - Debug.DrawLine(position, position + transform.forward * (gridSize * 0.5f), Color.red, 20f); + Debug.DrawLine( + position, + position + transform.forward * (gridSize * 0.5f), + Color.red, + 20f + ); #endif } } - if (stopEarly) { break; } + if (stopEarly) { + break; + } + } + if (stopEarly) { + break; } - if (stopEarly) { break; } } //reset to original position/rotation/horizon now that we are done - SetTransform(transform: transform, position: (Vector3?) oldPosition, rotation: (Quaternion?) oldRotation); + SetTransform( + transform: transform, + position: (Vector3?)oldPosition, + rotation: (Quaternion?)oldRotation + ); m_Camera.transform.localEulerAngles = oldHorizon; #if UNITY_EDITOR @@ -502,7 +556,7 @@ IEnumerator TeleportThenWaitThenCheckInteractable( // } } - public IEnumerator MoveAgent( + public IEnumerator MoveAgent( float moveMagnitude = 1, float speed = 1, float acceleration = 1 @@ -520,7 +574,7 @@ public IEnumerator MoveAgent( // Debug.Log($"preparing agent {this.transform.name} to move"); if (Mathf.Approximately(moveMagnitude, 0.0f)) { Debug.Log("Error! distance to move must be nonzero"); - // yield return nests the iterator structure because C# compiler forces + // yield return nests the iterator structure because C# compiler forces // to use yield return below and creates a nested Monad, (yield return (yield return val)) // better to return with .GetEnumerator(); return new ActionFinished() { @@ -555,7 +609,6 @@ public IEnumerator MoveAgent( ); } - public IEnumerator MoveAhead( float? moveMagnitude = null, float speed = 0.14f, @@ -586,7 +639,6 @@ public IEnumerator RotateRight( float acceleration = 22.5f ) { return RotateAgent( - degrees: degrees.GetValueOrDefault(rotateStepDegrees), speed: speed, acceleration: acceleration @@ -660,7 +712,9 @@ public ActionFinished TeleportArm( bool worldRelative = false, bool forceAction = false ) { - GameObject posRotManip = this.GetComponent().StretchArm.GetComponent().GetArmTarget(); + GameObject posRotManip = this.GetComponent() + .StretchArm.GetComponent() + .GetArmTarget(); // cache old values in case there's a failure Vector3 oldLocalPosition = posRotManip.transform.localPosition; @@ -705,9 +759,13 @@ public override IEnumerator RotateWristRelative( ) { // pitch and roll are not supported for the stretch and so we throw an error if (pitch != 0f || roll != 0f) { - throw new System.NotImplementedException("Pitch and roll are not supported for the stretch agent."); + throw new System.NotImplementedException( + "Pitch and roll are not supported for the stretch agent." + ); } - Debug.Log($"executing RotateWristRelative from ArticulatedAgentController with speed {speed}"); + Debug.Log( + $"executing RotateWristRelative from ArticulatedAgentController with speed {speed}" + ); var arm = getArmImplementation(); SetFloorColliderToHighFriction(); return arm.rotateWrist( diff --git a/unity/Assets/Scripts/ArticulatedAgentSolver.cs b/unity/Assets/Scripts/ArticulatedAgentSolver.cs index 24b7006896..325fe151c0 100644 --- a/unity/Assets/Scripts/ArticulatedAgentSolver.cs +++ b/unity/Assets/Scripts/ArticulatedAgentSolver.cs @@ -1,12 +1,16 @@ using System.Collections; using System.Collections.Generic; -using UnityEngine; +using System.Data.SqlClient; using System.Linq; -using UnityStandardAssets.Characters.FirstPerson; using System.Timers; -using System.Data.SqlClient; +using UnityEngine; +using UnityStandardAssets.Characters.FirstPerson; -public enum ABAgentState { Idle = 0, Moving = 1, Rotating = 2 }; +public enum ABAgentState { + Idle = 0, + Moving = 1, + Rotating = 2 +}; public class ABAgentPhysicsParams { public float distance; @@ -32,16 +36,24 @@ public class AgentMoveParams : ABAgentPhysicsParams { public class ArticulatedAgentSolver : MonoBehaviour, MovableContinuous { //pass in arm move parameters for Action based movement public AgentMoveParams currentAgentMoveParams = new AgentMoveParams(); + //reference for this joint's articulation body public ArticulationBody myAB; public ABAgentState agentState = ABAgentState.Idle; public float distanceTransformedSoFar; - public Vector3 prevStepTransformation, prevStepForward; + public Vector3 prevStepTransformation, + prevStepForward; + //private Vector3 directionWorld; private float accelerationTorque; - private float accelerationDistance, beginDecelerationSpeed, decelerationDistance, beginDecelerationTime; - private bool beginDeceleration, maxSpeed; - float deceleration, speedupTime; + private float accelerationDistance, + beginDecelerationSpeed, + decelerationDistance, + beginDecelerationTime; + private bool beginDeceleration, + maxSpeed; + float deceleration, + speedupTime; private Transform wristAB; private Transform fingersAB; @@ -77,7 +89,7 @@ public void PrepToControlAgentFromAction(AgentMoveParams agentMoveParams) { //initialize the buffer to cache positions to check for later currentAgentMoveParams.cachedPositions = new List(); currentAgentMoveParams.cachedFixedDeltaTimes = new List(); - + if (currentAgentMoveParams.agentState == ABAgentState.Moving) { // snapshot the initial agent position to compare with later during movement currentAgentMoveParams.initialTransformation = myAB.transform.position; @@ -88,9 +100,10 @@ public void PrepToControlAgentFromAction(AgentMoveParams agentMoveParams) { } prevStepForward = myAB.transform.forward; - + // determine if agent can even accelerate to max velocity and decelerate to 0 before reaching target position in best-case scenario - accelerationDistance = Mathf.Pow(currentAgentMoveParams.speed, 2) / (2 * currentAgentMoveParams.acceleration); + accelerationDistance = + Mathf.Pow(currentAgentMoveParams.speed, 2) / (2 * currentAgentMoveParams.acceleration); Debug.Log("accelerationDistance by default equals " + accelerationDistance); if (2 * accelerationDistance > currentAgentMoveParams.distance) { @@ -100,8 +113,8 @@ public void PrepToControlAgentFromAction(AgentMoveParams agentMoveParams) { beginDeceleration = false; } - - public void ContinuousUpdate(float fixedDeltaTime) { + + public void ContinuousUpdate(float fixedDeltaTime) { // Vector3 maxForce = currentAgentMoveParams.maxForce * currentAgentMoveParams.direction * Vector3.forward; float remainingDistance = currentAgentMoveParams.distance - distanceTransformedSoFar; @@ -109,62 +122,98 @@ public void ContinuousUpdate(float fixedDeltaTime) { Vector3 agentOrientedVelocity = myAB.transform.InverseTransformDirection(myAB.velocity); // Damping force for part of velocity that is not in the direction of movement - float dampingForceX = Mathf.Clamp(-100f * agentOrientedVelocity.x * currentAgentMoveParams.agentMass, -200f, 200f); + float dampingForceX = Mathf.Clamp( + -100f * agentOrientedVelocity.x * currentAgentMoveParams.agentMass, + -200f, + 200f + ); myAB.AddRelativeForce(new Vector3(dampingForceX, 0f, 0f)); - Debug.Log($"Damping force X equals: {dampingForceX} == clamp(-200 * {agentOrientedVelocity.x} * {currentAgentMoveParams.agentMass}, 100, 100)"); + Debug.Log( + $"Damping force X equals: {dampingForceX} == clamp(-200 * {agentOrientedVelocity.x} * {currentAgentMoveParams.agentMass}, 100, 100)" + ); accelerationDistance = 0.0f; if (currentAgentMoveParams.agentState == ABAgentState.Moving) { - float currentSpeed = Mathf.Abs(agentOrientedVelocity.z); float forceScaler = 1f / fixedDeltaTime; // CASE: Accelerate - Apply force calculated from difference between intended distance and actual distance after amount of time that has passed if (distanceTransformedSoFar < accelerationDistance) { - float desiredDistance = 0.5f * currentAgentMoveParams.acceleration * Mathf.Pow(currentAgentMoveParams.timePassed + fixedDeltaTime, 2); + float desiredDistance = + 0.5f + * currentAgentMoveParams.acceleration + * Mathf.Pow(currentAgentMoveParams.timePassed + fixedDeltaTime, 2); float distanceDelta = desiredDistance - distanceTransformedSoFar; // This shouldn't be the same formula as correcting for a velocityDelta, like in cruise-control mode, but for some reason, it's working great - float relativeForce = forceScaler * distanceDelta * currentAgentMoveParams.agentMass * currentAgentMoveParams.direction; - - relativeForce = Mathf.Clamp(relativeForce, -currentAgentMoveParams.maxForce, currentAgentMoveParams.maxForce); + float relativeForce = + forceScaler + * distanceDelta + * currentAgentMoveParams.agentMass + * currentAgentMoveParams.direction; + + relativeForce = Mathf.Clamp( + relativeForce, + -currentAgentMoveParams.maxForce, + currentAgentMoveParams.maxForce + ); Debug.Log( $"1. distanceDelta is {distanceDelta}. Applying force of {relativeForce} = " - + $"clamp({currentAgentMoveParams.maxForce}, {forceScaler} * {distanceDelta} * {currentAgentMoveParams.agentMass} * {currentAgentMoveParams.direction})." + + $"clamp({currentAgentMoveParams.maxForce}, {forceScaler} * {distanceDelta} * {currentAgentMoveParams.agentMass} * {currentAgentMoveParams.direction})." ); myAB.AddRelativeForce(new Vector3(0, 0, relativeForce)); - // CASE: Decelerate - Apply force calculated from difference between intended velocity and actual velocity at given distance remaining to travel - } else if (distanceTransformedSoFar >= currentAgentMoveParams.distance - accelerationDistance) { + // CASE: Decelerate - Apply force calculated from difference between intended velocity and actual velocity at given distance remaining to travel + } else if ( + distanceTransformedSoFar + >= currentAgentMoveParams.distance - accelerationDistance + ) { if (beginDeceleration == false) { beginDecelerationSpeed = currentSpeed; beginDeceleration = true; } - float desiredSpeed = beginDecelerationSpeed * (remainingDistance / accelerationDistance); + float desiredSpeed = + beginDecelerationSpeed * (remainingDistance / accelerationDistance); float speedDelta = desiredSpeed - currentSpeed; - - float relativeForce = forceScaler * speedDelta * currentAgentMoveParams.agentMass * currentAgentMoveParams.direction; - relativeForce = Mathf.Clamp(relativeForce, -currentAgentMoveParams.maxForce, currentAgentMoveParams.maxForce); + float relativeForce = + forceScaler + * speedDelta + * currentAgentMoveParams.agentMass + * currentAgentMoveParams.direction; + + relativeForce = Mathf.Clamp( + relativeForce, + -currentAgentMoveParams.maxForce, + currentAgentMoveParams.maxForce + ); Debug.Log( $"3. speedDelta is {speedDelta}. Applying force of {relativeForce} = " - + $"clamp({currentAgentMoveParams.maxForce}, {forceScaler} * {speedDelta} * {currentAgentMoveParams.agentMass} * {currentAgentMoveParams.direction})." + + $"clamp({currentAgentMoveParams.maxForce}, {forceScaler} * {speedDelta} * {currentAgentMoveParams.agentMass} * {currentAgentMoveParams.direction})." ); myAB.AddRelativeForce(new Vector3(0, 0, relativeForce)); - - // CASE: Cruise Control - Apply force calculated from difference between intended velocity and current velocity + + // CASE: Cruise Control - Apply force calculated from difference between intended velocity and current velocity } else { float speedDelta = currentAgentMoveParams.speed - currentSpeed; - float relativeForce = forceScaler * speedDelta * currentAgentMoveParams.agentMass * currentAgentMoveParams.direction; - - relativeForce = Mathf.Clamp(relativeForce, -currentAgentMoveParams.maxForce, currentAgentMoveParams.maxForce); + float relativeForce = + forceScaler + * speedDelta + * currentAgentMoveParams.agentMass + * currentAgentMoveParams.direction; + + relativeForce = Mathf.Clamp( + relativeForce, + -currentAgentMoveParams.maxForce, + currentAgentMoveParams.maxForce + ); Debug.Log( $"2. speedDelta is {speedDelta}. Applying force of {relativeForce} = " - + $"clamp({currentAgentMoveParams.maxForce}, {forceScaler} * {speedDelta} * {currentAgentMoveParams.agentMass} * {currentAgentMoveParams.direction})." + + $"clamp({currentAgentMoveParams.maxForce}, {forceScaler} * {speedDelta} * {currentAgentMoveParams.agentMass} * {currentAgentMoveParams.direction})." ); myAB.AddRelativeForce(new Vector3(0, 0, relativeForce)); @@ -180,7 +229,10 @@ public void ContinuousUpdate(float fixedDeltaTime) { // Determine (positive) distance covered based on forward progress, relative to previous physics-step's averaged forward-vector distanceTransformedThisFixedUpdate = Mathf.Clamp( - Vector3.Dot(currentPosition - prevStepTransformation, currentForward * currentAgentMoveParams.direction), + Vector3.Dot( + currentPosition - prevStepTransformation, + currentForward * currentAgentMoveParams.direction + ), 0, Mathf.Infinity ); @@ -188,91 +240,118 @@ public void ContinuousUpdate(float fixedDeltaTime) { // Store current values for comparing with next FixedUpdate prevStepTransformation = currentPosition; prevStepForward = myAB.transform.forward; - } else if (currentAgentMoveParams.agentState == ABAgentState.Rotating) { - // When rotating the agent shouldn't be moving forward/backwards but its wheels are moving so we use a smaller // damping force to counteract forward/backward movement (as opposed to the force used for lateral movement // above) - float dampingForceZ = Mathf.Clamp(-100f * agentOrientedVelocity.z * currentAgentMoveParams.agentMass, -50f, 50f); + float dampingForceZ = Mathf.Clamp( + -100f * agentOrientedVelocity.z * currentAgentMoveParams.agentMass, + -50f, + 50f + ); myAB.AddRelativeForce(new Vector3(0f, 0f, dampingForceZ)); - Debug.Log($"Damping force Z equals: {dampingForceZ} == clamp(-100 * {agentOrientedVelocity.z} * {currentAgentMoveParams.agentMass}, -50, 50)"); - + Debug.Log( + $"Damping force Z equals: {dampingForceZ} == clamp(-100 * {agentOrientedVelocity.z} * {currentAgentMoveParams.agentMass}, -50, 50)" + ); + float currentAngularSpeed = Mathf.Abs(myAB.angularVelocity.y); float forceScaler = 1f / fixedDeltaTime; // CASE: Accelerate - Apply force calculated from difference between intended distance and actual distance after amount of time that has passed if (distanceTransformedSoFar < accelerationDistance) { - float desiredAngularDistance = 0.5f * currentAgentMoveParams.acceleration * Mathf.Pow(currentAgentMoveParams.timePassed + fixedDeltaTime, 2); + float desiredAngularDistance = + 0.5f + * currentAgentMoveParams.acceleration + * Mathf.Pow(currentAgentMoveParams.timePassed + fixedDeltaTime, 2); float angularDistanceDelta = desiredAngularDistance - distanceTransformedSoFar; float relativeTorque = Mathf.Clamp( - forceScaler * angularDistanceDelta * myAB.inertiaTensor.y * currentAgentMoveParams.direction, + forceScaler + * angularDistanceDelta + * myAB.inertiaTensor.y + * currentAgentMoveParams.direction, -currentAgentMoveParams.maxForce, currentAgentMoveParams.maxForce ); Debug.Log( $"1. distanceDelta is {angularDistanceDelta}. Applying torque of {relativeTorque} = " - + $"clamp(one schmillion Newton-meters, {forceScaler} * {angularDistanceDelta} * {myAB.inertiaTensor.y} * {currentAgentMoveParams.direction})." + + $"clamp(one schmillion Newton-meters, {forceScaler} * {angularDistanceDelta} * {myAB.inertiaTensor.y} * {currentAgentMoveParams.direction})." ); myAB.AddRelativeTorque(new Vector3(0, relativeTorque, 0)); - // CASE: Decelerate - Apply force calculated from difference between intended angular velocity and actual angular velocity at given angular distance remaining to travel - } else if (distanceTransformedSoFar >= currentAgentMoveParams.distance - accelerationDistance) { + // CASE: Decelerate - Apply force calculated from difference between intended angular velocity and actual angular velocity at given angular distance remaining to travel + } else if ( + distanceTransformedSoFar + >= currentAgentMoveParams.distance - accelerationDistance + ) { if (beginDeceleration == false) { beginDecelerationSpeed = currentAngularSpeed; beginDeceleration = true; } - - float desiredAngularSpeed = beginDecelerationSpeed * (remainingDistance / accelerationDistance); + + float desiredAngularSpeed = + beginDecelerationSpeed * (remainingDistance / accelerationDistance); float angularSpeedDelta = desiredAngularSpeed - currentAngularSpeed; - + float relativeTorque = Mathf.Clamp( - forceScaler * angularSpeedDelta * myAB.inertiaTensor.y * currentAgentMoveParams.direction, + forceScaler + * angularSpeedDelta + * myAB.inertiaTensor.y + * currentAgentMoveParams.direction, -currentAgentMoveParams.maxForce, currentAgentMoveParams.maxForce ); Debug.Log( $"3. speedDelta is {angularSpeedDelta}. Applying torque of {relativeTorque} = " - + $"clamp(one schmillion Newton-meters, {forceScaler} * {angularSpeedDelta} * {myAB.inertiaTensor.y} * {currentAgentMoveParams.direction})." + + $"clamp(one schmillion Newton-meters, {forceScaler} * {angularSpeedDelta} * {myAB.inertiaTensor.y} * {currentAgentMoveParams.direction})." ); myAB.AddRelativeTorque(new Vector3(0, relativeTorque, 0)); - - // CASE: Cruise - Apply force calculated from difference between intended angular velocity and current angular velocity + + // CASE: Cruise - Apply force calculated from difference between intended angular velocity and current angular velocity } else { float angularSpeedDelta = currentAgentMoveParams.speed - currentAngularSpeed; float relativeTorque = Mathf.Clamp( - forceScaler * angularSpeedDelta * myAB.inertiaTensor.y * currentAgentMoveParams.direction, + forceScaler + * angularSpeedDelta + * myAB.inertiaTensor.y + * currentAgentMoveParams.direction, -currentAgentMoveParams.maxForce, currentAgentMoveParams.maxForce ); Debug.Log( $"2. speedDelta is {angularSpeedDelta}. Applying torque of {relativeTorque} = " - + $"clamp(one schmillion Newton-meters, {forceScaler} * {angularSpeedDelta} * {myAB.inertiaTensor.y} * {currentAgentMoveParams.direction})." + + $"clamp(one schmillion Newton-meters, {forceScaler} * {angularSpeedDelta} * {myAB.inertiaTensor.y} * {currentAgentMoveParams.direction})." ); myAB.AddRelativeTorque(new Vector3(0, relativeTorque, 0)); } - + // Begin checks to see if we have stopped moving or if we need to stop moving - + // Cache the rotation at the moment Vector3 currentRotation = myAB.transform.eulerAngles; // Determine (positive) angular distance covered - distanceTransformedThisFixedUpdate = Mathf.Deg2Rad * Mathf.Clamp( - (currentRotation.y - prevStepTransformation.y) * currentAgentMoveParams.direction, 0, Mathf.Infinity - ); + distanceTransformedThisFixedUpdate = + Mathf.Deg2Rad + * Mathf.Clamp( + (currentRotation.y - prevStepTransformation.y) + * currentAgentMoveParams.direction, + 0, + Mathf.Infinity + ); // Store current values for comparing with next FixedUpdate prevStepTransformation = currentRotation; } else if (currentAgentMoveParams.agentState == ABAgentState.Idle) { // Do nothing } else { - throw new System.NotImplementedException($"Agent is not in a valid movement state: {currentAgentMoveParams.agentState}."); + throw new System.NotImplementedException( + $"Agent is not in a valid movement state: {currentAgentMoveParams.agentState}." + ); } // Cache data used to check if we have stopped rotating or if we need to stop rotating @@ -288,41 +367,47 @@ public void ContinuousUpdate(float fixedDeltaTime) { } public bool ShouldHalt() { - // Debug.Log("checking ArticulatedAgentController shouldHalt"); - bool shouldStop = false; - ArticulatedAgentSolver a = this; - // Debug.Log($"checking agent: {a.transform.name}"); - // Debug.Log($"distance moved so far is: {a.distanceTransformedSoFar}"); - // Debug.Log($"current velocity is: {this.transform.GetComponent().velocity.magnitude}"); - - //check agent to see if it has halted or not - if (!a.shouldHalt( + // Debug.Log("checking ArticulatedAgentController shouldHalt"); + bool shouldStop = false; + ArticulatedAgentSolver a = this; + // Debug.Log($"checking agent: {a.transform.name}"); + // Debug.Log($"distance moved so far is: {a.distanceTransformedSoFar}"); + // Debug.Log($"current velocity is: {this.transform.GetComponent().velocity.magnitude}"); + + //check agent to see if it has halted or not + if ( + !a.shouldHalt( distanceTransformedSoFar: a.distanceTransformedSoFar, cachedPositions: a.currentAgentMoveParams.cachedPositions, cachedFixedTimeDeltas: a.currentAgentMoveParams.cachedFixedDeltaTimes, minMovementPerSecond: a.currentAgentMoveParams.minMovementPerSecond, haltCheckTimeWindow: a.currentAgentMoveParams.haltCheckTimeWindow - )) { - // if any single joint is still not halting, return false - // Debug.Log("still not done, don't halt yet"); - shouldStop = false; - return shouldStop; - } else { - //this joint returns that it should stop! - Debug.Log($"halted! Return shouldStop! Distance moved: {a.distanceTransformedSoFar}"); - shouldStop = true; - return shouldStop; - } + ) + ) { + // if any single joint is still not halting, return false + // Debug.Log("still not done, don't halt yet"); + shouldStop = false; + return shouldStop; + } else { + //this joint returns that it should stop! + Debug.Log($"halted! Return shouldStop! Distance moved: {a.distanceTransformedSoFar}"); + shouldStop = true; + return shouldStop; } - - // TODO remove from API - public virtual string GetHaltMessage() { return ""; } + } + + // TODO remove from API + public virtual string GetHaltMessage() { + return ""; + } public ActionFinished FinishContinuousMove(BaseFPSAgentController controller) { Debug.Log("starting continuousMoveFinishAB"); controller.transform.GetComponent().velocity = Vector3.zero; controller.transform.GetComponent().angularVelocity = Vector3.zero; - controller.transform.GetComponent().currentAgentMoveParams.agentState = ABAgentState.Idle; + controller + .transform.GetComponent() + .currentAgentMoveParams.agentState = ABAgentState.Idle; string debugMessage = "I guess everything is fine?"; //maybe needs to switch back to slippery here to prep for movement??? @@ -330,17 +415,16 @@ public ActionFinished FinishContinuousMove(BaseFPSAgentController controller) { //controller.SetFloorColliderToSlippery(); bool actionSuccess = IsFingerTransformCorrect(); - if (!actionSuccess) { + if (!actionSuccess) { controller.agentManager.SetCriticalErrorState(); } - debugMessage = actionSuccess ? debugMessage : "Articulated agent is broken, fingers dislodges all actions will fail from this point. Must call 'reset' and reload scene and re-initialize agent."; + debugMessage = actionSuccess + ? debugMessage + : "Articulated agent is broken, fingers dislodges all actions will fail from this point. Must call 'reset' and reload scene and re-initialize agent."; // controller.actionFinished(actionSuccess, debugMessage); - return new ActionFinished { - success = actionSuccess, - errorMessage = debugMessage - }; + return new ActionFinished { success = actionSuccess, errorMessage = debugMessage }; } //do checks based on what sort of joint I am @@ -352,9 +436,8 @@ public bool shouldHalt( double minMovementPerSecond, double haltCheckTimeWindow ) { - bool shouldHalt = false; - + //halt if positions/rotations are within tolerance and effectively not changing // Debug.Log("Distance moved is " + distanceTransformedSoFar + ", and distance to exceed is " + currentAgentMoveParams.distance); @@ -371,7 +454,6 @@ double haltCheckTimeWindow Debug.Log("halt due to position delta within tolerance"); return shouldHalt; } - //check if the amount moved/rotated exceeds this agents target else if (distanceTransformedSoFar >= currentAgentMoveParams.distance) { shouldHalt = true; @@ -379,7 +461,6 @@ double haltCheckTimeWindow Debug.Log("halt due to distance reached/exceeded"); return shouldHalt; } - //hard check for time limit else if (currentAgentMoveParams.timePassed >= currentAgentMoveParams.maxTimePassed) { shouldHalt = true; @@ -393,13 +474,16 @@ double haltCheckTimeWindow //check if all values in the array are within a threshold of motion or not public static bool ApproximatelyNoChange( - List positionDeltas, List timeDeltas, double minMovementPerSecond, double haltCheckTimeWindow + List positionDeltas, + List timeDeltas, + double minMovementPerSecond, + double haltCheckTimeWindow ) { double totalTime = 0f; double totalDistanceTraveled = 0f; for (int i = positionDeltas.Count - 1; i >= 0; i--) { totalTime += timeDeltas[i]; - totalDistanceTraveled += Mathf.Abs((float) positionDeltas[i]); + totalDistanceTraveled += Mathf.Abs((float)positionDeltas[i]); if (totalTime >= haltCheckTimeWindow) { break; } @@ -413,11 +497,9 @@ public static bool ApproximatelyNoChange( return totalDistanceTraveled / totalTime < minMovementPerSecond; } - void SetCenterOfMass(Vector3 worldCenterOfMass) - { + void SetCenterOfMass(Vector3 worldCenterOfMass) { ArticulationBody[] bodies = FindObjectsOfType(); - foreach (ArticulationBody body in bodies) - { + foreach (ArticulationBody body in bodies) { // Convert world-space center of mass to local space Vector3 localCenterOfMass = body.transform.InverseTransformPoint(worldCenterOfMass); body.centerOfMass = localCenterOfMass; diff --git a/unity/Assets/Scripts/ArticulatedArmController.cs b/unity/Assets/Scripts/ArticulatedArmController.cs index dd2db6c7b0..cba4dbc10f 100644 --- a/unity/Assets/Scripts/ArticulatedArmController.cs +++ b/unity/Assets/Scripts/ArticulatedArmController.cs @@ -1,26 +1,30 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -using System.Linq; + public partial class ArticulatedArmController : ArmController { public ArticulatedArmJointSolver[] joints; - + [SerializeField] //this wrist placeholder represents the posrot manipulator's position on the IK Stretch so we can match the distance magnitudes //it is weird because the origin point of the last joint in the AB is in a different offset, so we have to account for that for benchmarking - private Transform armBase, handCameraTransform, FirstJoint, wristPlaceholderTransform; + private Transform armBase, + handCameraTransform, + FirstJoint, + wristPlaceholderTransform; private float wristPlaceholderForwardOffset; - + private PhysicsRemoteFPSAgentController PhysicsController; //Distance from joint containing gripper camera to armTarget private Vector3 WristToManipulator = new Vector3(0, -0.09872628f, 0); //held objects, don't need a reference to colliders since we are "attaching" via fixed joints instead of cloning - public new List heldObjects; + public new List heldObjects; // TODO: Possibly reimplement this fucntions, if AB read of transform is ok then may not need to reimplement public override Transform pickupParent() { @@ -28,8 +32,11 @@ public override Transform pickupParent() { } public override Vector3 wristSpaceOffsetToWorldPos(Vector3 offset) { - return handCameraTransform.TransformPoint(offset) - handCameraTransform.position + WristToManipulator; + return handCameraTransform.TransformPoint(offset) + - handCameraTransform.position + + WristToManipulator; } + public override Vector3 armBaseSpaceOffsetToWorldPos(Vector3 offset) { return this.transform.TransformPoint(offset) - this.transform.position; } @@ -37,6 +44,7 @@ public override Vector3 armBaseSpaceOffsetToWorldPos(Vector3 offset) { public override Vector3 pointToWristSpace(Vector3 point) { return handCameraTransform.TransformPoint(point) + WristToManipulator; } + public override Vector3 pointToArmBaseSpace(Vector3 point) { return armBase.transform.TransformPoint(point); } @@ -60,24 +68,23 @@ public override bool ShouldHalt() { //Debug.Log($"distance moved so far for this joint is: {j.distanceTransformedSoFar}"); //check all joints that have had movement params set to see if they have halted or not - if(j.currentArmMoveParams != null) - { - if (!j.shouldHalt( - distanceTransformedSoFar: j.distanceTransformedSoFar, - cachedPositions: j.currentArmMoveParams.cachedPositions, - cachedFixedTimeDeltas: j.currentArmMoveParams.cachedFixedDeltaTimes, - minMovementPerSecond: j.currentArmMoveParams.minMovementPerSecond, - haltCheckTimeWindow: j.currentArmMoveParams.haltCheckTimeWindow - )) { + if (j.currentArmMoveParams != null) { + if ( + !j.shouldHalt( + distanceTransformedSoFar: j.distanceTransformedSoFar, + cachedPositions: j.currentArmMoveParams.cachedPositions, + cachedFixedTimeDeltas: j.currentArmMoveParams.cachedFixedDeltaTimes, + minMovementPerSecond: j.currentArmMoveParams.minMovementPerSecond, + haltCheckTimeWindow: j.currentArmMoveParams.haltCheckTimeWindow + ) + ) { //if any single joint is still not halting, return false //Debug.Log("still not done, don't halt yet"); shouldHalt = false; return shouldHalt; } - //this joint returns that it should stop! Now we must wait to see if there rest - else - { + else { //Debug.Log($"halted! Distance moved: {j.distanceTransformedSoFar}"); shouldHalt = true; continue; @@ -89,7 +96,6 @@ public override bool ShouldHalt() { return shouldHalt; } - public override ActionFinished FinishContinuousMove(BaseFPSAgentController controller) { Debug.Log("starting continuousMoveFinishAB"); string debugMessage = "I guess everything is fine?"; @@ -97,17 +103,16 @@ public override ActionFinished FinishContinuousMove(BaseFPSAgentController contr // TODO inherit both solvers from common code // bool actionSuccess = IsFingerTransformCorrect(); bool actionSuccess = true; - if (!actionSuccess) { + if (!actionSuccess) { controller.agentManager.SetCriticalErrorState(); } - debugMessage = actionSuccess ? debugMessage : "Articulated agent is broken, fingers dislodges all actions will fail from this point. Must call 'reset' and reload scene and re-initialize agent."; + debugMessage = actionSuccess + ? debugMessage + : "Articulated agent is broken, fingers dislodges all actions will fail from this point. Must call 'reset' and reload scene and re-initialize agent."; // controller.actionFinished(actionSuccess, debugMessage); - return new ActionFinished { - success = actionSuccess, - errorMessage = debugMessage - }; + return new ActionFinished { success = actionSuccess, errorMessage = debugMessage }; } public override GameObject GetArmTarget() { @@ -125,7 +130,7 @@ void Start() { //TODO: Initialization - // TODO: Replace Solver + // TODO: Replace Solver } //TODO: main functions to reimplement, use continuousMovement.moveAB/rotateAB @@ -138,9 +143,8 @@ public override IEnumerator moveArmRelative( string coordinateSpace, bool restrictTargetPosition ) { - - yield return new ActionFinished() { success = false, errorMessage = "Not implemented"}; - //not doing this one yet soooo uhhhhh ignore for now + yield return new ActionFinished() { success = false, errorMessage = "Not implemented" }; + //not doing this one yet soooo uhhhhh ignore for now } public IEnumerator moveArmTarget( @@ -171,7 +175,8 @@ public IEnumerator moveArmTarget( direction = 1; } - Dictionary jointToArmDistanceRatios = new Dictionary(); + Dictionary jointToArmDistanceRatios = + new Dictionary(); ArmMoveParams amp = new ArmMoveParams { distance = distance, @@ -196,7 +201,10 @@ public IEnumerator moveArmTarget( ); } - public float GetDriveUpperLimit(ArticulatedArmJointSolver joint, JointAxisType jointAxisType = JointAxisType.Extend) { + public float GetDriveUpperLimit( + ArticulatedArmJointSolver joint, + JointAxisType jointAxisType = JointAxisType.Extend + ) { float upperLimit = 0.0f; if (jointAxisType == JointAxisType.Extend) { @@ -256,10 +264,10 @@ bool useLimits //now need to do move call here I think return withLastStepCallback( - ContinuousMovement.moveAB( - movable: this, - controller: controller, - fixedDeltaTime: fixedDeltaTime + ContinuousMovement.moveAB( + movable: this, + controller: controller, + fixedDeltaTime: fixedDeltaTime ) ); } @@ -281,10 +289,12 @@ bool useLimits normalizedY: false, useLimits: useLimits ); - } - private void prepAllTheThingsBeforeJointMoves(ArticulatedArmJointSolver joint, ArmMoveParams armMoveParams) { + private void prepAllTheThingsBeforeJointMoves( + ArticulatedArmJointSolver joint, + ArmMoveParams armMoveParams + ) { //FloorCollider.material = sticky; joint.PrepToControlJointFromAction(armMoveParams); } @@ -325,10 +335,10 @@ bool returnToStartPositionIfFailed //now need to do move call here I think return withLastStepCallback( - ContinuousMovement.moveAB( - movable: this, - controller: controller, - fixedDeltaTime: fixedDeltaTime + ContinuousMovement.moveAB( + movable: this, + controller: controller, + fixedDeltaTime: fixedDeltaTime ) ); } @@ -355,7 +365,7 @@ public IEnumerable PickupObject(List objectIds) { // //add a fixed joint to this picked up object // FixedJoint ultraHand = sop.transform.gameObject.AddComponent(); - // //add reference to the wrist joint as connected articulated body + // //add reference to the wrist joint as connected articulated body // ultraHand.connectedArticulationBody = FinalJoint.GetComponent(); // ultraHand.enableCollision = true; //add to heldObjects list so we know when to drop @@ -367,21 +377,17 @@ public IEnumerable PickupObject(List objectIds) { if (!pickedUp) { errorMessage = ( objectIds != null - ? "No objects (specified by objectId) were valid to be picked up by the arm" - : "No objects were valid to be picked up by the arm" + ? "No objects (specified by objectId) were valid to be picked up by the arm" + : "No objects were valid to be picked up by the arm" ); } - yield return new ActionFinished() { - success = pickedUp, - errorMessage = errorMessage - }; + yield return new ActionFinished() { success = pickedUp, errorMessage = errorMessage }; } //called by ArmAgentController ReleaseObject - public override IEnumerator DropObject() { - foreach (SimObjPhysics sop in heldObjects) - { + public override IEnumerator DropObject() { + foreach (SimObjPhysics sop in heldObjects) { //remove the joint component //may need a null check for if we decide to break joints via force at some poine. //look into the OnJointBreak callback if needed @@ -389,7 +395,7 @@ public override IEnumerator DropObject() { sop.BeingDropped(); } - + heldObjects.Clear(); yield return ActionFinished.Success; } @@ -405,14 +411,15 @@ protected override void lastStepCallback() { // Check the joint type and get the current joint position and velocity if (myAB.jointType == ArticulationJointType.PrismaticJoint) { - -// Debug.Log($"joint {joint.gameObject}"); -// Debug.Log($"joint {myAB.jointType}"); -// Debug.Log($"solverIterations {myAB.solverIterations}"); -// Debug.Log($"solverVelocityIterations {myAB.solverVelocityIterations}"); + // Debug.Log($"joint {joint.gameObject}"); + // Debug.Log($"joint {myAB.jointType}"); + // Debug.Log($"solverIterations {myAB.solverIterations}"); + // Debug.Log($"solverVelocityIterations {myAB.solverVelocityIterations}"); if (myAB.dofCount != 1) { - throw new NotImplementedException("Prismatic joint must have 1 degree of freedom"); + throw new NotImplementedException( + "Prismatic joint must have 1 degree of freedom" + ); } float currentPosition = myAB.jointPosition[0]; @@ -447,11 +454,12 @@ protected override void lastStepCallback() { if (whichDrive == "z") { myAB.zDrive = activeDrive; } - } - else if (myAB.jointType == ArticulationJointType.RevoluteJoint) { + } else if (myAB.jointType == ArticulationJointType.RevoluteJoint) { // For revolute joints if (myAB.dofCount != 1) { - throw new NotImplementedException("Revolute joint must have 1 degree of freedom"); + throw new NotImplementedException( + "Revolute joint must have 1 degree of freedom" + ); } float currentPosition = Mathf.Rad2Deg * myAB.jointPosition[0]; // Weirdly not in degrees @@ -476,7 +484,7 @@ public override ArmMetadata GenerateMetadata() { return meta; } - //actual metadata implementation for articulation heirarchy + //actual metadata implementation for articulation heirarchy public ArticulationArmMetadata GenerateArticulationMetadata() { ArticulationArmMetadata meta = new ArticulationArmMetadata(); @@ -494,7 +502,8 @@ public ArticulationArmMetadata GenerateArticulationMetadata() { jMeta.position = joints[i].transform.position; - jMeta.rootRelativePosition = joints[0].transform.InverseTransformPoint(joints[i].transform.position); + jMeta.rootRelativePosition = joints[0] + .transform.InverseTransformPoint(joints[i].transform.position); jMeta.jointHeirarchyPosition = i; @@ -511,10 +520,16 @@ public ArticulationArmMetadata GenerateArticulationMetadata() { // ROOT-JOINT RELATIVE ROTATION // Grab rotation of current joint's angler relative to root joint - currentRotation = Quaternion.Inverse(joints[0].transform.rotation) * joints[i].transform.rotation; + currentRotation = + Quaternion.Inverse(joints[0].transform.rotation) * joints[i].transform.rotation; if (currentRotation != new Quaternion(0, 0, 0, -1)) { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); - jMeta.rootRelativeRotation = new Vector4(vectorRot.x, vectorRot.y, vectorRot.z, angleRot); + jMeta.rootRelativeRotation = new Vector4( + vectorRot.x, + vectorRot.y, + vectorRot.z, + angleRot + ); } else { jMeta.rootRelativeRotation = new Vector4(1, 0, 0, 0); } @@ -522,14 +537,22 @@ public ArticulationArmMetadata GenerateArticulationMetadata() { // LOCAL POSITION AND LOCAL ROTATION //get local position and local rotation relative to immediate parent in heirarchy if (i != 0) { - jMeta.localPosition = joints[i - 1].transform.InverseTransformPoint(joints[i].transform.position); - - var currentLocalRotation = Quaternion.Inverse(joints [i - 1].transform.rotation) * joints[i].transform.rotation; - if(currentLocalRotation != new Quaternion(0, 0, 0, -1)) { + jMeta.localPosition = joints[i - 1] + .transform.InverseTransformPoint(joints[i].transform.position); + + var currentLocalRotation = + Quaternion.Inverse(joints[i - 1].transform.rotation) + * joints[i].transform.rotation; + if (currentLocalRotation != new Quaternion(0, 0, 0, -1)) { currentLocalRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); - jMeta.localRotation = new Vector4(vectorRot.x, vectorRot.y, vectorRot.z, angleRot); + jMeta.localRotation = new Vector4( + vectorRot.x, + vectorRot.y, + vectorRot.z, + angleRot + ); } else { - jMeta.localRotation = new Vector4(1, 0, 0, 0); + jMeta.localRotation = new Vector4(1, 0, 0, 0); } } else { //special case for the lift since its the base of the arm @@ -556,9 +579,10 @@ public ArticulationArmMetadata GenerateArticulationMetadata() { meta.handSphereCenter = magnetSphere.transform.TransformPoint(magnetSphere.center); meta.handSphereRadius = magnetSphere.radius; List objectsInMagnet = WhatObjectsAreInsideMagnetSphereAsSOP(false); - meta.pickupableObjects = objectsInMagnet.Where( - x => x.PrimaryProperty == SimObjPrimaryProperty.CanPickup - ).Select(x => x.ObjectID).ToList(); + meta.pickupableObjects = objectsInMagnet + .Where(x => x.PrimaryProperty == SimObjPrimaryProperty.CanPickup) + .Select(x => x.ObjectID) + .ToList(); meta.objectsInsideHandSphereRadius = objectsInMagnet.Select(x => x.ObjectID).ToList(); return meta; diff --git a/unity/Assets/Scripts/ArticulatedArmExtender.cs b/unity/Assets/Scripts/ArticulatedArmExtender.cs index 3b1de24273..12d0607d41 100644 --- a/unity/Assets/Scripts/ArticulatedArmExtender.cs +++ b/unity/Assets/Scripts/ArticulatedArmExtender.cs @@ -4,8 +4,9 @@ // Handles collider stretching and arm extension animation public class ArticulatedArmExtender : MonoBehaviour { - - public Transform arm2, arm3, arm4; + public Transform arm2, + arm3, + arm4; public Transform[] myColliders; public float initialZPos; public float arm2InitialZPos; @@ -24,7 +25,11 @@ public void Start() { private void scaleColliders() { var currentZPos = this.gameObject.transform.localPosition.z; foreach (Transform go in myColliders) { - go.localScale = new Vector3(go.localScale.x, go.localScale.y, 1 + (currentZPos - initialZPos) * scaleMultiplier); + go.localScale = new Vector3( + go.localScale.x, + go.localScale.y, + 1 + (currentZPos - initialZPos) * scaleMultiplier + ); } } diff --git a/unity/Assets/Scripts/ArticulatedArmJointSolver.cs b/unity/Assets/Scripts/ArticulatedArmJointSolver.cs index 44e4ab34fa..e3b21e10ec 100644 --- a/unity/Assets/Scripts/ArticulatedArmJointSolver.cs +++ b/unity/Assets/Scripts/ArticulatedArmJointSolver.cs @@ -1,13 +1,33 @@ using System.Collections; using System.Collections.Generic; -using UnityEngine; using System.Linq; +using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public enum ArmLiftState { Idle = 0, MovingDown = -1, MovingUp = 1 }; -public enum ArmExtendState { Idle = 0, MovingBackward = -1, MovingForward = 1 }; -public enum ArmRotateState { Idle = 0, Negative = -1, Positive = 1 }; -public enum JointAxisType { Unassigned, Extend, Lift, Rotate }; +public enum ArmLiftState { + Idle = 0, + MovingDown = -1, + MovingUp = 1 +}; + +public enum ArmExtendState { + Idle = 0, + MovingBackward = -1, + MovingForward = 1 +}; + +public enum ArmRotateState { + Idle = 0, + Negative = -1, + Positive = 1 +}; + +public enum JointAxisType { + Unassigned, + Extend, + Lift, + Rotate +}; public class ArmMoveParams : ABAgentPhysicsParams { public ArticulatedAgentController controller; @@ -19,11 +39,14 @@ public class ArmMoveParams : ABAgentPhysicsParams { public class ArticulatedArmJointSolver : MonoBehaviour { [Header("What kind of joint is this?")] public JointAxisType jointAxisType = JointAxisType.Unassigned; + [Header("State of this joint's movements")] [SerializeField] public ArmRotateState rotateState = ArmRotateState.Idle; + [SerializeField] public ArmLiftState liftState = ArmLiftState.Idle; + [SerializeField] public ArmExtendState extendState = ArmExtendState.Idle; @@ -33,7 +56,8 @@ public class ArticulatedArmJointSolver : MonoBehaviour { //reference for this joint's articulation body public ArticulationBody myAB; - public float distanceTransformedSoFar, prevStepTransformation; + public float distanceTransformedSoFar, + prevStepTransformation; //these limits are from the Articulation Body drive's lower and uppper limit public float lowerArmBaseLimit = -0.1832155f; @@ -41,7 +65,6 @@ public class ArticulatedArmJointSolver : MonoBehaviour { public float lowerArmExtendLimit = 0.0f; public float upperArmExtendLimit = 0.516f; - void Start() { myAB = this.GetComponent(); } @@ -70,7 +93,6 @@ public void PrepToControlJointFromAction(ArmMoveParams armMoveParams) { //we are a lift type joint, moving along the local y axis if (jointAxisType == JointAxisType.Lift) { if (liftState == ArmLiftState.Idle) { - //set if we are moving up or down based on sign of distance from input if (armMoveParams.direction < 0) { Debug.Log("setting lift state to move down"); @@ -81,11 +103,9 @@ public void PrepToControlJointFromAction(ArmMoveParams armMoveParams) { } } } - //we are an extending joint, moving along the local z axis else if (jointAxisType == JointAxisType.Extend) { if (extendState == ArmExtendState.Idle) { - currentArmMoveParams.armExtender = this.GetComponent(); //currentArmMoveParams.armExtender.Init(); @@ -96,11 +116,10 @@ public void PrepToControlJointFromAction(ArmMoveParams armMoveParams) { extendState = ArmExtendState.MovingForward; } } - - //we are a rotating joint, rotating around the local y axis + + //we are a rotating joint, rotating around the local y axis } else if (jointAxisType == JointAxisType.Rotate) { if (rotateState == ArmRotateState.Idle) { - //set if we are rotating left or right if (armMoveParams.direction < 0) { rotateState = ArmRotateState.Negative; @@ -112,7 +131,6 @@ public void PrepToControlJointFromAction(ArmMoveParams armMoveParams) { } public void ControlJointFromAction(float fixedDeltaTime) { - if (currentArmMoveParams == null) { return; } @@ -127,22 +145,29 @@ public void ControlJointFromAction(float fixedDeltaTime) { //Debug.Log("start ControlJointFromAction for axis type LIFT"); var drive = myAB.yDrive; float currentPosition = myAB.jointPosition[0]; - float targetPosition = currentPosition + (float)liftState * fixedDeltaTime * currentArmMoveParams.speed; + float targetPosition = + currentPosition + + (float)liftState * fixedDeltaTime * currentArmMoveParams.speed; drive.target = targetPosition; myAB.yDrive = drive; // Begin checks to see if we have stopped moving or if we need to stop moving // Determine (positive) distance covered - distanceTransformedSoFar = Mathf.Abs(currentPosition - currentArmMoveParams.initialJointPosition); - distanceTransformedThisFixedUpdate = Mathf.Abs(currentPosition - prevStepTransformation); + distanceTransformedSoFar = Mathf.Abs( + currentPosition - currentArmMoveParams.initialJointPosition + ); + distanceTransformedThisFixedUpdate = Mathf.Abs( + currentPosition - prevStepTransformation + ); // Store current values for comparing with next FixedUpdate prevStepTransformation = currentPosition; if (currentArmMoveParams.useLimits) { Debug.Log("extending/retracting arm with limits"); - float distanceRemaining = currentArmMoveParams.distance - distanceTransformedSoFar; + float distanceRemaining = + currentArmMoveParams.distance - distanceTransformedSoFar; // New version of up-down drive float forceAppliedFromRest = currentArmMoveParams.maxForce; @@ -155,13 +180,22 @@ public void ControlJointFromAction(float fixedDeltaTime) { float offset = 1e-2f; if (liftState == ArmLiftState.MovingUp) { drive.upperLimit = Mathf.Min(upperArmBaseLimit, targetPosition + offset); - drive.lowerLimit = Mathf.Min(Mathf.Max(lowerArmBaseLimit, currentPosition), targetPosition); + drive.lowerLimit = Mathf.Min( + Mathf.Max(lowerArmBaseLimit, currentPosition), + targetPosition + ); } else if (liftState == ArmLiftState.MovingDown) { drive.lowerLimit = Mathf.Max(lowerArmBaseLimit, targetPosition); - drive.upperLimit = Mathf.Max(Mathf.Min(upperArmBaseLimit, currentPosition + offset), targetPosition + offset); + drive.upperLimit = Mathf.Max( + Mathf.Min(upperArmBaseLimit, currentPosition + offset), + targetPosition + offset + ); } - drive.damping = Mathf.Min(forceAppliedFromRest / currentArmMoveParams.speed, 10000f); + drive.damping = Mathf.Min( + forceAppliedFromRest / currentArmMoveParams.speed, + 10000f + ); float signedDistanceRemaining = direction * distanceRemaining; @@ -173,7 +207,8 @@ public void ControlJointFromAction(float fixedDeltaTime) { float switchWhenThisClose = 0.01f; bool willReachTargetSoon = ( - distanceRemaining < switchWhenThisClose || ( + distanceRemaining < switchWhenThisClose + || ( direction * curVelocity > 0f && distanceRemaining / Mathf.Max(curSpeed, 1e-7f) <= slowDownTime ) @@ -189,11 +224,17 @@ public void ControlJointFromAction(float fixedDeltaTime) { drive.targetVelocity = -direction * currentArmMoveParams.speed; } - float curForceApplied = drive.stiffness * (targetPosition - currentPosition) + drive.damping * (drive.targetVelocity - curVelocity); + float curForceApplied = + drive.stiffness * (targetPosition - currentPosition) + + drive.damping * (drive.targetVelocity - curVelocity); - Debug.Log($"position: {currentPosition} ({targetPosition} target) ({willReachTargetSoon} near target)"); + Debug.Log( + $"position: {currentPosition} ({targetPosition} target) ({willReachTargetSoon} near target)" + ); Debug.Log($"drive limits: {drive.lowerLimit}, {drive.upperLimit}"); - Debug.Log($"distance moved: {distanceTransformedSoFar} ({currentArmMoveParams.distance} target)"); + Debug.Log( + $"distance moved: {distanceTransformedSoFar} ({currentArmMoveParams.distance} target)" + ); Debug.Log($"velocity: {myAB.velocity.y} ({drive.targetVelocity} target)"); Debug.Log($"current force applied: {curForceApplied}"); @@ -202,7 +243,6 @@ public void ControlJointFromAction(float fixedDeltaTime) { } } } - //for extending arm joints, assume all extending joints will be in some state of movement based on input distance //the shouldHalt function in ArticulatedAgentController will wait for all individual extending joints to go back to //idle before actionFinished is called @@ -214,22 +254,28 @@ public void ControlJointFromAction(float fixedDeltaTime) { // Begin checks to see if we have stopped moving or if we need to stop moving // Determine (positive) distance covered - distanceTransformedSoFar = Mathf.Abs(currentPosition - currentArmMoveParams.initialJointPosition); - distanceTransformedThisFixedUpdate = Mathf.Abs(currentPosition - prevStepTransformation); + distanceTransformedSoFar = Mathf.Abs( + currentPosition - currentArmMoveParams.initialJointPosition + ); + distanceTransformedThisFixedUpdate = Mathf.Abs( + currentPosition - prevStepTransformation + ); // Store current values for comparing with next FixedUpdate prevStepTransformation = currentPosition; - if (!currentArmMoveParams.useLimits) { - float targetPosition = currentPosition + (float)extendState * fixedDeltaTime * currentArmMoveParams.speed; + float targetPosition = + currentPosition + + (float)extendState * fixedDeltaTime * currentArmMoveParams.speed; drive.target = targetPosition; myAB.zDrive = drive; Debug.Log($"currentPosition: {currentPosition}"); Debug.Log($"targetPosition: {targetPosition}"); } else { - float distanceRemaining = currentArmMoveParams.distance - distanceTransformedSoFar; + float distanceRemaining = + currentArmMoveParams.distance - distanceTransformedSoFar; Debug.Log("DISTANCE REMAINING: " + distanceRemaining); float forceAppliedFromRest = currentArmMoveParams.maxForce; @@ -242,13 +288,22 @@ public void ControlJointFromAction(float fixedDeltaTime) { float offset = 1e-2f; if (extendState == ArmExtendState.MovingForward) { drive.upperLimit = Mathf.Min(upperArmExtendLimit, targetPosition + offset); - drive.lowerLimit = Mathf.Min(Mathf.Max(lowerArmExtendLimit, currentPosition), targetPosition); + drive.lowerLimit = Mathf.Min( + Mathf.Max(lowerArmExtendLimit, currentPosition), + targetPosition + ); } else if (extendState == ArmExtendState.MovingBackward) { drive.lowerLimit = Mathf.Max(lowerArmExtendLimit, targetPosition); - drive.upperLimit = Mathf.Max(Mathf.Min(upperArmExtendLimit, currentPosition + offset), targetPosition + offset); + drive.upperLimit = Mathf.Max( + Mathf.Min(upperArmExtendLimit, currentPosition + offset), + targetPosition + offset + ); } - drive.damping = Mathf.Min(forceAppliedFromRest / currentArmMoveParams.speed, 10000f); + drive.damping = Mathf.Min( + forceAppliedFromRest / currentArmMoveParams.speed, + 10000f + ); float signedDistanceRemaining = direction * distanceRemaining; @@ -260,7 +315,8 @@ public void ControlJointFromAction(float fixedDeltaTime) { float switchWhenThisClose = 0.01f; bool willReachTargetSoon = ( - distanceRemaining < switchWhenThisClose || ( + distanceRemaining < switchWhenThisClose + || ( direction * curVelocity > 0f && distanceRemaining / Mathf.Max(curSpeed, 1e-7f) <= slowDownTime ) @@ -277,11 +333,17 @@ public void ControlJointFromAction(float fixedDeltaTime) { drive.targetVelocity = -direction * currentArmMoveParams.speed; } - float curForceApplied = drive.stiffness * (targetPosition - currentPosition) + drive.damping * (drive.targetVelocity - curVelocity); + float curForceApplied = + drive.stiffness * (targetPosition - currentPosition) + + drive.damping * (drive.targetVelocity - curVelocity); - Debug.Log($"position: {currentPosition} ({targetPosition} target) ({willReachTargetSoon} near target)"); + Debug.Log( + $"position: {currentPosition} ({targetPosition} target) ({willReachTargetSoon} near target)" + ); Debug.Log($"drive limits: {drive.lowerLimit}, {drive.upperLimit}"); - Debug.Log($"distance moved: {distanceTransformedSoFar} ({currentArmMoveParams.distance} target)"); + Debug.Log( + $"distance moved: {distanceTransformedSoFar} ({currentArmMoveParams.distance} target)" + ); Debug.Log($"velocity: {myAB.velocity.y} ({drive.targetVelocity} target)"); Debug.Log($"current force applied: {curForceApplied}"); @@ -293,7 +355,6 @@ public void ControlJointFromAction(float fixedDeltaTime) { currentArmMoveParams.armExtender.Extend(); } } - //if we are a revolute joint else if (jointAxisType == JointAxisType.Rotate) { if (rotateState != ArmRotateState.Idle) { @@ -303,17 +364,25 @@ public void ControlJointFromAction(float fixedDeltaTime) { //somehow this is already in radians, so we are converting to degrees here float currentRotation = Mathf.Rad2Deg * myAB.jointPosition[0]; // i think this speed is in rads per second????? - float targetRotation = currentRotation + (float)rotateState * currentArmMoveParams.speed * fixedDeltaTime; + float targetRotation = + currentRotation + + (float)rotateState * currentArmMoveParams.speed * fixedDeltaTime; drive.target = targetRotation; myAB.xDrive = drive; // Begin checks to see if we have stopped moving or if we need to stop moving - - // Determine (positive) angular distance covered - distanceTransformedSoFar = Mathf.Abs(currentRotation - currentArmMoveParams.initialJointPosition); - distanceTransformedThisFixedUpdate = Mathf.Abs(currentRotation - prevStepTransformation); - distanceTransformedSoFar = Mathf.Abs(currentRotation - Mathf.Rad2Deg * currentArmMoveParams.initialJointPosition); + // Determine (positive) angular distance covered + distanceTransformedSoFar = Mathf.Abs( + currentRotation - currentArmMoveParams.initialJointPosition + ); + distanceTransformedThisFixedUpdate = Mathf.Abs( + currentRotation - prevStepTransformation + ); + + distanceTransformedSoFar = Mathf.Abs( + currentRotation - Mathf.Rad2Deg * currentArmMoveParams.initialJointPosition + ); } } @@ -336,7 +405,6 @@ public bool shouldHalt( double minMovementPerSecond, double haltCheckTimeWindow ) { - //if we are already in an idle, state, immeidately return true if (jointAxisType == JointAxisType.Lift && liftState == ArmLiftState.Idle) { return true; @@ -373,8 +441,6 @@ double haltCheckTimeWindow Debug.Log("halt due to distance reached/exceeded"); return shouldHalt; } - - //hard check for time limit else if (currentArmMoveParams.timePassed >= currentArmMoveParams.maxTimePassed) { shouldHalt = true; @@ -389,14 +455,15 @@ double haltCheckTimeWindow private void IdleAllStates() { if (jointAxisType == JointAxisType.Lift) { liftState = ArmLiftState.Idle; - } if (jointAxisType == JointAxisType.Extend) { + } + if (jointAxisType == JointAxisType.Extend) { extendState = ArmExtendState.Idle; - } if (jointAxisType == JointAxisType.Rotate) { + } + if (jointAxisType == JointAxisType.Rotate) { rotateState = ArmRotateState.Idle; } //reset current movement params this.currentArmMoveParams = null; } - } diff --git a/unity/Assets/Scripts/BaseAgentComponent.cs b/unity/Assets/Scripts/BaseAgentComponent.cs index 2d23a58944..2c86c1bd6f 100644 --- a/unity/Assets/Scripts/BaseAgentComponent.cs +++ b/unity/Assets/Scripts/BaseAgentComponent.cs @@ -1,5 +1,6 @@ -using UnityEngine; using System.Collections.Generic; +using UnityEngine; + namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof(CharacterController))] public class BaseAgentComponent : MonoBehaviour { @@ -14,15 +15,15 @@ public class BaseAgentComponent : MonoBehaviour { public GameObject DebugPointPrefab; public GameObject GridRenderer = null; public GameObject DebugTargetPointPrefab; - public GameObject VisibilityCapsule = null;// used to keep track of currently active VisCap: see different vis caps for modes below - public GameObject TallVisCap;// meshes used for Tall mode - public GameObject DroneVisCap;// meshes used for Drone mode + public GameObject VisibilityCapsule = null; // used to keep track of currently active VisCap: see different vis caps for modes below + public GameObject TallVisCap; // meshes used for Tall mode + public GameObject DroneVisCap; // meshes used for Drone mode public GameObject StretchVisCap; // meshes used for Stretch mode public GameObject IKArm; // reference to the IK_Robot_Arm_Controller arm public GameObject StretchArm; // reference to the Stretch_Arm_Controller arm public GameObject StretchBodyColliders; //reference to the - public GameObject BotVisCap;// meshes used for Bot mode - public GameObject DroneBasket;// reference to the drone's basket object + public GameObject BotVisCap; // meshes used for Bot mode + public GameObject DroneBasket; // reference to the drone's basket object public GameObject CrackedCameraCanvas = null; public GameObject[] ToSetActive = null; public Material[] ScreenFaces; // 0 - neutral, 1 - Happy, 2 - Mad, 3 - Angriest @@ -40,11 +41,10 @@ void LateUpdate() { return; } - #if UNITY_WEBGL - // For object highlight shader to properly work, all visible objects should be populated not conditioned - // on the objectid of a completed action - this.agent.VisibleSimObjPhysics = this.agent.VisibleSimObjs(false); + // For object highlight shader to properly work, all visible objects should be populated not conditioned + // on the objectid of a completed action + this.agent.VisibleSimObjPhysics = this.agent.VisibleSimObjs(false); #endif // editor @@ -53,7 +53,6 @@ void LateUpdate() { // this.agent.VisibleSimObjPhysics = this.agent.VisibleSimObjs(false); // } #endif - } void FixedUpdate() { @@ -61,6 +60,7 @@ void FixedUpdate() { this.agent.FixedUpdate(); } } + // Handle collisions - CharacterControllers don't apply physics innately, see "PushMode" check below // XXX: this will be used for truly continuous movement over time, for now this is unused protected void OnControllerColliderHit(ControllerColliderHit hit) { @@ -69,12 +69,14 @@ protected void OnControllerColliderHit(ControllerColliderHit hit) { } if (hit.gameObject.GetComponent()) { - if (hit.gameObject.GetComponent().WhatIsMyStructureObjectTag == StructureObjectTag.Floor) { + if ( + hit.gameObject.GetComponent().WhatIsMyStructureObjectTag + == StructureObjectTag.Floor + ) { return; } } - if (!this.agent.collisionsInAction.Contains(hit.gameObject.name)) { this.agent.collisionsInAction.Add(hit.gameObject.name); } @@ -100,11 +102,8 @@ protected void OnControllerColliderHit(ControllerColliderHit hit) { // body.AddForceAtPosition (m_CharacterController.velocity * 15f, hit.point, ForceMode.Acceleration);// might have to adjust the force vector scalar later } - #if UNITY_EDITOR - public void OnDrawGizmos() { - - } - #endif - +#if UNITY_EDITOR + public void OnDrawGizmos() { } +#endif } } diff --git a/unity/Assets/Scripts/BaseFPSAgentController.cs b/unity/Assets/Scripts/BaseFPSAgentController.cs index ed39fb979e..e691c093c9 100644 --- a/unity/Assets/Scripts/BaseFPSAgentController.cs +++ b/unity/Assets/Scripts/BaseFPSAgentController.cs @@ -1,34 +1,31 @@ // Copyright Allen Institute for Artificial Intelligence 2017 using System; -using System.IO; using System.Collections; using System.Collections.Generic; -using System.Reflection; -using UnityStandardAssets.CrossPlatformInput; -using UnityStandardAssets.Utility; -using UnityEngine; -using UnityEngine.Rendering.PostProcessing; -using Random = UnityEngine.Random; -using UnityStandardAssets.ImageEffects; +using System.IO; +using System.IO; +using System.IO.Compression; using System.Linq; -using UnityEngine.AI; -using Newtonsoft.Json.Linq; +using System.Linq.Expressions; +using System.Reflection; +using MessagePack; +using MessagePack.Formatters; +using MessagePack.Resolvers; using MIConvexHull; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using Thor.Procedural; using Thor.Procedural.Data; -using Newtonsoft.Json; - -using MessagePack.Resolvers; -using MessagePack.Formatters; -using MessagePack; - -using System.IO; -using System.IO.Compression; -using System.Linq.Expressions; +using UnityEngine; +using UnityEngine.AI; +using UnityEngine.Rendering.PostProcessing; +using UnityStandardAssets.CrossPlatformInput; +using UnityStandardAssets.ImageEffects; +using UnityStandardAssets.Utility; +using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { - - abstract public class BaseFPSAgentController : ActionInvokable { + public abstract class BaseFPSAgentController : ActionInvokable { // debug draw bounds of objects in editor #if UNITY_EDITOR protected List gizmobounds = new List(); @@ -129,7 +126,6 @@ public Material[] ScreenFaces { public MeshRenderer MyFaceMesh { get => this.baseAgentComponent.MyFaceMesh; - } public GameObject[] TargetCircles { get => this.baseAgentComponent.TargetCircles; @@ -139,7 +135,6 @@ public GameObject[] GripperOpennessStates { get => this.baseAgentComponent.GripperOpennessStates; } - protected bool IsHandDefault = true; public GameObject ItemInHand = null; // current object in inventory protected bool inTopLevelView = false; @@ -150,42 +145,46 @@ public GameObject[] GripperOpennessStates { protected float gridVisualizeY = 0.005f; // used to visualize reachable position grid, offset from floor protected HashSet initiallyDisabledRenderers = new HashSet(); + // first person controller parameters protected bool m_IsWalking; protected float m_WalkSpeed; protected float m_RunSpeed; public float m_GravityMultiplier = 2f; protected static float gridSize = 0.25f; + // time the checkIfObjectHasStoppedMoving coroutine waits for objects to stop moving protected float TimeToWaitForObjectsToComeToRest = 0.0f; + // determins default move distance for move actions protected float moveMagnitude; // determines rotation increment of rotate functions protected float rotateStepDegrees = 90.0f; protected bool snapToGrid; - protected bool continuousMode;// deprecated, use snapToGrid instead + protected bool continuousMode; // deprecated, use snapToGrid instead public ImageSynthesis imageSynthesis; public ImageSynthesis ImageSynthesis { get { if (this.imageSynthesis == null) { - imageSynthesis = this.m_Camera.gameObject.GetComponent() ; + imageSynthesis = this.m_Camera.gameObject.GetComponent(); if (imageSynthesis == null) { - throw new NullReferenceException($"ImageSynthesis component is null or disabled in `{this.m_Camera.gameObject.name}` Gameobject."); + throw new NullReferenceException( + $"ImageSynthesis component is null or disabled in `{this.m_Camera.gameObject.name}` Gameobject." + ); } - - imageSynthesis.enabled = true; + + imageSynthesis.enabled = true; return imageSynthesis; - } - else { + } else { return imageSynthesis; } - } } private bool isVisible = true; public bool inHighFrictionArea = false; + // outbound object filter private SimObjPhysics[] simObjFilter = null; protected VisibilityScheme visibilityScheme = VisibilityScheme.Collider; @@ -202,19 +201,25 @@ public ImageSynthesis ImageSynthesis { public bool clearRandomizeMaterialsOnReset = false; private List debugSpheres = new List(); - - // these object types can have a placeable surface mesh associated ith it // this is to be used with screenToWorldTarget to filter out raycasts correctly - protected List hasPlaceableSurface = new List() { - SimObjType.Bathtub, SimObjType.Sink, SimObjType.Drawer, SimObjType.Cabinet, - SimObjType.CounterTop, SimObjType.Shelf + protected List hasPlaceableSurface = new List() + { + SimObjType.Bathtub, + SimObjType.Sink, + SimObjType.Drawer, + SimObjType.Cabinet, + SimObjType.CounterTop, + SimObjType.Shelf }; public const float DefaultAllowedErrorInShortestPath = 0.0001f; - public BaseFPSAgentController(BaseAgentComponent baseAgentComponent, AgentManager agentManager) { + public BaseFPSAgentController( + BaseAgentComponent baseAgentComponent, + AgentManager agentManager + ) { this.baseAgentComponent = baseAgentComponent; this.baseAgentComponent.agent = this; this.agentManager = agentManager; @@ -227,7 +232,7 @@ public BaseFPSAgentController(BaseAgentComponent baseAgentComponent, AgentManage this.m_CharacterController = GetComponent(); collidedObjects = new string[0]; collisionsInAction = new List(); - + // set agent initial states targetRotation = transform.rotation; @@ -236,8 +241,9 @@ public BaseFPSAgentController(BaseAgentComponent baseAgentComponent, AgentManage // culling in FirstPersonCharacterCull.cs to ignore tall mode renderers HideAllAgentRenderers(); // default nav mesh agent to false cause WHY DOES THIS BREAK THINGS I GUESS IT DOESN TLIKE TELEPORTING - if(this.GetComponentInChildren()) - this.GetComponentInChildren().enabled = false; + if (this.GetComponentInChildren()) { + this.GetComponentInChildren().enabled = false; + } // Recording initially disabled renderers and scene bounds // then setting up sceneBounds based on encapsulating all renderers @@ -264,7 +270,6 @@ public BaseFPSAgentController(BaseAgentComponent baseAgentComponent, AgentManage void Start() { Debug.Log("------------- BASE FPS Start"); - } // callback triggered by BaseAgentComponent @@ -272,7 +277,6 @@ public virtual void FixedUpdate() { } public bool IsVisible { get { return isVisible; } - set { // first default all Vis capsules of all modes to not enabled HideAllAgentRenderers(); @@ -287,9 +291,7 @@ public bool IsVisible { } public bool IsProcessing { - get { - return this.agentState == AgentState.Processing; - } + get { return this.agentState == AgentState.Processing; } } // convenciance function that can be called @@ -303,13 +305,14 @@ public void autoSyncTransforms() { public bool ReadyForCommand { get { - return this.agentState == AgentState.Emit || this.agentState == AgentState.ActionComplete; + return this.agentState == AgentState.Emit + || this.agentState == AgentState.ActionComplete; } - } protected float maxDownwardLookAngle = 60f; protected float maxUpwardLookAngle = 30f; + // allow agent to push sim objects that can move, for physics public bool PushMode = false; protected int actionCounter; @@ -327,14 +330,10 @@ public bool ReadyForCommand { protected Vector3 lastPosition; public string lastAction; - public bool lastActionSuccess { - get; - protected set; - } + public bool lastActionSuccess { get; protected set; } public string errorMessage; protected ServerActionErrorCode errorCode; - public System.Object actionReturn; protected Vector3 standingLocalCameraPosition; protected Vector3 crouchingLocalCameraPosition; @@ -352,13 +351,14 @@ public bool lastActionSuccess { protected Vector3[] actionVector3sReturn; protected string[] actionStringsReturn; public bool alwaysReturnVisibleRange = false; + // initial states public int actionDuration = 3; // internal state variables private float lastEmitTime; - public List collisionsInAction;// tracking collided objects - protected string[] collidedObjects;// container for collided objects + public List collisionsInAction; // tracking collided objects + protected string[] collidedObjects; // container for collided objects protected HashSet collidersToIgnoreDuringMovement = new HashSet(); protected Quaternion targetRotation; @@ -367,9 +367,10 @@ public bool lastActionSuccess { #if UNITY_WEBGL // Javascript communication private JavaScriptInterface jsInterface = null; - public Quaternion TargetRotation { - get { return targetRotation; } - } + public Quaternion TargetRotation + { + get { return targetRotation; } + } #endif // Arms @@ -378,11 +379,14 @@ public Quaternion TargetRotation { protected ArticulatedArmController AArm; private PhysicsSceneManager _physicsSceneManager = null; + // use as reference to the PhysicsSceneManager object protected PhysicsSceneManager physicsSceneManager { get { if (_physicsSceneManager == null) { - _physicsSceneManager = GameObject.Find("PhysicsSceneManager").GetComponent(); + _physicsSceneManager = GameObject + .Find("PhysicsSceneManager") + .GetComponent(); } return _physicsSceneManager; } @@ -394,7 +398,12 @@ public void DeleteMe() { // defaults all agent renderers, from all modes (tall, bot, drone), to hidden for initialization default protected void HideAllAgentRenderers() { - if (TallVisCap != null && BotVisCap != null && DroneVisCap != null && StretchVisCap != null) { + if ( + TallVisCap != null + && BotVisCap != null + && DroneVisCap != null + && StretchVisCap != null + ) { foreach (Renderer r in TallVisCap.GetComponentsInChildren()) { if (r.enabled) { r.enabled = false; @@ -421,21 +430,30 @@ protected void HideAllAgentRenderers() { } } - public void actionFinishedEmit(bool success, object actionReturn = null, string errorMessage = null) { + public void actionFinishedEmit( + bool success, + object actionReturn = null, + string errorMessage = null + ) { if (errorMessage != null) { this.errorMessage = errorMessage; } actionFinished(success: success, newState: AgentState.Emit, actionReturn: actionReturn); } - protected virtual void actionFinished(bool success, AgentState newState, object actionReturn = null) { + protected virtual void actionFinished( + bool success, + AgentState newState, + object actionReturn = null + ) { if (!this.IsProcessing) { Debug.LogError("ActionFinished called with agentState not in processing "); } if ( (!Physics.autoSyncTransforms) - && lastActionInitialPhysicsSimulateCount == PhysicsSceneManager.PhysicsSimulateCallCount + && lastActionInitialPhysicsSimulateCount + == PhysicsSceneManager.PhysicsSimulateCallCount ) { Physics.SyncTransforms(); } @@ -455,28 +473,40 @@ protected virtual void actionFinished(bool success, AgentState newState, object } else if (actionReturn != null) { Debug.Log($"actionReturn: '{actionReturn}'"); } - + #endif } - + public virtual void Complete(ActionFinished result) { // Check to not call `actionFinished` twice and overwriting values when running in new mode - // TODO: remove check once legacy actions are gone. + // TODO: remove check once legacy actions are gone. if (!result.isDummy) { if (result.errorMessage != null) { this.errorMessage = result.errorMessage; } this.errorCode = result.errorCode; - actionFinished(success: result.success, newState: !result.toEmitState ? AgentState.ActionComplete : AgentState.Emit, actionReturn: result.actionReturn); + actionFinished( + success: result.success, + newState: !result.toEmitState ? AgentState.ActionComplete : AgentState.Emit, + actionReturn: result.actionReturn + ); } } // Delete and use yield return ActionFinished - public virtual void actionFinished(bool success, object actionReturn = null, string errorMessage = null) { + public virtual void actionFinished( + bool success, + object actionReturn = null, + string errorMessage = null + ) { if (errorMessage != null) { this.errorMessage = errorMessage; } - actionFinished(success: success, newState: AgentState.ActionComplete, actionReturn: actionReturn); + actionFinished( + success: success, + newState: AgentState.ActionComplete, + actionReturn: actionReturn + ); this.resumePhysics(); } @@ -506,7 +536,9 @@ public Vector3[] getReachablePositions( // Debug.Log($"Capsule collider: {cc.radius}, height {cc.height}, innerheight: {cc.height / 2.0f - cc.radius;} startpos: {transform.position + cc.transform.TransformDirection(cc.center)}"); // Debug.Log($"Capsule collider: {cc.radius}, height {cc.height}, innerheight: {cc.height / 2.0f - cc.radius;} startpos: "); - Debug.Log($"Capsule collider: {capsule.radius} height {capsule.height}, innerheight: {capsule.height / 2.0f - capsule.radius} startpos: {transform.position + capsule.transform.TransformDirection(capsule.center)}"); + Debug.Log( + $"Capsule collider: {capsule.radius} height {capsule.height}, innerheight: {capsule.height / 2.0f - capsule.radius} startpos: {transform.position + capsule.transform.TransformDirection(capsule.center)}" + ); if (!gridSize.HasValue) { gridSize = BaseFPSAgentController.gridSize; @@ -531,7 +563,13 @@ public Vector3[] getReachablePositions( HashSet goodPoints = new HashSet(); HashSet<(int, int)> seenRightForwards = new HashSet<(int, int)>(); - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); int stepsTaken = 0; while (rightForwardQueue.Count != 0) { stepsTaken += 1; @@ -540,22 +578,27 @@ public Vector3[] getReachablePositions( // guarantees that floating point errors won't result in slight differences // between the same points. (int, int) rightForward = rightForwardQueue.Dequeue(); - Vector3 p = startPosition + gridSize.Value * gridMultiplier * ( - right * rightForward.Item1 + forward * rightForward.Item2 - ); + Vector3 p = + startPosition + + gridSize.Value + * gridMultiplier + * (right * rightForward.Item1 + forward * rightForward.Item2); if (!goodPoints.Contains(p)) { goodPoints.Add(p); - HashSet objectsAlreadyColliding = new HashSet(objectsCollidingWithAgent()); + HashSet objectsAlreadyColliding = new HashSet( + objectsCollidingWithAgent() + ); foreach ((int, int) rightForwardOffset in rightForwardOffsets) { (int, int) newRightForward = ( rightForward.Item1 + rightForwardOffset.Item1, rightForward.Item2 + rightForwardOffset.Item2 ); - Vector3 newPosition = startPosition + gridSize.Value * gridMultiplier * ( - right * newRightForward.Item1 + - forward * newRightForward.Item2 - ); + Vector3 newPosition = + startPosition + + gridSize.Value + * gridMultiplier + * (right * newRightForward.Item1 + forward * newRightForward.Item2); if (seenRightForwards.Contains(newRightForward)) { continue; } @@ -565,16 +608,18 @@ public Vector3[] getReachablePositions( cachedCapsule: capsule, skinWidth: sw, startPosition: p, - direction: right * rightForwardOffset.Item1 + forward * rightForwardOffset.Item2, + direction: right * rightForwardOffset.Item1 + + forward * rightForwardOffset.Item2, moveMagnitude: gridSize.Value * gridMultiplier, layerMask: layerMask ); bool shouldEnqueue = true; foreach (RaycastHit hit in hits) { - if (!ancestorHasName(hit.transform.gameObject, "Floor") && - !ancestorHasName(hit.transform.gameObject, "FPSController") && - !objectsAlreadyColliding.Contains(hit.collider) + if ( + !ancestorHasName(hit.transform.gameObject, "Floor") + && !ancestorHasName(hit.transform.gameObject, "FPSController") + && !objectsAlreadyColliding.Contains(hit.collider) ) { shouldEnqueue = false; break; @@ -588,24 +633,32 @@ public Vector3[] getReachablePositions( bool inBounds = agentManager.SceneBounds.Contains(newPosition); if (shouldEnqueue && !inBounds) { throw new InvalidOperationException( - "In " + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + - ", position " + newPosition.ToString() + - " can be reached via capsule cast but is beyond the scene bounds." + "In " + + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + + ", position " + + newPosition.ToString() + + " can be reached via capsule cast but is beyond the scene bounds." ); } - shouldEnqueue = shouldEnqueue && inBounds && ( - handObjectCanFitInPosition(newPosition, 0.0f) || - handObjectCanFitInPosition(newPosition, 90.0f) || - handObjectCanFitInPosition(newPosition, 180.0f) || - handObjectCanFitInPosition(newPosition, 270.0f) - ); + shouldEnqueue = + shouldEnqueue + && inBounds + && ( + handObjectCanFitInPosition(newPosition, 0.0f) + || handObjectCanFitInPosition(newPosition, 90.0f) + || handObjectCanFitInPosition(newPosition, 180.0f) + || handObjectCanFitInPosition(newPosition, 270.0f) + ); if (shouldEnqueue) { rightForwardQueue.Enqueue(newRightForward); if (visualize) { - var gridRenderer = Instantiate(GridRenderer, Vector3.zero, Quaternion.identity) as GameObject; - var gridLineRenderer = gridRenderer.GetComponentInChildren(); + var gridRenderer = + Instantiate(GridRenderer, Vector3.zero, Quaternion.identity) + as GameObject; + var gridLineRenderer = + gridRenderer.GetComponentInChildren(); if (gridColor.HasValue) { gridLineRenderer.startColor = gridColor.Value; gridLineRenderer.endColor = gridColor.Value; @@ -616,10 +669,13 @@ public Vector3[] getReachablePositions( gridLineRenderer.positionCount = 2; // gridLineRenderer.startWidth = 0.01f; // gridLineRenderer.endWidth = 0.01f; - gridLineRenderer.SetPositions(new Vector3[] { - new Vector3(p.x, gridVisualizeY, p.z), - new Vector3(newPosition.x, gridVisualizeY, newPosition.z) - }); + gridLineRenderer.SetPositions( + new Vector3[] + { + new Vector3(p.x, gridVisualizeY, p.z), + new Vector3(newPosition.x, gridVisualizeY, newPosition.z) + } + ); } #if UNITY_EDITOR Debug.DrawLine(p, newPosition, Color.cyan, 100000f); @@ -629,7 +685,9 @@ public Vector3[] getReachablePositions( } // default maxStepCount to scale based on gridSize if (stepsTaken > Math.Floor(maxStepCount / (gridSize.Value * gridSize.Value))) { - throw new InvalidOperationException("Too many steps taken in GetReachablePositions."); + throw new InvalidOperationException( + "Too many steps taken in GetReachablePositions." + ); } } @@ -670,21 +728,20 @@ public void GetReachablePositions( ); } - actionFinishedEmit( - success: true, - actionReturn: reachablePositions - ); + actionFinishedEmit(success: true, actionReturn: reachablePositions); } public abstract ActionFinished InitializeBody(ServerAction initializeAction); - protected bool ValidRotateStepDegreesWithSnapToGrid(float rotateDegrees) { + protected bool ValidRotateStepDegreesWithSnapToGrid(float rotateDegrees) { // float eps = 0.00001f; - return rotateDegrees == 90.0f || rotateDegrees == 180.0f || rotateDegrees == 270.0f || (rotateDegrees % 360.0f) == 0.0f; + return rotateDegrees == 90.0f + || rotateDegrees == 180.0f + || rotateDegrees == 270.0f + || (rotateDegrees % 360.0f) == 0.0f; } public void Initialize(ServerAction action) { - // Debug.Log("RUNNING B"); // limit camera from looking too far down/up //default max are 30 up and 60 down, different agent types may overwrite this @@ -710,7 +767,9 @@ public void Initialize(ServerAction action) { antiAliasing: action.antiAliasing ); } - m_Camera.GetComponent().SwitchRenderersToHide(this.VisibilityCapsule); + m_Camera + .GetComponent() + .SwitchRenderersToHide(this.VisibilityCapsule); if (action.gridSize == 0) { action.gridSize = 0.25f; @@ -757,31 +816,38 @@ public void Initialize(ServerAction action) { this.rotateStepDegrees = action.rotateStepDegrees; } - if (action.snapToGrid && !ValidRotateStepDegreesWithSnapToGrid(action.rotateStepDegrees)) { - errorMessage = $"Invalid values 'rotateStepDegrees': ${action.rotateStepDegrees} and 'snapToGrid':${action.snapToGrid}. 'snapToGrid': 'True' is not supported when 'rotateStepDegrees' is different from grid rotation steps of 0, 90, 180, 270 or 360."; + if ( + action.snapToGrid && !ValidRotateStepDegreesWithSnapToGrid(action.rotateStepDegrees) + ) { + errorMessage = + $"Invalid values 'rotateStepDegrees': ${action.rotateStepDegrees} and 'snapToGrid':${action.snapToGrid}. 'snapToGrid': 'True' is not supported when 'rotateStepDegrees' is different from grid rotation steps of 0, 90, 180, 270 or 360."; Debug.Log(errorMessage); actionFinished(false); return; } - if(action.maxDownwardLookAngle < 0) { + if (action.maxDownwardLookAngle < 0) { errorMessage = "maxDownwardLookAngle must be a non-negative float"; Debug.Log(errorMessage); actionFinished(false); return; } - if(action.maxUpwardLookAngle < 0) { + if (action.maxUpwardLookAngle < 0) { errorMessage = "maxUpwardLookAngle must be a non-negative float"; Debug.Log(errorMessage); actionFinished(false); return; } - this.snapToGrid = action.snapToGrid; - if (action.renderDepthImage || action.renderSemanticSegmentation || action.renderInstanceSegmentation || action.renderNormalsImage) { + if ( + action.renderDepthImage + || action.renderSemanticSegmentation + || action.renderInstanceSegmentation + || action.renderNormalsImage + ) { this.updateImageSynthesis(true); } @@ -795,7 +861,11 @@ public void Initialize(ServerAction action) { if (collider != null && navmeshAgent != null) { navmeshAgent.radius = collider.radius; navmeshAgent.height = collider.height; - navmeshAgent.transform.localPosition = new Vector3(navmeshAgent.transform.localPosition.x, navmeshAgent.transform.localPosition.y, collider.center.z); + navmeshAgent.transform.localPosition = new Vector3( + navmeshAgent.transform.localPosition.x, + navmeshAgent.transform.localPosition.y, + collider.center.z + ); } // navmeshAgent.radius = @@ -815,14 +885,23 @@ public void Initialize(ServerAction action) { // Debug.Log("Object " + action.controllerInitialization.ToString() + " dict " + (action.controllerInitialization.variableInitializations == null));//+ string.Join(";", action.controllerInitialization.variableInitializations.Select(x => x.Key + "=" + x.Value).ToArray())); - if (action.controllerInitialization != null && action.controllerInitialization.variableInitializations != null) { - foreach (KeyValuePair entry in action.controllerInitialization.variableInitializations) { + if ( + action.controllerInitialization != null + && action.controllerInitialization.variableInitializations != null + ) { + foreach ( + KeyValuePair entry in action + .controllerInitialization + .variableInitializations + ) { Debug.Log(" Key " + entry.Value.type + " field " + entry.Key); Type t = Type.GetType(entry.Value.type); - FieldInfo field = t.GetField(entry.Key, BindingFlags.Public | BindingFlags.Instance); + FieldInfo field = t.GetField( + entry.Key, + BindingFlags.Public | BindingFlags.Instance + ); field.SetValue(this, entry.Value); } - } this.visibilityScheme = action.GetVisibilityScheme(); @@ -833,15 +912,19 @@ public void Initialize(ServerAction action) { public IEnumerator checkInitializeAgentLocationAction() { yield return null; - + if (agentManager.agentMode != "stretchab") { Vector3 startingPosition = this.transform.position; // move ahead // move back float mult = 1 / gridSize; - float grid_x1 = Convert.ToSingle(Math.Floor(this.transform.position.x * mult) / mult); - float grid_z1 = Convert.ToSingle(Math.Floor(this.transform.position.z * mult) / mult); + float grid_x1 = Convert.ToSingle( + Math.Floor(this.transform.position.x * mult) / mult + ); + float grid_z1 = Convert.ToSingle( + Math.Floor(this.transform.position.z * mult) / mult + ); float[] xs = new float[] { grid_x1, grid_x1 + gridSize }; float[] zs = new float[] { grid_z1, grid_z1 + gridSize }; @@ -854,7 +937,7 @@ public IEnumerator checkInitializeAgentLocationAction() { yield return null; Vector3 target = new Vector3(x, this.transform.position.y, z); - + Vector3 dir = target - this.transform.position; Vector3 movement = dir.normalized * 100.0f; // Debug.Log("Target is at " + target + ", dir is at " + dir.y + ", and movement is " + movement); @@ -864,15 +947,14 @@ public IEnumerator checkInitializeAgentLocationAction() { // Debug.Log("PRE: movement-y is " + movement.y); movement.y = Physics.gravity.y * this.m_GravityMultiplier; // Debug.Log("POST: movement-y is " + movement.y); - if (agentManager.agentMode != "stretchab") { - m_CharacterController.Move(movement); - // Debug.Log("THIS SHOULDN'T BE SHOWING, but somehow agentMode is " + agentManager.agentMode); - } + if (agentManager.agentMode != "stretchab") { + m_CharacterController.Move(movement); + // Debug.Log("THIS SHOULDN'T BE SHOWING, but somehow agentMode is " + agentManager.agentMode); + } for (int i = 0; i < actionDuration; i++) { yield return null; Vector3 diff = this.transform.position - target; - if ((Math.Abs(diff.x) < 0.005) && (Math.Abs(diff.z) < 0.005)) { validMovements.Add(movement); break; @@ -884,37 +966,46 @@ public IEnumerator checkInitializeAgentLocationAction() { this.transform.position = startingPosition; autoSyncTransforms(); yield return null; - + if (validMovements.Count > 0) { //Debug.Log("Initialize: got total valid initial targets: " + validMovements.Count); Vector3 firstMove = validMovements[0]; // Debug.Log("First move is this: " + firstMove); // Debug.Log("STAGE 3. Starting position is (" + this.transform.position.x + ", " + this.transform.position.y + ", " + this.transform.position.z + ")"); - + firstMove.y = Physics.gravity.y * this.m_GravityMultiplier; m_CharacterController.Move(firstMove); // Debug.Log("STAGE 4. Starting position is (" + this.transform.position.x + ", " + this.transform.position.y + ", " + this.transform.position.z + ")"); snapAgentToGrid(); - - actionFinished(true, new InitializeReturn { - cameraNearPlane = m_Camera.nearClipPlane, - cameraFarPlane = m_Camera.farClipPlane - }); + + actionFinished( + true, + new InitializeReturn { + cameraNearPlane = m_Camera.nearClipPlane, + cameraFarPlane = m_Camera.farClipPlane + } + ); } else { // Debug.Log("Initialize: no valid starting positions found"); actionFinished(false); } } else { yield return null; - actionFinished(true, new InitializeReturn { - cameraNearPlane = m_Camera.nearClipPlane, - cameraFarPlane = m_Camera.farClipPlane - }); + actionFinished( + true, + new InitializeReturn { + cameraNearPlane = m_Camera.nearClipPlane, + cameraFarPlane = m_Camera.farClipPlane + } + ); } } - [ObsoleteAttribute(message: "This action is deprecated. Call RandomizeColors instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call RandomizeColors instead.", + error: false + )] public void ChangeColorOfMaterials() { RandomizeColors(); } @@ -947,8 +1038,13 @@ public void RandomizeMaterials( List excludedObjectIds = null ) { string scene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; - HashSet validRoomTypes = new HashSet() { - "bedroom", "bathroom", "kitchen", "livingroom", "robothor" + HashSet validRoomTypes = new HashSet() + { + "bedroom", + "bathroom", + "kitchen", + "livingroom", + "robothor" }; HashSet chosenRoomTypes = new HashSet(); @@ -960,10 +1056,11 @@ public void RandomizeMaterials( foreach (string roomType in inRoomTypes) { if (!validRoomTypes.Contains(roomType.ToLower())) { throw new ArgumentException( - $"inRoomTypes contains unknown room type: {roomType}.\n" + - "Valid room types include {\"Bedroom\", \"Bathroom\", \"LivingRoom\", \"Kitchen\", \"RoboTHOR\"}" + $"inRoomTypes contains unknown room type: {roomType}.\n" + + "Valid room types include {\"Bedroom\", \"Bathroom\", \"LivingRoom\", \"Kitchen\", \"RoboTHOR\"}" ); - }; + } + ; chosenRoomTypes.Add(roomType.ToLower()); } } @@ -986,9 +1083,12 @@ public void RandomizeMaterials( HashSet excludedMaterialNames = new HashSet(); foreach (string objectId in excludedObjectIds) { Debug.Log($"Exclude materials from {objectId}"); - SimObjPhysics objectWhoseMaterialsToExclude = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; + SimObjPhysics objectWhoseMaterialsToExclude = + physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; - foreach (var renderer in objectWhoseMaterialsToExclude.GetComponentsInChildren()) { + foreach ( + var renderer in objectWhoseMaterialsToExclude.GetComponentsInChildren() + ) { foreach (var mat in renderer.sharedMaterials) { if (mat != null && mat.name != null) { Debug.Log($"excluding {mat.name}"); @@ -1005,7 +1105,9 @@ public void RandomizeMaterials( useTrainMaterials: useTrainMaterials.HasValue ? useTrainMaterials.Value : true, useValMaterials: useValMaterials.HasValue ? useValMaterials.Value : true, useTestMaterials: useTestMaterials.HasValue ? useTestMaterials.Value : true, - useExternalMaterials: useExternalMaterials.HasValue ? useExternalMaterials.Value : true, + useExternalMaterials: useExternalMaterials.HasValue + ? useExternalMaterials.Value + : true, inRoomTypes: inRoomTypes != null ? chosenRoomTypes : validRoomTypes, excludedMaterialNames: excludedMaterialNames ); @@ -1020,16 +1122,30 @@ public void RandomizeMaterials( string sceneType; if (scene.EndsWith("_physics")) { // iTHOR scene - int sceneNumber = Int32.Parse( - scene.Substring(startIndex: "FloorPlan".Length, length: scene.Length - "FloorPlan_physics".Length) - ) % 100; - - int sceneGroup = Int32.Parse( - scene.Substring(startIndex: "FloorPlan".Length, length: scene.Length - "FloorPlan_physics".Length) - ) / 100; + int sceneNumber = + Int32.Parse( + scene.Substring( + startIndex: "FloorPlan".Length, + length: scene.Length - "FloorPlan_physics".Length + ) + ) % 100; + + int sceneGroup = + Int32.Parse( + scene.Substring( + startIndex: "FloorPlan".Length, + length: scene.Length - "FloorPlan_physics".Length + ) + ) / 100; if (inRoomTypes != null) { - string sceneGroupName = new string[] { "kitchen", "livingroom", "bedroom", "bathroom" }[Math.Max(sceneGroup - 1, 0)]; + string sceneGroupName = new string[] + { + "kitchen", + "livingroom", + "bedroom", + "bathroom" + }[Math.Max(sceneGroup - 1, 0)]; if (!chosenRoomTypes.Contains(sceneGroupName)) { throw new ArgumentException( $"inRoomTypes must include \"{sceneGroupName}\" inside of a {sceneGroupName} scene: {scene}." @@ -1058,7 +1174,9 @@ public void RandomizeMaterials( sceneType = "test"; break; default: - throw new Exception($"Unknown scene name: {scene}. Please open an issue on allenai/ai2thor."); + throw new Exception( + $"Unknown scene name: {scene}. Please open an issue on allenai/ai2thor." + ); } if (inRoomTypes != null) { if (!chosenRoomTypes.Contains("robothor")) { @@ -1072,7 +1190,9 @@ public void RandomizeMaterials( switch (sceneType) { case "train": if (useTrainMaterials.GetValueOrDefault(true) == false) { - throw new ArgumentException("Inside of RandomizeMaterials, cannot set useTrainMaterials=false inside of a train scene."); + throw new ArgumentException( + "Inside of RandomizeMaterials, cannot set useTrainMaterials=false inside of a train scene." + ); } useTrainMaterials = useTrainMaterials.GetValueOrDefault(true); useValMaterials = useValMaterials.GetValueOrDefault(false); @@ -1081,7 +1201,9 @@ public void RandomizeMaterials( break; case "val": if (useValMaterials.GetValueOrDefault(true) == false) { - throw new ArgumentException("Inside of RandomizeMaterials, cannot set useValMaterials=false inside of a val scene."); + throw new ArgumentException( + "Inside of RandomizeMaterials, cannot set useValMaterials=false inside of a val scene." + ); } useTrainMaterials = useTrainMaterials.GetValueOrDefault(false); useValMaterials = useValMaterials.GetValueOrDefault(true); @@ -1090,7 +1212,9 @@ public void RandomizeMaterials( break; case "test": if (useTestMaterials.GetValueOrDefault(true) == false) { - throw new ArgumentException("Inside of RandomizeMaterials, cannot set useTestMaterials=false inside of a test scene."); + throw new ArgumentException( + "Inside of RandomizeMaterials, cannot set useTestMaterials=false inside of a test scene." + ); } useTrainMaterials = useTrainMaterials.GetValueOrDefault(false); useValMaterials = useValMaterials.GetValueOrDefault(false); @@ -1119,7 +1243,8 @@ public void RandomizeMaterials( actionFinished( success: true, actionReturn: new Dictionary() { - ["chosenRoomTypes"] = chosenRoomTypes.Count == 0 ? validRoomTypes : chosenRoomTypes, + ["chosenRoomTypes"] = + chosenRoomTypes.Count == 0 ? validRoomTypes : chosenRoomTypes, ["useTrainMaterials"] = useTrainMaterials.Value, ["useValMaterials"] = useValMaterials.Value, ["useTestMaterials"] = useTestMaterials.Value, @@ -1203,8 +1328,8 @@ public void RandomizeLighting( if (saturation.Length != 2 || hue.Length != 2 || brightness.Length != 2) { throw new ArgumentException( - "Ranges for hue, saturation, and brightness must each have 2 values. You gave " + - $"saturation={saturation}, hue={hue}, brightness={brightness}." + "Ranges for hue, saturation, and brightness must each have 2 values. You gave " + + $"saturation={saturation}, hue={hue}, brightness={brightness}." ); } @@ -1212,7 +1337,9 @@ public void RandomizeLighting( throw new ArgumentOutOfRangeException($"hue range must be in [0:1], not {hue}"); } if (saturation[0] < 0 || saturation[0] > 1 || saturation[1] < 0 || saturation[1] > 1) { - throw new ArgumentOutOfRangeException($"saturation range must be in [0:1], not {saturation}"); + throw new ArgumentOutOfRangeException( + $"saturation range must be in [0:1], not {saturation}" + ); } float newRandomFloat() { @@ -1258,7 +1385,8 @@ Color newRandomColor() { ["color"] = light.color }; } - light.intensity = (float)originalLightingValues[id]["intensity"] * intensityMultiplier; + light.intensity = + (float)originalLightingValues[id]["intensity"] * intensityMultiplier; light.range = (float)originalLightingValues[id]["range"] * intensityMultiplier; if (randomizeColor) { light.color = randomColor; @@ -1329,10 +1457,12 @@ protected bool moveInDirection( HashSet ignoreColliders = null ) { Vector3 targetPosition = transform.position + direction; - if (checkIfSceneBoundsContainTargetPosition(targetPosition) && - CheckIfItemBlocksAgentMovement(direction, forceAction) && // forceAction = true allows ignoring movement restrictions caused by held objects - CheckIfAgentCanMove(direction, ignoreColliders)) { - + if ( + checkIfSceneBoundsContainTargetPosition(targetPosition) + && CheckIfItemBlocksAgentMovement(direction, forceAction) + && // forceAction = true allows ignoring movement restrictions caused by held objects + CheckIfAgentCanMove(direction, ignoreColliders) + ) { // only default hand if not manually interacting with things if (!manualInteract) { DefaultAgentHand(); @@ -1350,7 +1480,8 @@ protected bool moveInDirection( } SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; if (distanceToObject(sop) > maxDistanceToObject) { - errorMessage = "Agent movement would bring it beyond the max distance of " + objectId; + errorMessage = + "Agent movement would bring it beyond the max distance of " + objectId; transform.position = oldPosition; return false; } @@ -1389,14 +1520,20 @@ public bool CheckIfAgentCanMove( HashSet ignoreColliders = null, bool ignoreAgentColliders = true ) { - RaycastHit[] sweepResults = capsuleCastAllForAgent( GetAgentCapsule(), m_CharacterController.skinWidth, transform.position, offset.normalized, offset.magnitude, - LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent") + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent" + ) ); if (ignoreColliders == null) { @@ -1422,23 +1559,31 @@ public bool CheckIfAgentCanMove( continue; } - if (res.transform.gameObject != this.gameObject && res.transform.GetComponent()) { - - BaseAgentComponent maybeOtherAgent = res.transform.GetComponent(); + if ( + res.transform.gameObject != this.gameObject + && res.transform.GetComponent() + ) { + BaseAgentComponent maybeOtherAgent = + res.transform.GetComponent(); int thisAgentNum = agentManager.agents.IndexOf(this); int otherAgentNum = agentManager.agents.IndexOf(maybeOtherAgent.agent); - errorMessage = $"Agent {otherAgentNum} is blocking Agent {thisAgentNum} from moving by {offset.ToString("F4")}."; + errorMessage = + $"Agent {otherAgentNum} is blocking Agent {thisAgentNum} from moving by {offset.ToString("F4")}."; return false; } // including "Untagged" tag here so that the agent can't move through objects that are transparent - if ((!collidersToIgnoreDuringMovement.Contains(res.collider)) && ( - res.transform.GetComponent() || - res.transform.tag == "Structure" || - res.transform.tag == "Untagged" - )) { + if ( + (!collidersToIgnoreDuringMovement.Contains(res.collider)) + && ( + res.transform.GetComponent() + || res.transform.tag == "Structure" + || res.transform.tag == "Untagged" + ) + ) { int thisAgentNum = agentManager.agents.IndexOf(this); - errorMessage = $"{res.transform.name} is blocking Agent {thisAgentNum} from moving by {offset.ToString("F4")}."; + errorMessage = + $"{res.transform.name} is blocking Agent {thisAgentNum} from moving by {offset.ToString("F4")}."; // the moment we find a result that is blocking, return false here return false; } @@ -1493,7 +1638,10 @@ public void RemoveFromScene(string objectId) { actionFinished(success: true); } - [ObsoleteAttribute(message: "This action is deprecated. Call RemoveFromScene instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call RemoveFromScene instead.", + error: false + )] public void RemoveObjsFromScene(string[] objectIds) { RemoveFromScene(objectIds: objectIds); } @@ -1501,10 +1649,7 @@ public void RemoveObjsFromScene(string[] objectIds) { // remove a list of given sim object from the scene. public void RemoveFromScene(string[] objectIds) { if (objectIds == null || objectIds.Length == 0) { - actionFinished( - success: false, - errorMessage: "objectIds must not be empty!" - ); + actionFinished(success: false, errorMessage: "objectIds must not be empty!"); } // make sure all objectIds are valid before destorying any @@ -1549,14 +1694,13 @@ public bool CheckIfItemBlocksAgentMovement(Vector3 offset, bool forceAction = fa result = true; break; } else { - errorMessage = $"{res.transform.name} is blocking the Agent from moving by {offset.ToString("F4")} with {ItemInHand.name}"; + errorMessage = + $"{res.transform.name} is blocking the Agent from moving by {offset.ToString("F4")} with {ItemInHand.name}"; result = false; return result; } - } } - // if the array is empty, nothing was hit by the sweeptest so we are clear to move else { // Debug.Log("Agent Body can move " + orientation); @@ -1576,7 +1720,6 @@ protected bool checkIfSceneBoundsContainTargetPosition(Vector3 position) { } } - // This effectively freezes objects that exceed the MassThreshold configured // during initialization and reduces the chance of an object held by the // arm from moving a large mass object. This also eliminates the chance @@ -1584,14 +1727,21 @@ protected bool checkIfSceneBoundsContainTargetPosition(Vector3 position) { public void MakeObjectsStaticKinematicMassThreshold() { foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) { // check if the sopType is something that can be hung - if (sop.Type == SimObjType.Towel || sop.Type == SimObjType.HandTowel || sop.Type == SimObjType.ToiletPaper) { + if ( + sop.Type == SimObjType.Towel + || sop.Type == SimObjType.HandTowel + || sop.Type == SimObjType.ToiletPaper + ) { // if this object is actively hung on its corresponding object specific receptacle... skip it so it doesn't fall on the floor if (sop.GetComponentInParent()) { continue; } } - if (CollisionListener.useMassThreshold && sop.Mass > CollisionListener.massThreshold) { + if ( + CollisionListener.useMassThreshold + && sop.Mass > CollisionListener.massThreshold + ) { Rigidbody rb = sop.GetComponent(); rb.isKinematic = true; sop.PrimaryProperty = SimObjPrimaryProperty.Static; @@ -1631,7 +1781,6 @@ public void RotateLook(ServerAction response) { transform.rotation = Quaternion.Euler(new Vector3(0.0f, response.rotation.y, 0.0f)); m_Camera.transform.localEulerAngles = new Vector3(response.horizon, 0.0f, 0.0f); actionFinished(true); - } // rotate view with respect to mouse or server controls - I'm not sure when this is actually used @@ -1699,13 +1848,15 @@ private protected IEnumerator openAnimation( objectIdToOldParent = new Dictionary(); foreach (string objectId in target.GetAllSimObjectsInReceptacleTriggersByObjectID()) { - SimObjPhysics toReParent = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; + SimObjPhysics toReParent = physicsSceneManager.ObjectIdToSimObjPhysics[ + objectId + ]; objectIdToOldParent[objectId] = toReParent.transform.parent; toReParent.transform.parent = openableObject.transform; toReParent.GetComponent().isKinematic = true; } } - + // set conditions for ignoring certain fail-conditions or not // (must be stored on CanOpen_Object component for OnTriggerEnter event to work) openableObject.SetForceAction(forceAction); @@ -1721,12 +1872,13 @@ private protected IEnumerator openAnimation( useGripper: useGripper, returnToStartMode: false, posRotManip: posRotManip, - posRotRef: posRotRef); + posRotRef: posRotRef + ); // Wait until all animating is done yield return new WaitUntil(() => (openableObject.GetIsCurrentlyLerping() == false)); yield return null; bool succeeded = true; - + // if failure occurred, revert back to backup state (either start or lastSuccessful), and then report failure if (openableObject.GetFailState() != CanOpen_Object.failState.none) { succeeded = false; @@ -1739,13 +1891,15 @@ private protected IEnumerator openAnimation( useGripper: useGripper, returnToStartMode: true, posRotManip: posRotManip, - posRotRef: posRotRef); + posRotRef: posRotRef + ); yield return new WaitUntil(() => (openableObject.GetIsCurrentlyLerping() == false)); yield return null; if (openableObject.GetFailState() == CanOpen_Object.failState.collision) { - errorMessage = "Openable object collided with " + openableObject.GetFailureCollision().name; - } - else if (openableObject.GetFailState() == CanOpen_Object.failState.hyperextension) { + errorMessage = + "Openable object collided with " + + openableObject.GetFailureCollision().name; + } else if (openableObject.GetFailState() == CanOpen_Object.failState.hyperextension) { errorMessage = "Agent hyperextended arm while opening object"; } } @@ -1753,7 +1907,9 @@ private protected IEnumerator openAnimation( // stops any object located within this openableObject from moving if (freezeContained) { foreach (string objectId in objectIdToOldParent.Keys) { - SimObjPhysics toReParent = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; + SimObjPhysics toReParent = physicsSceneManager.ObjectIdToSimObjPhysics[ + objectId + ]; toReParent.transform.parent = objectIdToOldParent[toReParent.ObjectID]; Rigidbody rb = toReParent.GetComponent(); rb.velocity = new Vector3(0f, 0f, 0f); @@ -1765,7 +1921,7 @@ private protected IEnumerator openAnimation( // Reset conditions for next interaction openableObject.SetFailState(CanOpen_Object.failState.none); openableObject.SetFailureCollision(null); - + openableObject.SetForceAction(false); openableObject.SetIgnoreAgentInTransition(false); openableObject.SetStopAtNonStaticCol(false); @@ -1836,7 +1992,10 @@ protected void openObject( // This is a style choice that applies to Microwaves and Laptops, // where it doesn't make a ton of sense to open them, while they are in use. - if (codd.WhatReceptaclesMustBeOffToOpen().Contains(target.Type) && target.GetComponent().isOn) { + if ( + codd.WhatReceptaclesMustBeOffToOpen().Contains(target.Type) + && target.GetComponent().isOn + ) { errorMessage = "Target must be OFF to open!"; if (markActionFinished) { actionFinished(false); @@ -1867,19 +2026,42 @@ protected void openObject( // Opening objects with the gripper currently requires the gripper-sphere to have some overlap with the moving parts' collision geometry GameObject parentMovingPart = FindOverlappingMovingPart(codd); if (parentMovingPart == null) { - errorMessage = "Gripper must be making contact with at least one moving part's surface to open it!"; + errorMessage = + "Gripper must be making contact with at least one moving part's surface to open it!"; if (markActionFinished) { actionFinished(false); } return; } - GameObject posRotManip = this.GetComponent().IKArm.GetComponent().GetArmTarget(); + GameObject posRotManip = this.GetComponent() + .IKArm.GetComponent() + .GetArmTarget(); GameObject posRotRef = new GameObject("PosRotReference"); posRotRef.transform.parent = parentMovingPart.transform; posRotRef.transform.position = posRotManip.transform.position; posRotRef.transform.rotation = posRotManip.transform.rotation; - StartCoroutine(openAnimation( + StartCoroutine( + openAnimation( + openableObject: codd, + markActionFinished: markActionFinished, + openness: openness, + forceAction: forceAction, + returnToStart: returnToStart, + ignoreAgentInTransition: ignoreAgentInTransition, + stopAtNonStaticCol: stopAtNonStaticCol, + useGripper: useGripper, + physicsInterval: physicsInterval, + freezeContained: simplifyPhysics, + posRotManip: posRotManip, + posRotRef: posRotRef + ) + ); + return; + } + + StartCoroutine( + openAnimation( openableObject: codd, markActionFinished: markActionFinished, openness: openness, @@ -1889,33 +2071,17 @@ protected void openObject( stopAtNonStaticCol: stopAtNonStaticCol, useGripper: useGripper, physicsInterval: physicsInterval, - freezeContained: simplifyPhysics, - posRotManip: posRotManip, - posRotRef: posRotRef - )); - return; - } - - StartCoroutine(openAnimation( - openableObject: codd, - markActionFinished: markActionFinished, - openness: openness, - forceAction: forceAction, - returnToStart: returnToStart, - ignoreAgentInTransition: ignoreAgentInTransition, - stopAtNonStaticCol: stopAtNonStaticCol, - useGripper: useGripper, - physicsInterval: physicsInterval, - freezeContained: simplifyPhysics - )); + freezeContained: simplifyPhysics + ) + ); } //helper action to set the openness of a "rotate" typed open/close object immediately (no tween over time) - public void OpenObjectImmediate( - string objectId, - float openness = 1.0f - ) { - SimObjPhysics target = getInteractableSimObjectFromId(objectId: objectId, forceAction: true); + public void OpenObjectImmediate(string objectId, float openness = 1.0f) { + SimObjPhysics target = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: true + ); target.GetComponent().SetOpennessImmediate(openness); actionFinished(true); } @@ -1924,18 +2090,24 @@ public void OpenObjectImmediate( public GameObject FindOverlappingMovingPart(CanOpen_Object codd) { int layerMask = 1 << 8; - GameObject magnetSphere = this.GetComponent().IKArm.GetComponent().GetMagnetSphere(); + GameObject magnetSphere = this.GetComponent() + .IKArm.GetComponent() + .GetMagnetSphere(); foreach (GameObject movingPart in codd.GetComponent().MovingParts) { - foreach(Collider col in movingPart.GetComponentsInChildren()) { + foreach (Collider col in movingPart.GetComponentsInChildren()) { // Checking for matches between moving parts' colliders and colliders inside of gripper-sphere - foreach(Collider containedCol in Physics.OverlapSphere( - magnetSphere.transform.TransformPoint(magnetSphere.GetComponent().center), - magnetSphere.transform.GetComponent().radius, - layerMask)) { - if (col == containedCol) - { - return movingPart; - } + foreach ( + Collider containedCol in Physics.OverlapSphere( + magnetSphere.transform.TransformPoint( + magnetSphere.GetComponent().center + ), + magnetSphere.transform.GetComponent().radius, + layerMask + ) + ) { + if (col == containedCol) { + return movingPart; + } } } } @@ -1953,7 +2125,10 @@ public void OpenObject( bool useGripper = false, float? moveMagnitude = null // moveMagnitude is supported for backwards compatibility. Its new name is 'openness'. ) { - SimObjPhysics target = getInteractableSimObjectFromId(objectId: objectId, forceAction: forceAction); + SimObjPhysics target = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: forceAction + ); openObject( target: target, openness: openness, @@ -1976,7 +2151,9 @@ public void OpenObject( float? moveMagnitude = null // moveMagnitude is supported for backwards compatibility. It's new name is 'openness'. ) { SimObjPhysics target = getInteractableSimObjectFromXY( - x: x, y: y, forceAction: forceAction + x: x, + y: y, + forceAction: forceAction ); openObject( target: target, @@ -2007,17 +2184,18 @@ public void AdvancePhysicsStep( ) { if ((!allowAutoSimulation) && Physics.autoSimulation) { errorMessage = ( - "AdvancePhysicsStep can only be called if Physics AutoSimulation is currently " + - "paused or if you have passed allowAutoSimulation=true! Either use the" + - " PausePhysicsAutoSim() action first, or if you already used it, Physics" + - " AutoSimulation has been turned back on already." + "AdvancePhysicsStep can only be called if Physics AutoSimulation is currently " + + "paused or if you have passed allowAutoSimulation=true! Either use the" + + " PausePhysicsAutoSim() action first, or if you already used it, Physics" + + " AutoSimulation has been turned back on already." ); actionFinished(false); return; } if (timeStep <= 0.0f || timeStep > 0.05f) { - errorMessage = "Please use a timeStep between 0.0f and 0.05f. Larger timeSteps produce inconsistent simulation results."; + errorMessage = + "Please use a timeStep between 0.0f and 0.05f. Larger timeSteps produce inconsistent simulation results."; actionFinished(false); return; } @@ -2041,7 +2219,6 @@ public void UnpausePhysicsAutoSim() { actionFinished(true); } - // Check if agent is collided with other objects protected bool IsCollided() { return collisionsInAction.Count > 0; @@ -2052,7 +2229,11 @@ public bool IsInteractable(SimObjPhysics sop) { throw new NullReferenceException("null SimObjPhysics passed to IsInteractable"); } - return GetAllVisibleSimObjPhysics(camera: this.m_Camera, maxDistance: this.maxVisibleDistance, filterSimObjs: new List { sop }).Length == 1; + return GetAllVisibleSimObjPhysics( + camera: this.m_Camera, + maxDistance: this.maxVisibleDistance, + filterSimObjs: new List { sop } + ).Length == 1; } public virtual SimpleSimObj[] allSceneObjects() { @@ -2065,6 +2246,7 @@ public void ResetObjectFilter() { // make this return a `actionFinishedEmit` actionFinished(true); } + public void SetObjectFilter(string[] objectIds) { SimObjPhysics[] simObjects = GameObject.FindObjectsOfType(); HashSet filter = new HashSet(); @@ -2085,7 +2267,7 @@ public void SetObjectFilterForType(string[] objectTypes) { HashSet filter = new HashSet(); HashSet filterObjectTypes = new HashSet(objectTypes); foreach (var simObj in simObjects) { - if (filterObjectTypes.Contains( Enum.GetName(typeof(SimObjType), simObj.Type) )) { + if (filterObjectTypes.Contains(Enum.GetName(typeof(SimObjType), simObj.Type))) { filter.Add(simObj); } } @@ -2096,28 +2278,34 @@ public void SetObjectFilterForType(string[] objectTypes) { } public ObjectMetadata setReceptacleMetadata(ObjectMetadata meta) { - - return meta; } public virtual ObjectMetadata[] generateObjectMetadata(SimObjPhysics[] simObjects) { if (simObjects == null) { - throw new NullReferenceException("null SimObjPhysics passed to generateObjectMetadata"); + throw new NullReferenceException( + "null SimObjPhysics passed to generateObjectMetadata" + ); } SimObjPhysics[] interactable; - HashSet visibleSimObjsHash = new HashSet(GetAllVisibleSimObjPhysics( - this.m_Camera, - this.maxVisibleDistance, - out interactable, - simObjects)); + HashSet visibleSimObjsHash = new HashSet( + GetAllVisibleSimObjPhysics( + this.m_Camera, + this.maxVisibleDistance, + out interactable, + simObjects + ) + ); - HashSet interactableSimObjsHash = new HashSet(interactable); + HashSet interactableSimObjsHash = new HashSet( + interactable + ); int numObj = simObjects.Length; List metadata = new List(); - Dictionary> parentReceptacles = new Dictionary>(); + Dictionary> parentReceptacles = + new Dictionary>(); #if UNITY_EDITOR // debug draw bounds reset list @@ -2132,7 +2320,9 @@ public virtual ObjectMetadata[] generateObjectMetadata(SimObjPhysics[] simObject interactableSimObjsHash.Contains(simObj) ); if (meta.toggleable) { - SimObjPhysics[] controlled = simObj.GetComponent().ReturnControlledSimObjects(); + SimObjPhysics[] controlled = simObj + .GetComponent() + .ReturnControlledSimObjects(); List controlledList = new List(); foreach (SimObjPhysics csop in controlled) { controlledList.Add(csop.objectID); @@ -2140,12 +2330,11 @@ public virtual ObjectMetadata[] generateObjectMetadata(SimObjPhysics[] simObject meta.controlledObjects = controlledList.ToArray(); } if (meta.receptacle) { - List containedObjectsAsID = new List(); foreach (GameObject go in simObj.ContainedGameObjects()) { containedObjectsAsID.Add(go.GetComponent().ObjectID); } - List roid = containedObjectsAsID;// simObj.Contains(); + List roid = containedObjectsAsID; // simObj.Contains(); foreach (string oid in roid) { if (!parentReceptacles.ContainsKey(oid)) { @@ -2155,7 +2344,10 @@ public virtual ObjectMetadata[] generateObjectMetadata(SimObjPhysics[] simObject } meta.receptacleObjectIds = roid.ToArray(); } - meta.distance = Vector3.Distance(transform.position, simObj.gameObject.transform.position); + meta.distance = Vector3.Distance( + transform.position, + simObj.gameObject.transform.position + ); metadata.Add(meta); } foreach (ObjectMetadata meta in metadata) { @@ -2167,7 +2359,11 @@ public virtual ObjectMetadata[] generateObjectMetadata(SimObjPhysics[] simObject } // generates object metatada based on sim object's properties - public virtual ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics simObj, bool isVisible, bool isInteractable) { + public virtual ObjectMetadata ObjectMetadataFromSimObjPhysics( + SimObjPhysics simObj, + bool isVisible, + bool isInteractable + ) { ObjectMetadata objMeta = new ObjectMetadata(); GameObject o = simObj.gameObject; objMeta.name = o.name; @@ -2185,8 +2381,12 @@ public virtual ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics simO objMeta.toggleable = simObj.IsToggleable; //note: not all objects that report back `isToggled` are themselves `toggleable`, however they all do have the `CanToggleOnOff` secondary sim object property //this is to account for cases like a [stove burner], which can report `isToggled` but cannot have the "ToggleObjectOn" action performed on them directly, and instead - //a [stove knob] linked to the [stove burner] must have a "ToggleObjectOn" action performed on it to have both the knob and burner set to a state of `isToggled = true` - if (simObj.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanToggleOnOff)) { + //a [stove knob] linked to the [stove burner] must have a "ToggleObjectOn" action performed on it to have both the knob and burner set to a state of `isToggled = true` + if ( + simObj.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanToggleOnOff + ) + ) { objMeta.isToggled = simObj.IsToggled; } @@ -2212,7 +2412,11 @@ public virtual ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics simO } // if the sim object is moveable or pickupable - if (simObj.IsPickupable || simObj.IsMoveable || (simObj.salientMaterials != null && simObj.salientMaterials.Length > 0)) { + if ( + simObj.IsPickupable + || simObj.IsMoveable + || (simObj.salientMaterials != null && simObj.salientMaterials.Length > 0) + ) { // this object should report back mass and salient materials string[] salientMaterialsToString = new string[simObj.salientMaterials.Length]; @@ -2225,7 +2429,6 @@ public virtual ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics simO // this object should also report back mass since it is moveable/pickupable objMeta.mass = simObj.Mass; - } // can this object change others to hot? @@ -2254,7 +2457,7 @@ public virtual ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics simO objMeta.temperature = simObj.CurrentObjTemp.ToString(); objMeta.pickupable = simObj.IsPickupable; - objMeta.isPickedUp = simObj.isPickedUp;// returns true for if this object is currently being held by the agent + objMeta.isPickedUp = simObj.isPickedUp; // returns true for if this object is currently being held by the agent objMeta.moveable = simObj.IsMoveable; @@ -2270,7 +2473,7 @@ public virtual ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics simO //note using forceAction=True will ignore the isInteractable requirement objMeta.isInteractable = isInteractable; - objMeta.isMoving = simObj.inMotion;// keep track of if this object is actively moving + objMeta.isMoving = simObj.inMotion; // keep track of if this object is actively moving objMeta.objectOrientedBoundingBox = simObj.ObjectOrientedBoundingBox; @@ -2279,10 +2482,13 @@ public virtual ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics simO return objMeta; } - - public virtual MinimalObjectMetadata[] generateMinimalObjectMetadata(SimObjPhysics[] simObjects) { + public virtual MinimalObjectMetadata[] generateMinimalObjectMetadata( + SimObjPhysics[] simObjects + ) { if (simObjects == null) { - throw new NullReferenceException("null SimObjPhysics passed to generateObjectMetadata"); + throw new NullReferenceException( + "null SimObjPhysics passed to generateObjectMetadata" + ); } int numObj = simObjects.Length; @@ -2346,17 +2552,20 @@ public void GetObjectMetadata(List objectIds = null) { public SceneBounds GenerateSceneBounds(Bounds bounding) { SceneBounds b = new SceneBounds(); List cornerPoints = new List(); - float[] xs = new float[]{ - bounding.center.x + bounding.size.x/2f, - bounding.center.x - bounding.size.x/2f + float[] xs = new float[] + { + bounding.center.x + bounding.size.x / 2f, + bounding.center.x - bounding.size.x / 2f }; - float[] ys = new float[]{ - bounding.center.y + bounding.size.y/2f, - bounding.center.y - bounding.size.y/2f + float[] ys = new float[] + { + bounding.center.y + bounding.size.y / 2f, + bounding.center.y - bounding.size.y / 2f }; - float[] zs = new float[]{ - bounding.center.z + bounding.size.z/2f, - bounding.center.z - bounding.size.z/2f + float[] zs = new float[] + { + bounding.center.z + bounding.size.z / 2f, + bounding.center.z - bounding.size.z / 2f }; foreach (float x in xs) { foreach (float y in ys) { @@ -2403,12 +2612,12 @@ public virtual MetadataWrapper generateMetadataWrapper() { metaMessage.sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; metaMessage.objects = this.generateObjectMetadata( ( - this.simObjFilter == null ? - physicsSceneManager.ObjectIdToSimObjPhysics.Values.ToArray() : - this.simObjFilter + this.simObjFilter == null + ? physicsSceneManager.ObjectIdToSimObjPhysics.Values.ToArray() + : this.simObjFilter ) ); - + metaMessage.isSceneAtRest = physicsSceneManager.isSceneAtRest; metaMessage.sceneBounds = GenerateSceneBounds(agentManager.SceneBounds); @@ -2425,13 +2634,17 @@ public virtual MetadataWrapper generateMetadataWrapper() { //main camera's local space coordinates need to be translated to world space first var worldSpaceCameraPosition = m_Camera.transform.position; //now convert camera position to agent relative local space - metaMessage.agentPositionRelativeCameraPosition = transform.InverseTransformPoint(worldSpaceCameraPosition); + metaMessage.agentPositionRelativeCameraPosition = transform.InverseTransformPoint( + worldSpaceCameraPosition + ); //Debug.Log($"agentRelativeCameraPosition: {metaMessage.agentPositionRelativeCameraPosition}"); //ok to get local euler angles we need to do... some shenanigans lets go var worldSpaceCameraRotationAsQuaternion = m_Camera.transform.rotation; - var localSpaceCameraRotationAsQuaternion = Quaternion.Inverse(transform.rotation) * worldSpaceCameraRotationAsQuaternion; - metaMessage.agentPositionRelativeCameraRotation = localSpaceCameraRotationAsQuaternion.eulerAngles; + var localSpaceCameraRotationAsQuaternion = + Quaternion.Inverse(transform.rotation) * worldSpaceCameraRotationAsQuaternion; + metaMessage.agentPositionRelativeCameraRotation = + localSpaceCameraRotationAsQuaternion.eulerAngles; //Debug.Log($"agentRelativeCameraRotation: {metaMessage.agentPositionRelativeCameraRotation}"); metaMessage.cameraOrthSize = cameraOrthSize; @@ -2470,11 +2683,9 @@ public virtual MetadataWrapper generateMetadataWrapper() { // ARM if (Arm != null) { metaMessage.arm = Arm.GenerateMetadata(); - } - else if (SArm != null) { + } else if (SArm != null) { metaMessage.arm = SArm.GenerateMetadata(); - } - else if (AArm != null) { + } else if (AArm != null) { metaMessage.articulationArm = AArm.GenerateArticulationMetadata(); } @@ -2514,10 +2725,10 @@ public virtual MetadataWrapper generateMetadataWrapper() { return metaMessage; } - public virtual void updateImageSynthesis(bool status) { if (this.imageSynthesis == null) { - imageSynthesis = this.m_Camera.gameObject.GetComponent() as ImageSynthesis; + imageSynthesis = + this.m_Camera.gameObject.GetComponent() as ImageSynthesis; } imageSynthesis.enabled = status; } @@ -2533,7 +2744,11 @@ public void ProcessControlCommand(ServerAction serverAction) { lastAction = serverAction.action; lastActionSuccess = false; - lastPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z); + lastPosition = new Vector3( + transform.position.x, + transform.position.y, + transform.position.z + ); System.Reflection.MethodInfo method = this.GetType().GetMethod(serverAction.action); this.agentState = AgentState.Processing; @@ -2554,7 +2769,6 @@ public void ProcessControlCommand(ServerAction serverAction) { errorMessage += e.ToString(); actionFinished(false); } - } // the parameter name is different to avoid failing a test @@ -2568,7 +2782,8 @@ public void ProcessControlCommand(DynamicServerAction controlCommand) { ProcessControlCommand(controlCommand: controlCommand, target: this); } - public void ProcessControlCommand(DynamicServerAction controlCommand, T target) where T: ActionInvokable{ + public void ProcessControlCommand(DynamicServerAction controlCommand, T target) + where T : ActionInvokable { lastActionInitialPhysicsSimulateCount = PhysicsSceneManager.PhysicsSimulateCallCount; errorMessage = ""; errorCode = ServerActionErrorCode.Undefined; @@ -2576,7 +2791,11 @@ public void ProcessControlCommand(DynamicServerAction controlCommand, T targe lastAction = controlCommand.action; lastActionSuccess = false; - lastPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z); + lastPosition = new Vector3( + transform.position.x, + transform.position.y, + transform.position.z + ); this.agentState = AgentState.Processing; try { @@ -2584,33 +2803,42 @@ public void ProcessControlCommand(DynamicServerAction controlCommand, T targe ActionDispatcher.Dispatch(target: target, dynamicServerAction: controlCommand); } catch (InvalidArgumentsException e) { errorMessage = - $"\n\tAction: \"{controlCommand.action}\" called with invalid argument{(e.InvalidArgumentNames.Count() > 1 ? "s" : "")}: {string.Join(", ", e.InvalidArgumentNames.Select(name => $"'{name}'").ToArray())}" + - $"\n\tExpected arguments: {string.Join(", ", e.ParameterNames)}" + - $"\n\tYour arguments: {string.Join(", ", e.ArgumentNames.Select(name => $"'{name}'"))}" + - $"\n\tValid ways to call \"{controlCommand.action}\" action:\n\t\t{string.Join("\n\t\t", e.PossibleOverwrites)}"; + $"\n\tAction: \"{controlCommand.action}\" called with invalid argument{(e.InvalidArgumentNames.Count() > 1 ? "s" : "")}: {string.Join(", ", e.InvalidArgumentNames.Select(name => $"'{name}'").ToArray())}" + + $"\n\tExpected arguments: {string.Join(", ", e.ParameterNames)}" + + $"\n\tYour arguments: {string.Join(", ", e.ArgumentNames.Select(name => $"'{name}'"))}" + + $"\n\tValid ways to call \"{controlCommand.action}\" action:\n\t\t{string.Join("\n\t\t", e.PossibleOverwrites)}"; errorCode = ServerActionErrorCode.InvalidArgument; - var possibleOverwrites = ActionDispatcher.getMatchingMethodOverwrites(target.GetType(), controlCommand); + var possibleOverwrites = ActionDispatcher.getMatchingMethodOverwrites( + target.GetType(), + controlCommand + ); actionFinished(false); } catch (ToObjectArgumentActionException e) { - Dictionary typeMap = new Dictionary{ - {"Single", "float"}, - {"Double", "float"}, - {"Int16", "int"}, - {"Int32", "int"}, - {"Int64", "int"} + Dictionary typeMap = new Dictionary + { + { "Single", "float" }, + { "Double", "float" }, + { "Int16", "int" }, + { "Int32", "int" }, + { "Int64", "int" } }; Type underlingType = Nullable.GetUnderlyingType(e.parameterType); string typeName = underlingType == null ? e.parameterType.Name : underlingType.Name; if (typeMap.ContainsKey(typeName)) { typeName = typeMap[typeName]; } - errorMessage = $"action: {controlCommand.action} has an invalid argument: {e.parameterName} (=={e.parameterValueAsStr})." + - $" Cannot convert to: {typeName}"; + errorMessage = + $"action: {controlCommand.action} has an invalid argument: {e.parameterName} (=={e.parameterValueAsStr})." + + $" Cannot convert to: {typeName}"; errorCode = ServerActionErrorCode.InvalidArgument; actionFinished(false); } catch (MissingArgumentsActionException e) { - errorMessage = "action: " + controlCommand.action + " is missing the following arguments: " + string.Join(",", e.ArgumentNames.ToArray()); + errorMessage = + "action: " + + controlCommand.action + + " is missing the following arguments: " + + string.Join(",", e.ArgumentNames.ToArray()); errorCode = ServerActionErrorCode.MissingArguments; actionFinished(false); } catch (AmbiguousActionException e) { @@ -2619,15 +2847,18 @@ public void ProcessControlCommand(DynamicServerAction controlCommand, T targe actionFinished(false); } catch (InvalidActionException) { errorCode = ServerActionErrorCode.InvalidAction; - actionFinished(success: false, errorMessage: "Invalid action: " + controlCommand.action); + actionFinished( + success: false, + errorMessage: "Invalid action: " + controlCommand.action + ); } catch (TargetInvocationException e) { // TargetInvocationException is called whenever an action // throws an exception. It is used to short circuit errors, // which terminates the action immediately. #if UNITY_EDITOR - Debug.Log("Caught target invocation exception"); - Debug.Log(e); - Debug.Log(e.InnerException.Message); + Debug.Log("Caught target invocation exception"); + Debug.Log(e); + Debug.Log(e.InnerException.Message); #endif actionFinished( success: false, @@ -2636,10 +2867,9 @@ public void ProcessControlCommand(DynamicServerAction controlCommand, T targe } catch (MissingActionFinishedException e) { errorCode = ServerActionErrorCode.MissingActionFinished; actionFinished( - false, - errorMessage: $"Action '{controlCommand.action}' did not return an `ActionFinished`. Possible bug with the action and it's execution path given the arguments it was called with. Arguments: {controlCommand.jObject.ToString()}" + false, + errorMessage: $"Action '{controlCommand.action}' did not return an `ActionFinished`. Possible bug with the action and it's execution path given the arguments it was called with. Arguments: {controlCommand.jObject.ToString()}" ); - } catch (Exception e) { Debug.LogError("Caught error with invoke for action: " + controlCommand.action); Debug.LogError("Action error message: " + errorMessage); @@ -2681,13 +2911,17 @@ public void Done() { actionFinished(true); } - // Helper method that parses objectId parameter to return the sim object that it target. // The action is halted if the objectId does not appear in the scene. - protected SimObjPhysics getInteractableSimObjectFromId(string objectId, bool forceAction = false) { + protected SimObjPhysics getInteractableSimObjectFromId( + string objectId, + bool forceAction = false + ) { // an objectId was given, so find that target in the scene if it exists if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { - throw new ArgumentException($"objectId: {objectId} is not the objectId on any object in the scene!"); + throw new ArgumentException( + $"objectId: {objectId} is not the objectId on any object in the scene!" + ); } SimObjPhysics sop = getSimObjectFromId(objectId); @@ -2696,15 +2930,25 @@ protected SimObjPhysics getInteractableSimObjectFromId(string objectId, bool for } SimObjPhysics[] interactable; - bool visible = GetAllVisibleSimObjPhysics(camera: this.m_Camera, maxDistance: this.maxVisibleDistance, out interactable, filterSimObjs: new List { sop }).Length == 1; + bool visible = + GetAllVisibleSimObjPhysics( + camera: this.m_Camera, + maxDistance: this.maxVisibleDistance, + out interactable, + filterSimObjs: new List { sop } + ).Length == 1; // target not found! if (!visible && !forceAction) { - throw new NullReferenceException("Target object not found within the specified visibility."); + throw new NullReferenceException( + "Target object not found within the specified visibility." + ); } if (interactable.Length == 0 && !forceAction) { - throw new NullReferenceException("Target object is visible but not interactable. It is likely obstructed by some clear object like glass."); + throw new NullReferenceException( + "Target object is visible but not interactable. It is likely obstructed by some clear object like glass." + ); } return sop; @@ -2728,7 +2972,16 @@ protected SimObjPhysics getInteractableSimObjectFromXY(float x, float y, bool fo ray: ray, hitInfo: out hit, maxDistance: Mathf.Infinity, - layerMask: LayerMask.GetMask("Default", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "SimObjVisible", "Agent", "PlaceableSurface"), + layerMask: LayerMask.GetMask( + "Default", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "SimObjVisible", + "Agent", + "PlaceableSurface" + ), queryTriggerInteraction: QueryTriggerInteraction.Ignore ); @@ -2743,8 +2996,8 @@ protected SimObjPhysics getInteractableSimObjectFromXY(float x, float y, bool fo assertPosInView(targetPosition: hit.point); } catch (InvalidOperationException e) { throw new InvalidOperationException( - $"Target sim object: ({target.ObjectID}) at screen coordinate: ({x}, {y}) is beyond your visibilityDistance: {maxVisibleDistance}!\n" + - "Hint: Ignore this check by passing in forceAction=True or update visibility distance, call controller.reset(visibilityDistance=)." + $"Target sim object: ({target.ObjectID}) at screen coordinate: ({x}, {y}) is beyond your visibilityDistance: {maxVisibleDistance}!\n" + + "Hint: Ignore this check by passing in forceAction=True or update visibility distance, call controller.reset(visibilityDistance=)." ); } } @@ -2769,7 +3022,9 @@ protected void assertPosInView( // now make sure that the targetPosition is within the Agent's x/y view, restricted by camera Vector3 vp = m_Camera.WorldToViewportPoint(targetPosition); - if (inViewport && (vp.z < 0 || vp.x > 1.0f || vp.y < 0.0f || vp.y > 1.0f || vp.y < 0.0f)) { + if ( + inViewport && (vp.z < 0 || vp.x > 1.0f || vp.y < 0.0f || vp.y > 1.0f || vp.y < 0.0f) + ) { throw new InvalidOperationException("target is outside of Agent Viewport"); } } @@ -2819,7 +3074,16 @@ protected void screenToWorldTarget( ray, out hit, Mathf.Infinity, - LayerMask.GetMask("Default", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "SimObjVisible", "Agent", "PlaceableSurface"), + LayerMask.GetMask( + "Default", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "SimObjVisible", + "Agent", + "PlaceableSurface" + ), QueryTriggerInteraction.Ignore ) ) { @@ -2860,18 +3124,15 @@ protected void screenToWorldTarget( // will hit the transparent object FIRST public void GetObjectInFrame(float x, float y, bool checkVisible = false) { SimObjPhysics target = null; - screenToWorldTarget( - x: x, - y: y, - target: ref target, - checkVisible: checkVisible - ); + screenToWorldTarget(x: x, y: y, target: ref target, checkVisible: checkVisible); actionFinishedEmit(success: true, actionReturn: target.ObjectID); } public void GetCoordinateFromRaycast(float x, float y) { if (x < 0 || y < 0 || x > 1 || y > 1) { - throw new ArgumentOutOfRangeException($"x and y must be in [0:1] not (x={x}, y={y})."); + throw new ArgumentOutOfRangeException( + $"x and y must be in [0:1] not (x={x}, y={y})." + ); } Ray ray = m_Camera.ViewportPointToRay(new Vector3(x, 1 - y, 0)); @@ -2880,14 +3141,20 @@ public void GetCoordinateFromRaycast(float x, float y) { ray: ray, hitInfo: out hit, maxDistance: Mathf.Infinity, - layerMask: LayerMask.GetMask("Default", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent", "SimObjVisible", "PlaceableSurface"), + layerMask: LayerMask.GetMask( + "Default", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent", + "SimObjVisible", + "PlaceableSurface" + ), queryTriggerInteraction: QueryTriggerInteraction.Ignore ); - actionFinishedEmit( - success: true, - actionReturn: hit.point - ); + actionFinishedEmit(success: true, actionReturn: hit.point); } public void GetObjectHitFromRaycast(Vector3 origin, Vector3 destination) { @@ -2898,16 +3165,24 @@ public void GetObjectHitFromRaycast(Vector3 origin, Vector3 destination) { direction: destination - origin, hitInfo: out hit, maxDistance: Mathf.Infinity, - layerMask: LayerMask.GetMask("Default", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "SimObjVisible", "NonInteractive"), + layerMask: LayerMask.GetMask( + "Default", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "SimObjVisible", + "NonInteractive" + ), queryTriggerInteraction: QueryTriggerInteraction.Ignore ) ) { actionFinishedEmit( success: false, errorMessage: ( - $"Raycast from ({origin.x}, {origin.y}, {origin.z})" + - $" to ({destination.x}, {destination.y}, {destination.z})" + - " failed to hit any target object!" + $"Raycast from ({origin.x}, {origin.y}, {origin.z})" + + $" to ({destination.x}, {destination.y}, {destination.z})" + + " failed to hit any target object!" ) ); return; @@ -2917,17 +3192,14 @@ public void GetObjectHitFromRaycast(Vector3 origin, Vector3 destination) { actionFinishedEmit( success: false, errorMessage: ( - $"Raycast from ({origin.x}, {origin.y}, {origin.z})" + - $" to ({destination.x}, {destination.y}, {destination.z})" + - " hit object, but not a SimObject!" + $"Raycast from ({origin.x}, {origin.y}, {origin.z})" + + $" to ({destination.x}, {destination.y}, {destination.z})" + + " hit object, but not a SimObject!" ) ); return; } - actionFinishedEmit( - success: true, - actionReturn: target.ObjectID - ); + actionFinishedEmit(success: true, actionReturn: target.ObjectID); } public void PerformRaycast(Vector3 origin, Vector3 destination) { @@ -2938,16 +3210,24 @@ public void PerformRaycast(Vector3 origin, Vector3 destination) { direction: destination - origin, hitInfo: out hit, maxDistance: Mathf.Infinity, - layerMask: LayerMask.GetMask("Default", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "SimObjVisible", "NonInteractive"), + layerMask: LayerMask.GetMask( + "Default", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "SimObjVisible", + "NonInteractive" + ), queryTriggerInteraction: QueryTriggerInteraction.Ignore ) ) { actionFinishedEmit( success: false, errorMessage: ( - $"Raycast from ({origin.x}, {origin.y}, {origin.z})" + - $" to ({destination.x}, {destination.y}, {destination.z})" + - " failed to hit any target object!" + $"Raycast from ({origin.x}, {origin.y}, {origin.z})" + + $" to ({destination.x}, {destination.y}, {destination.z})" + + " failed to hit any target object!" ) ); return; @@ -2957,9 +3237,9 @@ public void PerformRaycast(Vector3 origin, Vector3 destination) { actionFinishedEmit( success: false, errorMessage: ( - $"Raycast from ({origin.x}, {origin.y}, {origin.z})" + - $" to ({destination.x}, {destination.y}, {destination.z})" + - " hit object, but not a SimObject!" + $"Raycast from ({origin.x}, {origin.y}, {origin.z})" + + $" to ({destination.x}, {destination.y}, {destination.z})" + + " hit object, but not a SimObject!" ) ); return; @@ -2975,7 +3255,10 @@ public void PerformRaycast(Vector3 origin, Vector3 destination) { } public void GetVisibilityPoints(string objectId) { - SimObjPhysics sop = getInteractableSimObjectFromId(objectId: objectId, forceAction: true); + SimObjPhysics sop = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: true + ); if (sop.VisibilityPoints == null) { throw new ArgumentException($"objectId: {objectId} has no visibility points!"); } @@ -2984,10 +3267,7 @@ public void GetVisibilityPoints(string objectId) { for (int i = 0; i < points.Length; i++) { points[i] = sop.VisibilityPoints[i].position; } - actionFinishedEmit( - success: true, - actionReturn: points - ); + actionFinishedEmit(success: true, actionReturn: points); } protected void snapAgentToGrid() { @@ -3006,10 +3286,7 @@ protected bool isPositionOnGrid(Vector3 xyz) { float gridX = Convert.ToSingle(Math.Round(xyz.x * mult) / mult); float gridZ = Convert.ToSingle(Math.Round(xyz.z * mult) / mult); - return ( - Mathf.Approximately(gridX, xyz.x) && - Mathf.Approximately(gridZ, xyz.z) - ); + return (Mathf.Approximately(gridX, xyz.x) && Mathf.Approximately(gridZ, xyz.z)); } else { return true; } @@ -3051,7 +3328,6 @@ virtual protected void moveCharacter(ServerAction action, int targetOrientation) // StartCoroutine(checkMoveAction(action)); } - // iterates to next allowed downward horizon angle for AgentCamera (max 60 degrees down) public virtual void LookDown(ServerAction controlCommand) { m_Camera.transform.Rotate(controlCommand.degrees, 0, 0); @@ -3074,20 +3350,37 @@ protected bool checkForUpDownAngleLimit(string direction, float degrees) { // zero out the rotation first rotPoint.transform.rotation = m_Camera.transform.rotation; - // print(Vector3.Angle(rotPoint.transform.forward, m_CharacterController.transform.forward)); if (direction == "down") { rotPoint.Rotate(new Vector3(degrees, 0, 0)); // note: maxDownwardLookAngle is negative because SignedAngle() returns a... signed angle... so even though the input is LookDown(degrees) with // degrees being positive, it still needs to check against this negatively signed direction. - if (Mathf.Round(Vector3.SignedAngle(rotPoint.transform.forward, m_CharacterController.transform.forward, m_CharacterController.transform.right) * 10.0f) / 10.0f < -maxDownwardLookAngle) { + if ( + Mathf.Round( + Vector3.SignedAngle( + rotPoint.transform.forward, + m_CharacterController.transform.forward, + m_CharacterController.transform.right + ) * 10.0f + ) / 10.0f + < -maxDownwardLookAngle + ) { result = false; } } if (direction == "up") { rotPoint.Rotate(new Vector3(-degrees, 0, 0)); - if (Mathf.Round(Vector3.SignedAngle(rotPoint.transform.forward, m_CharacterController.transform.forward, m_CharacterController.transform.right) * 10.0f) / 10.0f > maxUpwardLookAngle) { + if ( + Mathf.Round( + Vector3.SignedAngle( + rotPoint.transform.forward, + m_CharacterController.transform.forward, + m_CharacterController.transform.right + ) * 10.0f + ) / 10.0f + > maxUpwardLookAngle + ) { result = false; } } @@ -3101,7 +3394,10 @@ protected bool checkForUpDownAngleLimit(string direction, float degrees) { // As opposed to an action, these args are required because we explicitly // want base classes to pass all of them in. protected void teleport( - Vector3? position, Vector3? rotation, float? horizon, bool forceAction + Vector3? position, + Vector3? rotation, + float? horizon, + bool forceAction ) { teleportFull( position: position, @@ -3127,14 +3423,16 @@ protected virtual void assertTeleportedNearGround(Vector3? targetPosition) { // move otherwise the agent will end up in a different // location from the targetPosition autoSyncTransforms(); - m_CharacterController.Move(new Vector3(0f, Physics.gravity.y * this.m_GravityMultiplier, 0f)); + m_CharacterController.Move( + new Vector3(0f, Physics.gravity.y * this.m_GravityMultiplier, 0f) + ); // perhaps like y=2 was specified, with an agent's standing height of 0.9 if (Mathf.Abs(transform.position.y - pos.y) > 0.05f) { throw new InvalidOperationException( - "After teleporting and adjusting agent position to floor, there was too large a change" + - $"({Mathf.Abs(transform.position.y - pos.y)} > 0.05) in the y component." + - " Consider using `forceAction=true` if you'd like to teleport anyway." + "After teleporting and adjusting agent position to floor, there was too large a change" + + $"({Mathf.Abs(transform.position.y - pos.y)} > 0.05) in the y component." + + " Consider using `forceAction=true` if you'd like to teleport anyway." ); } } @@ -3145,21 +3443,35 @@ protected virtual void teleportFull( float? horizon, bool forceAction ) { - if (rotation.HasValue && (!Mathf.Approximately(rotation.Value.x, 0f) || !Mathf.Approximately(rotation.Value.z, 0f))) { + if ( + rotation.HasValue + && ( + !Mathf.Approximately(rotation.Value.x, 0f) + || !Mathf.Approximately(rotation.Value.z, 0f) + ) + ) { throw new ArgumentOutOfRangeException( - "No agents currently can change in pitch or roll. So, you must set rotation(x=0, y=yaw, z=0)." + - $" You gave {rotation.Value.ToString("F6")}." + "No agents currently can change in pitch or roll. So, you must set rotation(x=0, y=yaw, z=0)." + + $" You gave {rotation.Value.ToString("F6")}." ); } // recall that horizon=60 is look down 60 degrees and horizon=-30 is look up 30 degrees - if (!forceAction && horizon.HasValue && (horizon.Value > maxDownwardLookAngle || horizon.Value < -maxUpwardLookAngle)) { + if ( + !forceAction + && horizon.HasValue + && (horizon.Value > maxDownwardLookAngle || horizon.Value < -maxUpwardLookAngle) + ) { throw new ArgumentOutOfRangeException( $"Each horizon must be in [{-maxUpwardLookAngle}:{maxDownwardLookAngle}]. You gave {horizon}." ); } - if (!forceAction && position.HasValue && !agentManager.SceneBounds.Contains(position.Value)) { + if ( + !forceAction + && position.HasValue + && !agentManager.SceneBounds.Contains(position.Value) + ) { throw new ArgumentOutOfRangeException( $"Teleport position {position.Value.ToString("F6")} out of scene bounds! Ignore this by setting forceAction=true." ); @@ -3185,9 +3497,11 @@ bool forceAction oldCameraLocalEulerAngles.z ); - if (!forceAction && - isAgentCapsuleColliding( - collidersToIgnore: collidersToIgnoreDuringMovement, includeErrorMessage: true + if ( + !forceAction + && isAgentCapsuleColliding( + collidersToIgnore: collidersToIgnoreDuringMovement, + includeErrorMessage: true ) ) { transform.position = oldPosition; @@ -3197,7 +3511,7 @@ bool forceAction } } - public void TeleportObject( + public void TeleportObject( string objectId, Vector3 position, Vector3 rotation, @@ -3238,7 +3552,6 @@ public void TeleportObject( } } - public void TeleportObject( string objectId, Vector3[] positions, @@ -3313,13 +3626,17 @@ public bool TeleportObject( sop.GetComponent().isKinematic = true; } if (!forceAction) { - Collider colliderHitIfTeleported = UtilityFunctions.firstColliderObjectCollidingWith(sop.gameObject); + Collider colliderHitIfTeleported = + UtilityFunctions.firstColliderObjectCollidingWith(sop.gameObject); if (colliderHitIfTeleported != null) { sop.transform.position = oldPosition; sop.transform.rotation = oldRotation; - SimObjPhysics hitSop = ancestorSimObjPhysics(colliderHitIfTeleported.gameObject); + SimObjPhysics hitSop = ancestorSimObjPhysics( + colliderHitIfTeleported.gameObject + ); if (includeErrorMessage) { - errorMessage = $"{sop.ObjectID} is colliding with {(hitSop != null ? hitSop.ObjectID : colliderHitIfTeleported.name)} after teleport."; + errorMessage = + $"{sop.ObjectID} is colliding with {(hitSop != null ? hitSop.ObjectID : colliderHitIfTeleported.name)} after teleport."; } return false; } @@ -3345,7 +3662,10 @@ public bool TeleportObject( ItemInHand.transform.parent = null; } - sop.DropContainedObjects(reparentContainedObjects: true, forceKinematic: forceKinematic); + sop.DropContainedObjects( + reparentContainedObjects: true, + forceKinematic: forceKinematic + ); sop.isInAgentHand = false; ItemInHand = null; } @@ -3376,11 +3696,12 @@ public void TeleportObject( } // used to check if an specified sim object has come to rest - // set useTimeout bool to use a faster time out + // set useTimeout bool to use a faster time out // TODO: Change to new action type protected IEnumerator checkIfObjectHasStoppedMoving( SimObjPhysics sop, - bool useTimeout = false) { + bool useTimeout = false + ) { // yield for the physics update to make sure this yield is consistent regardless of framerate yield return new WaitForFixedUpdate(); @@ -3400,7 +3721,9 @@ protected IEnumerator checkIfObjectHasStoppedMoving( break; } - float currentVelocity = Math.Abs(rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude); + float currentVelocity = Math.Abs( + rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude + ); float accel = (currentVelocity - sop.lastVelocity) / Time.fixedDeltaTime; // ok the accel is basically zero, so it has stopped moving @@ -3423,10 +3746,9 @@ protected IEnumerator checkIfObjectHasStoppedMoving( actionFinished(false); yield break; } - + DefaultAgentHand(); actionFinished(true, sop.transform.position); - } else { errorMessage = "null reference sim obj in checkIfObjectHasStoppedMoving call"; actionFinished(false); @@ -3436,7 +3758,8 @@ protected IEnumerator checkIfObjectHasStoppedMoving( public void SetObjectPoses(ServerAction action) { // make sure objectPoses and also the Object Pose elements inside are initialized correctly if (action.objectPoses == null || action.objectPoses[0] == null) { - errorMessage = "objectPoses was not initialized correctly. Please make sure each element in the objectPoses list is initialized."; + errorMessage = + "objectPoses was not initialized correctly. Please make sure each element in the objectPoses list is initialized."; actionFinished(false); return; } @@ -3445,11 +3768,15 @@ public void SetObjectPoses(ServerAction action) { // SetObjectPoses is performed in a coroutine otherwise if // a frame does not pass prior to this AND the imageSynthesis - // is enabled for say depth or normals, Unity will crash on + // is enabled for say depth or normals, Unity will crash on // a subsequent scene reset() protected IEnumerator setObjectPoses(ObjectPose[] objectPoses, bool placeStationary) { yield return new WaitForEndOfFrame(); - bool success = physicsSceneManager.SetObjectPoses(objectPoses, out errorMessage, placeStationary); + bool success = physicsSceneManager.SetObjectPoses( + objectPoses, + out errorMessage, + placeStationary + ); //update image synthesis since scene has changed if (this.imageSynthesis && this.imageSynthesis.enabled) { @@ -3458,7 +3785,6 @@ protected IEnumerator setObjectPoses(ObjectPose[] objectPoses, bool placeStation actionFinished(success, errorMessage); } - // pass in a Vector3, presumably from GetReachablePositions, and try to place a sim object flush on a surface below that point // unlike PlaceHeldObject or InitialRandomSpawn, this won't be limited by a Receptacle, but only limited by collision public void PlaceObjectAtPoint( @@ -3508,7 +3834,8 @@ public bool PlaceObjectAtPoint( // make sure point we are moving the object to is valid if (!agentManager.sceneBounds.Contains(position)) { if (includeErrorMessage) { - errorMessage = $"Position coordinate ({position}) is not within scene bounds ({agentManager.sceneBounds})"; + errorMessage = + $"Position coordinate ({position}) is not within scene bounds ({agentManager.sceneBounds})"; } return false; } @@ -3518,7 +3845,8 @@ public bool PlaceObjectAtPoint( target.transform.rotation = Quaternion.Euler(rotation.Value); } Vector3 originalPos = target.transform.position; - target.transform.position = agentManager.SceneBounds.min - new Vector3(-100f, -100f, -100f); + target.transform.position = + agentManager.SceneBounds.min - new Vector3(-100f, -100f, -100f); if (!Physics.autoSyncTransforms) { Physics.SyncTransforms(); @@ -3539,13 +3867,16 @@ public bool PlaceObjectAtPoint( Vector3 bottomPoint = b.ClosestPoint(targetNegY); b.enabled = false; - float distFromSopToBottomPoint = Vector3.Distance(bottomPoint, target.transform.position); + float distFromSopToBottomPoint = Vector3.Distance( + bottomPoint, + target.transform.position + ); float offset = distFromSopToBottomPoint + 0.005f; // Offset in case the surface below isn't completely flat Vector3 finalPos = GetSurfacePointBelowPosition(position) + new Vector3(0, offset, 0); - // Check spawn area here + // Check spawn area here target.transform.position = finalPos; if (!Physics.autoSyncTransforms) { @@ -3567,12 +3898,11 @@ public bool PlaceObjectAtPoint( // Additional stuff we need to do if placing item that was in hand if (wasInHand) { - rb.constraints = RigidbodyConstraints.None; rb.useGravity = true; // change collision detection mode while falling so that obejcts don't phase through colliders. - // this is reset to discrete on SimObjPhysics.cs's update + // this is reset to discrete on SimObjPhysics.cs's update rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; GameObject topObject = GameObject.Find("Objects"); @@ -3582,10 +3912,12 @@ public bool PlaceObjectAtPoint( ItemInHand.transform.parent = null; } - target.DropContainedObjects(reparentContainedObjects: true, forceKinematic: forceKinematic); + target.DropContainedObjects( + reparentContainedObjects: true, + forceKinematic: forceKinematic + ); target.isInAgentHand = false; ItemInHand = null; - } return true; } @@ -3683,14 +4015,16 @@ public bool placeObjectAtPoint(SimObjPhysics t, Vector3 position) { Vector3 bottomPoint = b.ClosestPoint(targetNegY); b.enabled = false; - float distFromSopToBottomPoint = Vector3.Distance(bottomPoint, target.transform.position); + float distFromSopToBottomPoint = Vector3.Distance( + bottomPoint, + target.transform.position + ); float offset = distFromSopToBottomPoint; // final position to place on surface Vector3 finalPos = GetSurfacePointBelowPosition(position) + new Vector3(0, offset, 0); - // check spawn area, if its clear, then place object at finalPos InstantiatePrefabTest ipt = physicsSceneManager.GetComponent(); if (ipt.CheckSpawnArea(target, finalPos, target.transform.rotation, false)) { @@ -3714,20 +4048,27 @@ public Vector3 GetSurfacePointBelowPosition(Vector3 position) { Vector3.down, out hit, 10f, - LayerMask.GetMask("Default", "SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent"), + LayerMask.GetMask( + "Default", + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent" + ), QueryTriggerInteraction.Ignore ) ) { point = hit.point; return point; } - // nothing hit, return the original position? else { return position; } } - + protected T[] flatten2DimArray(T[,] array) { int nrow = array.GetLength(0); int ncol = array.GetLength(1); @@ -3763,9 +4104,24 @@ protected List visibleRange() { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { RaycastHit hit; - Ray ray = m_Camera.ViewportPointToRay(new Vector3( - (i + 0.5f) / n, (j + 0.5f) / n, 0.0f)); - if (Physics.Raycast(ray, out hit, 100f, LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent"))) { + Ray ray = m_Camera.ViewportPointToRay( + new Vector3((i + 0.5f) / n, (j + 0.5f) / n, 0.0f) + ); + if ( + Physics.Raycast( + ray, + out hit, + 100f, + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent" + ) + ) + ) { points.Add(hit.point); } } @@ -3781,10 +4137,10 @@ protected List visibleRange() { // (invisible agents for example). protected void updateAllAgentCollidersForVisibilityCheck(bool enableColliders) { foreach (BaseFPSAgentController agent in this.agentManager.agents) { - bool overlapping = (transform.position - agent.transform.position).magnitude < 0.001f; + bool overlapping = + (transform.position - agent.transform.position).magnitude < 0.001f; if (overlapping || agent == this || !agent.IsVisible) { agent.updateCollidersForVisiblityCheck(enableColliders); - } } } @@ -3823,7 +4179,6 @@ protected virtual void updateCollidersForVisiblityCheck(bool enableColliders) { } } } - // Stretch arm else if (SArm != null && SArm.gameObject.activeSelf) { if (this.IsVisible) { @@ -3842,7 +4197,10 @@ protected virtual void updateCollidersForVisiblityCheck(bool enableColliders) { } foreach (Collider c in this.GetComponentsInChildren()) { - if(c.transform.gameObject.layer == LayerMask.NameToLayer("ArticulatedAgent") || c.transform.gameObject.layer == LayerMask.NameToLayer("FloorAgent")) { + if ( + c.transform.gameObject.layer == LayerMask.NameToLayer("ArticulatedAgent") + || c.transform.gameObject.layer == LayerMask.NameToLayer("FloorAgent") + ) { continue; } @@ -3966,9 +4324,13 @@ protected bool objectIsWithinViewport(SimObjPhysics sop) { float ViewPointRangeHigh = 1.0f; float ViewPointRangeLow = 0.0f; - if (viewPoint.z > 0 && - viewPoint.x < ViewPointRangeHigh && viewPoint.x > ViewPointRangeLow && // within x bounds of viewport - viewPoint.y < ViewPointRangeHigh && viewPoint.y > ViewPointRangeLow // within y bounds of viewport + if ( + viewPoint.z > 0 + && viewPoint.x < ViewPointRangeHigh + && viewPoint.x > ViewPointRangeLow + && // within x bounds of viewport + viewPoint.y < ViewPointRangeHigh + && viewPoint.y > ViewPointRangeLow // within y bounds of viewport ) { return true; } @@ -4011,7 +4373,12 @@ public VisibilityCheck isSimObjVisible(Camera camera, SimObjPhysics sop, float m } // if this particular point is in view... - visCheck |= CheckIfVisibilityPointInViewport(sop, point, camera, sop.IsReceptacle); + visCheck |= CheckIfVisibilityPointInViewport( + sop, + point, + camera, + sop.IsReceptacle + ); if (visCheck.visible && visCheck.interactable) { #if !UNITY_EDITOR // If we're in the unity editor then don't break on finding a visible @@ -4032,18 +4399,23 @@ public VisibilityCheck isSimObjVisible(Camera camera, SimObjPhysics sop, float m return visCheck; } - public VisibilityCheck isSimObjVisible(Camera camera, SimObjPhysics sop, float maxDistance, Plane[] planes) { + public VisibilityCheck isSimObjVisible( + Camera camera, + SimObjPhysics sop, + float maxDistance, + Plane[] planes + ) { // check against all visibility points, accumulate count. If at least one point is visible, set object to visible VisibilityCheck visCheck = new VisibilityCheck(); - if (sop.VisibilityPoints != null - && sop.VisibilityPoints.Length > 0 - ) { + if (sop.VisibilityPoints != null && sop.VisibilityPoints.Length > 0) { AxisAlignedBoundingBox aabb = sop.AxisAlignedBoundingBox; - if (!GeometryUtility.TestPlanesAABB( - planes: planes, - bounds: new Bounds(center: aabb.center, size:aabb.size) - )) { + if ( + !GeometryUtility.TestPlanesAABB( + planes: planes, + bounds: new Bounds(center: aabb.center, size: aabb.size) + ) + ) { return visCheck; } Transform[] visPoints = sop.VisibilityPoints; @@ -4083,9 +4455,11 @@ public VisibilityCheck isSimObjVisible(Camera camera, SimObjPhysics sop, float m } // if this particular point is in view... - visCheck |= (CheckIfVisibilityPointRaycast(sop, point, camera, false) | CheckIfVisibilityPointRaycast(sop, point, camera, true)); + visCheck |= ( + CheckIfVisibilityPointRaycast(sop, point, camera, false) + | CheckIfVisibilityPointRaycast(sop, point, camera, true) + ); if (visCheck.visible && visCheck.interactable) { - #if !UNITY_EDITOR // If we're in the unity editor then don't break on finding a visible // point as we want to draw lines to each visible point. @@ -4098,7 +4472,7 @@ public VisibilityCheck isSimObjVisible(Camera camera, SimObjPhysics sop, float m #if UNITY_EDITOR sop.debugIsVisible = visCheck.visible; sop.debugIsInteractable = visCheck.interactable; -#endif +#endif } else { Debug.Log("Error! Set at least 1 visibility point on SimObjPhysics " + sop + "."); } @@ -4114,6 +4488,7 @@ public SimObjPhysics[] VisibleSimObjs(bool forceVisible = false) { return GetAllVisibleSimObjPhysics(m_Camera, maxVisibleDistance); } } + protected SimObjPhysics[] GetAllVisibleSimObjPhysics( Camera camera, float maxDistance, @@ -4122,9 +4497,19 @@ protected SimObjPhysics[] GetAllVisibleSimObjPhysics( SimObjPhysics[] interactable; if (this.visibilityScheme == VisibilityScheme.Collider) { - return GetAllVisibleSimObjPhysicsCollider(camera, maxDistance, filterSimObjs, out interactable); + return GetAllVisibleSimObjPhysicsCollider( + camera, + maxDistance, + filterSimObjs, + out interactable + ); } else { - return GetAllVisibleSimObjPhysicsDistance(camera, maxDistance, filterSimObjs, out interactable); + return GetAllVisibleSimObjPhysicsDistance( + camera, + maxDistance, + filterSimObjs, + out interactable + ); } } @@ -4134,11 +4519,20 @@ protected SimObjPhysics[] GetAllVisibleSimObjPhysics( out SimObjPhysics[] interactable, IEnumerable filterSimObjs = null ) { - if (this.visibilityScheme == VisibilityScheme.Collider) { - return GetAllVisibleSimObjPhysicsCollider(camera, maxDistance, filterSimObjs, out interactable); + return GetAllVisibleSimObjPhysicsCollider( + camera, + maxDistance, + filterSimObjs, + out interactable + ); } else { - return GetAllVisibleSimObjPhysicsDistance(camera, maxDistance, filterSimObjs, out interactable); + return GetAllVisibleSimObjPhysicsDistance( + camera, + maxDistance, + filterSimObjs, + out interactable + ); } } @@ -4148,12 +4542,14 @@ protected VisibilityScheme getVisibilityScheme(string visibilityScheme = null) { visibilityScheme = visibilityScheme.ToLower(); if ( - visibilityScheme == Enum.GetName(typeof(VisibilityScheme), VisibilityScheme.Collider).ToLower() + visibilityScheme + == Enum.GetName(typeof(VisibilityScheme), VisibilityScheme.Collider).ToLower() ) { visSchemeEnum = VisibilityScheme.Collider; } else if ( - visibilityScheme == Enum.GetName(typeof(VisibilityScheme), VisibilityScheme.Distance).ToLower() - ) { + visibilityScheme + == Enum.GetName(typeof(VisibilityScheme), VisibilityScheme.Distance).ToLower() + ) { visSchemeEnum = VisibilityScheme.Distance; } else { throw new System.NotImplementedException( @@ -4190,12 +4586,14 @@ public void GetVisibleObjects( if (objectIds != null) { foreach (string objectId in objectIds) { if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { - throw new ArgumentException($"Object with id {objectId} does not exist in scene."); + throw new ArgumentException( + $"Object with id {objectId} does not exist in scene." + ); } } - filterSimObjs = objectIds.Select( - objectId => physicsSceneManager.ObjectIdToSimObjPhysics[objectId] - ).ToList(); + filterSimObjs = objectIds + .Select(objectId => physicsSceneManager.ObjectIdToSimObjPhysics[objectId]) + .ToList(); } SimObjPhysics[] interactable; @@ -4219,35 +4617,41 @@ public void GetVisibleObjects( $"Visibility scheme {visSchemeEnum} is not implemented. Must be 'distance' or 'collider'." ); } - #if UNITY_EDITOR - foreach (SimObjPhysics sop in visible) { - Debug.Log("Visible: " + sop.name); - } - #endif +#if UNITY_EDITOR + foreach (SimObjPhysics sop in visible) { + Debug.Log("Visible: " + sop.name); + } +#endif // Return only the ObjectIds of the visible objects actionFinishedEmit(true, visible.Select(sop => sop.ObjectID).ToList()); } public void GetObjaverseAnnotations() { - Dictionary> annotations = new Dictionary>(); + Dictionary> annotations = + new Dictionary>(); - foreach (Thor.Objaverse.ObjaverseAnnotation oa in GameObject.FindObjectsOfType()) { + foreach ( + Thor.Objaverse.ObjaverseAnnotation oa in GameObject.FindObjectsOfType() + ) { SimObjPhysics sop = oa.gameObject.GetComponent(); annotations[sop.ObjectID] = new Dictionary(); annotations[sop.ObjectID]["objectType"] = oa.ObjectCategory; annotations[sop.ObjectID]["dataset"] = oa.MostSpecificDataset.ToString(); -// Debug.Log(sop.ObjectID); -// Debug.Log(oa.ObjectCategory); -// Debug.Log(oa.MostSpecificDataset.ToString()); + // Debug.Log(sop.ObjectID); + // Debug.Log(oa.ObjectCategory); + // Debug.Log(oa.MostSpecificDataset.ToString()); } actionFinishedEmit(true, annotations); } - [ObsoleteAttribute(message: "This action is deprecated. Call GetVisibleObjects instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call GetVisibleObjects instead.", + error: false + )] public void ObjectsVisibleFromThirdPartyCamera( int thirdPartyCameraIndex, float? maxDistance = null, @@ -4266,7 +4670,10 @@ public void ObjectsVisibleFromThirdPartyCamera( // range and is visibile outside of the range, it will get reported as invisible // by the new scheme, but visible in the current scheme. protected SimObjPhysics[] GetAllVisibleSimObjPhysicsDistance( - Camera camera, float maxDistance, IEnumerable filterSimObjs, out SimObjPhysics[] interactable + Camera camera, + float maxDistance, + IEnumerable filterSimObjs, + out SimObjPhysics[] interactable ) { if (filterSimObjs == null) { filterSimObjs = physicsSceneManager.ObjectIdToSimObjPhysics.Values; @@ -4290,12 +4697,22 @@ protected SimObjPhysics[] GetAllVisibleSimObjPhysicsDistance( return visible.ToArray(); } - private SimObjPhysics[] GetAllVisibleSimObjPhysicsCollider(Camera camera, float maxDistance, IEnumerable filterSimObjs, out SimObjPhysics[] interactable) { + private SimObjPhysics[] GetAllVisibleSimObjPhysicsCollider( + Camera camera, + float maxDistance, + IEnumerable filterSimObjs, + out SimObjPhysics[] interactable + ) { HashSet currentlyVisibleItems = new HashSet(); HashSet interactableItems = new HashSet(); #if UNITY_EDITOR - foreach (KeyValuePair pair in physicsSceneManager.ObjectIdToSimObjPhysics) { + foreach ( + KeyValuePair< + string, + SimObjPhysics + > pair in physicsSceneManager.ObjectIdToSimObjPhysics + ) { // Set all objects to not be visible pair.Value.debugIsVisible = false; pair.Value.debugIsInteractable = false; @@ -4316,7 +4733,8 @@ private SimObjPhysics[] GetAllVisibleSimObjPhysicsCollider(Camera camera, float // get all sim objects in range around us that have colliders in layer 8 (visible), ignoring objects in the SimObjInvisible layer // this will make it so the receptacle trigger boxes don't occlude the objects within them. CapsuleCollider agentCapsuleCollider = GetComponent(); - Vector3 point0, point1; + Vector3 point0, + point1; float radius; agentCapsuleCollider.ToWorldSpaceCapsule(out point0, out point1, out radius); if (point0.y <= point1.y) { @@ -4329,12 +4747,23 @@ private SimObjPhysics[] GetAllVisibleSimObjPhysicsCollider(Camera camera, float // and any invisible agents. updateAllAgentCollidersForVisibilityCheck(false); - HashSet<(SimObjPhysics, bool)> sopAndIncInvisibleTuples = new HashSet<(SimObjPhysics, bool)>(); + HashSet<(SimObjPhysics, bool)> sopAndIncInvisibleTuples = + new HashSet<(SimObjPhysics, bool)>(); // Find all nearby colliders corresponding to visible components and grab // their corresponding SimObjPhysics component Collider[] collidersInView = Physics.OverlapCapsule( - point0, point1, maxDistance, LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"), QueryTriggerInteraction.Collide + point0, + point1, + maxDistance, + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ), + QueryTriggerInteraction.Collide ); if (collidersInView != null) { foreach (Collider c in collidersInView) { @@ -4373,8 +4802,7 @@ private SimObjPhysics[] GetAllVisibleSimObjPhysicsCollider(Camera camera, float foreach (SimObjPhysics sop in Arm.heldObjects.Keys) { sopAndIncInvisibleTuples.Add((sop, false)); } - } - else if (SArm != null && SArm.gameObject.activeSelf) { + } else if (SArm != null && SArm.gameObject.activeSelf) { foreach (SimObjPhysics sop in SArm.heldObjects.Keys) { sopAndIncInvisibleTuples.Add((sop, false)); } @@ -4395,7 +4823,12 @@ private SimObjPhysics[] GetAllVisibleSimObjPhysicsCollider(Camera camera, float foreach (Transform point in visPoints) { // if this particular point is in view... // if we see at least one vis point, the object is "visible" - visCheck |= CheckIfVisibilityPointInViewport(sop, point, camera, includeInvisible); + visCheck |= CheckIfVisibilityPointInViewport( + sop, + point, + camera, + includeInvisible + ); if (visCheck.visible && visCheck.interactable) { #if !UNITY_EDITOR // If we're in the unity editor then don't break on finding a visible @@ -4408,7 +4841,7 @@ private SimObjPhysics[] GetAllVisibleSimObjPhysicsCollider(Camera camera, float #if UNITY_EDITOR sop.debugIsVisible = visCheck.visible; sop.debugIsInteractable = visCheck.interactable; -#endif +#endif if (visCheck.visible && !currentlyVisibleItems.Contains(sop)) { currentlyVisibleItems.Add(sop); } @@ -4417,7 +4850,11 @@ private SimObjPhysics[] GetAllVisibleSimObjPhysicsCollider(Camera camera, float interactableItems.Add(sop); } } else { - Debug.Log("Error! Set at least 1 visibility point on SimObjPhysics " + sop + "."); + Debug.Log( + "Error! Set at least 1 visibility point on SimObjPhysics " + + sop + + "." + ); } } } @@ -4430,16 +4867,32 @@ private SimObjPhysics[] GetAllVisibleSimObjPhysicsCollider(Camera camera, float List currentlyVisibleItemsToList = currentlyVisibleItems.ToList(); List interactableItemsToList = interactableItems.ToList(); - interactableItemsToList.Sort((x, y) => Vector3.Distance(x.transform.position, agentCameraPos).CompareTo(Vector3.Distance(y.transform.position, agentCameraPos))); - currentlyVisibleItemsToList.Sort((x, y) => Vector3.Distance(x.transform.position, agentCameraPos).CompareTo(Vector3.Distance(y.transform.position, agentCameraPos))); + interactableItemsToList.Sort( + (x, y) => + Vector3 + .Distance(x.transform.position, agentCameraPos) + .CompareTo(Vector3.Distance(y.transform.position, agentCameraPos)) + ); + currentlyVisibleItemsToList.Sort( + (x, y) => + Vector3 + .Distance(x.transform.position, agentCameraPos) + .CompareTo(Vector3.Distance(y.transform.position, agentCameraPos)) + ); interactable = interactableItemsToList.ToArray(); return currentlyVisibleItemsToList.ToArray(); } protected virtual LayerMask GetVisibilityRaycastLayerMask(bool withSimObjInvisible = false) { - string[] layers = new string[] { - "SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent" + string[] layers = new string[] + { + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent" }; if (withSimObjInvisible) { layers = layers.Append("SimObjInvisible").ToArray(); @@ -4447,8 +4900,7 @@ protected virtual LayerMask GetVisibilityRaycastLayerMask(bool withSimObjInvisib return LayerMask.GetMask(layers); } - -// check if the visibility point on a sim object, sop, is within the viewport + // check if the visibility point on a sim object, sop, is within the viewport // has a includeInvisible bool to check against triggerboxes as well, to check for visibility with things like Cabinets/Drawers protected VisibilityCheck CheckIfVisibilityPointRaycast( SimObjPhysics sop, @@ -4467,7 +4919,9 @@ bool includeInvisible // LayerMask mask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "SimObjInvisible", "Agent"); // change mask if its a floor so it ignores the receptacle trigger boxes on the floor - LayerMask mask = GetVisibilityRaycastLayerMask(withSimObjInvisible: sop.Type != SimObjType.Floor); + LayerMask mask = GetVisibilityRaycastLayerMask( + withSimObjInvisible: sop.Type != SimObjType.Floor + ); // change mask if its a floor so it ignores the receptacle trigger boxes on the floor // if (sop.Type == SimObjType.Floor) { @@ -4475,16 +4929,33 @@ bool includeInvisible // mask = GetVisibilityRaycastLayerMask(withSimObjInvisible: false); // } - bool isSopHeldByArm = ( Arm != null && Arm.gameObject.activeSelf && Arm.heldObjects.ContainsKey(sop) ) || - ( SArm != null && SArm.gameObject.activeSelf && SArm.heldObjects.ContainsKey(sop) ); + bool isSopHeldByArm = + (Arm != null && Arm.gameObject.activeSelf && Arm.heldObjects.ContainsKey(sop)) + || ( + SArm != null && SArm.gameObject.activeSelf && SArm.heldObjects.ContainsKey(sop) + ); // check raycast against both visible and invisible layers, to check against ReceptacleTriggerBoxes which are normally // ignored by the other raycast if (includeInvisible) { - if (Physics.Raycast(camera.transform.position, position - camera.transform.position, out hit, raycastDistance, mask)) { + if ( + Physics.Raycast( + camera.transform.position, + position - camera.transform.position, + out hit, + raycastDistance, + mask + ) + ) { if ( hit.transform == sop.transform - || ( isSopHeldByArm && ((Arm != null && Arm.heldObjects[sop].Contains(hit.collider)) || (SArm != null && SArm.heldObjects[sop].Contains(hit.collider))) ) + || ( + isSopHeldByArm + && ( + (Arm != null && Arm.heldObjects[sop].Contains(hit.collider)) + || (SArm != null && SArm.heldObjects[sop].Contains(hit.collider)) + ) + ) ) { visCheck.visible = true; visCheck.interactable = true; @@ -4494,7 +4965,6 @@ bool includeInvisible } } } - // only check against the visible layer, ignore the invisible layer // so if an object ONLY has colliders on it that are not on layer 8, this raycast will go through them else if ( @@ -4503,12 +4973,25 @@ bool includeInvisible position - camera.transform.position, out hit, raycastDistance, - LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent") + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent" + ) ) ) { if ( hit.transform == sop.transform - || ( isSopHeldByArm && ((Arm != null && Arm.heldObjects[sop].Contains(hit.collider)) || (SArm != null && SArm.heldObjects[sop].Contains(hit.collider))) ) + || ( + isSopHeldByArm + && ( + (Arm != null && Arm.heldObjects[sop].Contains(hit.collider)) + || (SArm != null && SArm.heldObjects[sop].Contains(hit.collider)) + ) + ) ) { // if this line is drawn, then this visibility point is in camera frame and not occluded // might want to use this for a targeting check as well at some point.... @@ -4519,7 +5002,12 @@ bool includeInvisible // check if it's because we hit something see-through SimObjPhysics hitSop = hit.transform.GetComponent(); - if (hitSop != null && hitSop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanSeeThrough)) { + if ( + hitSop != null + && hitSop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanSeeThrough + ) + ) { // we hit something see through, so now find all objects in the path between // the sop and the camera RaycastHit[] hits; @@ -4527,7 +5015,13 @@ bool includeInvisible camera.transform.position, position - camera.transform.position, raycastDistance, - LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"), + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ), QueryTriggerInteraction.Ignore ); @@ -4541,8 +5035,16 @@ bool includeInvisible foreach (RaycastHit h in hits) { if ( h.transform == sop.transform - || (Arm != null && isSopHeldByArm && Arm.heldObjects[sop].Contains(hit.collider)) - || (SArm != null && isSopHeldByArm && SArm.heldObjects[sop].Contains(hit.collider)) + || ( + Arm != null + && isSopHeldByArm + && Arm.heldObjects[sop].Contains(hit.collider) + ) + || ( + SArm != null + && isSopHeldByArm + && SArm.heldObjects[sop].Contains(hit.collider) + ) ) { // found the object we are looking for, great! //set it to visible via 'result' but the object is not interactable because it is behind some transparent object @@ -4553,7 +5055,12 @@ bool includeInvisible // Didn't find it, continue on only if the hit object was translucent SimObjPhysics sopHitOnPath = null; sopHitOnPath = h.transform.GetComponentInParent(); - if (sopHitOnPath == null || !sopHitOnPath.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanSeeThrough)) { + if ( + sopHitOnPath == null + || !sopHitOnPath.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanSeeThrough + ) + ) { break; } } @@ -4581,7 +5088,10 @@ bool includeInvisible // now cast a ray out toward the point, if anything occludes this point, that point is not visible RaycastHit hit; - float distFromPointToCamera = Vector3.Distance(point.position, camera.transform.position); + float distFromPointToCamera = Vector3.Distance( + point.position, + camera.transform.position + ); return CheckIfVisibilityPointRaycast( sop: sop, @@ -4591,7 +5101,6 @@ bool includeInvisible ); } - protected VisibilityCheck CheckIfVisibilityPointInViewport( SimObjPhysics sop, Transform point, @@ -4605,11 +5114,13 @@ bool includeInvisible float ViewPointRangeHigh = 1.0f; float ViewPointRangeLow = 0.0f; - if (viewPoint.z > 0 //&& viewPoint.z < maxDistance * DownwardViewDistance // is in front of camera and within range of visibility sphere - && - viewPoint.x < ViewPointRangeHigh && viewPoint.x > ViewPointRangeLow // within x bounds of viewport - && - viewPoint.y < ViewPointRangeHigh && viewPoint.y > ViewPointRangeLow) // within y bounds of viewport + if ( + viewPoint.z > 0 //&& viewPoint.z < maxDistance * DownwardViewDistance // is in front of camera and within range of visibility sphere + && viewPoint.x < ViewPointRangeHigh + && viewPoint.x > ViewPointRangeLow // within x bounds of viewport + && viewPoint.y < ViewPointRangeHigh + && viewPoint.y > ViewPointRangeLow + ) // within y bounds of viewport { visCheck = CheckIfVisibilityPointRaycast(sop, point, camera, includeInvisible); } @@ -4651,21 +5162,18 @@ public void ApproximateAgentRadius(int n = 12) { b.Encapsulate(c.bounds); } } - #if UNITY_EDITOR +#if UNITY_EDITOR Debug.Log(Mathf.Sqrt(b.extents.x * b.extents.x + b.extents.z * b.extents.z)); - #endif - radius = Mathf.Max( - radius, - Mathf.Max(b.extents.x, b.extents.z) - ); +#endif + radius = Mathf.Max(radius, Mathf.Max(b.extents.x, b.extents.z)); } this.transform.rotation = oldRot; Physics.SyncTransforms(); - #if UNITY_EDITOR - Debug.Log("Final radius"); - Debug.Log(radius); - #endif +#if UNITY_EDITOR + Debug.Log("Final radius"); + Debug.Log(radius); +#endif actionFinishedEmit(true, radius); } @@ -4725,7 +5233,7 @@ public void InitialRandomSpawn( } ItemInHand.GetComponent().isInAgentHand = false; // agent hand flag - DefaultAgentHand();// also default agent hand + DefaultAgentHand(); // also default agent hand ItemInHand = null; } @@ -4739,10 +5247,12 @@ public void InitialRandomSpawn( // check if strings used for excludedReceptacles are valid object types foreach (string receptacleType in excludedReceptacles) { try { - SimObjType objType = (SimObjType)System.Enum.Parse(typeof(SimObjType), receptacleType); + SimObjType objType = (SimObjType) + System.Enum.Parse(typeof(SimObjType), receptacleType); listOfExcludedReceptacleTypes.Add(objType); } catch (Exception) { - errorMessage = "invalid Object Type used in excludedReceptacles array: " + receptacleType; + errorMessage = + "invalid Object Type used in excludedReceptacles array: " + receptacleType; actionFinished(false); return; } @@ -4809,12 +5319,16 @@ public void SetTopLevelView(bool topView = false) { actionFinished(true); } - [ObsoleteAttribute(message: "This action is deprecated. Use GetMapViewCameraProperties with a third party camera instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Use GetMapViewCameraProperties with a third party camera instead.", + error: false + )] public void ToggleMapView() { SyncTransform[] syncInChildren; List structureObjsList = new List(); - StructureObject[] structureObjs = GameObject.FindObjectsOfType(typeof(StructureObject)) as StructureObject[]; + StructureObject[] structureObjs = + GameObject.FindObjectsOfType(typeof(StructureObject)) as StructureObject[]; foreach (StructureObject structure in structureObjs) { switch (structure.WhatIsMyStructureObjectTag) { @@ -4833,7 +5347,9 @@ public void ToggleMapView() { m_Camera.transform.localRotation = lastLocalCameraRotation; // restore agent body culling - m_Camera.transform.GetComponent().StopCullingThingsForASecond = false; + m_Camera + .transform.GetComponent() + .StopCullingThingsForASecond = false; syncInChildren = gameObject.GetComponentsInChildren(); foreach (SyncTransform sync in syncInChildren) { sync.StopSyncingForASecond = false; @@ -4844,7 +5360,9 @@ public void ToggleMapView() { } } else { // stop culling the agent's body so it's visible from the top? - m_Camera.transform.GetComponent().StopCullingThingsForASecond = true; + m_Camera + .transform.GetComponent() + .StopCullingThingsForASecond = true; syncInChildren = gameObject.GetComponentsInChildren(); foreach (SyncTransform sync in syncInChildren) { sync.StopSyncingForASecond = true; @@ -4869,7 +5387,8 @@ public void ToggleMapView() { } protected Dictionary getMapViewCameraProperties() { - StructureObject[] structureObjs = GameObject.FindObjectsOfType(typeof(StructureObject)) as StructureObject[]; + StructureObject[] structureObjs = + GameObject.FindObjectsOfType(typeof(StructureObject)) as StructureObject[]; Bounds bounds = new Bounds(); bool boundsDidUpdate = false; @@ -4916,27 +5435,29 @@ protected Dictionary getMapViewCameraProperties() { return new Dictionary() { ["position"] = new Vector3(midX, yValue, midZ), ["rotation"] = new Vector3(90, 0, 0), - ["orthographicSize"] = Math.Max((bounds.max.x - bounds.min.x) / 2f, (bounds.max.z - bounds.min.z) / 2f), + ["orthographicSize"] = Math.Max( + (bounds.max.x - bounds.min.x) / 2f, + (bounds.max.z - bounds.min.z) / 2f + ), ["orthographic"] = true }; } public void GetMapViewCameraProperties() { - actionFinishedEmit( - success: true, - actionReturn: getMapViewCameraProperties() - ); + actionFinishedEmit(success: true, actionReturn: getMapViewCameraProperties()); } protected IEnumerable pointsOnSurfaceOfBoxCollider(BoxCollider bc, int divisions) { if (divisions < 2) { - throw new ArgumentException($"divisions must be >= 2 (currently equals {divisions})."); + throw new ArgumentException( + $"divisions must be >= 2 (currently equals {divisions})." + ); } Vector3 halfSize = 0.5f * bc.size; - List xMinMax = new List {-halfSize.x, halfSize.x}; - List yMinMax = new List {-halfSize.y, halfSize.y}; - List zMinMax = new List {-halfSize.z, halfSize.z}; + List xMinMax = new List { -halfSize.x, halfSize.x }; + List yMinMax = new List { -halfSize.y, halfSize.y }; + List zMinMax = new List { -halfSize.z, halfSize.z }; List xCenterVals = new List(); List yCenterVals = new List(); @@ -4950,7 +5471,7 @@ protected IEnumerable pointsOnSurfaceOfBoxCollider(BoxCollider bc, int for (int whichX = 0; whichX < 2; whichX++) { List xVals = whichX == 1 ? xMinMax : xCenterVals; - + for (int whichY = 0; whichY < 2; whichY++) { List yVals = whichY == 1 ? yMinMax : yCenterVals; @@ -4961,13 +5482,15 @@ protected IEnumerable pointsOnSurfaceOfBoxCollider(BoxCollider bc, int continue; } - # if UNITY_EDITOR +# if UNITY_EDITOR Vector3? lastPoint = null; - # endif +# endif foreach (float x in xVals) { foreach (float y in yVals) { foreach (float z in zVals) { - Vector3 worldPoint = bc.transform.TransformPoint(bc.center + new Vector3(x, y, z)); + Vector3 worldPoint = bc.transform.TransformPoint( + bc.center + new Vector3(x, y, z) + ); /* # if UNITY_EDITOR if (lastPoint.HasValue) { @@ -4986,7 +5509,7 @@ protected IEnumerable pointsOnSurfaceOfBoxCollider(BoxCollider bc, int } } - public void BBoxDistance(string objectId0, string objectId1, int divisions=3) { + public void BBoxDistance(string objectId0, string objectId1, int divisions = 3) { SimObjPhysics sop0 = getSimObjectFromId(objectId0); SimObjPhysics sop1 = getSimObjectFromId(objectId1); if (sop0 == null || sop1 == null) { @@ -5010,9 +5533,9 @@ public void BBoxDistance(string objectId0, string objectId1, int divisions=3) { // 0.5 used below because `size` corresponds to full box extents, not half extents // and are measuring things from the center. if ( - (-0.5f * size.x < pLocal.x && pLocal.x < 0.5f * size.x) && - (-0.5f * size.y < pLocal.y && pLocal.y < 0.5f * size.y) && - (-0.5f * size.z < pLocal.z && pLocal.z < 0.5f * size.z) + (-0.5f * size.x < pLocal.x && pLocal.x < 0.5f * size.x) + && (-0.5f * size.y < pLocal.y && pLocal.y < 0.5f * size.y) + && (-0.5f * size.z < pLocal.z && pLocal.z < 0.5f * size.z) ) { # if UNITY_EDITOR Debug.Log($"{objectId0} is inside {objectId1}, distance is 0"); @@ -5036,9 +5559,9 @@ public void BBoxDistance(string objectId0, string objectId1, int divisions=3) { Vector3 pLocal = c0.transform.InverseTransformPoint(p) - c0.center; Vector3 size = c0.size; if ( - (-0.5f * size.x < pLocal.x && pLocal.x < 0.5f * size.x) && - (-0.5f * size.y < pLocal.y && pLocal.y < 0.5f * size.y) && - (-0.5f * size.z < pLocal.z && pLocal.z < 0.5f * size.z) + (-0.5f * size.x < pLocal.x && pLocal.x < 0.5f * size.x) + && (-0.5f * size.y < pLocal.y && pLocal.y < 0.5f * size.y) + && (-0.5f * size.z < pLocal.z && pLocal.z < 0.5f * size.z) ) { # if UNITY_EDITOR Debug.Log($"{objectId1} is inside {objectId0}, distance is 0"); @@ -5103,14 +5626,15 @@ RaycastHit hit in Physics.RaycastAll( ) { if (!okColliders.Contains(hit.collider)) { SimObjPhysics hitSop = ancestorSimObjPhysics(hit.collider.gameObject); - string hitId = (hitSop != null) ? hitSop.ObjectID : hit.collider.gameObject.name; + string hitId = + (hitSop != null) ? hitSop.ObjectID : hit.collider.gameObject.name; objectsInWay.Add(hitId); } } toReturn["adjacent"] = objectsInWay.Count == 0; #if UNITY_EDITOR - string are_arent = (bool) toReturn["adjacent"] ? "are" : "aren't"; + string are_arent = (bool)toReturn["adjacent"] ? "are" : "aren't"; Debug.Log($"Objects {are_arent} adjacent ({String.Join(", ", objectsInWay)})."); #endif toReturn["objectInWay"] = objectsInWay; @@ -5138,13 +5662,16 @@ bool returnOnFirstHit sop.syncBoundingBoxes(forceCreateObjectOrientedBoundingBox: true); // Ensures the sop has an object oriented bounding box attached List points = pointsOnSurfaceOfBoxCollider( - sop.BoundingBox.GetComponent(), - divisions - ).ToList(); + sop.BoundingBox.GetComponent(), + divisions + ) + .ToList(); points.Sort((v0, v1) => v0.y.CompareTo(v1.y)); HashSet onObjectIds = new HashSet(); - List collidersToDisable = sop.GetComponentsInChildren().Where(c => c.enabled).ToList(); + List collidersToDisable = sop.GetComponentsInChildren() + .Where(c => c.enabled) + .ToList(); try { foreach (Collider c in collidersToDisable) { c.enabled = false; @@ -5154,15 +5681,22 @@ bool returnOnFirstHit Vector3 point = points[i]; # if UNITY_EDITOR - Debug.DrawLine(point + transform.up * 1e-3f, point - transform.up * belowDistance, Color.red, 10.0f); + Debug.DrawLine( + point + transform.up * 1e-3f, + point - transform.up * belowDistance, + Color.red, + 10.0f + ); # endif RaycastHit hit; if ( Physics.Raycast( - point + transform.up * 1e-3f, -transform.up, + point + transform.up * 1e-3f, + -transform.up, out hit, belowDistance + 1e-3f, - LayerMask.GetMask("SimObjVisible")) + LayerMask.GetMask("SimObjVisible") + ) ) { SimObjPhysics onSop = ancestorSimObjPhysics(hit.collider.gameObject); if (onSop != null) { @@ -5174,7 +5708,8 @@ bool returnOnFirstHit onObjectIds.Add(onSop.ObjectID); # if !UNITY_EDITOR - if (returnOnFirstHit) { + if (returnOnFirstHit) + { break; } # endif @@ -5189,7 +5724,11 @@ bool returnOnFirstHit return onObjectIds; } - public void CheckWhatObjectOn(string objectId, int divisions=3, float belowDistance=1e-2f) { + public void CheckWhatObjectOn( + string objectId, + int divisions = 3, + float belowDistance = 1e-2f + ) { SimObjPhysics sop = getSimObjectFromId(objectId); if (sop == null) { actionFinishedEmit(false); // Error message set already by getSimObjectFromId @@ -5197,12 +5736,23 @@ public void CheckWhatObjectOn(string objectId, int divisions=3, float belowDista } actionFinishedEmit( true, - whatObjectOn(sop: sop, divisions: divisions, belowDistance: belowDistance, returnOnFirstHit: false).ToList() + whatObjectOn( + sop: sop, + divisions: divisions, + belowDistance: belowDistance, + returnOnFirstHit: false + ) + .ToList() ); } - public void CheckWhatObjectsOn(List objectIds, int divisions=3, float belowDistance=1e-2f) { - Dictionary> objectIdToOnObjectId = new Dictionary>(); + public void CheckWhatObjectsOn( + List objectIds, + int divisions = 3, + float belowDistance = 1e-2f + ) { + Dictionary> objectIdToOnObjectId = + new Dictionary>(); foreach (string objectId in objectIds) { SimObjPhysics sop = getSimObjectFromId(objectId); if (sop == null) { @@ -5210,16 +5760,16 @@ public void CheckWhatObjectsOn(List objectIds, int divisions=3, float be return; } objectIdToOnObjectId[objectId] = whatObjectOn( - sop: sop, divisions: divisions, belowDistance: belowDistance, returnOnFirstHit: false - ).ToList(); + sop: sop, + divisions: divisions, + belowDistance: belowDistance, + returnOnFirstHit: false + ) + .ToList(); } - actionFinishedEmit( - true, - objectIdToOnObjectId - ); + actionFinishedEmit(true, objectIdToOnObjectId); } - /* Get the 2D (x, z) convex hull of a GameObject. See the Get2DSemanticHulls function for more information. @@ -5233,7 +5783,9 @@ protected List> Get2DSemanticHull(GameObject go) { foreach (MeshFilter meshFilter in go.GetComponentsInChildren()) { foreach (Vector3 localVertex in meshFilter.mesh.vertices) { Vector3 globalVertex = meshFilter.transform.TransformPoint(localVertex); - vertices.Add(new MIConvexHull.DefaultVertex2D(x: globalVertex.x, y: globalVertex.z)); + vertices.Add( + new MIConvexHull.DefaultVertex2D(x: globalVertex.x, y: globalVertex.z) + ); maxY = Math.Max(maxY, globalVertex.y); } } @@ -5244,10 +5796,7 @@ protected List> Get2DSemanticHull(GameObject go) { ConvexHullCreationResult miconvexHull = null; - miconvexHull = MIConvexHull.ConvexHull.Create2D( - data: vertices, - tolerance: 1e-10 - ); + miconvexHull = MIConvexHull.ConvexHull.Create2D(data: vertices, tolerance: 1e-10); #if UNITY_EDITOR DefaultVertex2D[] pointsOnHullArray = miconvexHull.Result.ToArray(); @@ -5305,14 +5854,15 @@ public void Get2DSemanticHulls( // Only consider sim objects which correspond to objectIds if given. SimObjPhysics[] sopsFilteredByObjectIds = null; if (objectIds != null) { - sopsFilteredByObjectIds = objectIds.Select( - key => physicsSceneManager.ObjectIdToSimObjPhysics[key] - ).ToArray(); + sopsFilteredByObjectIds = objectIds + .Select(key => physicsSceneManager.ObjectIdToSimObjPhysics[key]) + .ToArray(); } else { sopsFilteredByObjectIds = GameObject.FindObjectsOfType(); } - Dictionary>> objectIdToConvexHull = new Dictionary>>(); + Dictionary>> objectIdToConvexHull = + new Dictionary>>(); foreach (SimObjPhysics sop in sopsFilteredByObjectIds) { // Skip objects that don't have one of the required types (if given) if ( @@ -5341,14 +5891,18 @@ public void Get2DSemanticHull(string objectId) { } else { actionFinishedEmit( true, - Get2DSemanticHull(physicsSceneManager.ObjectIdToSimObjPhysics[objectId].gameObject) + Get2DSemanticHull( + physicsSceneManager.ObjectIdToSimObjPhysics[objectId].gameObject + ) ); } } public void UpdateDisplayGameObject(GameObject go, bool display) { if (go != null) { - foreach (MeshRenderer mr in go.GetComponentsInChildren() as MeshRenderer[]) { + foreach ( + MeshRenderer mr in go.GetComponentsInChildren() as MeshRenderer[] + ) { if (!initiallyDisabledRenderers.Contains(mr.GetInstanceID())) { mr.enabled = display; } @@ -5356,11 +5910,7 @@ public void UpdateDisplayGameObject(GameObject go, bool display) { } } - public void HighlightObject( - string objectId, - float lineWidth = 0.095f, - float? height = 2.0f - ) { + public void HighlightObject(string objectId, float lineWidth = 0.095f, float? height = 2.0f) { SimObjPhysics sop = getSimObjectFromId(objectId: objectId); AxisAlignedBoundingBox bbox = sop.AxisAlignedBoundingBox; float minX = bbox.center.x - bbox.size.x / 2; @@ -5378,13 +5928,16 @@ public void HighlightObject( lineRenderer.SetWidth(start: lineWidth, end: lineWidth); lineRenderer.positionCount = 5; - lineRenderer.SetPositions(new Vector3[] { - new Vector3(minX, height.Value, minZ), - new Vector3(minX, height.Value, maxZ), - new Vector3(maxX, height.Value, maxZ), - new Vector3(maxX, height.Value, minZ), - new Vector3(minX, height.Value, minZ), - }); + lineRenderer.SetPositions( + new Vector3[] + { + new Vector3(minX, height.Value, minZ), + new Vector3(minX, height.Value, maxZ), + new Vector3(maxX, height.Value, maxZ), + new Vector3(maxX, height.Value, minZ), + new Vector3(minX, height.Value, minZ), + } + ); actionFinished(true); } @@ -5431,7 +5984,11 @@ public void VisualizePath( GameObject endGo; if (parent == null) { parent = new GameObject(pathName); - endGo = Instantiate(DebugTargetPointPrefab, path[path.Count() - 1], Quaternion.identity); + endGo = Instantiate( + DebugTargetPointPrefab, + path[path.Count() - 1], + Quaternion.identity + ); endGo.name = "End"; endGo.transform.parent = parent.transform; if (endText != null) { @@ -5459,7 +6016,6 @@ public void VisualizePath( } } - var lineRenderer = go.GetComponentInChildren(); if (pathGradient != null && pathGradient.colorKeys.Length > 0) { @@ -5476,14 +6032,16 @@ public void VisualizePath( // this one is used for in-editor debug draw, currently calls to this are commented out private void VisualizePath(Vector3 startPosition, NavMeshPath path) { var pathDistance = 0.0; - #if UNITY_EDITOR - Debug.Log($"Visualize Path, corner lenght: {path.corners.Length}"); - #endif +#if UNITY_EDITOR + Debug.Log($"Visualize Path, corner lenght: {path.corners.Length}"); +#endif for (int i = 0; i < path.corners.Length - 1; i++) { Debug.DrawLine(path.corners[i], path.corners[i + 1], Color.red, 5.0f); - #if UNITY_EDITOR - Debug.Log("P i:" + i + " : " + path.corners[i] + " i+1:" + i + 1 + " : " + path.corners[i]); - #endif +#if UNITY_EDITOR + Debug.Log( + "P i:" + i + " : " + path.corners[i] + " i+1:" + i + 1 + " : " + path.corners[i] + ); +#endif pathDistance += Vector3.Distance(path.corners[i], path.corners[i + 1]); } @@ -5499,7 +6057,12 @@ private void VisualizePath(Vector3 startPosition, NavMeshPath path) { private string[] objectTypeToObjectIds(string objectTypeString) { List objectIds = new List(); try { - SimObjType objectType = (SimObjType)Enum.Parse(typeof(SimObjType), objectTypeString.Replace(" ", String.Empty), true); + SimObjType objectType = (SimObjType) + Enum.Parse( + typeof(SimObjType), + objectTypeString.Replace(" ", String.Empty), + true + ); foreach (var s in physicsSceneManager.ObjectIdToSimObjPhysics) { if (s.Value.ObjType == objectType) { objectIds.Add(s.Value.objectID); @@ -5531,6 +6094,7 @@ protected SimObjPhysics getSimObjectFromId(string objectId) { return sop; } + private SimObjPhysics getSimObjectFromTypeOrId(string objectType, string objectId) { if (!String.IsNullOrEmpty(objectType) && String.IsNullOrEmpty(objectId)) { var ids = objectTypeToObjectIds(objectType); @@ -5583,18 +6147,25 @@ public string objectNavExpertAction( SimObjPhysics sop = getSimObjectFromTypeOrId(objectType, objectId); path = getShortestPath(sop, true, navMeshIds: navMeshIds); visibilityTest = () => objectIsWithinViewport(sop); - } - else { + } else { var startPosition = this.transform.position; var startRotation = this.transform.rotation; - SafelyComputeFirstNavMeshPath(startPosition, position.Value, path, DefaultAllowedErrorInShortestPath, navMeshIds, sampleFromNavmesh: sampleFromNavmesh); + SafelyComputeFirstNavMeshPath( + startPosition, + position.Value, + path, + DefaultAllowedErrorInShortestPath, + navMeshIds, + sampleFromNavmesh: sampleFromNavmesh + ); visibilityTest = () => true; } if (path.status == UnityEngine.AI.NavMeshPathStatus.PathComplete) { - int parts = (int) Math.Round(360f / rotateStepDegrees); + int parts = (int)Math.Round(360f / rotateStepDegrees); if (Math.Abs((parts * 1.0f) - 360f / rotateStepDegrees) > 1e-5) { - errorMessage = "Invalid rotate step degrees for agent, must divide 360 without a remainder."; + errorMessage = + "Invalid rotate step degrees for agent, must divide 360 without a remainder."; return null; } int numLeft = parts / 2; @@ -5614,9 +6185,14 @@ public string objectNavExpertAction( for (int i = -numLeft; i <= numRight; i++) { transform.Rotate(0.0f, i * rotateStepDegrees, 0.0f); for (int horizon = -1; horizon <= 2; horizon++) { - m_Camera.transform.localEulerAngles = new Vector3(30f * horizon, 0.0f, 0.0f); + m_Camera.transform.localEulerAngles = new Vector3( + 30f * horizon, + 0.0f, + 0.0f + ); if (visibilityTest()) { - int numActions = Math.Abs(i) + Math.Abs(horizon - (int)(startCameraRot.x / 30f)); + int numActions = + Math.Abs(i) + Math.Abs(horizon - (int)(startCameraRot.x / 30f)); if (numActions < bestNumActions) { bestNumActions = numActions; relRotate = i; @@ -5666,7 +6242,9 @@ public string objectNavExpertAction( bool couldMove = moveInDirection(this.transform.forward * gridSize); if (couldMove) { - float newDistance = Math.Abs(nextCorner.x - transform.position.x) + Math.Abs(nextCorner.z - transform.position.z); + float newDistance = + Math.Abs(nextCorner.x - transform.position.x) + + Math.Abs(nextCorner.z - transform.position.z); if (newDistance + 1e-6 < bestDistance) { bestDistance = newDistance; whichBest = i; @@ -5679,7 +6257,8 @@ public string objectNavExpertAction( } if (bestDistance >= 1000f) { - errorMessage = "Can't seem to move in any direction. Error messages: " + errorMessages; + errorMessage = + "Can't seem to move in any direction. Error messages: " + errorMessages; return null; } @@ -5710,7 +6289,12 @@ public void ObjectNavExpertAction( Vector3? position = null, IEnumerable navMeshIds = null ) { - string action = objectNavExpertAction(objectId, objectType, position, navMeshIds: navMeshIds); + string action = objectNavExpertAction( + objectId, + objectType, + position, + navMeshIds: navMeshIds + ); if (action != null) { actionFinished(true, action); @@ -5722,10 +6306,10 @@ public void ObjectNavExpertAction( } public UnityEngine.AI.NavMeshPath getShortestPath( - SimObjPhysics sop, - bool useAgentTransform, - ServerAction action = null, - IEnumerable navMeshIds = null, + SimObjPhysics sop, + bool useAgentTransform, + ServerAction action = null, + IEnumerable navMeshIds = null, bool sampleFromNavmesh = true ) { var startPosition = this.transform.position; @@ -5735,10 +6319,16 @@ public UnityEngine.AI.NavMeshPath getShortestPath( startRotation = Quaternion.Euler(action.rotation); } - return GetSimObjectNavMeshTarget(sop, startPosition, startRotation, DefaultAllowedErrorInShortestPath, navMeshIds: navMeshIds, sampleFromNavmesh: sampleFromNavmesh); + return GetSimObjectNavMeshTarget( + sop, + startPosition, + startRotation, + DefaultAllowedErrorInShortestPath, + navMeshIds: navMeshIds, + sampleFromNavmesh: sampleFromNavmesh + ); } - private void getShortestPath( string objectType, string objectId, @@ -5749,7 +6339,14 @@ private void getShortestPath( bool sampleFromNavmesh = true ) { SimObjPhysics sop = getSimObjectFromTypeOrId(objectType, objectId); - var path = GetSimObjectNavMeshTarget(sop, startPosition, startRotation, allowedError, navMeshIds: navMeshIds, sampleFromNavmesh: sampleFromNavmesh); + var path = GetSimObjectNavMeshTarget( + sop, + startPosition, + startRotation, + allowedError, + navMeshIds: navMeshIds, + sampleFromNavmesh: sampleFromNavmesh + ); // VisualizePath(startPosition, path); actionFinishedEmit(success: true, actionReturn: path); } @@ -5763,7 +6360,15 @@ public void GetShortestPath( IEnumerable navMeshIds = null, bool sampleFromNavmesh = true ) { - getShortestPath(objectType: objectType, objectId: objectId, startPosition: position, startRotation: Quaternion.Euler(rotation), allowedError: allowedError, navMeshIds: navMeshIds, sampleFromNavmesh: sampleFromNavmesh); + getShortestPath( + objectType: objectType, + objectId: objectId, + startPosition: position, + startRotation: Quaternion.Euler(rotation), + allowedError: allowedError, + navMeshIds: navMeshIds, + sampleFromNavmesh: sampleFromNavmesh + ); } // public void GetShortestPathNew( @@ -5771,7 +6376,7 @@ public void GetShortestPath( // Vector3 rotation, // string objectId = null, // float allowedError = DefaultAllowedErrorInShortestPath, - // int navMeshId = + // int navMeshId = // ) { // Debug.Log("----- GetShortestPathNew"); // getShortestPath(objectType: null, objectId: objectId, startPosition: position, startRotation: Quaternion.Euler(rotation), allowedError: allowedError, navMeshId: navMeshId); @@ -5796,7 +6401,15 @@ public void GetShortestPath( bool sampleFromNavmesh = true ) { // this.transform.position = new Vector3(this.transform.position.x, 0.01f, this.transform.position.z); - getShortestPath(objectType, objectId, position, Quaternion.Euler(Vector3.zero), allowedError, navMeshIds, sampleFromNavmesh: sampleFromNavmesh); + getShortestPath( + objectType, + objectId, + position, + Quaternion.Euler(Vector3.zero), + allowedError, + navMeshIds, + sampleFromNavmesh: sampleFromNavmesh + ); } public void GetShortestPath( @@ -5806,7 +6419,15 @@ public void GetShortestPath( IEnumerable navMeshIds = null, bool sampleFromNavmesh = true ) { - getShortestPath(objectType, objectId, this.transform.position, this.transform.rotation, allowedError, navMeshIds, sampleFromNavmesh: sampleFromNavmesh); + getShortestPath( + objectType, + objectId, + this.transform.position, + this.transform.rotation, + allowedError, + navMeshIds, + sampleFromNavmesh: sampleFromNavmesh + ); } private bool GetPathFromReachablePositions( @@ -5814,8 +6435,8 @@ private bool GetPathFromReachablePositions( Vector3 targetPosition, Transform agentTransform, string targetSimObjectId, - UnityEngine.AI.NavMeshPath path) { - + UnityEngine.AI.NavMeshPath path + ) { Vector3 fixedPosition = new Vector3(float.MinValue, float.MinValue, float.MinValue); // bool success = false; var PhysicsController = this; @@ -5831,28 +6452,60 @@ private bool GetPathFromReachablePositions( } } - var pathSuccess = UnityEngine.AI.NavMesh.CalculatePath(agentTransform.position, fixedPosition, UnityEngine.AI.NavMesh.AllAreas, path); + var pathSuccess = UnityEngine.AI.NavMesh.CalculatePath( + agentTransform.position, + fixedPosition, + UnityEngine.AI.NavMesh.AllAreas, + path + ); return pathSuccess; } - protected Collider[] overlapCollider(BoxCollider box, Vector3 newCenter, float rotateBy, int layerMask) { - Vector3 center, halfExtents; + protected Collider[] overlapCollider( + BoxCollider box, + Vector3 newCenter, + float rotateBy, + int layerMask + ) { + Vector3 center, + halfExtents; Quaternion orientation; box.ToWorldSpaceBox(out center, out halfExtents, out orientation); orientation = Quaternion.Euler(0f, rotateBy, 0f) * orientation; - return Physics.OverlapBox(newCenter, halfExtents, orientation, layerMask, QueryTriggerInteraction.Ignore); + return Physics.OverlapBox( + newCenter, + halfExtents, + orientation, + layerMask, + QueryTriggerInteraction.Ignore + ); } - protected Collider[] overlapCollider(SphereCollider sphere, Vector3 newCenter, int layerMask) { + protected Collider[] overlapCollider( + SphereCollider sphere, + Vector3 newCenter, + int layerMask + ) { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); - return Physics.OverlapSphere(newCenter, radius, layerMask, QueryTriggerInteraction.Ignore); + return Physics.OverlapSphere( + newCenter, + radius, + layerMask, + QueryTriggerInteraction.Ignore + ); } - protected Collider[] overlapCollider(CapsuleCollider capsule, Vector3 newCenter, float rotateBy, int layerMask) { - Vector3 point0, point1; + protected Collider[] overlapCollider( + CapsuleCollider capsule, + Vector3 newCenter, + float rotateBy, + int layerMask + ) { + Vector3 point0, + point1; float radius; capsule.ToWorldSpaceCapsule(out point0, out point1, out radius); @@ -5866,7 +6519,13 @@ protected Collider[] overlapCollider(CapsuleCollider capsule, Vector3 newCenter, point0 = rotator * point0 + newCenter; point1 = rotator * point1 + newCenter; - return Physics.OverlapCapsule(point0, point1, radius, layerMask, QueryTriggerInteraction.Ignore); + return Physics.OverlapCapsule( + point0, + point1, + radius, + layerMask, + QueryTriggerInteraction.Ignore + ); } protected bool handObjectCanFitInPosition(Vector3 newAgentPosition, float rotation) { @@ -5877,12 +6536,18 @@ protected bool handObjectCanFitInPosition(Vector3 newAgentPosition, float rotati SimObjPhysics soInHand = ItemInHand.GetComponent(); Vector3 handObjPosRelAgent = - Quaternion.Euler(0, rotation - transform.eulerAngles.y, 0) * - (transform.position - ItemInHand.transform.position); + Quaternion.Euler(0, rotation - transform.eulerAngles.y, 0) + * (transform.position - ItemInHand.transform.position); Vector3 newHandPosition = handObjPosRelAgent + newAgentPosition; - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); foreach (CapsuleCollider cc in soInHand.GetComponentsInChildren()) { foreach (Collider c in overlapCollider(cc, newHandPosition, rotation, layerMask)) { if (!hasAncestor(c.transform.gameObject, gameObject)) { @@ -5921,13 +6586,15 @@ public RaycastHit[] capsuleCastAllForAgent( int layerMask ) { // make sure to offset this by capsuleCollider.center since we adjust the capsule size vertically, and in some cases horizontally - Vector3 startPositionCapsuleCenter = startPosition + capsule.transform.TransformDirection(capsule.center); + Vector3 startPositionCapsuleCenter = + startPosition + capsule.transform.TransformDirection(capsule.center); float radius = capsule.radius + skinWidth; float innerHeight = capsule.height / 2.0f - radius; Vector3 point1 = startPositionCapsuleCenter + new Vector3(0, innerHeight, 0); - Vector3 point2 = startPositionCapsuleCenter + new Vector3(0, -innerHeight + skinWidth, 0); - + Vector3 point2 = + startPositionCapsuleCenter + new Vector3(0, -innerHeight + skinWidth, 0); + return Physics.CapsuleCastAll( point1: point1, point2: point2, @@ -5943,14 +6610,23 @@ protected bool isAgentCapsuleColliding( HashSet collidersToIgnore = null, bool includeErrorMessage = false ) { - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); foreach ( Collider c in PhysicsExtensions.OverlapCapsule( - GetComponent(), layerMask, QueryTriggerInteraction.Ignore + GetComponent(), + layerMask, + QueryTriggerInteraction.Ignore ) ) { - if ((!hasAncestor(c.transform.gameObject, gameObject)) && ( - collidersToIgnore == null || !collidersToIgnoreDuringMovement.Contains(c)) + if ( + (!hasAncestor(c.transform.gameObject, gameObject)) + && (collidersToIgnore == null || !collidersToIgnoreDuringMovement.Contains(c)) ) { if (includeErrorMessage) { SimObjPhysics sop = ancestorSimObjPhysics(c.gameObject); @@ -5978,14 +6654,23 @@ protected bool isAgentBoxColliding( HashSet collidersToIgnore = null, bool includeErrorMessage = false ) { - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); foreach ( Collider c in PhysicsExtensions.OverlapBox( - transformWithBoxCollider.GetComponent(), layerMask, QueryTriggerInteraction.Ignore + transformWithBoxCollider.GetComponent(), + layerMask, + QueryTriggerInteraction.Ignore ) ) { - if ((!hasAncestor(c.transform.gameObject, gameObject)) && ( - collidersToIgnore == null || !collidersToIgnoreDuringMovement.Contains(c)) + if ( + (!hasAncestor(c.transform.gameObject, gameObject)) + && (collidersToIgnore == null || !collidersToIgnoreDuringMovement.Contains(c)) ) { if (includeErrorMessage) { SimObjPhysics sop = ancestorSimObjPhysics(c.gameObject); @@ -6009,12 +6694,28 @@ Collider c in PhysicsExtensions.OverlapBox( } protected Collider[] objectsCollidingWithAgent() { - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); - return PhysicsExtensions.OverlapCapsule(GetComponent(), layerMask, QueryTriggerInteraction.Ignore); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); + return PhysicsExtensions.OverlapCapsule( + GetComponent(), + layerMask, + QueryTriggerInteraction.Ignore + ); } - public virtual RaycastHit[] CastBodyTrayectory(Vector3 startPosition, Vector3 direction, float skinWidth, float moveMagnitude, int layerMask, CapsuleData cachedCapsule) { - + public virtual RaycastHit[] CastBodyTrayectory( + Vector3 startPosition, + Vector3 direction, + float skinWidth, + float moveMagnitude, + int layerMask, + CapsuleData cachedCapsule + ) { return capsuleCastAllForAgent( capsule: cachedCapsule, skinWidth: skinWidth, @@ -6035,7 +6736,8 @@ public bool getReachablePositionToObjectVisible( float sw = m_CharacterController.skinWidth; Queue pointsQueue = new Queue(); pointsQueue.Enqueue(transform.position); - Vector3[] directions = { + Vector3[] directions = + { new Vector3(1.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 1.0f), new Vector3(-1.0f, 0.0f, 0.0f), @@ -6045,7 +6747,13 @@ public bool getReachablePositionToObjectVisible( HashSet goodPoints = new HashSet(); HashSet seenPoints = new HashSet(); - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); int stepsTaken = 0; pos = Vector3.negativeInfinity; while (pointsQueue.Count != 0) { @@ -6067,7 +6775,9 @@ public bool getReachablePositionToObjectVisible( return true; } - HashSet objectsAlreadyColliding = new HashSet(objectsCollidingWithAgent()); + HashSet objectsAlreadyColliding = new HashSet( + objectsCollidingWithAgent() + ); foreach (Vector3 d in directions) { Vector3 newPosition = p + d * gridSize * gridMultiplier; if (seenPoints.Contains(newPosition)) { @@ -6086,10 +6796,12 @@ public bool getReachablePositionToObjectVisible( bool shouldEnqueue = true; foreach (RaycastHit hit in hits) { - if (!ancestorHasName(hit.transform.gameObject, "Floor") && + if ( + !ancestorHasName(hit.transform.gameObject, "Floor") + && // hit.transform.gameObject.name != "Floor" && // Dont know why this worked on procedural - !ancestorHasName(hit.transform.gameObject, "FPSController") && - !objectsAlreadyColliding.Contains(hit.collider) + !ancestorHasName(hit.transform.gameObject, "FPSController") + && !objectsAlreadyColliding.Contains(hit.collider) ) { shouldEnqueue = false; break; @@ -6102,18 +6814,23 @@ public bool getReachablePositionToObjectVisible( bool inBounds = agentManager.SceneBounds.Contains(newPosition); if (errorMessage == "" && !inBounds) { - errorMessage = "In " + - UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + - ", position " + newPosition.ToString() + - " can be reached via capsule cast but is beyond the scene bounds."; + errorMessage = + "In " + + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + + ", position " + + newPosition.ToString() + + " can be reached via capsule cast but is beyond the scene bounds."; } - shouldEnqueue = shouldEnqueue && inBounds && ( - handObjectCanFitInPosition(newPosition, 0.0f) || - handObjectCanFitInPosition(newPosition, 90.0f) || - handObjectCanFitInPosition(newPosition, 180.0f) || - handObjectCanFitInPosition(newPosition, 270.0f) - ); + shouldEnqueue = + shouldEnqueue + && inBounds + && ( + handObjectCanFitInPosition(newPosition, 0.0f) + || handObjectCanFitInPosition(newPosition, 90.0f) + || handObjectCanFitInPosition(newPosition, 180.0f) + || handObjectCanFitInPosition(newPosition, 270.0f) + ); if (shouldEnqueue) { pointsQueue.Enqueue(newPosition); #if UNITY_EDITOR @@ -6162,13 +6879,16 @@ private UnityEngine.AI.NavMeshPath GetSimObjectNavMeshTarget( agentTransform.position = initialPosition; agentTransform.rotation = initialRotation; - bool wasObjectVisible = getReachablePositionToObjectVisible(targetSimObject, out fixedPosition); + bool wasObjectVisible = getReachablePositionToObjectVisible( + targetSimObject, + out fixedPosition + ); agentTransform.position = originalAgentPosition; agentTransform.rotation = originalAgentRotation; m_Camera.transform.rotation = originalCameraRotation; - if(!wasObjectVisible) { + if (!wasObjectVisible) { throw new InvalidOperationException( $"Target object {targetSOP.objectID} is not visible on navigation path given current agent parameters: maxVisibleDistance ({maxVisibleDistance}), gridSize ({gridSize}), fieldOfView ({m_Camera.fieldOfView}), camera width ({Screen.width}), camera height ({Screen.height})" ); @@ -6232,17 +6952,20 @@ protected void SafelyComputeFirstNavMeshPath( string debugTargetObjectId = "", bool sampleFromNavmesh = true ) { - var navMeshAgent = this.GetComponentInChildren(); var navmeshSurfaces = GameObject.FindObjectsOfType(); // Debug.Log($"---NavMeshSurfaceExtended size {navmeshSurfaces.Count()}"); // Debug.Log($"---NavMeshSurface size {GameObject.FindObjectsOfType().Count()}"); var defaultNavmeshIds = new List() { null }; if (navmeshSurfaces.Count() > 0) { - defaultNavmeshIds = new List() { NavMeshSurfaceExtended.activeSurfaces[0].agentTypeID }; + defaultNavmeshIds = new List() + { + NavMeshSurfaceExtended.activeSurfaces[0].agentTypeID + }; } - IEnumerable navMeshIdsWIthDefault = navMeshIds != null ? navMeshIds.Select(x => (int?)x) : defaultNavmeshIds; + IEnumerable navMeshIdsWIthDefault = + navMeshIds != null ? navMeshIds.Select(x => (int?)x) : defaultNavmeshIds; foreach (var navmeshId in navMeshIdsWIthDefault) { SafelyComputeNavMeshPath( @@ -6273,20 +6996,23 @@ protected void SafelyComputeNavMeshPath( UnityEngine.AI.NavMeshAgent navmehsAgent = null, // for speedup NavMeshSurfaceExtended[] navmeshSurfaces = null ) { - - var navMeshAgent = navmehsAgent ?? this.GetComponentInChildren(); + var navMeshAgent = + navmehsAgent ?? this.GetComponentInChildren(); navMeshAgent.enabled = true; - navmeshSurfaces = navmeshSurfaces ?? GameObject.FindObjectsOfType(); + navmeshSurfaces = + navmeshSurfaces ?? GameObject.FindObjectsOfType(); - var activeNavMesh = ProceduralTools.activateOnlyNavmeshSurface(navmeshSurfaces, navMeshId); + var activeNavMesh = ProceduralTools.activateOnlyNavmeshSurface( + navmeshSurfaces, + navMeshId + ); // var yPos = activeNavMesh.buildSettings.agentHeight / 2.0f; var pathStartPosition = new Vector3(start.x, start.y, start.z); var pathTargetPosition = new Vector3(target.x, start.y, target.z); if (sampleFromNavmesh) { - float floorY = Math.Min( getFloorY(start.x, start.y, start.z), getFloorY(target.x, target.y, target.z) @@ -6295,16 +7021,21 @@ protected void SafelyComputeNavMeshPath( Debug.Log($"----- Navmesh floorY {floorY.ToString("F6")}"); Vector3 targetPositionWithFloorY = new Vector3(target.x, floorY, target.z); - NavMeshHit startHit; // startPosition.y = 0.167557f; bool startWasHit = UnityEngine.AI.NavMesh.SamplePosition( - startPositionWithFloorY, out startHit, Math.Max(0.2f, allowedError), UnityEngine.AI.NavMesh.AllAreas + startPositionWithFloorY, + out startHit, + Math.Max(0.2f, allowedError), + UnityEngine.AI.NavMesh.AllAreas ); NavMeshHit targetHit; bool targetWasHit = UnityEngine.AI.NavMesh.SamplePosition( - targetPositionWithFloorY, out targetHit, Math.Max(0.2f, allowedError), UnityEngine.AI.NavMesh.AllAreas + targetPositionWithFloorY, + out targetHit, + Math.Max(0.2f, allowedError), + UnityEngine.AI.NavMesh.AllAreas ); pathStartPosition = startHit.position; @@ -6326,29 +7057,43 @@ protected void SafelyComputeNavMeshPath( float startOffset = Vector3.Distance( pathStartPosition, - new Vector3(startPositionWithFloorY.x, startHit.position.y, startPositionWithFloorY.z) + new Vector3( + startPositionWithFloorY.x, + startHit.position.y, + startPositionWithFloorY.z + ) ); float targetOffset = Vector3.Distance( pathTargetPosition, - new Vector3(targetPositionWithFloorY.x, targetHit.position.y, targetPositionWithFloorY.z) + new Vector3( + targetPositionWithFloorY.x, + targetHit.position.y, + targetPositionWithFloorY.z + ) ); if (startOffset > allowedError && targetOffset > allowedError) { this.GetComponentInChildren().enabled = false; - var extraDebug = !string.IsNullOrEmpty(debugTargetObjectId) ? $" For objectId: '{debugTargetObjectId}'" : ""; + var extraDebug = !string.IsNullOrEmpty(debugTargetObjectId) + ? $" For objectId: '{debugTargetObjectId}'" + : ""; throw new InvalidOperationException( - $"Closest point on NavMesh was too far from the agent: " + - $" (startPosition={startPositionWithFloorY.ToString("F3")}," + - $" closest navmesh position {pathStartPosition.ToString("F3")}) and" + - $" (targetPosition={targetPositionWithFloorY.ToString("F3")}," + - $" closest navmesh position {pathTargetPosition.ToString("F3")})." + - $"{extraDebug}" + $"Closest point on NavMesh was too far from the agent: " + + $" (startPosition={startPositionWithFloorY.ToString("F3")}," + + $" closest navmesh position {pathStartPosition.ToString("F3")}) and" + + $" (targetPosition={targetPositionWithFloorY.ToString("F3")}," + + $" closest navmesh position {pathTargetPosition.ToString("F3")})." + + $"{extraDebug}" ); } } - + #if UNITY_EDITOR - Debug.Log($"Attempting to find path from {pathStartPosition.ToString("F6")} to {pathTargetPosition.ToString("F6")}."); - Debug.Log($"NavmeshAgent start position {navMeshAgent.transform.position.ToString("F6")}"); + Debug.Log( + $"Attempting to find path from {pathStartPosition.ToString("F6")} to {pathTargetPosition.ToString("F6")}." + ); + Debug.Log( + $"NavmeshAgent start position {navMeshAgent.transform.position.ToString("F6")}" + ); #endif var prevPosition = this.transform.position; @@ -6356,20 +7101,25 @@ protected void SafelyComputeNavMeshPath( this.transform.position = pathStartPosition; // navMeshAgent.radius = 2.0f; Physics.SyncTransforms(); - // navMeshAgent.agentTypeID = - + // navMeshAgent.agentTypeID = + // Useless more of unity's broken APIS for runtime >:( // NavMeshQueryFilter queryFilter = new NavMeshQueryFilter() { // agentTypeID = queryAgentId, // areaMask = navMesh.layerMask // }; bool pathSuccess = UnityEngine.AI.NavMesh.CalculatePath( - pathStartPosition, pathTargetPosition, UnityEngine.AI.NavMesh.AllAreas, path + pathStartPosition, + pathTargetPosition, + UnityEngine.AI.NavMesh.AllAreas, + path ); - #if UNITY_EDITOR - Debug.Log($"-----Navmesh Pathsuccess {pathSuccess} path status: {path.status} corner lenght {path.corners.Count()} corners: {string.Join(", ", path.corners.Select(c => c.ToString("F6")))}"); - #endif +#if UNITY_EDITOR + Debug.Log( + $"-----Navmesh Pathsuccess {pathSuccess} path status: {path.status} corner lenght {path.corners.Count()} corners: {string.Join(", ", path.corners.Select(c => c.ToString("F6")))}" + ); +#endif ProceduralTools.activateAllNavmeshSurfaces(navmeshSurfaces); @@ -6378,19 +7128,20 @@ protected void SafelyComputeNavMeshPath( // startHit.position, targetHit.position, UnityEngine.AI.NavMesh.AllAreas, path // ); if (path.status != UnityEngine.AI.NavMeshPathStatus.PathComplete) { - var extraDebug = !string.IsNullOrEmpty(debugTargetObjectId) ? $" For objectId: '{debugTargetObjectId}'" : ""; + var extraDebug = !string.IsNullOrEmpty(debugTargetObjectId) + ? $" For objectId: '{debugTargetObjectId}'" + : ""; this.GetComponentInChildren().enabled = false; throw new InvalidOperationException( - $"Could not find path between {pathStartPosition.ToString("F6")}" + - $" and {pathTargetPosition.ToString("F6")} using the NavMesh." + - $"{extraDebug}" + $"Could not find path between {pathStartPosition.ToString("F6")}" + + $" and {pathTargetPosition.ToString("F6")} using the NavMesh." + + $"{extraDebug}" ); } #if UNITY_EDITOR VisualizePath(pathStartPosition, path); #endif this.GetComponentInChildren().enabled = false; - } private void randomizeSmoothness(string objectId) { @@ -6410,7 +7161,6 @@ private void randomizeSmoothness(string objectId) { public void MakeAllObjectsUnbreakable() { UpdateBreakabilityOfAllObjects(true); - } public void MakeAllObjectsBreakable() { @@ -6418,17 +7168,22 @@ public void MakeAllObjectsBreakable() { } private void UpdateBreakabilityOfAllObjects(bool isUnbreakable) { - SimObjPhysics[] simObjs = GameObject.FindObjectsOfType(typeof(SimObjPhysics)) as SimObjPhysics[]; + SimObjPhysics[] simObjs = + GameObject.FindObjectsOfType(typeof(SimObjPhysics)) as SimObjPhysics[]; if (simObjs != null) { foreach (SimObjPhysics sop in simObjs) { - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBreak)) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBreak + ) + ) { sop.GetComponentInChildren().Unbreakable = isUnbreakable; } } } actionFinished(true); } - + public void RandomizeSmoothness(string objectId) { randomizeSmoothness(objectId: objectId); actionFinished(success: true); @@ -6445,25 +7200,41 @@ public void RandomizeSmoothness(string[] objectIds) { } public void GetShortestPathToPoint( - Vector3 position, Vector3 target, float allowedError = DefaultAllowedErrorInShortestPath, IEnumerable navMeshIds = null, bool sampleFromNavmesh = true + Vector3 position, + Vector3 target, + float allowedError = DefaultAllowedErrorInShortestPath, + IEnumerable navMeshIds = null, + bool sampleFromNavmesh = true ) { var path = new UnityEngine.AI.NavMeshPath(); - SafelyComputeFirstNavMeshPath(position, target, path, allowedError, navMeshIds, sampleFromNavmesh: sampleFromNavmesh); + SafelyComputeFirstNavMeshPath( + position, + target, + path, + allowedError, + navMeshIds, + sampleFromNavmesh: sampleFromNavmesh + ); actionFinished(success: true, actionReturn: path); } public void GetShortestPathToPoint( Vector3 target, float allowedError = DefaultAllowedErrorInShortestPath, - IEnumerable navMeshIds = null, - bool sampleFromNavmesh = true + IEnumerable navMeshIds = null, + bool sampleFromNavmesh = true ) { var startPosition = this.transform.position; - GetShortestPathToPoint(startPosition, target, allowedError, navMeshIds, sampleFromNavmesh); + GetShortestPathToPoint( + startPosition, + target, + allowedError, + navMeshIds, + sampleFromNavmesh + ); } public void VisualizeShortestPaths(ServerAction action) { - SimObjPhysics sop = getSimObjectFromTypeOrId(action.objectType, action.objectId); if (sop == null) { actionFinished(false); @@ -6480,7 +7251,13 @@ public void VisualizeShortestPaths(ServerAction action) { var textMesh = go.GetComponentInChildren(); textMesh.text = i.ToString(); - var path = GetSimObjectNavMeshTarget(sop, pos, Quaternion.identity, 0.1f, sampleFromNavmesh: action.sampleFromNavmesh); + var path = GetSimObjectNavMeshTarget( + sop, + pos, + Quaternion.identity, + 0.1f, + sampleFromNavmesh: action.sampleFromNavmesh + ); var lineRenderer = go.GetComponentInChildren(); @@ -6494,14 +7271,20 @@ public void VisualizeShortestPaths(ServerAction action) { if (path.status == UnityEngine.AI.NavMeshPathStatus.PathComplete) { lineRenderer.positionCount = path.corners.Length; - lineRenderer.SetPositions(path.corners.Select(c => new Vector3(c.x, gridVisualizeY + 0.005f, c.z)).ToArray()); + lineRenderer.SetPositions( + path.corners.Select(c => new Vector3(c.x, gridVisualizeY + 0.005f, c.z)) + .ToArray() + ); } } actionFinished(true, results.ToArray()); } - public void VisualizeWaypoints(List waypoints, bool grid = false, Color? gridColor = null) { - + public void VisualizeWaypoints( + List waypoints, + bool grid = false, + Color? gridColor = null + ) { getReachablePositions(1.0f, 10000, grid, gridColor); for (var i = 0; i < waypoints.Count; i++) { @@ -6529,36 +7312,38 @@ public void CameraCrack(int randomSeed = 0) { } public void SimObjPhysicsTypeIsReceptacle(float receptacleRatioTolerance = 0.001f) { - - var sops = GameObject.FindObjectOfType() + var sops = GameObject + .FindObjectOfType() .GetPrefabs() .Select(a => a.GetComponent()) .Where(sop => sop != null); - - var categoriesCount = sops.GroupBy(sop => sop.ObjType).ToDictionary(g => g.Key, g => g.Count()); + var categoriesCount = sops.GroupBy(sop => sop.ObjType) + .ToDictionary(g => g.Key, g => g.Count()); - var result = sops - .Where(sop => sop.SecondaryProperties.Contains(SimObjSecondaryProperty.Receptacle)) + var result = sops.Where(sop => + sop.SecondaryProperties.Contains(SimObjSecondaryProperty.Receptacle) + ) .GroupBy(sop => sop.ObjType) .Select(g => new { simObjType = g.Key.ToString(), totalInCategory = categoriesCount[g.Key], totalIsReceptacle = categoriesCount[g.Key] }) - .Where( - s => s.totalIsReceptacle / (0.0f + s.totalIsReceptacle) > receptacleRatioTolerance + .Where(s => + s.totalIsReceptacle / (0.0f + s.totalIsReceptacle) > receptacleRatioTolerance ) .Select(s => s.simObjType); Debug.Log(result); - actionFinished( - true, - actionReturn: result.ToList() - ); + actionFinished(true, actionReturn: result.ToList()); } - public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresMax = 0.075f, float worldOffset=-100f) { + public static void TryToAddReceptacleTriggerBox( + SimObjPhysics sop, + float yThresMax = 0.075f, + float worldOffset = -100f + ) { if (sop == null) { throw new NotImplementedException( $"Adding receptacle trigger box is only possible the active game object, has an associated SimObjPhysics script." @@ -6624,7 +7409,7 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM for (int iX = 0; iX < n; iX++) { float x = xMin + iX * (xMax - xMin) / (n - 1.0f); // Debug.Log($"x val: {x}"); - + var yVals = new List(); for (int iZ = 0; iZ < n; iZ++) { float z = zMin + iZ * (zMax - zMin) / (n - 1.0f); @@ -6632,14 +7417,16 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM // Debug.Log($"Pos: ({iX}, {iZ}), vals ({x}, {z})"); RaycastHit hit; - if (Physics.Raycast( - origin: new Vector3(x, yStart, z), - direction: new Vector3(0f, -1f, 0f), - hitInfo: out hit, - maxDistance: 10f, - layerMask: LayerMask.GetMask("SimObjVisible"), - queryTriggerInteraction: QueryTriggerInteraction.Ignore - )) { + if ( + Physics.Raycast( + origin: new Vector3(x, yStart, z), + direction: new Vector3(0f, -1f, 0f), + hitInfo: out hit, + maxDistance: 10f, + layerMask: LayerMask.GetMask("SimObjVisible"), + queryTriggerInteraction: QueryTriggerInteraction.Ignore + ) + ) { // Debug.Log($"HITS {hit.point.y}"); // Debug.DrawLine(hit.point, hit.point + new Vector3(0f, 0.1f, 0f), Color.cyan, 15f); @@ -6654,11 +7441,12 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM } mat.Add(yVals); } - + Dictionary<(int, int), int> posToGroup = new Dictionary<(int, int), int>(); Dictionary groupToMaxYVal = new Dictionary(); Dictionary groupToMinYVal = new Dictionary(); - Dictionary> groupToPos = new Dictionary>(); + Dictionary> groupToPos = + new Dictionary>(); int nextGroup = 0; for (int iX = 0; iX < n; iX++) { @@ -6680,8 +7468,8 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM float otherMinYVal = groupToMinYVal[group]; if ( - Mathf.Abs(curYVal - otherMaxYVal) < yThres && - Mathf.Abs(curYVal - otherMinYVal) < yThres + Mathf.Abs(curYVal - otherMaxYVal) < yThres + && Mathf.Abs(curYVal - otherMinYVal) < yThres ) { posToGroup[(iX, iZ)] = group; groupToPos[group].Add((iX, iZ)); @@ -6697,8 +7485,8 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM float otherMinYVal = groupToMinYVal[group]; if ( - Mathf.Abs(curYVal - otherMaxYVal) < yThres && - Mathf.Abs(curYVal - otherMinYVal) < yThres + Mathf.Abs(curYVal - otherMaxYVal) < yThres + && Mathf.Abs(curYVal - otherMinYVal) < yThres ) { posToGroup[(iX, iZ)] = group; groupToPos[group].Add((iX, iZ)); @@ -6722,7 +7510,8 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM foreach (int group in groupToPos.Keys) { var posSet = new HashSet<(int, int)>(groupToPos[group]); - List<((int, int), (int, int))> rectangles = new List<((int, int), (int, int))>(); + List<((int, int), (int, int))> rectangles = + new List<((int, int), (int, int))>(); while (posSet.Count > 0) { (int, int) nextiXiZ = posSet.Min(); @@ -6766,7 +7555,15 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM } var vector3CornerLists = new List>(); - List colors = new List{Color.cyan, Color.yellow, Color.red, Color.magenta, Color.green, Color.blue}; + List colors = new List + { + Color.cyan, + Color.yellow, + Color.red, + Color.magenta, + Color.green, + Color.blue + }; int yar = -1; foreach (int group in groupToRectangles.Keys) { float y = groupToMinYVal[group]; @@ -6779,10 +7576,15 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM float startX = xMin + (start.Item1 - 0.5f) * (xMax - xMin) / (n - 1.0f); float endX = xMin + (end.Item1 + 0.5f) * (xMax - xMin) / (n - 1.0f); - float startZ = zMin + (start.Item2 - 0.5f) * (zMax - zMin) / (n - 1.0f); + float startZ = zMin + (start.Item2 - 0.5f) * (zMax - zMin) / (n - 1.0f); float endZ = zMin + (end.Item2 + 0.5f) * (zMax - zMin) / (n - 1.0f); - if (Math.Min(Math.Abs(start.Item1 - end.Item1), Math.Abs(start.Item2 - end.Item2)) <= 1) { + if ( + Math.Min( + Math.Abs(start.Item1 - end.Item1), + Math.Abs(start.Item2 - end.Item2) + ) <= 1 + ) { continue; } @@ -6814,7 +7616,7 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM go.transform.parent = sop.transform; } Physics.SyncTransforms(); - + int cornerListInd = 0; List boxGos = new List(); foreach (List cornerList in vector3CornerLists) { @@ -6830,7 +7632,10 @@ public static void TryToAddReceptacleTriggerBox(SimObjPhysics sop, float yThresM rtb.layer = LayerMask.NameToLayer("SimObjInvisible"); rtb.AddComponent(); BoxCollider bc = rtb.AddComponent(); - bc.center = (c0 + c1 + c2 + c3) * 0.25f - rtb.transform.position + new Vector3(0f, rtbYSize / 2.0f, 0f); + bc.center = + (c0 + c1 + c2 + c3) * 0.25f + - rtb.transform.position + + new Vector3(0f, rtbYSize / 2.0f, 0f); bc.size = c2 - c0 + new Vector3(0f, rtbYSize, 0f); bc.isTrigger = true; } @@ -6887,7 +7692,6 @@ string backTexturePath actionFinished(true); } - public ActionFinished CreateRuntimeAsset(ProceduralAsset asset) { var assetDb = GameObject.FindObjectOfType(); if (assetDb.ContainsAssetKey(asset.name)) { @@ -6903,20 +7707,20 @@ public ActionFinished CreateRuntimeAsset(ProceduralAsset asset) { name: asset.name, triangles: asset.triangles, uvs: asset.uvs, - albedoTexturePath: asset.albedoTexturePath , - metallicSmoothnessTexturePath: asset.metallicSmoothnessTexturePath , - normalTexturePath: asset.normalTexturePath , + albedoTexturePath: asset.albedoTexturePath, + metallicSmoothnessTexturePath: asset.metallicSmoothnessTexturePath, + normalTexturePath: asset.normalTexturePath, emissionTexturePath: asset.emissionTexturePath, - colliders: asset.colliders , + colliders: asset.colliders, physicalProperties: asset.physicalProperties, - visibilityPoints: asset.visibilityPoints , - annotations: asset.annotations , - receptacleCandidate: asset.receptacleCandidate , - yRotOffset: asset.yRotOffset , + visibilityPoints: asset.visibilityPoints, + annotations: asset.annotations, + receptacleCandidate: asset.receptacleCandidate, + yRotOffset: asset.yRotOffset, serializable: asset.serializable, parentTexturesDir: asset.parentTexturesDir ); - return new ActionFinished{ success = true, actionReturn = assetData}; + return new ActionFinished { success = true, actionReturn = assetData }; } public ActionFinished CreateRuntimeAsset( @@ -6934,26 +7738,43 @@ public ActionFinished CreateRuntimeAsset( toEmitState: true ); } - var validDirs = new List() { + var validDirs = new List() + { Application.persistentDataPath, Application.streamingAssetsPath }; - var supportedExtensions = new HashSet(){ - ".gz", ".msgpack", ".msgpack.gz", ".json" + var supportedExtensions = new HashSet() + { + ".gz", + ".msgpack", + ".msgpack.gz", + ".json" }; extension = !extension.StartsWith(".") ? $".{extension}" : extension; extension = extension.Trim(); if (!supportedExtensions.Contains(extension)) { - return new ActionFinished(success: false, errorMessage: $"Unsupported extension `{extension}`. Only supported: {string.Join(", ", supportedExtensions)}", actionReturn: null); + return new ActionFinished( + success: false, + errorMessage: $"Unsupported extension `{extension}`. Only supported: {string.Join(", ", supportedExtensions)}", + actionReturn: null + ); } var filename = $"{id}{extension}"; - var filepath = Path.GetFullPath(Path.Combine(dir, id, filename)); + var filepath = Path.GetFullPath(Path.Combine(dir, id, filename)); if (!File.Exists(filepath)) { - return new ActionFinished(success: false, actionReturn: null, errorMessage: $"Asset fiile '{filepath}' does not exist."); + return new ActionFinished( + success: false, + actionReturn: null, + errorMessage: $"Asset fiile '{filepath}' does not exist." + ); } // to support different - var presentStages = extension.Split('.').Reverse().Where(s => !string.IsNullOrEmpty(s)).ToArray(); + var presentStages = extension + .Split('.') + .Reverse() + .Where(s => !string.IsNullOrEmpty(s)) + .ToArray(); using FileStream rawFileStream = File.Open(filepath, FileMode.Open); using var resultStream = new MemoryStream(); @@ -6977,7 +7798,7 @@ public ActionFinished CreateRuntimeAsset( } else if (presentStages.Length == 1) { resultStream.Seek(0, SeekOrigin.Begin); using var reader = new StreamReader(resultStream); - + var jsonResolver = new ShouldSerializeContractResolver(); var serializer = new Newtonsoft.Json.JsonSerializerSettings() { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, @@ -6988,40 +7809,40 @@ public ActionFinished CreateRuntimeAsset( // procAsset = Newtonsoft.Json.JsonConvert.DeserializeObject(reader.ReadToEnd(), serializer); procAsset = JsonConvert.DeserializeObject(json); } else { - return new ActionFinished( - success: false, - errorMessage: $"Unexpected error with extension `{extension}`, filepath: `{filepath}`, compression stages: {string.Join(".", presentStages)}. Only supported: {string.Join(", ", supportedExtensions)}", + return new ActionFinished( + success: false, + errorMessage: $"Unexpected error with extension `{extension}`, filepath: `{filepath}`, compression stages: {string.Join(".", presentStages)}. Only supported: {string.Join(", ", supportedExtensions)}", actionReturn: null - ); + ); } - procAsset.parentTexturesDir = Path.Combine(dir, id); + procAsset.parentTexturesDir = Path.Combine(dir, id); var assetData = ProceduralTools.CreateAsset( - procAsset.vertices, - procAsset.normals, - procAsset.name, - procAsset.triangles, - procAsset.uvs, - procAsset.albedoTexturePath , - procAsset.metallicSmoothnessTexturePath , - procAsset.normalTexturePath , - procAsset.emissionTexturePath , - procAsset.colliders , - procAsset.physicalProperties, - procAsset.visibilityPoints , - procAsset.annotations ?? annotations, - procAsset.receptacleCandidate , - procAsset.yRotOffset , - returnObject: true, - serializable: serializable, - parent:null, - addAnotationComponent: false, - parentTexturesDir: procAsset.parentTexturesDir - ); + procAsset.vertices, + procAsset.normals, + procAsset.name, + procAsset.triangles, + procAsset.uvs, + procAsset.albedoTexturePath, + procAsset.metallicSmoothnessTexturePath, + procAsset.normalTexturePath, + procAsset.emissionTexturePath, + procAsset.colliders, + procAsset.physicalProperties, + procAsset.visibilityPoints, + procAsset.annotations ?? annotations, + procAsset.receptacleCandidate, + procAsset.yRotOffset, + returnObject: true, + serializable: serializable, + parent: null, + addAnotationComponent: false, + parentTexturesDir: procAsset.parentTexturesDir + ); - // Debug.Log($"root is null? {parent == null} - {parent}"); - return new ActionFinished(success: true, actionReturn: assetData); + // Debug.Log($"root is null? {parent == null} - {parent}"); + return new ActionFinished(success: true, actionReturn: assetData); } public void GetStreamingAssetsPath() { @@ -7037,14 +7858,13 @@ public void CreateHouse(ProceduralHouse house) { var materials = ProceduralTools.GetMaterials(); var materialIds = new HashSet( - house.rooms.SelectMany( - r => r.ceilings - .Select(c => c.material.name) + house + .rooms.SelectMany(r => + r.ceilings.Select(c => c.material.name) .Concat(new List() { r.floorMaterial.name }) .Concat(house.walls.Select(w => w.material.name)) - ).Concat( - new List() { house.proceduralParameters.ceilingMaterial.name } - ) + ) + .Concat(new List() { house.proceduralParameters.ceilingMaterial.name }) ); var missingIds = materialIds.Where(id => id != null && !materials.ContainsKey(id)); if (missingIds.Count() > 0) { @@ -7059,8 +7879,7 @@ public void CreateHouse(ProceduralHouse house) { try { ProceduralTools.CreateHouse(house: house, materialDb: materials); - } - catch (Exception e) { + } catch (Exception e) { Debug.Log(e); var msg = $"Exception creating house.\n'{e.Message}'\n'{e.InnerException}'"; Debug.Log(msg); @@ -7121,7 +7940,6 @@ public void GetHouseFromTemplate(HouseTemplate template) { } protected Dictionary getAssetMetadata(GameObject asset) { - if (asset.GetComponent() == null) { return null; } @@ -7133,7 +7951,9 @@ protected Dictionary getAssetMetadata(GameObject asset) { ["name"] = simObj.gameObject.name, ["objectType"] = simObj.Type.ToString(), ["primaryProperty"] = simObj.PrimaryProperty.ToString(), - ["secondaryProperties"] = simObj.SecondaryProperties.Select(s => s.ToString()).ToList(), + ["secondaryProperties"] = simObj + .SecondaryProperties.Select(s => s.ToString()) + .ToList(), ["boundingBox"] = new BoundingBox() { min = bb.center - bb.size / 2.0f, max = bb.center + bb.size / 2.0f @@ -7151,7 +7971,6 @@ public void GetAssetDatabase() { var metadata = new Dictionary>(); foreach (GameObject p in assetDb.GetPrefabs()) { - var meta = getAssetMetadata(p); if (meta == null) { continue; @@ -7173,10 +7992,7 @@ public void GetAssetDatabase() { public void AssetInDatabase(string assetId) { var assetMap = ProceduralTools.getAssetMap(); - actionFinishedEmit( - success: true, - actionReturn: assetMap.ContainsKey(assetId) - ); + actionFinishedEmit(success: true, actionReturn: assetMap.ContainsKey(assetId)); } public void TouchProceduralLRUCache(List assetIds) { @@ -7189,13 +8005,13 @@ public void DeleteLRUFromProceduralCache(int assetLimit) { var assetDB = GameObject.FindObjectOfType(); if (assetDB == null) { errorMessage = "No ProceduralAssetDatabase seems to exist."; -// Debug.Log(errorMessage); + // Debug.Log(errorMessage); actionFinishedEmit(success: false); return; } -// Debug.Log($"Attempting to remove until {assetLimit}"); + // Debug.Log($"Attempting to remove until {assetLimit}"); assetDB.removeLRUItems(assetLimit); -// Debug.Log($"Items removed."); + // Debug.Log($"Items removed."); actionFinishedEmit(success: true); } @@ -7207,24 +8023,25 @@ public void GetLRUCacheKeys() { ); } - public void AssetsInDatabase(List assetIds, bool updateProceduralLRUCache = false) { var assetDB = GameObject.FindObjectOfType(); - + if (updateProceduralLRUCache) { assetDB.touchProceduralLRUCache(assetIds); } var assetMap = assetDB.assetMap; actionFinishedEmit( success: true, - actionReturn: assetIds.Select(id => (id, inDatabase: assetMap.ContainsKey(id))).ToDictionary(it => it.id, it => it.inDatabase) + actionReturn: assetIds + .Select(id => (id, inDatabase: assetMap.ContainsKey(id))) + .ToDictionary(it => it.id, it => it.inDatabase) ); } // returns manually annotated "hole" metadata for connectors like doors of windows, to generate // the correct procedural polygons when creating a procedural house. public void GetAssetHoleMetadata(string assetId) { - var assetDb = GameObject.FindObjectOfType(); + var assetDb = GameObject.FindObjectOfType(); if (assetDb == null) { actionFinishedEmit( success: false, @@ -7249,24 +8066,22 @@ public void GetAssetHoleMetadata(string assetId) { success: false, errorMessage: $"Asset '{assetId}' does not have a HoleMetadata component, it's probably not a connector like a door or window or component has to be added in the prefab." ); - - } - else { - actionFinishedEmit( - success: false, - actionReturn: result - ); + } else { + actionFinishedEmit(success: false, actionReturn: result); } } - // asset geometry + // asset geometry public void GetInSceneAssetGeometry( string objectId, bool triangles = false, bool uv = false, bool normals = false ) { - SimObjPhysics asset = getInteractableSimObjectFromId(objectId: objectId, forceAction: true); + SimObjPhysics asset = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: true + ); MeshFilter[] meshFilters = asset.GetComponentsInChildren(); var geometries = new List(); @@ -7311,7 +8126,12 @@ public void DestroyHouse() { actionFinished(success: true); } - public void GetAsset3DGeometry(string assetId, bool triangleIndices = true, bool uvs = false, bool normals = false) { + public void GetAsset3DGeometry( + string assetId, + bool triangleIndices = true, + bool uvs = false, + bool normals = false + ) { var assetDb = GameObject.FindObjectOfType(); if (assetDb == null) { errorMessage = "ProceduralAssetDatabase not in scene."; @@ -7321,7 +8141,8 @@ public void GetAsset3DGeometry(string assetId, bool triangleIndices = true, bool var assetMap = ProceduralTools.getAssetMap(); if (!assetMap.ContainsKey(assetId)) { - errorMessage = $"Object '{assetId}' is not contained in asset database, you may need to rebuild asset database."; + errorMessage = + $"Object '{assetId}' is not contained in asset database, you may need to rebuild asset database."; actionFinishedEmit(false); return; } @@ -7330,14 +8151,16 @@ public void GetAsset3DGeometry(string assetId, bool triangleIndices = true, bool var meshFilters = asset.GetComponentsInChildren(); - var geoList = meshFilters.Select(meshFilter => { - var mesh = meshFilter.sharedMesh; - var geo = new Geometry3D() { vertices = mesh.vertices }; - geo.triangleIndices = triangleIndices ? mesh.triangles : null; - geo.normals = normals ? mesh.normals : null; - geo.uvs = uvs ? mesh.uv : null; - return geo; - }).ToList(); + var geoList = meshFilters + .Select(meshFilter => { + var mesh = meshFilter.sharedMesh; + var geo = new Geometry3D() { vertices = mesh.vertices }; + geo.triangleIndices = triangleIndices ? mesh.triangles : null; + geo.normals = normals ? mesh.normals : null; + geo.uvs = uvs ? mesh.uv : null; + return geo; + }) + .ToList(); actionFinishedEmit(true, geoList); } @@ -7349,11 +8172,11 @@ public ActionFinished SpawnAsset( ) { var assetDb = GameObject.FindObjectOfType(); if (assetDb == null) { - return new ActionFinished() { - toEmitState = true, + return new ActionFinished() { + toEmitState = true, success = false, errorMessage = "ProceduralAssetDatabase not in scene." - }; + }; } var assetMap = ProceduralTools.getAssetMap(); @@ -7361,7 +8184,8 @@ public ActionFinished SpawnAsset( return new ActionFinished() { toEmitState = true, success = false, - errorMessage = $"Object '{assetId}' is not contained in asset database, you may need to rebuild asset database." + errorMessage = + $"Object '{assetId}' is not contained in asset database, you may need to rebuild asset database." }; } @@ -7371,7 +8195,9 @@ public ActionFinished SpawnAsset( id: generatedId, assetId: assetId, position: position.GetValueOrDefault(Vector3.zero), - rotation: rotation.HasValue ? Quaternion.Euler(rotation.Value) : Quaternion.identity, + rotation: rotation.HasValue + ? Quaternion.Euler(rotation.Value) + : Quaternion.identity, collisionDetectionMode: CollisionDetectionMode.ContinuousSpeculative ); @@ -7403,7 +8229,8 @@ public void GetAssetSphereBounds(string assetId) { } var assetMap = ProceduralTools.getAssetMap(); if (!assetMap.ContainsKey(assetId)) { - errorMessage = $"Asset '{assetId}' is not contained in asset database, you may need to rebuild asset database."; + errorMessage = + $"Asset '{assetId}' is not contained in asset database, you may need to rebuild asset database."; actionFinishedEmit(false); return; } @@ -7412,11 +8239,14 @@ public void GetAssetSphereBounds(string assetId) { var bounds = GetObjectSphereBounds(asset); - actionFinishedEmit(true, new ObjectSphereBounds() { - id = assetId, - worldSpaceCenter = bounds.center, - radius = bounds.extents.magnitude - }); + actionFinishedEmit( + true, + new ObjectSphereBounds() { + id = assetId, + worldSpaceCenter = bounds.center, + radius = bounds.extents.magnitude + } + ); } public void LookAtObjectCenter(string objectId = "asset_0", Vector3? position = null) { @@ -7455,26 +8285,33 @@ private void LookAtObjectCenter(GameObject gameObject) { var dist = radius / Mathf.Tan(m_Camera.fieldOfView / 2.0f); // Debug.Log($"Center: {bounds.center} radius: {radius} dist: {dist} sum: {radius + dist}"); m_CharacterController.transform.rotation = Quaternion.identity; - m_CharacterController.transform.position = bounds.center + Vector3.forward * (radius + dist); - #if UNITY_EDITOR - debugSpheres.Add(new DebugSphere() { + m_CharacterController.transform.position = + bounds.center + Vector3.forward * (radius + dist); +#if UNITY_EDITOR + debugSpheres.Add( + new DebugSphere() { color = Color.yellow, radius = radius, worldSpaceCenter = bounds.center - }); - #endif + } + ); +#endif m_Camera.transform.localPosition = Vector3.zero; m_Camera.transform.LookAt(bounds.center, Vector3.up); } private Bounds GetObjectSphereBounds(GameObject gameObject) { - return gameObject.GetComponentsInChildren() + return gameObject + .GetComponentsInChildren() .Select(renderer => renderer.bounds) - .Aggregate(new Bounds(), (allBounds, partBounds) => { - allBounds.Encapsulate(partBounds); - return allBounds; - }); + .Aggregate( + new Bounds(), + (allBounds, partBounds) => { + allBounds.Encapsulate(partBounds); + return allBounds; + } + ); } protected static Vector3[] GetBoundsCorners(Bounds bounds) { @@ -7496,18 +8333,25 @@ protected static bool IsPointInView(Camera camera, Vector3 point, float minSlack return ( viewportPoint.z > 0 && viewportPoint.x >= minSlack - && viewportPoint.x <= 1-minSlack + && viewportPoint.x <= 1 - minSlack && viewportPoint.y >= minSlack - && viewportPoint.y <= 1-minSlack + && viewportPoint.y <= 1 - minSlack ); } - private static bool AreBoundsInViewAtDistance(Camera camera, Bounds bounds, float distance, float minSlack) { + private static bool AreBoundsInViewAtDistance( + Camera camera, + Bounds bounds, + float distance, + float minSlack + ) { // Position the camera temporarily to calculate the visibility at the given distance Vector3 originalPosition = camera.transform.position; Quaternion originalRotation = camera.transform.rotation; - camera.transform.position = bounds.center + Vector3.Normalize(camera.transform.position + bounds.center) * distance; + camera.transform.position = + bounds.center + + Vector3.Normalize(camera.transform.position + bounds.center) * distance; camera.transform.LookAt(bounds.center); // Check each corner of the bounds to see if it's visible @@ -7527,14 +8371,20 @@ private static bool AreBoundsInViewAtDistance(Camera camera, Bounds bounds, floa return allCornersInView; } - public float FindClosestDistance(Camera camera, Bounds objectBounds, float minSlack = 0.01f) { float minDistance = 0.01f; // Minimum possible distance, avoid division by zero or negative values // Find a reasonable max distance by doubling until the object is in view float maxDistance = 1f; for (int i = 0; i < 10; i++) { - if (!AreBoundsInViewAtDistance(camera, objectBounds, maxDistance, minSlack: minSlack)) { + if ( + !AreBoundsInViewAtDistance( + camera, + objectBounds, + maxDistance, + minSlack: minSlack + ) + ) { maxDistance *= 2; } else { break; @@ -7548,7 +8398,9 @@ public float FindClosestDistance(Camera camera, Bounds objectBounds, float minSl while (minDistance < maxDistance - targetAccuracy) { float midDistance = (minDistance + maxDistance) / 2; Debug.Log(midDistance); - if (AreBoundsInViewAtDistance(camera, objectBounds, midDistance, minSlack: minSlack)) { + if ( + AreBoundsInViewAtDistance(camera, objectBounds, midDistance, minSlack: minSlack) + ) { maxDistance = midDistance; } else { minDistance = midDistance; @@ -7582,10 +8434,16 @@ float cameraHeightMultiplier } float objectSize = Mathf.Max(bounds.size.x, bounds.size.y, bounds.size.z); - float objectRadius = Mathf.Sqrt(bounds.extents.x * bounds.extents.x + bounds.extents.z * bounds.extents.z); + float objectRadius = Mathf.Sqrt( + bounds.extents.x * bounds.extents.x + bounds.extents.z * bounds.extents.z + ); float cameraHeight = bounds.size.y * cameraHeightMultiplier; // Adjust for 3/4 view - RenderTexture renderTexture = new RenderTexture((int)renderResolution.x, (int)renderResolution.y, 24); + RenderTexture renderTexture = new RenderTexture( + (int)renderResolution.x, + (int)renderResolution.y, + 24 + ); renderCamera.targetTexture = renderTexture; List byte_arrays = new List(); @@ -7608,9 +8466,10 @@ float cameraHeightMultiplier byte_arrays = null; break; } -// Debug.Log($"Computed dist: {dist}"); + // Debug.Log($"Computed dist: {dist}"); - cameraPosition = bounds.center + Vector3.Normalize(cameraPosition - bounds.center) * dist; + cameraPosition = + bounds.center + Vector3.Normalize(cameraPosition - bounds.center) * dist; renderCamera.transform.position = cameraPosition; // Render @@ -7618,15 +8477,19 @@ float cameraHeightMultiplier Texture2D renderResult = new Texture2D(renderTexture.width, renderTexture.height); RenderTexture.active = renderTexture; - renderResult.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0); + renderResult.ReadPixels( + new Rect(0, 0, renderTexture.width, renderTexture.height), + 0, + 0 + ); renderResult.Apply(); // Save the image byte[] byteArray = renderResult.EncodeToPNG(); byte_arrays.Add(byteArray); -// string filePath = Path.Combine("/Users/lucaw/tmp/yar", $"render_{angle}.png"); -// File.WriteAllBytes(filePath, byteArray); + // string filePath = Path.Combine("/Users/lucaw/tmp/yar", $"render_{angle}.png"); + // File.WriteAllBytes(filePath, byteArray); // Clean up Texture2D.Destroy(renderResult); @@ -7655,7 +8518,9 @@ public void RenderObjectFromAngles( StartCoroutine( renderObjectFromAngles( renderCamera: m_Camera, - targetObject: physicsSceneManager.ObjectIdToSimObjPhysics[objectId].gameObject, + targetObject: physicsSceneManager + .ObjectIdToSimObjPhysics[objectId] + .gameObject, renderResolution: renderResolution, angles: angles, cameraHeightMultiplier: cameraHeightMultiplier @@ -7676,7 +8541,11 @@ public void RemoveObject(string objectId) { actionFinished(true); } - public void RotateObject(FlexibleRotation angleAxisRotation, string objectId = "asset_0", bool absolute = true) { + public void RotateObject( + FlexibleRotation angleAxisRotation, + string objectId = "asset_0", + bool absolute = true + ) { var obj = GameObject.Find(objectId); if (obj == null) { errorMessage = $"Object does not exist in scene."; @@ -7689,9 +8558,17 @@ public void RotateObject(FlexibleRotation angleAxisRotation, string objectId = " if (absolute) { obj.transform.position = Vector3.zero; obj.transform.rotation = Quaternion.identity; - obj.transform.RotateAround(bounds.center, angleAxisRotation.axis, angleAxisRotation.degrees); + obj.transform.RotateAround( + bounds.center, + angleAxisRotation.axis, + angleAxisRotation.degrees + ); } else { - obj.transform.RotateAround(bounds.center, angleAxisRotation.axis, angleAxisRotation.degrees); + obj.transform.RotateAround( + bounds.center, + angleAxisRotation.axis, + angleAxisRotation.degrees + ); //obj.transform.rotation = rot * obj.transform.rotation; } @@ -7701,7 +8578,11 @@ public void RotateObject(FlexibleRotation angleAxisRotation, string objectId = " public void BakeNavMesh() { var navmesh = GameObject.FindObjectOfType(); if (navmesh == null) { - actionFinishedEmit(false, null, "No NavMeshSurface component found, make sure scene was proceduraly created by `CreateHouse`."); + actionFinishedEmit( + false, + null, + "No NavMeshSurface component found, make sure scene was proceduraly created by `CreateHouse`." + ); return; } ProceduralTools.tagObjectNavmesh(this.gameObject, ignore: true); @@ -7712,20 +8593,23 @@ public void BakeNavMesh() { public void OverwriteNavMeshes(List navMeshConfigs) { var navmesh = GameObject.FindObjectOfType(); Transform parent; - if (navmesh == null) { + if (navmesh == null) { var go = GameObject.Find(ProceduralTools.NavMeshSurfaceParent()); if (go == null) { - actionFinishedEmit(false, null, $"No '{ProceduralTools.NavMeshSurfaceParent()}' gameobject found, make sure scene was proceduraly created by `CreateHouse`."); + actionFinishedEmit( + false, + null, + $"No '{ProceduralTools.NavMeshSurfaceParent()}' gameobject found, make sure scene was proceduraly created by `CreateHouse`." + ); return; } parent = go.transform; - } - else { + } else { parent = navmesh.transform.parent; } var floorGo = parent.parent; - for (var i =0; i< parent.transform.childCount; i++) { + for (var i = 0; i < parent.transform.childCount; i++) { var navmeshObj = parent.transform.GetChild(i); var navMeshSurf = navmeshObj.GetComponent(); navMeshSurf.RemoveData(); @@ -7733,27 +8617,33 @@ public void OverwriteNavMeshes(List navMeshConfigs) { } Destroy(parent.gameObject); - ProceduralTools.buildNavMeshes(floorGo.gameObject, navMeshConfigs); actionFinishedEmit(success: true); - } public void ReBakeNavMeshes(List navMeshConfigs = null) { var navmeshes = GameObject.FindObjectsOfType(); if (navmeshes == null || navmeshes.Count() == 0) { - actionFinishedEmit(false, null, "No NavMeshSurfaceExtended component found, make sure scene was proceduraly created by `CreateHouse`."); + actionFinishedEmit( + false, + null, + "No NavMeshSurfaceExtended component found, make sure scene was proceduraly created by `CreateHouse`." + ); return; } if (navMeshConfigs != null && navMeshConfigs.Count != navmeshes.Count()) { - actionFinishedEmit(success: false, errorMessage: $"Provided `navMeshConfigs` count does not match active navmeshSurfaces, provided: {navMeshConfigs.Count} current: {navmeshes.Count()}"); - } - else if (navMeshConfigs != null){ + actionFinishedEmit( + success: false, + errorMessage: $"Provided `navMeshConfigs` count does not match active navmeshSurfaces, provided: {navMeshConfigs.Count} current: {navmeshes.Count()}" + ); + } else if (navMeshConfigs != null) { for (var i = 0; i < navmeshes.Count(); i++) { - navmeshes[i].BuildNavMesh(ProceduralTools.navMeshConfigToBuildSettings(navMeshConfigs[i])); + navmeshes[i] + .BuildNavMesh( + ProceduralTools.navMeshConfigToBuildSettings(navMeshConfigs[i]) + ); } - } - else { + } else { foreach (var navmesh in navmeshes) { navmesh.BuildNavMesh(navmesh.buildSettings); } @@ -7764,30 +8654,38 @@ public void ReBakeNavMeshes(List navMeshConfigs = null) { public void GetNavMeshConfigs() { var navmeshes = GameObject.FindObjectsOfType(); if (navmeshes == null || navmeshes.Count() == 0) { - actionFinishedEmit(false, null, "No NavMeshSurfaceExtended component found, make sure scene was proceduraly created by `CreateHouse`."); + actionFinishedEmit( + false, + null, + "No NavMeshSurfaceExtended component found, make sure scene was proceduraly created by `CreateHouse`." + ); return; } - actionFinishedEmit(success: true, actionReturn: navmeshes.Select(n => ProceduralTools.navMeshBuildSettingsToConfig(n.buildSettings)).ToList()); - + actionFinishedEmit( + success: true, + actionReturn: navmeshes + .Select(n => ProceduralTools.navMeshBuildSettingsToConfig(n.buildSettings)) + .ToList() + ); } - public void CreateNewNavMesh(NavMeshConfig navMeshConfig) { - var navmesh = GameObject.FindObjectOfType(); - if (navmesh == null) { - actionFinishedEmit(false, null, "No NavMeshSurfaceExtended component found, make sure scene was proceduraly created by `CreateHouse`."); + if (navmesh == null) { + actionFinishedEmit( + false, + null, + "No NavMeshSurfaceExtended component found, make sure scene was proceduraly created by `CreateHouse`." + ); return; } var navMeshParent = navmesh.transform.parent; var id = NavMeshSurfaceExtended.activeSurfaces.Count(); - var go = ProceduralTools.buildNavMeshSurface(navMeshConfig, id); go.transform.parent = navMeshParent.transform; - // ProceduralTools.tagObjectNavmesh(this.gameObject, ignore: true); // navmesh.BuildNavMesh(); actionFinishedEmit(true); @@ -7808,11 +8706,13 @@ public bool CheckIfPointIsInViewport(Vector3 point) { float ViewPointRangeHigh = 1.0f; float ViewPointRangeLow = 0.0f; - if (viewPoint.z > 0 //&& viewPoint.z < maxDistance * DownwardViewDistance // is in front of camera and within range of visibility sphere - && - viewPoint.x < ViewPointRangeHigh && viewPoint.x > ViewPointRangeLow // within x bounds of viewport - && - viewPoint.y < ViewPointRangeHigh && viewPoint.y > ViewPointRangeLow) // within y bounds of viewport + if ( + viewPoint.z > 0 //&& viewPoint.z < maxDistance * DownwardViewDistance // is in front of camera and within range of visibility sphere + && viewPoint.x < ViewPointRangeHigh + && viewPoint.x > ViewPointRangeLow // within x bounds of viewport + && viewPoint.y < ViewPointRangeHigh + && viewPoint.y > ViewPointRangeLow + ) // within y bounds of viewport { RaycastHit hit; @@ -7825,7 +8725,14 @@ public bool CheckIfPointIsInViewport(Vector3 point) { point - m_Camera.transform.position, out hit, Vector3.Distance(m_Camera.transform.position, point) - 0.01f, - LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent") + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent" + ) ) ) { updateAllAgentCollidersForVisibilityCheck(true); @@ -7839,7 +8746,9 @@ public bool CheckIfPointIsInViewport(Vector3 point) { } protected List approxObjectMask( - SimObjPhysics sop, int divisions, int? thirdPartyCameraIndex = null + SimObjPhysics sop, + int divisions, + int? thirdPartyCameraIndex = null ) { if (divisions <= 2) { throw new ArgumentException("divisions must be >=3"); @@ -7847,10 +8756,15 @@ protected List approxObjectMask( ObjectOrientedBoundingBox oobb = sop.ObjectOrientedBoundingBox; if (oobb == null) { - sop.syncBoundingBoxes(forceCacheReset: true, forceCreateObjectOrientedBoundingBox: true); + sop.syncBoundingBoxes( + forceCacheReset: true, + forceCreateObjectOrientedBoundingBox: true + ); oobb = sop.ObjectOrientedBoundingBox; if (oobb == null) { - throw new ArgumentException($"{sop.objectID} does not have an object oriented bounding box"); + throw new ArgumentException( + $"{sop.objectID} does not have an object oriented bounding box" + ); } } float[][] oobbPoints = oobb.cornerPoints; @@ -7867,8 +8781,15 @@ protected List approxObjectMask( float maxY = 0.0f; float maxDist = 0.0f; for (int i = 0; i < 8; i++) { - Vector3 worldSpaceCornerPoint = new Vector3(oobbPoints[i][0], oobbPoints[i][1], oobbPoints[i][2]); - maxDist = Mathf.Max(Vector3.Distance(worldSpaceCornerPoint, camera.transform.position), maxDist); + Vector3 worldSpaceCornerPoint = new Vector3( + oobbPoints[i][0], + oobbPoints[i][1], + oobbPoints[i][2] + ); + maxDist = Mathf.Max( + Vector3.Distance(worldSpaceCornerPoint, camera.transform.position), + maxDist + ); Vector3 viewPoint = camera.WorldToViewportPoint(worldSpaceCornerPoint); minX = Math.Min(viewPoint.x, minX); @@ -7890,12 +8811,12 @@ protected List approxObjectMask( // Here we shift minX and maxX slightly 2% towards one another so that we're // not sampling directly along the boundary float alpha = 0.02f; - float shrunkMinX = minX * (1-alpha) + maxX * alpha; - float shrunkMaxX = minX * alpha + maxX * (1-alpha); + float shrunkMinX = minX * (1 - alpha) + maxX * alpha; + float shrunkMaxX = minX * alpha + maxX * (1 - alpha); // Same for minY and maxY - float shrunkMinY = minY * (1-alpha) + maxY * alpha; - float shrunkMaxY = minY * alpha + maxY * (1-alpha); + float shrunkMinY = minY * (1 - alpha) + maxY * alpha; + float shrunkMaxY = minY * alpha + maxY * (1 - alpha); for (int i = 0; i < divisions; i++) { for (int j = 0; j < divisions; j++) { @@ -7905,7 +8826,14 @@ protected List approxObjectMask( // Convert x,y to a worldspace coordinate at distance maxDist from the camera Vector3 point = camera.ViewportToWorldPoint(new Vector3(x, y, maxDist)); - if (CheckIfVisibilityPointRaycast(sop: sop, position: point, camera: camera, includeInvisible: false).visible) { + if ( + CheckIfVisibilityPointRaycast( + sop: sop, + position: point, + camera: camera, + includeInvisible: false + ).visible + ) { points.Add(new Vector2(x, y)); } } @@ -7918,7 +8846,10 @@ public void GetApproxObjectMask( int divisions = 10, int? thirdPartyCameraIndex = null ) { - SimObjPhysics sop = getInteractableSimObjectFromId(objectId: objectId, forceAction: true); + SimObjPhysics sop = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: true + ); List points = approxObjectMask( sop, divisions: divisions, @@ -7928,10 +8859,7 @@ public void GetApproxObjectMask( } public void unrollSimulatePhysics(IEnumerator enumerator, float fixedDeltaTime) { - ContinuousMovement.unrollSimulatePhysics( - enumerator, - fixedDeltaTime - ); + ContinuousMovement.unrollSimulatePhysics(enumerator, fixedDeltaTime); } public void GetSceneBounds() { @@ -7949,16 +8877,15 @@ public void GetSceneBounds() { public void GetLights() { print("GetLights in BASE happening now"); //debug - #if UNITY_EDITOR +#if UNITY_EDITOR List lights = UtilityFunctions.GetLightPropertiesOfScene(); UtilityFunctions.debugGetLightPropertiesOfScene(lights); - #endif +#endif actionFinishedEmit(true, UtilityFunctions.GetLightPropertiesOfScene()); } public void SetLights() { - //check that name of light specified exists in scene, if not throw exception actionFinished(true); @@ -7987,18 +8914,16 @@ public void SetObjectsCollisionMode(string collisionDetectionMode) { ); } CollisionDetectionMode collDet = CollisionDetectionMode.ContinuousSpeculative; - + Enum.TryParse(collisionDetectionMode, true, out collDet); - for (var i = 0; i(); - if (!rb.isKinematic) { + if (!rb.isKinematic) { rb.collisionDetectionMode = collDet; } } - actionFinished( - success: true - ); + actionFinished(success: true); } #if UNITY_EDITOR @@ -8057,7 +8982,11 @@ public void TestFastEmit(string rvalue) { actionFinishedEmit(true, rvalue); } - public void TestActionDispatchNoopAllDefault2(float param12, float param10 = 0.0f, float param11 = 1.0f) { + public void TestActionDispatchNoopAllDefault2( + float param12, + float param10 = 0.0f, + float param11 = 1.0f + ) { actionFinished(true, "somedefault"); } @@ -8084,6 +9013,7 @@ public void TestActionDispatchNoop(bool param1, bool param2) { public void TestActionDispatchConflict(string param22) { actionFinished(true); } + public void TestActionDispatchConflict(bool param22) { actionFinished(true); } @@ -8102,7 +9032,8 @@ public void TestActionDispatchFindAmbiguous(string typeName) { } public void TestActionDispatchFindConflicts(string typeName) { - Dictionary> conflicts = ActionDispatcher.FindMethodVariableNameConflicts(Type.GetType(typeName)); + Dictionary> conflicts = + ActionDispatcher.FindMethodVariableNameConflicts(Type.GetType(typeName)); string[] ignore = new string[] { "GetComponent", "StopCoroutine" }; foreach (var methodName in ignore) { if (conflicts.ContainsKey(methodName)) { @@ -8116,19 +9047,23 @@ public void print(string message) { MonoBehaviour.print(message); } - public T GetComponent() where T : Component { + public T GetComponent() + where T : Component { return this.baseAgentComponent.GetComponent(); } - public T GetComponentInParent() where T : Component { + public T GetComponentInParent() + where T : Component { return this.baseAgentComponent.GetComponentInParent(); } - public T GetComponentInChildren() where T : Component { + public T GetComponentInChildren() + where T : Component { return this.baseAgentComponent.GetComponentInChildren(); } - public T[] GetComponentsInChildren() where T : Component { + public T[] GetComponentsInChildren() + where T : Component { return this.baseAgentComponent.GetComponentsInChildren(); } @@ -8143,7 +9078,6 @@ public GameObject Instantiate(GameObject original, Vector3 position, Quaternion public void Destroy(GameObject targetObject) { MonoBehaviour.Destroy(targetObject); } - } public class VisibilityCheck { @@ -8157,5 +9091,4 @@ public class VisibilityCheck { return c; } } - } diff --git a/unity/Assets/Scripts/BatchRename.cs b/unity/Assets/Scripts/BatchRename.cs index 60cfbdce6e..2339dc1ca0 100644 --- a/unity/Assets/Scripts/BatchRename.cs +++ b/unity/Assets/Scripts/BatchRename.cs @@ -2,13 +2,10 @@ // Via Alan Thorn (TW: @thorn_alan) #if UNITY_EDITOR using UnityEngine; - using UnityEditor; - using System.Collections; public class BatchRename : ScriptableWizard { - /// /// Base name /// @@ -47,7 +44,6 @@ void OnSelectionChange() { /// Update selection counter /// void UpdateSelectionHelper() { - helpString = ""; if (Selection.objects != null) { @@ -55,12 +51,10 @@ void UpdateSelectionHelper() { } } - /// /// Rename /// void OnWizardCreate() { - // If selection is empty, then exit if (Selection.objects == null) { return; @@ -76,4 +70,4 @@ void OnWizardCreate() { } } } -#endif \ No newline at end of file +#endif diff --git a/unity/Assets/Scripts/Bathtub.cs b/unity/Assets/Scripts/Bathtub.cs index e357e02930..9d5df6b326 100644 --- a/unity/Assets/Scripts/Bathtub.cs +++ b/unity/Assets/Scripts/Bathtub.cs @@ -1,10 +1,9 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; [ExecuteInEditMode] public class Bathtub : MonoBehaviour { - public SimObj ParentObj; public bool EditorFilled = false; public GameObject FilledObject; @@ -20,7 +19,8 @@ void OnEnable() { Animator a = ParentObj.gameObject.GetComponent(); if (a == null) { a = ParentObj.gameObject.AddComponent(); - a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; + a.runtimeAnimatorController = + Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; } } } diff --git a/unity/Assets/Scripts/Bed.cs b/unity/Assets/Scripts/Bed.cs index f3e4995bd5..b58881b5a4 100644 --- a/unity/Assets/Scripts/Bed.cs +++ b/unity/Assets/Scripts/Bed.cs @@ -1,14 +1,15 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; [ExecuteInEditMode] public class Bed : MonoBehaviour { - public SimObj ParentObj; + // public GameObject FittedSheet; public GameObject TidyBlanket; public GameObject MessyBlanket; + [Range(0, 2)] public int EditorState = 0; @@ -23,13 +24,13 @@ void OnEnable() { Animator a = ParentObj.gameObject.GetComponent(); if (a == null) { a = ParentObj.gameObject.AddComponent(); - a.runtimeAnimatorController = Resources.Load("StateAnimController") as RuntimeAnimatorController; + a.runtimeAnimatorController = + Resources.Load("StateAnimController") as RuntimeAnimatorController; } } } void Update() { - int state = EditorState; if (Application.isPlaying) { state = ParentObj.Animator.GetInteger("AnimState1"); diff --git a/unity/Assets/Scripts/Blinds.cs b/unity/Assets/Scripts/Blinds.cs index 79325849f0..6728a8de77 100644 --- a/unity/Assets/Scripts/Blinds.cs +++ b/unity/Assets/Scripts/Blinds.cs @@ -1,10 +1,9 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; [ExecuteInEditMode] public class Blinds : MonoBehaviour { - public SimObj ParentObj; public bool EditorOpen = false; public bool OpenByDefault = true; @@ -23,7 +22,8 @@ void OnEnable() { Animator a = ParentObj.gameObject.GetComponent(); if (a == null) { a = ParentObj.gameObject.AddComponent(); - a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; + a.runtimeAnimatorController = + Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; } } else { if (OpenByDefault) { diff --git a/unity/Assets/Scripts/Box.cs b/unity/Assets/Scripts/Box.cs index ce6d2fa4fc..d8a4dc27d4 100644 --- a/unity/Assets/Scripts/Box.cs +++ b/unity/Assets/Scripts/Box.cs @@ -1,10 +1,9 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; [ExecuteInEditMode] public class Box : MonoBehaviour { - public SimObj ParentSimObj; public GameObject[] Lids; public bool EditorClosed = true; @@ -17,7 +16,11 @@ void OnEnable() { if (r != null) { bool lighten = SceneManager.Current.SceneNumber % 2 == 0; Material darkerMat = r.material; - darkerMat.color = Color.Lerp(darkerMat.color, (lighten ? Color.white : Color.black), 0.15f); + darkerMat.color = Color.Lerp( + darkerMat.color, + (lighten ? Color.white : Color.black), + 0.15f + ); } } } diff --git a/unity/Assets/Scripts/Break.cs b/unity/Assets/Scripts/Break.cs index 189ab9aaeb..478a947659 100644 --- a/unity/Assets/Scripts/Break.cs +++ b/unity/Assets/Scripts/Break.cs @@ -4,9 +4,9 @@ using UnityStandardAssets.Characters.FirstPerson; public class Break : MonoBehaviour { - [SerializeField] private GameObject PrefabToSwapTo = null; + [SerializeField] private GameObject DirtyPrefabToSwapTo = null; @@ -14,9 +14,10 @@ public class Break : MonoBehaviour { protected float ImpulseThreshold = 3.6f; // set this to lower if this object should be easier to break. Higher if the object requires more force to break [SerializeField] - protected float HighFrictionImpulseOffset = 2.0f;// if the object is colliding with a "soft" high friction zone, offset the ImpulseThreshold to be harder to break + protected float HighFrictionImpulseOffset = 2.0f; // if the object is colliding with a "soft" high friction zone, offset the ImpulseThreshold to be harder to break + + protected float CurrentImpulseThreshold; // modify this with ImpulseThreshold and HighFrictionImpulseOffset based on trigger callback functions - protected float CurrentImpulseThreshold;// modify this with ImpulseThreshold and HighFrictionImpulseOffset based on trigger callback functions [SerializeField] protected bool readytobreak = true; @@ -26,32 +27,67 @@ public class Break : MonoBehaviour { // if set to true, all breakable objects cannot be broken automatically. Instaed, only the Break() action targeting specific objects will allow them to be broken. public bool Unbreakable = false; - // what does this object need to do when it is in the broken state? + // what does this object need to do when it is in the broken state? // Some need a decal to show a cracked screen on the surface, others need a prefab swap to shattered pieces - protected enum BreakType { PrefabSwap, MaterialSwap, Decal }; + protected enum BreakType { + PrefabSwap, + MaterialSwap, + Decal + }; [SerializeField] protected BreakType breakType; // please select how this object should be broken here [SerializeField] - protected SwapObjList[] MaterialSwapObjects;// swap screen/surface with cracked version + protected SwapObjList[] MaterialSwapObjects; // swap screen/surface with cracked version // if these soft objects hit this breakable object, ignore the breakobject check because it's soft so yeah why would it break this object? private List TooSmalOrSoftToBreakOtherObjects = new List() - {SimObjType.TeddyBear, SimObjType.Pillow, SimObjType.Cloth, SimObjType.Bread, SimObjType.BreadSliced, SimObjType.Egg, SimObjType.EggShell, SimObjType.Omelette, - SimObjType.EggCracked, SimObjType.LettuceSliced, SimObjType.TissueBox, SimObjType.Newspaper, SimObjType.TissueBoxEmpty, SimObjType.TissueBoxEmpty, - SimObjType.CreditCard, SimObjType.ToiletPaper, SimObjType.ToiletPaperRoll, SimObjType.SoapBar, SimObjType.Pen, SimObjType.Pencil, SimObjType.Towel, - SimObjType.Watch, SimObjType.DishSponge, SimObjType.Tissue, SimObjType.CD, SimObjType.HandTowel}; + { + SimObjType.TeddyBear, + SimObjType.Pillow, + SimObjType.Cloth, + SimObjType.Bread, + SimObjType.BreadSliced, + SimObjType.Egg, + SimObjType.EggShell, + SimObjType.Omelette, + SimObjType.EggCracked, + SimObjType.LettuceSliced, + SimObjType.TissueBox, + SimObjType.Newspaper, + SimObjType.TissueBoxEmpty, + SimObjType.TissueBoxEmpty, + SimObjType.CreditCard, + SimObjType.ToiletPaper, + SimObjType.ToiletPaperRoll, + SimObjType.SoapBar, + SimObjType.Pen, + SimObjType.Pencil, + SimObjType.Towel, + SimObjType.Watch, + SimObjType.DishSponge, + SimObjType.Tissue, + SimObjType.CD, + SimObjType.HandTowel + }; public bool isBroken() { return broken; } + // Start is called before the first frame update void Start() { #if UNITY_EDITOR - // TODO refactor Break logic as separate from DecalCollision.cs to avoid error, and remove last part of AND - if ((gameObject.GetComponentInParent() != null && !gameObject.GetComponentInParent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBreak)) && !gameObject.GetComponentInParent().IsReceptacle) { - + // TODO refactor Break logic as separate from DecalCollision.cs to avoid error, and remove last part of AND + if ( + ( + gameObject.GetComponentInParent() != null + && !gameObject + .GetComponentInParent() + .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBreak) + ) && !gameObject.GetComponentInParent().IsReceptacle + ) { Debug.LogError(gameObject.name + " is missing the CanBreak secondary property!"); } @@ -76,8 +112,9 @@ public void BreakObject(Collision collision) { //before disabling things, if this object is a receptacle, unparent all objects contained if (gameObject.GetComponent().IsReceptacle) { - foreach (GameObject go in gameObject.GetComponent().ContainedGameObjects()) { - + foreach ( + GameObject go in gameObject.GetComponent().ContainedGameObjects() + ) { //only reset rigidbody properties if contained object was pickupable/moveable if (go.GetComponentInParent()) { SimObjPhysics containedSOP = go.GetComponentInParent(); @@ -87,7 +124,8 @@ public void BreakObject(Collision collision) { childrb.isKinematic = false; childrb.useGravity = true; childrb.constraints = RigidbodyConstraints.None; - childrb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; + childrb.collisionDetectionMode = + CollisionDetectionMode.ContinuousSpeculative; } } } @@ -133,8 +171,14 @@ public void BreakObject(Collision collision) { if (resultObject.GetComponent()) { if (resultObject.GetComponent().Type == SimObjType.EggCracked) { resultObject.transform.rotation = Quaternion.Euler(Vector3.zero); - PhysicsSceneManager psm = GameObject.Find("PhysicsSceneManager").GetComponent(); - psm.Generate_InheritedObjectID(gameObject.GetComponent(), resultObject.GetComponent(), 0); + PhysicsSceneManager psm = GameObject + .Find("PhysicsSceneManager") + .GetComponent(); + psm.Generate_InheritedObjectID( + gameObject.GetComponent(), + resultObject.GetComponent(), + 0 + ); Rigidbody resultrb = resultObject.GetComponent(); resultrb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; @@ -151,7 +195,8 @@ public void BreakObject(Collision collision) { // decal logic here if (MaterialSwapObjects.Length > 0) { for (int i = 0; i < MaterialSwapObjects.Length; i++) { - MaterialSwapObjects[i].MyObject.GetComponent().materials = MaterialSwapObjects[i].OnMaterials; + MaterialSwapObjects[i].MyObject.GetComponent().materials = + MaterialSwapObjects[i].OnMaterials; } } @@ -171,7 +216,10 @@ public void BreakObject(Collision collision) { BreakForDecalType(collision); } - BaseFPSAgentController primaryAgent = GameObject.Find("PhysicsSceneManager").GetComponent().PrimaryAgent; + BaseFPSAgentController primaryAgent = GameObject + .Find("PhysicsSceneManager") + .GetComponent() + .PrimaryAgent; if (primaryAgent.imageSynthesis) { if (primaryAgent.imageSynthesis.enabled) { primaryAgent.imageSynthesis.OnSceneChange(); @@ -180,12 +228,9 @@ public void BreakObject(Collision collision) { } // Override for Decal behavior - protected virtual void BreakForDecalType(Collision collision) { - - } + protected virtual void BreakForDecalType(Collision collision) { } void OnCollisionEnter(Collision col) { - // do nothing if this specific breakable sim objects has been set to unbreakable if (Unbreakable) { return; @@ -199,13 +244,20 @@ void OnCollisionEnter(Collision col) { // if the other collider hit is on the list of things that shouldn't cause this object to break, return and do nothing if (col.transform.GetComponentInParent()) { - if (TooSmalOrSoftToBreakOtherObjects.Contains(col.transform.GetComponentInParent().Type)) { + if ( + TooSmalOrSoftToBreakOtherObjects.Contains( + col.transform.GetComponentInParent().Type + ) + ) { return; } } // ImpulseForce.Add(col.impulse.magnitude); - if (col.impulse.magnitude > CurrentImpulseThreshold && !col.transform.GetComponentInParent()) { + if ( + col.impulse.magnitude > CurrentImpulseThreshold + && !col.transform.GetComponentInParent() + ) { if (readytobreak) { readytobreak = false; BreakObject(col); @@ -226,4 +278,4 @@ public void OnTriggerExit(Collider other) { CurrentImpulseThreshold = ImpulseThreshold; } } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/Breakdown.cs b/unity/Assets/Scripts/Breakdown.cs index 27dc4f54b9..8efdf7ca5b 100644 --- a/unity/Assets/Scripts/Breakdown.cs +++ b/unity/Assets/Scripts/Breakdown.cs @@ -21,13 +21,14 @@ void Start() { rb.AddTorque(new Vector3(Random.value, Random.value, Random.value)); // add the rigidbody to cache of all rigidbodies in scene - GameObject.Find("PhysicsSceneManager").GetComponent().AddToRBSInScene(rb); + GameObject + .Find("PhysicsSceneManager") + .GetComponent() + .AddToRBSInScene(rb); } } } // Update is called once per frame - void Update() { - - } + void Update() { } } diff --git a/unity/Assets/Scripts/Cabinet.cs b/unity/Assets/Scripts/Cabinet.cs index a08c90e034..f7a1be722a 100644 --- a/unity/Assets/Scripts/Cabinet.cs +++ b/unity/Assets/Scripts/Cabinet.cs @@ -1,6 +1,6 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; public enum CabinetOpenStyle { SingleDoorLeft, @@ -11,19 +11,15 @@ public enum CabinetOpenStyle { [ExecuteInEditMode] public class Cabinet : MonoBehaviour { - public bool Animate = false; public bool Open; public SimObj ParentObj; - - public CabinetOpenStyle OpenStyle; public Transform LeftDoor; public Transform RightDoor; public Transform DrawerDoor; // DRAWER - public Vector3 OpenAngleRight = new Vector3(0f, -90f, 0f); public Vector3 OpenAngleLeft = new Vector3(0f, 90f, 0f); public Vector3 ClosedAngleRight = new Vector3(0f, 0f, 0f); @@ -31,11 +27,10 @@ public class Cabinet : MonoBehaviour { public Vector3 ClosedLocalPosition = new Vector3(0f, 0f, 0f); public Vector3 OpenLocalPosition = new Vector3(0f, 0f, 0f); - Vector3 rightDoorTargetRotation; Vector3 leftDoorTargetRotation; - // Drawer Stuff// + // Drawer Stuff// /* In order for any drawer to be visible under the visibiliy checking sphere, make sure that the drawer parenting heirarchy is set up as: @@ -47,7 +42,7 @@ public class Cabinet : MonoBehaviour { -Pivot When a drawer is in the closed position, the visibiliy collider will become flat and move up to the forward - face of the drawer so the agent's sight is not occluded by stacked drawers or geometry. + face of the drawer so the agent's sight is not occluded by stacked drawers or geometry. When a drawer is in the open position, the visibility collider resets the position to the center and expands so that the Agent can see what is inside the drawer. @@ -58,7 +53,7 @@ center and expands so that the Agent can see what is inside the drawer. Vector3 drawerTargetPosition; // Drawer's position if either open or closed Vector3 drawerVisColPosition; // Drawer's visibility collider position if open or closed - Vector3 drawerVisColScale; // Drawer's visibility collider scale if open or closed + Vector3 drawerVisColScale; // Drawer's visibility collider scale if open or closed public Vector3 ClosedVisColPosition = new Vector3(0f, 0f, 0f); // Drawer's visibility collider position if CLOSED public Vector3 ClosedVisColScale = new Vector3(1f, 1f, 1f); // drawer's visiblity collider scale if CLOSED @@ -77,12 +72,12 @@ public void OnEnable() { Animator a = ParentObj.gameObject.GetComponent(); if (a == null) { a = ParentObj.gameObject.AddComponent(); - a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; + a.runtimeAnimatorController = + Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; } } } - public void Update() { bool open = Open; if (Application.isPlaying) { @@ -112,7 +107,6 @@ public void Update() { } void UpdateAnimationSmooth(bool open) { - Quaternion rightDoorStartRotation = Quaternion.identity; Quaternion leftDoorStartRotation = Quaternion.identity; @@ -130,9 +124,20 @@ void UpdateAnimationSmooth(bool open) { leftDoorTargetRotation = LeftDoor.localEulerAngles; rightDoorTargetRotation = RightDoor.localEulerAngles; - RightDoor.rotation = Quaternion.RotateTowards(rightDoorStartRotation, RightDoor.rotation, Time.deltaTime * SimUtil.SmoothAnimationSpeed * 25); - LeftDoor.rotation = Quaternion.RotateTowards(leftDoorStartRotation, LeftDoor.rotation, Time.deltaTime * SimUtil.SmoothAnimationSpeed * 25); - animatingDistance = Vector3.Distance(RightDoor.localEulerAngles, rightDoorTargetRotation); + RightDoor.rotation = Quaternion.RotateTowards( + rightDoorStartRotation, + RightDoor.rotation, + Time.deltaTime * SimUtil.SmoothAnimationSpeed * 25 + ); + LeftDoor.rotation = Quaternion.RotateTowards( + leftDoorStartRotation, + LeftDoor.rotation, + Time.deltaTime * SimUtil.SmoothAnimationSpeed * 25 + ); + animatingDistance = Vector3.Distance( + RightDoor.localEulerAngles, + rightDoorTargetRotation + ); break; case CabinetOpenStyle.SingleDoorLeft: @@ -140,8 +145,15 @@ void UpdateAnimationSmooth(bool open) { leftDoorTargetRotation = open ? OpenAngleLeft : ClosedAngleLeft; LeftDoor.localEulerAngles = leftDoorTargetRotation; leftDoorTargetRotation = LeftDoor.localEulerAngles; - LeftDoor.rotation = Quaternion.RotateTowards(leftDoorStartRotation, LeftDoor.rotation, Time.deltaTime * SimUtil.SmoothAnimationSpeed * 25); - animatingDistance = Vector3.Distance(LeftDoor.localEulerAngles, leftDoorTargetRotation); + LeftDoor.rotation = Quaternion.RotateTowards( + leftDoorStartRotation, + LeftDoor.rotation, + Time.deltaTime * SimUtil.SmoothAnimationSpeed * 25 + ); + animatingDistance = Vector3.Distance( + LeftDoor.localEulerAngles, + leftDoorTargetRotation + ); break; case CabinetOpenStyle.SingleDoorRight: @@ -149,14 +161,28 @@ void UpdateAnimationSmooth(bool open) { rightDoorTargetRotation = open ? OpenAngleRight : ClosedAngleRight; RightDoor.localEulerAngles = rightDoorTargetRotation; rightDoorTargetRotation = RightDoor.localEulerAngles; - RightDoor.rotation = Quaternion.RotateTowards(rightDoorStartRotation, RightDoor.rotation, Time.deltaTime * SimUtil.SmoothAnimationSpeed * 25); - animatingDistance = Vector3.Distance(RightDoor.localEulerAngles, rightDoorTargetRotation); + RightDoor.rotation = Quaternion.RotateTowards( + rightDoorStartRotation, + RightDoor.rotation, + Time.deltaTime * SimUtil.SmoothAnimationSpeed * 25 + ); + animatingDistance = Vector3.Distance( + RightDoor.localEulerAngles, + rightDoorTargetRotation + ); break; case CabinetOpenStyle.Drawer: drawerTargetPosition = open ? OpenLocalPosition : ClosedLocalPosition; - DrawerDoor.localPosition = Vector3.Lerp(DrawerDoor.localPosition, drawerTargetPosition, Time.deltaTime * SimUtil.SmoothAnimationSpeed); - animatingDistance = Vector3.Distance(DrawerDoor.localPosition, drawerTargetPosition); + DrawerDoor.localPosition = Vector3.Lerp( + DrawerDoor.localPosition, + drawerTargetPosition, + Time.deltaTime * SimUtil.SmoothAnimationSpeed + ); + animatingDistance = Vector3.Distance( + DrawerDoor.localPosition, + drawerTargetPosition + ); // drawerVisColScale = open ? OpenVisColScale : ClosedVisColScale; // drawerVisColPosition = open ? OpenVisColPosition : ClosedVisColPosition; @@ -198,7 +224,9 @@ void UpdateAnimationInstant(bool open) { // if the drawer is closed, move the vis collider to the outer edge so it is visible // if the door is open, move visibility collider so agent can pick up/place things in drawer - VisCollider.transform.localPosition = open ? OpenVisColPosition : ClosedVisColPosition; + VisCollider.transform.localPosition = open + ? OpenVisColPosition + : ClosedVisColPosition; VisCollider.transform.localScale = open ? OpenVisColScale : ClosedVisColScale; break; } diff --git a/unity/Assets/Scripts/CameraControls.cs b/unity/Assets/Scripts/CameraControls.cs index 03838ca5e4..43b474df43 100644 --- a/unity/Assets/Scripts/CameraControls.cs +++ b/unity/Assets/Scripts/CameraControls.cs @@ -1,9 +1,8 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; public class CameraControls : MonoBehaviour { - Camera cam; void Start() { diff --git a/unity/Assets/Scripts/CameraDepthSetup.cs b/unity/Assets/Scripts/CameraDepthSetup.cs index 78a05a2f84..b27b3920db 100644 --- a/unity/Assets/Scripts/CameraDepthSetup.cs +++ b/unity/Assets/Scripts/CameraDepthSetup.cs @@ -1,8 +1,8 @@ using System.Collections; using System.Collections.Generic; using UnityEngine; -[ExecuteInEditMode] +[ExecuteInEditMode] public class CameraDepthSetup : MonoBehaviour { void Start() { Camera.main.depthTextureMode = DepthTextureMode.Depth; diff --git a/unity/Assets/Scripts/CanOpen_Object.cs b/unity/Assets/Scripts/CanOpen_Object.cs index e19afa55a2..f515bec84d 100644 --- a/unity/Assets/Scripts/CanOpen_Object.cs +++ b/unity/Assets/Scripts/CanOpen_Object.cs @@ -22,21 +22,29 @@ public class CanOpen_Object : MonoBehaviour { public bool triggerEnabled = true; [SerializeField] - public float currentOpenness = 1.0f; // 0.0 to 1.0 - percent of openPosition the object opens. - + public float currentOpenness = 1.0f; // 0.0 to 1.0 - percent of openPosition the object opens. + // used to reset on failure private float startOpenness; private float lastSuccessfulOpenness; - public enum failState {none, collision, hyperextension}; + + public enum failState { + none, + collision, + hyperextension + }; + private failState failure = failState.none; private GameObject failureCollision; - + // used to store whether moving parts should treat non-static SimObjects as barriers private bool forceAction = false; private bool ignoreAgentInTransition = false; private bool stopAtNonStaticCol = false; - [Header("Objects To Ignore Collision With - For Cabinets/Drawers with hinges too close together")] + [Header( + "Objects To Ignore Collision With - For Cabinets/Drawers with hinges too close together" + )] // these are objects to ignore collision with. This is in case the fridge doors touch each other or something that might // prevent them from closing all the way. Probably not needed but it's here if there is an edge case [SerializeField] @@ -47,18 +55,22 @@ public enum failState {none, collision, hyperextension}; public bool isOpen = false; private bool isCurrentlyLerping = false; + // [SerializeField] //public bool isCurrentlyResetting = false; // private bool isCurrentlyResetting = false; - public enum MovementType { Slide, Rotate, Scale }; + public enum MovementType { + Slide, + Rotate, + Scale + }; [SerializeField] protected MovementType movementType; // keep a list of all objects that, if able to turn on/off, must be in the Off state before opening (no opening microwave unless it's off!); - private List MustBeOffToOpen = new List() - {SimObjType.Microwave}; + private List MustBeOffToOpen = new List() { SimObjType.Microwave }; //[Header("References for the Open or Closed bounding box for openable and pickupable objects")] //// the bounding box to use when this object is in the open state @@ -75,9 +87,11 @@ public List WhatReceptaclesMustBeOffToOpen() { // Use this for initialization void Start() { - #if UNITY_EDITOR - if (!this.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanOpen)) { + if ( + !this.GetComponent() + .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanOpen) + ) { Debug.LogError(this.name + "is missing the CanOpen Secondary Property! Please set it!"); } #endif @@ -105,8 +119,14 @@ void Update() { #if UNITY_EDITOR void OnEnable() { // debug check for missing CanOpen property - if (!gameObject.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanOpen)) { - Debug.LogError(gameObject.transform.name + " is missing the Secondary Property CanOpen!"); + if ( + !gameObject + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanOpen) + ) { + Debug.LogError( + gameObject.transform.name + " is missing the Secondary Property CanOpen!" + ); } } @@ -121,14 +141,14 @@ public void SetMovementToRotate() { public void SetMovementToScale() { movementType = MovementType.Scale; } - #endif //sets the openness of a "rotation" based open/close object immediately without using tweening //specifically used for pre-scene setup public void SetOpennessImmediate(float openness = 1.0f) { for (int i = 0; i < MovingParts.Length; i++) { - Vector3 newRot = new Vector3(openPositions[i].x, openPositions[i].y, openPositions[i].z) * openness; + Vector3 newRot = + new Vector3(openPositions[i].x, openPositions[i].y, openPositions[i].z) * openness; MovingParts[i].transform.localRotation = Quaternion.Euler(newRot); } @@ -143,8 +163,7 @@ public void Interact( bool returnToStartMode = false, GameObject posRotManip = null, GameObject posRotRef = null - ) { - + ) { // if this object is pickupable AND it's trying to open (book, box, laptop, etc) // before trying to open or close, these objects must have kinematic = false otherwise it might clip through other objects SimObjPhysics sop = gameObject.GetComponent(); @@ -165,48 +184,60 @@ public void Interact( // okay let's open / reset the object! if (movementType == MovementType.Slide) { if (failure == failState.none || returnToStart == true) { - StartCoroutine(LerpPosition( - movingParts: MovingParts, - closedLocalPositions: closedPositions, - openLocalPositions: openPositions, - initialOpenness: currentOpenness, - desiredOpenness: targetOpenness, - animationTime: animationTime, - physicsInterval: (float)physicsInterval, - useGripper: useGripper, - returnToStartMode: returnToStartMode, - posRotManip: posRotManip, - posRotRef: posRotRef - )); + StartCoroutine( + LerpPosition( + movingParts: MovingParts, + closedLocalPositions: closedPositions, + openLocalPositions: openPositions, + initialOpenness: currentOpenness, + desiredOpenness: targetOpenness, + animationTime: animationTime, + physicsInterval: (float)physicsInterval, + useGripper: useGripper, + returnToStartMode: returnToStartMode, + posRotManip: posRotManip, + posRotRef: posRotRef + ) + ); } else { currentOpenness = lastSuccessfulOpenness; for (int i = 0; i < MovingParts.Length; i++) { - MovingParts[i].transform.localPosition = Vector3.Lerp(closedPositions[i], openPositions[i], currentOpenness); + MovingParts[i].transform.localPosition = Vector3.Lerp( + closedPositions[i], + openPositions[i], + currentOpenness + ); } SyncPosRot(posRotManip, posRotRef); - + setIsOpen(currentOpenness); isCurrentlyLerping = false; } } else if (movementType == MovementType.Rotate) { if (failure == failState.none || returnToStart == true) { - StartCoroutine(LerpRotation( - movingParts: MovingParts, - closedLocalRotations: closedPositions, - openLocalRotations: openPositions, - initialOpenness: currentOpenness, - desiredOpenness: targetOpenness, - animationTime: animationTime, - physicsInterval: (float)physicsInterval, - useGripper: useGripper, - returnToStartMode: returnToStartMode, - posRotManip: posRotManip, - posRotRef: posRotRef - )); + StartCoroutine( + LerpRotation( + movingParts: MovingParts, + closedLocalRotations: closedPositions, + openLocalRotations: openPositions, + initialOpenness: currentOpenness, + desiredOpenness: targetOpenness, + animationTime: animationTime, + physicsInterval: (float)physicsInterval, + useGripper: useGripper, + returnToStartMode: returnToStartMode, + posRotManip: posRotManip, + posRotRef: posRotRef + ) + ); } else { currentOpenness = lastSuccessfulOpenness; for (int i = 0; i < MovingParts.Length; i++) { - MovingParts[i].transform.localRotation = Quaternion.Lerp(Quaternion.Euler(closedPositions[i]), Quaternion.Euler(openPositions[i]), currentOpenness); + MovingParts[i].transform.localRotation = Quaternion.Lerp( + Quaternion.Euler(closedPositions[i]), + Quaternion.Euler(openPositions[i]), + currentOpenness + ); } SyncPosRot(posRotManip, posRotRef); @@ -215,23 +246,29 @@ public void Interact( } } else if (movementType == MovementType.Scale) { if (failure == failState.none || returnToStart == true) { - StartCoroutine(LerpScale( - movingParts: MovingParts, - closedLocalScales: closedPositions, - openLocalScales: openPositions, - initialOpenness: currentOpenness, - desiredOpenness: targetOpenness, - animationTime: animationTime, - physicsInterval: (float)physicsInterval, - useGripper: useGripper, - returnToStartMode: returnToStartMode, - posRotManip: posRotManip, - posRotRef: posRotRef - )); + StartCoroutine( + LerpScale( + movingParts: MovingParts, + closedLocalScales: closedPositions, + openLocalScales: openPositions, + initialOpenness: currentOpenness, + desiredOpenness: targetOpenness, + animationTime: animationTime, + physicsInterval: (float)physicsInterval, + useGripper: useGripper, + returnToStartMode: returnToStartMode, + posRotManip: posRotManip, + posRotRef: posRotRef + ) + ); } else { currentOpenness = lastSuccessfulOpenness; for (int i = 0; i < MovingParts.Length; i++) { - MovingParts[i].transform.localScale = Vector3.Lerp(closedPositions[i], openPositions[i], currentOpenness); + MovingParts[i].transform.localScale = Vector3.Lerp( + closedPositions[i], + openPositions[i], + currentOpenness + ); } SyncPosRot(posRotManip, posRotRef); @@ -255,17 +292,24 @@ private protected IEnumerator LerpPosition( GameObject posRotRef ) { float elapsedTime = 0f; - while (elapsedTime < animationTime && (failure == failState.none || returnToStartMode == true)) - { + while ( + elapsedTime < animationTime && (failure == failState.none || returnToStartMode == true) + ) { lastSuccessfulOpenness = currentOpenness; elapsedTime += physicsInterval; currentOpenness = Mathf.Clamp( - initialOpenness + (desiredOpenness - initialOpenness) * (elapsedTime / animationTime), + initialOpenness + + (desiredOpenness - initialOpenness) * (elapsedTime / animationTime), Mathf.Min(initialOpenness, desiredOpenness), - Mathf.Max(initialOpenness, desiredOpenness)); + Mathf.Max(initialOpenness, desiredOpenness) + ); for (int i = 0; i < movingParts.Length; i++) { - movingParts[i].transform.localPosition = Vector3.Lerp(closedLocalPositions[i], openLocalPositions[i], currentOpenness); + movingParts[i].transform.localPosition = Vector3.Lerp( + closedLocalPositions[i], + openLocalPositions[i], + currentOpenness + ); } if (useGripper == true) { @@ -297,17 +341,24 @@ private protected IEnumerator LerpRotation( GameObject posRotRef ) { float elapsedTime = 0f; - while (elapsedTime < animationTime && (failure == failState.none || returnToStartMode == true)) - { + while ( + elapsedTime < animationTime && (failure == failState.none || returnToStartMode == true) + ) { lastSuccessfulOpenness = currentOpenness; elapsedTime += physicsInterval; currentOpenness = Mathf.Clamp( - initialOpenness + (desiredOpenness - initialOpenness) * (elapsedTime / animationTime), + initialOpenness + + (desiredOpenness - initialOpenness) * (elapsedTime / animationTime), Mathf.Min(initialOpenness, desiredOpenness), - Mathf.Max(initialOpenness, desiredOpenness)); + Mathf.Max(initialOpenness, desiredOpenness) + ); for (int i = 0; i < movingParts.Length; i++) { - movingParts[i].transform.localRotation = Quaternion.Lerp(Quaternion.Euler(closedLocalRotations[i]), Quaternion.Euler(openLocalRotations[i]), currentOpenness); + movingParts[i].transform.localRotation = Quaternion.Lerp( + Quaternion.Euler(closedLocalRotations[i]), + Quaternion.Euler(openLocalRotations[i]), + currentOpenness + ); } if (useGripper == true) { @@ -340,17 +391,24 @@ GameObject posRotRef ) { float elapsedTime = 0f; - while (elapsedTime < animationTime && (failure == failState.none || returnToStartMode == true)) - { + while ( + elapsedTime < animationTime && (failure == failState.none || returnToStartMode == true) + ) { lastSuccessfulOpenness = currentOpenness; elapsedTime += physicsInterval; currentOpenness = Mathf.Clamp( - initialOpenness + (desiredOpenness - initialOpenness) * (elapsedTime / animationTime), + initialOpenness + + (desiredOpenness - initialOpenness) * (elapsedTime / animationTime), Mathf.Min(initialOpenness, desiredOpenness), - Mathf.Max(initialOpenness, desiredOpenness)); + Mathf.Max(initialOpenness, desiredOpenness) + ); for (int i = 0; i < movingParts.Length; i++) { - movingParts[i].transform.localScale = Vector3.Lerp(closedLocalScales[i], openLocalScales[i], currentOpenness); + movingParts[i].transform.localScale = Vector3.Lerp( + closedLocalScales[i], + openLocalScales[i], + currentOpenness + ); } if (useGripper == true) { @@ -377,10 +435,7 @@ public bool GetisOpen() { return isOpen; } - public void stepOpen( - float physicsInterval, - bool useGripper, - float elapsedTime) { + public void stepOpen(float physicsInterval, bool useGripper, float elapsedTime) { if (Physics.autoSimulation != true) { PhysicsSceneManager.PhysicsSimulateTHOR(physicsInterval); Physics.SyncTransforms(); @@ -389,11 +444,19 @@ public void stepOpen( // failure check (The OnTriggerEnter collision check is listening at all times, // but this hyperextension check must be called manually) if (useGripper == true && forceAction == false) { - FK_IK_Solver armBase = GameObject.Find("FPSController").GetComponent().IKArm.GetComponent().GetArmBase().GetComponent(); - if ((armBase.IKTarget.position - armBase.armShoulder.position).magnitude + 1e-5 >= armBase.bone2Length + armBase.bone3Length) { + FK_IK_Solver armBase = GameObject + .Find("FPSController") + .GetComponent() + .IKArm.GetComponent() + .GetArmBase() + .GetComponent(); + if ( + (armBase.IKTarget.position - armBase.armShoulder.position).magnitude + 1e-5 + >= armBase.bone2Length + armBase.bone3Length + ) { failure = failState.hyperextension; #if UNITY_EDITOR - Debug.Log("Agent-arm hyperextended at " + elapsedTime + ". Resetting openness."); + Debug.Log("Agent-arm hyperextended at " + elapsedTime + ". Resetting openness."); #endif } } @@ -432,7 +495,7 @@ public void OnTriggerEnter(Collider other) { } // If the collider is a BoundingBox or ReceptacleTriggerBox, then ignore - if (other.gameObject.layer == LayerMask.NameToLayer ("SimObjectInvisible")) { + if (other.gameObject.layer == LayerMask.NameToLayer("SimObjectInvisible")) { // Debug.Log(other + " is bounding box or receptacle trigger box"); return; } @@ -444,16 +507,22 @@ public void OnTriggerEnter(Collider other) { } // If the overlapping collider is a descendant of the agent when ignoreAgentInTransition is true, then ignore - if (ignoreAgentInTransition == true && hasAncestor(other.transform.gameObject, GameObject.Find("FPSController"))) { + if ( + ignoreAgentInTransition == true + && hasAncestor(other.transform.gameObject, GameObject.Find("FPSController")) + ) { // Debug.Log(other + " belongs to agent, and ignoreAgentInTransition is active!"); return; } // If the overlapping collider belongs to a non-static SimObject, then ignore // (Unless we explicitly tell the action to treat non-static SimObjects as barriers) - if (ancestorSimObjPhysics(other.gameObject) != null && - ancestorSimObjPhysics(other.gameObject).PrimaryProperty != SimObjPrimaryProperty.Static && - stopAtNonStaticCol == false) { + if ( + ancestorSimObjPhysics(other.gameObject) != null + && ancestorSimObjPhysics(other.gameObject).PrimaryProperty + != SimObjPrimaryProperty.Static + && stopAtNonStaticCol == false + ) { // Debug.Log("Ignore nonstatics " + other); return; } @@ -462,8 +531,7 @@ public void OnTriggerEnter(Collider other) { failure = failState.collision; if (ancestorSimObjPhysics(other.gameObject) != null) { failureCollision = other.GetComponentInParent().gameObject; - } - else { + } else { failureCollision = other.gameObject; } #if UNITY_EDITOR @@ -475,12 +543,13 @@ public void OnTriggerEnter(Collider other) { // return true if it should ignore the object hit. Return false to cause this object to reset to the original position public bool IsInIgnoreArray(Collider other, GameObject[] ignoredObjects) { foreach (GameObject ignoredObject in ignoredObjects) { - foreach (Collider ignoredCollider in ignoredObject.GetComponentsInChildren()) + foreach (Collider ignoredCollider in ignoredObject.GetComponentsInChildren()) { if (other == ignoredCollider) { return true; } + } } - return false; + return false; } private bool hasAncestor(GameObject child, GameObject potentialAncestor) { @@ -510,43 +579,53 @@ private static SimObjPhysics ancestorSimObjPhysics(GameObject go) { public MovementType GetMovementType() { return movementType; } + public float GetStartOpenness() { return startOpenness; } + public void SetFailState(failState failState) { failure = failState; } + public failState GetFailState() { return failure; } + public void SetFailureCollision(GameObject collision) { failureCollision = collision; } + public GameObject GetFailureCollision() { return failureCollision; } + public void SetForceAction(bool forceAction) { this.forceAction = forceAction; } + public void SetIgnoreAgentInTransition(bool ignoreAgentInTransition) { this.ignoreAgentInTransition = ignoreAgentInTransition; } + public void SetStopAtNonStaticCol(bool stopAtNonStaticCol) { this.stopAtNonStaticCol = stopAtNonStaticCol; } + public bool GetIsCurrentlyLerping() { if (this.isCurrentlyLerping) { return true; - } - else { + } else { return false; } } + public void SetIsCurrentlyLerping(bool isCurrentlyLerping) { this.isCurrentlyLerping = isCurrentlyLerping; } + public void SyncPosRot(GameObject child, GameObject parent) { - child.transform.position = parent.transform.position; - child.transform.rotation = parent.transform.rotation; + child.transform.position = parent.transform.position; + child.transform.rotation = parent.transform.rotation; } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/CanToggleOnOff.cs b/unity/Assets/Scripts/CanToggleOnOff.cs index e03f65c2c6..db42f092e4 100644 --- a/unity/Assets/Scripts/CanToggleOnOff.cs +++ b/unity/Assets/Scripts/CanToggleOnOff.cs @@ -19,11 +19,10 @@ public class SwapObjList { [Header("Materials for Off state")] [SerializeField] public Material[] OffMaterials; - } public class CanToggleOnOff : MonoBehaviour { - // the array of moving parts and lightsources will correspond with each other based on their + // the array of moving parts and lightsources will correspond with each other based on their // position in the array // these are any switches, dials, levers, etc that should change position or orientation when toggle on or off @@ -47,7 +46,6 @@ public class CanToggleOnOff : MonoBehaviour { public GameObject[] effects; [Header("Animation Parameters")] - // rotations or translations for the MovingParts when On [SerializeField] public Vector3[] OnPositions; @@ -66,14 +64,19 @@ public class CanToggleOnOff : MonoBehaviour { private bool isCurrentlyLerping = false; - protected enum MovementType { Slide, Rotate }; + protected enum MovementType { + Slide, + Rotate + }; [SerializeField] protected MovementType movementType; // keep a list of all objects that can turn on, but must be in the closed state before turning on (ie: can't microwave an object with the door open!) protected List MustBeClosedToTurnOn = new List() - {SimObjType.Microwave}; + { + SimObjType.Microwave + }; // if this object controls the on/off state of ONLY itself, set to true (lamps, laptops, etc.) // if this object's on/off state is not controlled by itself, but instead controlled by another sim object (ex: stove burner is controlled by the stove knob) set this to false @@ -115,17 +118,20 @@ public void SetMovementToSlide() { public void SetMovementToRotate() { movementType = MovementType.Rotate; } - #endif // Use this for initialization void Start() { - //setLightSourcesNames(); #if UNITY_EDITOR - if (!this.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanToggleOnOff)) { - Debug.LogError(this.name + "is missing the CanToggleOnOff Secondary Property! Please set it!"); + if ( + !this.GetComponent() + .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanToggleOnOff) + ) { + Debug.LogError( + this.name + "is missing the CanToggleOnOff Secondary Property! Please set it!" + ); } #endif } @@ -135,7 +141,7 @@ void Start() { // public void setLightSourcesNames () { // for (int i = 0; i < LightSources.Length; i++ ) { // Light actualLightCauseSometimesTheseAreNested = LightSources[i].GetComponentInChildren(); - // actualLightCauseSometimesTheseAreNested.name = + // actualLightCauseSometimesTheseAreNested.name = // this.GetComponent().objectID + "|" + LightSources[i].GetComponentInChildren().type.ToString()+ "|" + i.ToString(); // } // } @@ -143,12 +149,11 @@ void Start() { // Update is called once per frame void Update() { // // test if it can open without Agent Command - Debug Purposes - #if UNITY_EDITOR - if (Input.GetKeyDown(KeyCode.Minus)) - { +#if UNITY_EDITOR + if (Input.GetKeyDown(KeyCode.Minus)) { Toggle(); } - #endif +#endif } public void Toggle() { @@ -156,7 +161,7 @@ public void Toggle() { if (!SelfControlled) { return; } - + isCurrentlyLerping = true; // check if there are moving parts // check if there are lights/materials etc to swap out @@ -164,25 +169,27 @@ public void Toggle() { if (MovingParts.Length > 0) { for (int i = 0; i < MovingParts.Length; i++) { if (movementType == MovementType.Slide) { - StartCoroutine(LerpPosition( - movingParts: MovingParts, - offLocalPositions: OffPositions, - onLocalPositions: OnPositions, - initialOpenness: 0, - desiredOpenness: 1, - animationTime: animationTime - )); - } - - else if (movementType == MovementType.Rotate) { - StartCoroutine(LerpRotation( - movingParts: MovingParts, - offLocalRotations: OffPositions, - onLocalRotations: OnPositions, - initialOpenness: 0, - desiredOpenness: 1, - animationTime: animationTime - )); + StartCoroutine( + LerpPosition( + movingParts: MovingParts, + offLocalPositions: OffPositions, + onLocalPositions: OnPositions, + initialOpenness: 0, + desiredOpenness: 1, + animationTime: animationTime + ) + ); + } else if (movementType == MovementType.Rotate) { + StartCoroutine( + LerpRotation( + movingParts: MovingParts, + offLocalRotations: OffPositions, + onLocalRotations: OnPositions, + initialOpenness: 0, + desiredOpenness: 1, + animationTime: animationTime + ) + ); } } } @@ -192,26 +199,28 @@ public void Toggle() { if (MovingParts.Length > 0) { for (int i = 0; i < MovingParts.Length; i++) { if (movementType == MovementType.Slide) { - StartCoroutine(LerpPosition( - movingParts: MovingParts, - offLocalPositions: OffPositions, - onLocalPositions: OnPositions, - initialOpenness: 1, - desiredOpenness: 0, - animationTime: animationTime - )); + StartCoroutine( + LerpPosition( + movingParts: MovingParts, + offLocalPositions: OffPositions, + onLocalPositions: OnPositions, + initialOpenness: 1, + desiredOpenness: 0, + animationTime: animationTime + ) + ); + } else if (movementType == MovementType.Rotate) { + StartCoroutine( + LerpRotation( + movingParts: MovingParts, + offLocalRotations: OffPositions, + onLocalRotations: OnPositions, + initialOpenness: 1, + desiredOpenness: 0, + animationTime: animationTime + ) + ); } - - else if (movementType == MovementType.Rotate) { - StartCoroutine(LerpRotation( - movingParts: MovingParts, - offLocalRotations: OffPositions, - onLocalRotations: OnPositions, - initialOpenness: 1, - desiredOpenness: 0, - animationTime: animationTime - )); - } } } @@ -230,8 +239,8 @@ private void setisOn() { } } - if(effects.Length > 0) { - for (int i = 0; i< effects.Length; i++) { + if (effects.Length > 0) { + for (int i = 0; i < effects.Length; i++) { effects[i].SetActive(false); } } @@ -239,7 +248,7 @@ private void setisOn() { if (MaterialSwapObjects.Length > 0) { for (int i = 0; i < MaterialSwapObjects.Length; i++) { MaterialSwapObjects[i].MyObject.GetComponent().materials = - MaterialSwapObjects[i].OffMaterials; + MaterialSwapObjects[i].OffMaterials; } } @@ -252,7 +261,6 @@ private void setisOn() { isOn = false; } - // if isOn false, set to true and then turn ON all lights and activate material swaps else { if (LightSources.Length > 0) { @@ -261,8 +269,8 @@ private void setisOn() { } } - if(effects.Length > 0) { - for (int i = 0; i< effects.Length; i++) { + if (effects.Length > 0) { + for (int i = 0; i < effects.Length; i++) { effects[i].SetActive(true); } } @@ -270,7 +278,7 @@ private void setisOn() { if (MaterialSwapObjects.Length > 0) { for (int i = 0; i < MaterialSwapObjects.Length; i++) { MaterialSwapObjects[i].MyObject.GetComponent().materials = - MaterialSwapObjects[i].OnMaterials; + MaterialSwapObjects[i].OnMaterials; } } @@ -297,15 +305,22 @@ float animationTime while (elapsedTime < animationTime) { elapsedTime += Time.fixedDeltaTime; float currentOpenness = Mathf.Clamp( - initialOpenness + (desiredOpenness - initialOpenness) * (elapsedTime / animationTime), + initialOpenness + + (desiredOpenness - initialOpenness) * (elapsedTime / animationTime), Mathf.Min(initialOpenness, desiredOpenness), - Mathf.Max(initialOpenness, desiredOpenness)); + Mathf.Max(initialOpenness, desiredOpenness) + ); for (int i = 0; i < movingParts.Length; i++) { - movingParts[i].transform.localPosition = Vector3.Lerp(offLocalPositions[i], onLocalPositions[i], currentOpenness); + movingParts[i].transform.localPosition = Vector3.Lerp( + offLocalPositions[i], + onLocalPositions[i], + currentOpenness + ); } } yield break; } + private protected IEnumerator LerpRotation( GameObject[] movingParts, Vector3[] offLocalRotations, @@ -318,30 +333,36 @@ float animationTime while (elapsedTime < animationTime) { elapsedTime += Time.fixedDeltaTime; float currentOpenness = Mathf.Clamp( - initialOpenness + (desiredOpenness - initialOpenness) * (elapsedTime / animationTime), + initialOpenness + + (desiredOpenness - initialOpenness) * (elapsedTime / animationTime), Mathf.Min(initialOpenness, desiredOpenness), - Mathf.Max(initialOpenness, desiredOpenness)); + Mathf.Max(initialOpenness, desiredOpenness) + ); for (int i = 0; i < MovingParts.Length; i++) { - MovingParts[i].transform.localRotation = Quaternion.Lerp(Quaternion.Euler(offLocalRotations[i]), Quaternion.Euler(onLocalRotations[i]), currentOpenness); - } + MovingParts[i].transform.localRotation = Quaternion.Lerp( + Quaternion.Euler(offLocalRotations[i]), + Quaternion.Euler(onLocalRotations[i]), + currentOpenness + ); + } } yield break; } + public bool GetIsCurrentlyLerping() { if (this.isCurrentlyLerping) { return true; - } - else { + } else { return false; } } - + // [ContextMenu("Get On-Off Materials")] // void ContextOnOffMaterials() // { // foreach (SwapObjList swap in MaterialSwapObjects) // { - // List list = + // List list = // new List(swap.MyObject.GetComponent().sharedMaterials); // // print(swap.MyObject.name); diff --git a/unity/Assets/Scripts/ChangeLighting.cs b/unity/Assets/Scripts/ChangeLighting.cs index 8da872e21e..da85e4c7ad 100644 --- a/unity/Assets/Scripts/ChangeLighting.cs +++ b/unity/Assets/Scripts/ChangeLighting.cs @@ -7,14 +7,10 @@ public class ChangeLighting : MonoBehaviour { public GameObject[] Lights; // Start is called before the first frame update - void Start() { - - } + void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } public void SetLights(int lightset) { foreach (GameObject go in Lights) { diff --git a/unity/Assets/Scripts/ClippingPlane/ClippingPlane.cs b/unity/Assets/Scripts/ClippingPlane/ClippingPlane.cs index 1fbd7320d9..e3587046c3 100644 --- a/unity/Assets/Scripts/ClippingPlane/ClippingPlane.cs +++ b/unity/Assets/Scripts/ClippingPlane/ClippingPlane.cs @@ -5,22 +5,32 @@ using UnityEngine; -namespace Ronja { +namespace Ronja +{ [ExecuteAlways] - public class ClippingPlane : MonoBehaviour { + public class ClippingPlane : MonoBehaviour + { // Materials we pass the values to public Material[] materials = null; public bool shouldClip = true; // Execute every frame - void Update () { + void Update() + { // Create plane Plane plane = new Plane(transform.up, transform.position); // Transfer values from plane to vector4 - Vector4 planeRepresentation = new Vector4(plane.normal.x, plane.normal.y, plane.normal.z, plane.distance); + Vector4 planeRepresentation = new Vector4( + plane.normal.x, + plane.normal.y, + plane.normal.z, + plane.distance + ); // Pass vector to shader - if (materials != null) { - foreach (Material mat in materials) { + if (materials != null) + { + foreach (Material mat in materials) + { mat.SetVector("_Plane", planeRepresentation); mat.SetInt("_IsEnabled", (shouldClip ? 1 : 0)); } @@ -28,4 +38,3 @@ void Update () { } } } - diff --git a/unity/Assets/Scripts/ColdZone.cs b/unity/Assets/Scripts/ColdZone.cs index ef7ce2165e..a432165da0 100644 --- a/unity/Assets/Scripts/ColdZone.cs +++ b/unity/Assets/Scripts/ColdZone.cs @@ -4,14 +4,10 @@ public class ColdZone : MonoBehaviour { // Start is called before the first frame update - void Start() { - - } + void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } public void OnTriggerStay(Collider other) { // if any simobjphys are touching this zone, set their temperature values to Cold diff --git a/unity/Assets/Scripts/CollisionEventResolver.cs b/unity/Assets/Scripts/CollisionEventResolver.cs index 4b0c7bd76f..6debb01d8f 100644 --- a/unity/Assets/Scripts/CollisionEventResolver.cs +++ b/unity/Assets/Scripts/CollisionEventResolver.cs @@ -2,17 +2,18 @@ using System.Collections.Generic; using UnityEngine; - public abstract class CollisionEventResolver : MonoBehaviour { - protected void Start() { var listener = this.transform.GetComponentInParent(); if (listener != null) { listener.setCollisionEventResolver(this); } } - public abstract StaticCollision resolveToStaticCollision(Collider externalCollider, HashSet internalColliders); + public abstract StaticCollision resolveToStaticCollision( + Collider externalCollider, + HashSet internalColliders + ); } // Class to track what was hit while arm was moving @@ -35,4 +36,4 @@ public string name { } } } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/CollisionListener.cs b/unity/Assets/Scripts/CollisionListener.cs index 69c9b871cc..ba544a72c6 100644 --- a/unity/Assets/Scripts/CollisionListener.cs +++ b/unity/Assets/Scripts/CollisionListener.cs @@ -1,13 +1,13 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using UnityEngine; - using UnityStandardAssets.Characters.FirstPerson; -using System.Linq; public class CollisionListener : MonoBehaviour { - public Dictionary> externalColliderToInternalCollisions = new Dictionary>(); + public Dictionary> externalColliderToInternalCollisions = + new Dictionary>(); public List doNotRegisterChildrenWithin = new List(); public bool deadZoneCheck; public static bool useMassThreshold = false; @@ -15,14 +15,17 @@ public class CollisionListener : MonoBehaviour { public CollisionEventResolver collisionEventResolver; - private HashSet collisionListenerChildren = new HashSet(); + private HashSet collisionListenerChildren = + new HashSet(); void Start() { registerAllChildColliders(); foreach (CollisionListener cl in this.GetComponentsInChildren()) { if (cl.gameObject != this.gameObject) { #if UNITY_EDITOR - Debug.Log($"Offending CollisionListener: {cl.gameObject} a descendent of {this.gameObject}"); + Debug.Log( + $"Offending CollisionListener: {cl.gameObject} a descendent of {this.gameObject}" + ); #endif throw new InvalidOperationException( "A CollisionListener should not be included as a component on a descendent of a GameObject that already has a CollisionListener component." @@ -104,7 +107,8 @@ public void Reset() { } private static bool debugCheckIfCollisionIsNonTrivial( - Collider internalCollider, Collider externalCollider + Collider internalCollider, + Collider externalCollider ) { Vector3 direction; float distance = 0f; @@ -118,7 +122,9 @@ private static bool debugCheckIfCollisionIsNonTrivial( out direction, out distance ); - Debug.Log($"Us: {internalCollider.transform.gameObject}, Them: {externalCollider.gameObject}"); + Debug.Log( + $"Us: {internalCollider.transform.gameObject}, Them: {externalCollider.gameObject}" + ); Debug.Log($"Distance: {distance}, direction: {direction.ToString("F4")}"); return distance > 0.001f; } @@ -129,14 +135,16 @@ private StaticCollision ColliderToStaticCollision(Collider collider) { if (collider.GetComponentInParent()) { // how does this handle nested sim objects? maybe it's fine? SimObjPhysics sop = collider.GetComponentInParent(); - if (sop.PrimaryProperty == SimObjPrimaryProperty.Static || sop.GetComponent().isKinematic == true) { + if ( + sop.PrimaryProperty == SimObjPrimaryProperty.Static + || sop.GetComponent().isKinematic == true + ) { // #if UNITY_EDITOR // Debug.Log("Collided with static sim obj " + sop.name); // #endif sc = new StaticCollision(); sc.simObjPhysics = sop; sc.gameObject = collider.gameObject; - } else if (useMassThreshold) { // if a moveable or pickupable object is too heavy for the arm to move // flag it as a static collision so the arm will stop @@ -149,19 +157,17 @@ private StaticCollision ColliderToStaticCollision(Collider collider) { } else if (collider.gameObject.CompareTag("Structure")) { sc = new StaticCollision(); sc.gameObject = collider.gameObject; + } else if (collisionEventResolver != null) { + sc = collisionEventResolver.resolveToStaticCollision( + collider, + externalColliderToInternalCollisions[collider] + ); } - else if (collisionEventResolver != null) { - sc = collisionEventResolver.resolveToStaticCollision(collider, externalColliderToInternalCollisions[collider]); - } - - } return sc; } - public IEnumerable StaticCollisions( - IEnumerable colliders - ) { + public IEnumerable StaticCollisions(IEnumerable colliders) { foreach (Collider c in colliders) { var staticCollision = ColliderToStaticCollision(collider: c); if (staticCollision != null) { @@ -182,9 +188,13 @@ public bool TransformChecks(PhysicsRemoteFPSAgentController controller, Transfor // this action is specifically for a stretch wrist-rotation with limits if (deadZoneCheck) { float currentYaw = objectTarget.rotation.eulerAngles.y; - float cLimit = controller.gameObject.GetComponentInChildren().wristClockwiseLocalRotationLimit; - float ccLimit = controller.gameObject.GetComponentInChildren().wristCounterClockwiseLocalRotationLimit; - + float cLimit = controller + .gameObject.GetComponentInChildren() + .wristClockwiseLocalRotationLimit; + float ccLimit = controller + .gameObject.GetComponentInChildren() + .wristCounterClockwiseLocalRotationLimit; + // Consolidate reachable euler-rotations (which are normally bounded by [0, 360)) into a continuous number line, // bounded instead by [continuousCounterClockwiseLocalRotationLimit, continuousClockwiseLocalRotationLimit + 360) if (cLimit < ccLimit) { @@ -207,5 +217,4 @@ public bool TransformChecks(PhysicsRemoteFPSAgentController controller, Transfor public virtual bool ShouldHalt() { return StaticCollisions().GetEnumerator().MoveNext(); } - } diff --git a/unity/Assets/Scripts/CollisionListenerAB.cs b/unity/Assets/Scripts/CollisionListenerAB.cs index 26ddf0ca06..b521bf4c50 100644 --- a/unity/Assets/Scripts/CollisionListenerAB.cs +++ b/unity/Assets/Scripts/CollisionListenerAB.cs @@ -1,11 +1,8 @@ public class CollisionListenerAB : CollisionListener { - // public ArticulatedArmController armController; public override bool ShouldHalt() { - // TODO: Implement halting condition, you can use armController.GetArmTarget() , and othe properties return false; } - } diff --git a/unity/Assets/Scripts/CollisionListenerChild.cs b/unity/Assets/Scripts/CollisionListenerChild.cs index e3a5d0ce70..236906846e 100644 --- a/unity/Assets/Scripts/CollisionListenerChild.cs +++ b/unity/Assets/Scripts/CollisionListenerChild.cs @@ -1,7 +1,6 @@ using System.Collections; using System.Collections.Generic; using UnityEngine; - using UnityStandardAssets.Characters.FirstPerson; public class CollisionListenerChild : MonoBehaviour { @@ -14,7 +13,6 @@ public void Start() { us = this.gameObject.GetComponent(); } - public void OnDestroy() { if (parent != null) { parent.deregisterChild(this.GetComponent()); @@ -31,7 +29,12 @@ public void OnTriggerStay(Collider col) { #if UNITY_EDITOR if (!parent.externalColliderToInternalCollisions.ContainsKey(col)) { if (col.gameObject.name == "StandardIslandHeight" || col.gameObject.name == "Sphere") { - Debug.Log("got collision stay with " + col.gameObject.name + " this" + this.gameObject.name); + Debug.Log( + "got collision stay with " + + col.gameObject.name + + " this" + + this.gameObject.name + ); } } #endif @@ -44,7 +47,12 @@ public void OnTriggerEnter(Collider col) { #if UNITY_EDITOR if (!parent.externalColliderToInternalCollisions.ContainsKey(col)) { if (col.gameObject.name == "StandardIslandHeight" || col.gameObject.name == "Sphere") { - Debug.Log("got collision enter with " + col.gameObject.name + " this" + this.gameObject.name); + Debug.Log( + "got collision enter with " + + col.gameObject.name + + " this" + + this.gameObject.name + ); } } #endif diff --git a/unity/Assets/Scripts/ColorChanger.cs b/unity/Assets/Scripts/ColorChanger.cs index 1a1c6542cb..7ea2e4e137 100644 --- a/unity/Assets/Scripts/ColorChanger.cs +++ b/unity/Assets/Scripts/ColorChanger.cs @@ -1,9 +1,7 @@ -using UnityEngine; -using System.Collections.Generic; +using System.Collections.Generic; +using UnityEngine; using Random = UnityEngine.Random; - - public class ColorChanger : MonoBehaviour { // These will eventually be turned into sets, such that they are // easily checkable at runtime. @@ -14,7 +12,8 @@ public class ColorChanger : MonoBehaviour { private ResourceAssetManager assetManager; protected void cacheMaterials() { - var objectMaterialLabels = new string[] { + var objectMaterialLabels = new string[] + { "AlarmClockMaterials", "AppleMaterials", "BasketballMaterials", @@ -68,7 +67,8 @@ protected void cacheMaterials() { "PanDecalMaterials", "CoffeeMachineMaterials" }; - var materialGroupLabels = new string[] { + var materialGroupLabels = new string[] + { "RawTrainMaterials", "RawValMaterials", "RawTestMaterials", @@ -89,7 +89,11 @@ protected void cacheMaterials() { materialGroupPaths = new Dictionary>(); foreach (var label in materialGroupLabels) { HashSet paths = new HashSet(); - foreach (var resourceAssetRef in this.assetManager.FindResourceAssetReferences(label)) { + foreach ( + var resourceAssetRef in this.assetManager.FindResourceAssetReferences( + label + ) + ) { paths.Add(resourceAssetRef.ResourcePath); } @@ -120,7 +124,10 @@ private void swapMaterial(Material mat1, Material mat2) { } } - private void shuffleMaterials(HashSet activeMaterialNames, List> materialGroup) { + private void shuffleMaterials( + HashSet activeMaterialNames, + List> materialGroup + ) { for (int n = materialGroup.Count - 1; n >= 0; n--) { int i = Random.Range(0, n + 1); @@ -136,8 +143,6 @@ private void shuffleMaterials(HashSet activeMaterialNames, List activeMaterialNames = new HashSet(); @@ -180,13 +185,25 @@ public int RandomizeMaterials( } } - foreach (KeyValuePair>> materialGroup in objectMaterials) { - List> validMaterials = new List>(); + foreach ( + KeyValuePair< + string, + List> + > materialGroup in objectMaterials + ) { + List> validMaterials = + new List>(); foreach (ResourceAssetReference resourceAssetReference in materialGroup.Value) { if ( - useTrainMaterials && materialGroupPaths["RawTrainMaterials"].Contains(resourceAssetReference.ResourcePath) || - useValMaterials && materialGroupPaths["RawValMaterials"].Contains(resourceAssetReference.ResourcePath) || - useTestMaterials && materialGroupPaths["RawTestMaterials"].Contains(resourceAssetReference.ResourcePath) + useTrainMaterials + && materialGroupPaths["RawTrainMaterials"] + .Contains(resourceAssetReference.ResourcePath) + || useValMaterials + && materialGroupPaths["RawValMaterials"] + .Contains(resourceAssetReference.ResourcePath) + || useTestMaterials + && materialGroupPaths["RawTestMaterials"] + .Contains(resourceAssetReference.ResourcePath) ) { if (inRoomTypes == null) { validMaterials.Add(resourceAssetReference); @@ -194,7 +211,10 @@ public int RandomizeMaterials( } else { foreach (string roomType in inRoomTypes) { string roomLabel = roomTypeLabelMap[roomType]; - if (materialGroupPaths[roomLabel].Contains(resourceAssetReference.ResourcePath)) { + if ( + materialGroupPaths[roomLabel] + .Contains(resourceAssetReference.ResourcePath) + ) { validMaterials.Add(resourceAssetReference); numTotalMaterials++; break; @@ -207,8 +227,6 @@ public int RandomizeMaterials( shuffleMaterials(activeMaterialNames, validMaterials); } - - return numTotalMaterials; } diff --git a/unity/Assets/Scripts/ConnectionProperties.cs b/unity/Assets/Scripts/ConnectionProperties.cs index 0443d00eb2..f73a0de346 100644 --- a/unity/Assets/Scripts/ConnectionProperties.cs +++ b/unity/Assets/Scripts/ConnectionProperties.cs @@ -1,7 +1,7 @@ using System.Collections; using System.Collections.Generic; -using UnityEngine; using EasyButtons; +using UnityEngine; public enum ConnectionType { Unknown = 0, @@ -19,8 +19,6 @@ public class ConnectionProperties : MonoBehaviour { //public Material WallMaterialId [Button] public void ToggleOpen() { - - var canOpen = this.gameObject.GetComponentInChildren(); if (canOpen != null) { canOpen.SetOpennessImmediate(!this.IsOpen ? 1.0f : 0.0f); @@ -29,7 +27,7 @@ public void ToggleOpen() { } // [Button] - // public void Close() { + // public void Close() { // this.IsOpen = false; // var canOpen = this.gameObject..GetComponentInChildren(); // if (canOpen != null) { diff --git a/unity/Assets/Scripts/Contains.cs b/unity/Assets/Scripts/Contains.cs index 53bcff4f55..75a3b0d87e 100644 --- a/unity/Assets/Scripts/Contains.cs +++ b/unity/Assets/Scripts/Contains.cs @@ -1,7 +1,6 @@ using System.Collections; using System.Collections.Generic; using UnityEngine; - // we need to grab the FPSController for some checks using UnityStandardAssets.Characters.FirstPerson; @@ -26,7 +25,8 @@ public ReceptacleSpawnPoint(Vector3 p, BoxCollider box, Contains c, SimObjPhysic } public class Contains : MonoBehaviour { - [SerializeField] protected List CurrentlyContains = new List(); + [SerializeField] + protected List CurrentlyContains = new List(); // this is an object reference to the sim object that is linked to this receptacle box public GameObject myParent = null; @@ -49,14 +49,16 @@ void OnEnable() { myParent = gameObject.GetComponentInParent().transform.gameObject; } } - } + void Start() { // check that all objects with receptacles components have the correct Receptacle secondary property #if UNITY_EDITOR SimObjPhysics go = gameObject.GetComponentInParent(); if (!go.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { - Debug.LogError(go.transform.name + " is missing Receptacle Secondary Property! please hook them up"); + Debug.LogError( + go.transform.name + " is missing Receptacle Secondary Property! please hook them up" + ); } #endif } @@ -100,27 +102,33 @@ public List CurrentlyContainedGameObjects() { Vector3 worldCenter = b.transform.TransformPoint(b.center); // size of this receptacle box, but we need to scale by transform - Vector3 worldHalfExtents = new Vector3(b.size.x * b.transform.lossyScale.x / 2, b.size.y * b.transform.lossyScale.y / 2, b.size.z * b.transform.lossyScale.z / 2); + Vector3 worldHalfExtents = new Vector3( + b.size.x * b.transform.lossyScale.x / 2, + b.size.y * b.transform.lossyScale.y / 2, + b.size.z * b.transform.lossyScale.z / 2 + ); ////////////////////////////////////////////////// // uncomment to debug "draw" where the OverlapBox goes - // GameObject surrogateGeo = GameObject.CreatePrimitive(PrimitiveType.Cube); - // Destroy(surrogateGeo.GetComponent()); - // surrogateGeo.name = transform.parent.gameObject + "_dimensions"; - // surrogateGeo.transform.position = worldCenter; - // surrogateGeo.transform.rotation = b.transform.rotation; - // surrogateGeo.transform.localScale = worldHalfExtents * 2; - // surrogateGeo.transform.parent = b.transform; + // GameObject surrogateGeo = GameObject.CreatePrimitive(PrimitiveType.Cube); + // Destroy(surrogateGeo.GetComponent()); + // surrogateGeo.name = transform.parent.gameObject + "_dimensions"; + // surrogateGeo.transform.position = worldCenter; + // surrogateGeo.transform.rotation = b.transform.rotation; + // surrogateGeo.transform.localScale = worldHalfExtents * 2; + // surrogateGeo.transform.parent = b.transform; //////////////////////////////////////////////////// // ok now create an overlap box using these values and return all contained objects - foreach (Collider col in Physics.OverlapBox(worldCenter, worldHalfExtents, b.transform.rotation)) { + foreach ( + Collider col in Physics.OverlapBox(worldCenter, worldHalfExtents, b.transform.rotation) + ) { // ignore triggers if (col.GetComponentInParent() && !col.isTrigger) { // grab reference to game object this collider is part of SimObjPhysics sop = col.GetComponentInParent(); - // don't add any colliders from our parent object, so things like a + // don't add any colliders from our parent object, so things like a // shelf or drawer nested inside another shelving unit or dresser sim object // don't contain the object they are nested inside if (!hasAncestor(this.transform.gameObject, sop.transform.gameObject)) { @@ -171,7 +179,9 @@ public List CurrentlyContainedObjectIDs() { //returns the gridpoints in local space relative to the trigger box collider of this Contains.cs object public List GetValidSpawnPointsFromTriggerBoxLocalSpace(bool top = true) { - Vector3 p1, p2, p4; // in case we need all the corners later for something... + Vector3 p1, + p2, + p4; // in case we need all the corners later for something... BoxCollider b = GetComponent(); @@ -212,16 +222,18 @@ public List GetValidSpawnPointsFromTriggerBoxLocalSpace(bool top = true //ok at this point all the grid points I believe are in world space??? sooo List localGridPoints = new List(); - foreach(Vector3 point in gridpoints) { + foreach (Vector3 point in gridpoints) { localGridPoints.Add(this.transform.InverseTransformPoint(point)); - } + } return localGridPoints; } // returns a grid of points above the target receptacle public List GetValidSpawnPointsFromTriggerBox(bool top = true) { - Vector3 p1, p2, p4; // in case we need all the corners later for something... + Vector3 p1, + p2, + p4; // in case we need all the corners later for something... BoxCollider b = GetComponent(); @@ -259,16 +271,15 @@ public List GetValidSpawnPointsFromTriggerBox(bool top = true) { gridpoints.Add(PointsOnLineXdir[i] + zdir * (zdist * (j * lineincrement))); } } - #if UNITY_EDITOR +#if UNITY_EDITOR foreach (Vector3 point in gridpoints) { //debug draw the gridpoints if you wanna see em Debug.DrawLine(point, point + new Vector3(0, 0.2f, 0), Color.red, 100f); } - #endif +#endif return gridpoints; } - // generate a grid of potential spawn points, set ReturnPointsClosestToAgent to true if // the list of points should be filtered closest to agent, if false @@ -276,7 +287,11 @@ public List GetValidSpawnPointsFromTriggerBox(bool top = true) { public List GetValidSpawnPoints(BaseFPSAgentController agent = null) { List PossibleSpawnPoints = new List(); - Vector3 p1, p2, /*p3,*/ p4, p5 /*p6, p7, p8*/; // in case we need all the corners later for something... + Vector3 p1, + p2, /*p3,*/ + p4, + p5 /*p6, p7, p8*/ + ; // in case we need all the corners later for something... BoxCollider b = GetComponent(); @@ -336,19 +351,38 @@ public List GetValidSpawnPoints(BaseFPSAgentController age -ydir, out hit, ydist, - LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"), + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ), QueryTriggerInteraction.Collide ) ) { - // IMPORTANT NOTE: For objects like Sinks and Bathtubs where the interior simobject (SinkBasin, BathtubBasin) are children, make sure the interior Contains scripts have their 'myParent' field // set to the PARENT object of the sim object, not the sim object itself ie: SinkBasin's myParent = Sink if (hit.transform == myParent.transform) { // print("raycast hit: " + hit.transform.name); if (agent == null) { - PossibleSpawnPoints.Add(new ReceptacleSpawnPoint(hit.point, b, this, myParent.GetComponent())); + PossibleSpawnPoints.Add( + new ReceptacleSpawnPoint( + hit.point, + b, + this, + myParent.GetComponent() + ) + ); } else if (narrowDownValidSpawnPoints(agent, hit.point)) { - PossibleSpawnPoints.Add(new ReceptacleSpawnPoint(hit.point, b, this, myParent.GetComponent())); + PossibleSpawnPoints.Add( + new ReceptacleSpawnPoint( + hit.point, + b, + this, + myParent.GetComponent() + ) + ); } } } @@ -356,9 +390,23 @@ public List GetValidSpawnPoints(BaseFPSAgentController age Vector3 BottomPoint = point + -(ydir * ydist); // didn't hit anything that could obstruct, so this point is good to go if (agent == null) { - PossibleSpawnPoints.Add(new ReceptacleSpawnPoint(BottomPoint, b, this, myParent.GetComponent())); + PossibleSpawnPoints.Add( + new ReceptacleSpawnPoint( + BottomPoint, + b, + this, + myParent.GetComponent() + ) + ); } else if (narrowDownValidSpawnPoints(agent, BottomPoint)) { - PossibleSpawnPoints.Add(new ReceptacleSpawnPoint(BottomPoint, b, this, myParent.GetComponent())); + PossibleSpawnPoints.Add( + new ReceptacleSpawnPoint( + BottomPoint, + b, + this, + myParent.GetComponent() + ) + ); } } @@ -378,7 +426,6 @@ public List GetValidSpawnPoints(BaseFPSAgentController age // additional checks if the point is valid. Return true if it's valid private bool narrowDownValidSpawnPoints(BaseFPSAgentController agent, Vector3 point) { - // get agent's camera point, get point to check, find the distance from agent camera point to point to check // set the distance so that it is within the radius maxvisdist from the agent @@ -390,7 +437,7 @@ private bool narrowDownValidSpawnPoints(BaseFPSAgentController agent, Vector3 po return false; } - // ok cool, it's within distance to the agent, now let's check + // ok cool, it's within distance to the agent, now let's check // if the point is within the viewport of the agent as well Camera agentCam = agent.m_Camera; @@ -415,7 +462,6 @@ private bool narrowDownValidSpawnPoints(BaseFPSAgentController agent, Vector3 po } return false; - } // used to check if a given Vector3 is inside this receptacle box in world space @@ -428,9 +474,14 @@ public bool CheckIfPointIsInsideReceptacleTriggerBox(Vector3 point) { float halfX = (myBox.size.x * 0.5f); float halfY = (myBox.size.y * 0.5f); float halfZ = (myBox.size.z * 0.5f); - if (point.x < halfX && point.x > -halfX && - point.y < halfY && point.y > -halfY && - point.z < halfZ && point.z > -halfZ) { + if ( + point.x < halfX + && point.x > -halfX + && point.y < halfY + && point.y > -halfY + && point.z < halfZ + && point.z > -halfZ + ) { return true; } else { return false; @@ -445,9 +496,14 @@ public bool CheckIfPointIsAboveReceptacleTriggerBox(Vector3 point) { float halfX = (myBox.size.x * 0.5f); float BIGY = (myBox.size.y * 10.0f); float halfZ = (myBox.size.z * 0.5f); - if (point.x < halfX && point.x > -halfX && - point.y < BIGY && point.y > -BIGY && - point.z < halfZ && point.z > -halfZ) { + if ( + point.x < halfX + && point.x > -halfX + && point.y < BIGY + && point.y > -BIGY + && point.z < halfZ + && point.z > -halfZ + ) { return true; } else { return false; @@ -462,15 +518,41 @@ void OnDrawGizmos() { // these values will be off. Make sure that all parents in the heirarchy are at 1,1,1 scale and we can use these values // as a "valid area" for spawning objects inside of receptacles. Gizmos.color = Color.green; - Gizmos.DrawCube(transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, b.size.z) * 0.5f), new Vector3(0.01f, 0.01f, 0.01f)); - Gizmos.DrawCube(transform.TransformPoint(b.center + new Vector3(-b.size.x, -b.size.y, b.size.z) * 0.5f), new Vector3(0.01f, 0.01f, 0.01f)); - Gizmos.DrawCube(transform.TransformPoint(b.center + new Vector3(-b.size.x, -b.size.y, -b.size.z) * 0.5f), new Vector3(0.01f, 0.01f, 0.01f)); - Gizmos.DrawCube(transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, -b.size.z) * 0.5f), new Vector3(0.01f, 0.01f, 0.01f)); - - Gizmos.DrawCube(transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, b.size.z) * 0.5f), new Vector3(0.01f, 0.01f, 0.01f)); - Gizmos.DrawCube(transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, b.size.z) * 0.5f), new Vector3(0.01f, 0.01f, 0.01f)); - Gizmos.DrawCube(transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, -b.size.z) * 0.5f), new Vector3(0.01f, 0.01f, 0.01f)); - Gizmos.DrawCube(transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, -b.size.z) * 0.5f), new Vector3(0.01f, 0.01f, 0.01f)); + Gizmos.DrawCube( + transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, b.size.z) * 0.5f), + new Vector3(0.01f, 0.01f, 0.01f) + ); + Gizmos.DrawCube( + transform.TransformPoint(b.center + new Vector3(-b.size.x, -b.size.y, b.size.z) * 0.5f), + new Vector3(0.01f, 0.01f, 0.01f) + ); + Gizmos.DrawCube( + transform.TransformPoint( + b.center + new Vector3(-b.size.x, -b.size.y, -b.size.z) * 0.5f + ), + new Vector3(0.01f, 0.01f, 0.01f) + ); + Gizmos.DrawCube( + transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, -b.size.z) * 0.5f), + new Vector3(0.01f, 0.01f, 0.01f) + ); + + Gizmos.DrawCube( + transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, b.size.z) * 0.5f), + new Vector3(0.01f, 0.01f, 0.01f) + ); + Gizmos.DrawCube( + transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, b.size.z) * 0.5f), + new Vector3(0.01f, 0.01f, 0.01f) + ); + Gizmos.DrawCube( + transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, -b.size.z) * 0.5f), + new Vector3(0.01f, 0.01f, 0.01f) + ); + Gizmos.DrawCube( + transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, -b.size.z) * 0.5f), + new Vector3(0.01f, 0.01f, 0.01f) + ); // foreach(Vector3 v in Corners) // { @@ -501,7 +583,7 @@ void OnDrawGizmos() { // Vector3 boxPosition = coll.transform.position; // // Vector3 boxPosition = coll.transform.TransformPoint(coll.center); - // // convert from world position to local position + // // convert from world position to local position // boxPosition = transform.InverseTransformPoint(boxPosition) + coll.center; // Gizmos.DrawWireCube(boxPosition, coll.size); @@ -510,7 +592,6 @@ void OnDrawGizmos() { // Gizmos.color = prevColor; // Gizmos.matrix = prevMatrix; // } - } #endif } diff --git a/unity/Assets/Scripts/ContinuousMovement.cs b/unity/Assets/Scripts/ContinuousMovement.cs index f4dba53c8b..e64e37b1be 100644 --- a/unity/Assets/Scripts/ContinuousMovement.cs +++ b/unity/Assets/Scripts/ContinuousMovement.cs @@ -1,22 +1,19 @@ +using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -using System; - - public interface MovableContinuous { - public bool ShouldHalt(); - public void ContinuousUpdate(float fixedDeltaTime); - public ActionFinished FinishContinuousMove(BaseFPSAgentController controller); - // TODO remove from API integrate in FinishContinuousMove - // public string GetHaltMessage(); - } +public interface MovableContinuous { + public bool ShouldHalt(); + public void ContinuousUpdate(float fixedDeltaTime); + public ActionFinished FinishContinuousMove(BaseFPSAgentController controller); + // TODO remove from API integrate in FinishContinuousMove + // public string GetHaltMessage(); +} namespace UnityStandardAssets.Characters.FirstPerson { - public class ContinuousMovement { - public static int unrollSimulatePhysics(IEnumerator enumerator, float fixedDeltaTime) { int count = 0; PhysicsSceneManager.PhysicsSimulateCallCount = 0; @@ -47,7 +44,8 @@ public static IEnumerator rotate( Func getRotFunc = (t) => t.rotation; Action setRotFunc = (t, target) => t.rotation = target; - Func nextRotFunc = (t, target) => Quaternion.RotateTowards(t.rotation, target, fixedDeltaTime * degreesPerSecond); + Func nextRotFunc = (t, target) => + Quaternion.RotateTowards(t.rotation, target, fixedDeltaTime * degreesPerSecond); if (teleport) { nextRotFunc = (t, target) => target; @@ -84,8 +82,13 @@ public static IEnumerator move( ) { bool teleport = (unitsPerSecond == float.PositiveInfinity) && fixedDeltaTime == 0f; - Func, Action, Func, IEnumerator> moveClosure = - (get, set, next) => updateTransformPropertyFixedUpdate( + Func< + Func, + Action, + Func, + IEnumerator + > moveClosure = (get, set, next) => + updateTransformPropertyFixedUpdate( movable: movable, controller: controller, moveTransform: moveTransform, @@ -98,7 +101,7 @@ public static IEnumerator move( fixedDeltaTime: fixedDeltaTime, returnToStartPropIfFailed: returnToStartPropIfFailed, epsilon: 1e-6 // Since the distance metric uses SqrMagnitude this amounts to a distance of 1 millimeter - ); + ); Func getPosFunc; Action setPosFunc; @@ -106,22 +109,20 @@ public static IEnumerator move( if (localPosition) { getPosFunc = (t) => t.localPosition; setPosFunc = (t, pos) => t.localPosition = pos; - nextPosFunc = (t, direction) => t.localPosition + direction * unitsPerSecond * fixedDeltaTime; + nextPosFunc = (t, direction) => + t.localPosition + direction * unitsPerSecond * fixedDeltaTime; } else { getPosFunc = (t) => t.position; setPosFunc = (t, pos) => t.position = pos; - nextPosFunc = (t, direction) => t.position + direction * unitsPerSecond * fixedDeltaTime; + nextPosFunc = (t, direction) => + t.position + direction * unitsPerSecond * fixedDeltaTime; } if (teleport) { nextPosFunc = (t, direction) => targetPosition; } - return moveClosure( - getPosFunc, - setPosFunc, - nextPosFunc - ); + return moveClosure(getPosFunc, setPosFunc, nextPosFunc); } public static IEnumerator moveAB( @@ -135,7 +136,7 @@ float fixedDeltaTime fixedDeltaTime: fixedDeltaTime ); } - + protected static IEnumerator finallyDestroyGameObjects( List gameObjectsToDestroy, IEnumerator steps @@ -185,7 +186,8 @@ public static IEnumerator rotateAroundPoint( tmpObjects.Add(wristProxy); Func directionFunc = (target, current) => target; - Func distanceFunc = (target, current) => Quaternion.Angle(current, target); + Func distanceFunc = (target, current) => + Quaternion.Angle(current, target); Func getRotFunc = (t) => t.rotation; Action setRotFunc = (t, newRotation) => { @@ -194,7 +196,11 @@ public static IEnumerator rotateAroundPoint( updateTransform.rotation = newRotation; }; Func nextRotFunc = (t, target) => { - return Quaternion.RotateTowards(t.rotation, target, fixedDeltaTime * degreesPerSecond); + return Quaternion.RotateTowards( + t.rotation, + target, + fixedDeltaTime * degreesPerSecond + ); }; if (teleport) { @@ -220,15 +226,12 @@ public static IEnumerator rotateAroundPoint( ); } - public static IEnumerator continuousUpdateAB( + public static IEnumerator continuousUpdateAB( MovableContinuous movable, BaseFPSAgentController controller, float fixedDeltaTime - ) - { - - while(!movable.ShouldHalt()) - { + ) { + while (!movable.ShouldHalt()) { movable.ContinuousUpdate(fixedDeltaTime); // TODO: Remove below? if (!Physics.autoSimulation) { @@ -262,18 +265,19 @@ public static IEnumerator updateTransformPropertyFixedUpdate( bool returnToStartPropIfFailed, double epsilon, T? secTarget = null - ) where T : struct { + ) + where T : struct { T originalProperty = getProp(moveTransform); var previousProperty = originalProperty; // TODO: do not pass controller, and pass a lambda for the update function or an - // interface + // interface // var arm = controller.GetComponentInChildren(); - // commenting out the WaitForEndOfFrame here since we shoudn't need + // commenting out the WaitForEndOfFrame here since we shoudn't need // this as we already wait for a frame to pass when we execute each action // yield return yieldInstruction; - + int transformIterations = 1; if (secTarget != null) { transformIterations = 2; @@ -304,13 +308,13 @@ public static IEnumerator updateTransformPropertyFixedUpdate( // } while (!movable.ShouldHalt()) { - // TODO: put in movable && !collisionListener.TransformChecks(controller, moveTransform)) { + // TODO: put in movable && !collisionListener.TransformChecks(controller, moveTransform)) { previousProperty = getProp(moveTransform); T next = nextProp(moveTransform, directionToTarget); float nextDistance = distanceMetric((T)currentTarget, next); - + // allows for snapping behaviour to target when the target is close // if nextDistance is too large then it will overshoot, in this case we snap to the target // this can happen if the speed it set high @@ -323,20 +327,20 @@ public static IEnumerator updateTransformPropertyFixedUpdate( setProp(moveTransform, next); } - // this will be a NOOP for Rotate/Move/Height actions - movable.ContinuousUpdate(fixedDeltaTime); - //Debug.Log("2"); - - // if (!Physics.autoSimulation) { - // //Debug.Log("3.1"); - // if (fixedDeltaTime == 0f) { - // Physics.SyncTransforms(); - // } else { - // PhysicsSceneManager.PhysicsSimulateTHOR(fixedDeltaTime); - // } - // } - yield return new WaitForFixedUpdate(); - //Debug.Log("3.2"); + // this will be a NOOP for Rotate/Move/Height actions + movable.ContinuousUpdate(fixedDeltaTime); + //Debug.Log("2"); + + // if (!Physics.autoSimulation) { + // //Debug.Log("3.1"); + // if (fixedDeltaTime == 0f) { + // Physics.SyncTransforms(); + // } else { + // PhysicsSceneManager.PhysicsSimulateTHOR(fixedDeltaTime); + // } + // } + yield return new WaitForFixedUpdate(); + //Debug.Log("3.2"); yield return new WaitForFixedUpdate(); @@ -411,7 +415,7 @@ public static IEnumerator updateTransformPropertyFixedUpdate( // ) { // ActionFinished actionFinished = movable.FinishContinuousMove(controller); - + // if (!actionFinished.success) { // setProp(moveTransform, resetProp); // } diff --git a/unity/Assets/Scripts/Convertable.cs b/unity/Assets/Scripts/Convertable.cs index 8e6cbf709f..c5ee20f281 100644 --- a/unity/Assets/Scripts/Convertable.cs +++ b/unity/Assets/Scripts/Convertable.cs @@ -1,7 +1,7 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; -using System.Collections; using System; +using System.Collections; +using UnityEngine; [Serializable] public class SimObjState { @@ -14,9 +14,7 @@ public class Convertable : MonoBehaviour { public SimObjState[] States; public int DefaultState = 0; public int CurrentState { - get { - return currentState; - } + get { return currentState; } } #if UNITY_EDITOR public int EditorState; diff --git a/unity/Assets/Scripts/CookObject.cs b/unity/Assets/Scripts/CookObject.cs index a211ef9855..bf46dc2a9c 100644 --- a/unity/Assets/Scripts/CookObject.cs +++ b/unity/Assets/Scripts/CookObject.cs @@ -13,7 +13,11 @@ public class CookObject : MonoBehaviour { void Start() { #if UNITY_EDITOR - if (!gameObject.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeCooked)) { + if ( + !gameObject + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeCooked) + ) { Debug.LogError(gameObject.name + " is missing the CanBeCooked secondary property!"); } #endif @@ -39,7 +43,7 @@ public void Cook() { if (MaterialSwapObjects.Length > 0) { for (int i = 0; i < MaterialSwapObjects.Length; i++) { MaterialSwapObjects[i].MyObject.GetComponent().materials = - MaterialSwapObjects[i].OnMaterials; + MaterialSwapObjects[i].OnMaterials; } isCooked = true; diff --git a/unity/Assets/Scripts/CopyLightingSettings.cs b/unity/Assets/Scripts/CopyLightingSettings.cs index 2d4a64c410..a68a1fb7ae 100644 --- a/unity/Assets/Scripts/CopyLightingSettings.cs +++ b/unity/Assets/Scripts/CopyLightingSettings.cs @@ -9,15 +9,15 @@ static class CopyLightingSettings { // Written by Peter Schraut // http://www.console-dev.de // - // This Unity editor extension allows yoyu to copy&paste lighting settings + // This Unity editor extension allows yoyu to copy&paste lighting settings // from one scene to another. Check the following video to see it in action - // https://youtu.be/-TQzrVn1kWM + // https://youtu.be/-TQzrVn1kWM // // Save this file as "Assets/Editor/CopyLightingSettings.cs" // // Download most recent version from: // https://bitbucket.org/snippets/pschraut/LeykeL - // + // static SerializedObject s_SourceLightmapSettings; static SerializedObject s_SourceRenderSettings; @@ -33,7 +33,13 @@ static class CopyLightingSettings { [MenuItem(k_CopySettingsMenuPath, priority = 200)] static void CopySettings() { UnityEngine.Object lightmapSettings; - if (!TryGetSettings(typeof(LightmapEditorSettings), "GetLightmapSettings", out lightmapSettings)) { + if ( + !TryGetSettings( + typeof(LightmapEditorSettings), + "GetLightmapSettings", + out lightmapSettings + ) + ) { return; } @@ -49,7 +55,13 @@ static void CopySettings() { [MenuItem(k_PasteSettingsMenuPath, priority = 201)] static void PasteSettings() { UnityEngine.Object lightmapSettings; - if (!TryGetSettings(typeof(LightmapEditorSettings), "GetLightmapSettings", out lightmapSettings)) { + if ( + !TryGetSettings( + typeof(LightmapEditorSettings), + "GetLightmapSettings", + out lightmapSettings + ) + ) { return; } @@ -73,7 +85,9 @@ static void CopyInternal(SerializedObject source, SerializedObject dest) { var prop = source.GetIterator(); while (prop.Next(true)) { var copyProperty = true; - foreach (var propertyName in new[] { "m_Sun", "m_FileID", "m_PathID", "m_ObjectHideFlags" }) { + foreach ( + var propertyName in new[] { "m_Sun", "m_FileID", "m_PathID", "m_ObjectHideFlags" } + ) { if (string.Equals(prop.name, propertyName, System.StringComparison.Ordinal)) { copyProperty = false; break; @@ -93,13 +107,21 @@ static bool TryGetSettings(System.Type type, string methodName, out UnityEngine. var method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic); if (method == null) { - Debug.LogErrorFormat("CopyLightingSettings: Could not find {0}.{1}", type.Name, methodName); + Debug.LogErrorFormat( + "CopyLightingSettings: Could not find {0}.{1}", + type.Name, + methodName + ); return false; } var value = method.Invoke(null, null) as UnityEngine.Object; if (value == null) { - Debug.LogErrorFormat("CopyLightingSettings: Could get data from {0}.{1}", type.Name, methodName); + Debug.LogErrorFormat( + "CopyLightingSettings: Could get data from {0}.{1}", + type.Name, + methodName + ); return false; } @@ -107,4 +129,4 @@ static bool TryGetSettings(System.Type type, string methodName, out UnityEngine. return true; } } -#endif \ No newline at end of file +#endif diff --git a/unity/Assets/Scripts/CreatePrefab.cs b/unity/Assets/Scripts/CreatePrefab.cs index 5c1808757b..80b9b0346d 100644 --- a/unity/Assets/Scripts/CreatePrefab.cs +++ b/unity/Assets/Scripts/CreatePrefab.cs @@ -4,15 +4,16 @@ using System.Collections; using UnityEditor; - public class CreatePrefab : MonoBehaviour { - [MenuItem("Extras/Create Prefab From Selection")] static void DoCreatePrefab() { Transform[] transforms = Selection.transforms; foreach (Transform t in transforms) { - PrefabUtility.SaveAsPrefabAsset(t.gameObject, "Assets/Prefabs/" + t.gameObject.name + ".prefab"); + PrefabUtility.SaveAsPrefabAsset( + t.gameObject, + "Assets/Prefabs/" + t.gameObject.name + ".prefab" + ); } } } -#endif \ No newline at end of file +#endif diff --git a/unity/Assets/Scripts/DebugDiscreteAgentController.cs b/unity/Assets/Scripts/DebugDiscreteAgentController.cs index 95d43fe861..5ab2aa575b 100644 --- a/unity/Assets/Scripts/DebugDiscreteAgentController.cs +++ b/unity/Assets/Scripts/DebugDiscreteAgentController.cs @@ -1,8 +1,8 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; -using System; namespace UnityStandardAssets.Characters.FirstPerson { public class DebugDiscreteAgentController : MonoBehaviour { @@ -10,14 +10,18 @@ public class DebugDiscreteAgentController : MonoBehaviour { public AgentManager AManager = null; private InputField inputField; - [SerializeField] private GameObject InputMode_Text = null; + [SerializeField] + private GameObject InputMode_Text = null; + // Start is called before the first frame update void Start() { InputFieldObj = GameObject.Find("DebugCanvasPhysics/InputField"); var Debug_Canvas = GameObject.Find("DebugCanvasPhysics"); inputField = InputFieldObj.GetComponent(); - AManager = GameObject.Find("PhysicsSceneManager").GetComponentInChildren(); + AManager = GameObject + .Find("PhysicsSceneManager") + .GetComponentInChildren(); Cursor.visible = true; Cursor.lockState = CursorLockMode.None; @@ -27,7 +31,6 @@ void Start() { Cursor.visible = true; Cursor.lockState = CursorLockMode.None; } - } BaseFPSAgentController CurrentActiveController() { @@ -41,9 +44,7 @@ public void OnEnable() { } } - public void OnDisable() { - - } + public void OnDisable() { } void Update() { // use these for the Breakable Window demo video @@ -81,17 +82,21 @@ void Update() { // if we press enter, select the input field if (CurrentActiveController().ReadyForCommand) { if (Input.GetKeyDown(KeyCode.Return)) { - UnityEngine.EventSystems.EventSystem.current.SetSelectedGameObject(InputFieldObj); + UnityEngine.EventSystems.EventSystem.current.SetSelectedGameObject( + InputFieldObj + ); } if (!inputField.isFocused) { - bool shiftHeld = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); + bool shiftHeld = + Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); bool altHeld = Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt); bool noModifier = (!shiftHeld) && (!altHeld); bool armMoveMode = shiftHeld && !altHeld; bool armRotateMode = shiftHeld && altHeld; - bool isArticulated = CurrentActiveController().GetType() == typeof(ArticulatedAgentController); + bool isArticulated = + CurrentActiveController().GetType() == typeof(ArticulatedAgentController); Dictionary action = new Dictionary(); var physicsSimulationParams = new PhysicsSimulationParams() { autoSimulation = false @@ -129,7 +134,6 @@ void Update() { action["acceleration"] = 22.5f; } } else { - if (Input.GetKeyDown(KeyCode.W)) { action["action"] = "MoveAhead"; action["moveMagnitude"] = WalkMagnitude; @@ -170,13 +174,13 @@ void Update() { if ((string)action["action"] != "") { if ( ((string)action["action"]).Contains("Move") - && CurrentActiveController().GetType() == typeof(KinovaArmAgentController) + && CurrentActiveController().GetType() + == typeof(KinovaArmAgentController) ) { action["returnToStart"] = false; } this.CurrentActiveController().ProcessControlCommand(action); } - } else if (armMoveMode) { var actionName = "MoveArmRelative"; var localPos = new Vector3(0, 0, 0); @@ -224,7 +228,7 @@ void Update() { } if (actionName != "") { - if (((string) action["action"]).StartsWith("MoveArm")) { + if (((string)action["action"]).StartsWith("MoveArm")) { action["useLimits"] = useLimits; } this.CurrentActiveController().ProcessControlCommand(action); diff --git a/unity/Assets/Scripts/DebugFPSAgentController.cs b/unity/Assets/Scripts/DebugFPSAgentController.cs index a447e51bef..b2044fafcf 100644 --- a/unity/Assets/Scripts/DebugFPSAgentController.cs +++ b/unity/Assets/Scripts/DebugFPSAgentController.cs @@ -1,34 +1,52 @@ // Copyright Allen Institute for Artificial Intelligence 2017 // Check Assets/Prefabs/DebugController for ReadMe on how to use this Debug Controller -using UnityEngine; -using Random = UnityEngine.Random; using System; -using System.IO; using System.Collections; using System.Collections.Generic; -using UnityStandardAssets.CrossPlatformInput; -using UnityStandardAssets.Utility; +using System.IO; +using Newtonsoft.Json.Linq; +using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; -using Newtonsoft.Json.Linq; +using UnityStandardAssets.CrossPlatformInput; +using UnityStandardAssets.Utility; +using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof(CharacterController))] public class DebugFPSAgentController : MonoBehaviour { // for use with mouse/keyboard input - [SerializeField] protected bool m_IsWalking; - [SerializeField] protected float m_WalkSpeed; - [SerializeField] protected float m_RunSpeed; + [SerializeField] + protected bool m_IsWalking; + + [SerializeField] + protected float m_WalkSpeed; + + [SerializeField] + protected float m_RunSpeed; + + [SerializeField] + protected float m_GravityMultiplier; - [SerializeField] protected float m_GravityMultiplier; - [SerializeField] protected MouseLook m_MouseLook; + [SerializeField] + protected MouseLook m_MouseLook; + + [SerializeField] + protected GameObject Debug_Canvas = null; - [SerializeField] protected GameObject Debug_Canvas = null; // [SerializeField] private GameObject Inventory_Text = null; - [SerializeField] protected GameObject InputMode_Text = null; - [SerializeField] protected float MaxViewDistance = 5.0f; - [SerializeField] private float MaxChargeThrowSeconds = 1.4f; - [SerializeField] private float MaxThrowForce = 1000.0f; + [SerializeField] + protected GameObject InputMode_Text = null; + + [SerializeField] + protected float MaxViewDistance = 5.0f; + + [SerializeField] + private float MaxChargeThrowSeconds = 1.4f; + + [SerializeField] + private float MaxThrowForce = 1000.0f; + // public bool FlightMode = false; public bool FPSEnabled = true; @@ -52,16 +70,25 @@ private void Start() { m_Camera = Camera.main; m_MouseLook.Init(transform, m_Camera.transform); - // find debug canvas related objects + // find debug canvas related objects Debug_Canvas = GameObject.Find("DebugCanvasPhysics"); InputMode_Text = GameObject.Find("DebugCanvasPhysics/InputModeText"); InputFieldObj = GameObject.Find("DebugCanvasPhysics/InputField"); - AgentManager agentManager = GameObject.Find("PhysicsSceneManager").GetComponentInChildren(); + AgentManager agentManager = GameObject + .Find("PhysicsSceneManager") + .GetComponentInChildren(); agentManager.SetUpPhysicsController(); PhysicsController = agentManager.PrimaryAgent as PhysicsRemoteFPSAgentController; - highlightController = new ObjectHighlightController(PhysicsController, MaxViewDistance, enableHighlightShader, true, MaxThrowForce, MaxChargeThrowSeconds); + highlightController = new ObjectHighlightController( + PhysicsController, + MaxViewDistance, + enableHighlightShader, + true, + MaxThrowForce, + MaxChargeThrowSeconds + ); // if this component is enabled, turn on the targeting reticle and target text if (this.isActiveAndEnabled) { @@ -73,12 +100,13 @@ private void Start() { // FlightMode = PhysicsController.FlightMode; #if UNITY_WEBGL - FPSEnabled = false; - Cursor.visible = true; - Cursor.lockState = CursorLockMode.None; - HideHUD(); + FPSEnabled = false; + Cursor.visible = true; + Cursor.lockState = CursorLockMode.None; + HideHUD(); #endif } + public Vector3 ScreenPointMoveHand(float yOffset) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); @@ -165,10 +193,7 @@ private void DebugKeyboardControls() { // swap between text input and not #if !UNITY_WEBGL - if ( - Input.GetKeyDown(KeyCode.BackQuote) - || Input.GetKeyDown(KeyCode.Escape) - ) { + if (Input.GetKeyDown(KeyCode.BackQuote) || Input.GetKeyDown(KeyCode.Escape)) { // Switch to Text Mode if (FPSEnabled) { DisableMouseControl(); @@ -187,17 +212,20 @@ private void DebugKeyboardControls() { var eps = 1e-6; if (Mathf.Abs(scrollAmount) > eps) { // webGL action - var action = new Dictionary() { - {"action", "MoveHandAhead"}, - {"moveMagnitude", scrollAmount} - }; + var action = new Dictionary() + { + { "action", "MoveHandAhead" }, + { "moveMagnitude", scrollAmount } + }; this.PhysicsController.ProcessControlCommand(action); } } } private void Update() { - highlightController.UpdateHighlightedObject(new Vector3(Screen.width / 2, Screen.height / 2)); + highlightController.UpdateHighlightedObject( + new Vector3(Screen.width / 2, Screen.height / 2) + ); highlightController.MouseControls(); DebugKeyboardControls(); @@ -220,15 +248,15 @@ public void OnGUI() { var eps = 1e-6; if (Mathf.Abs(scrollAmount.x) > eps || Mathf.Abs(scrollAmount.y) > eps) { // Actioned called through webGL, using dynamic not supported by IL2CPP - var action = new Dictionary() { - {"action", "MoveHandDelta"}, - {"x", scrollAmount.x * 0.05f}, - {"z", scrollAmount.y * -0.05f}, - {"y", 0.0f} + var action = new Dictionary() + { + { "action", "MoveHandDelta" }, + { "x", scrollAmount.x * 0.05f }, + { "z", scrollAmount.y * -0.05f }, + { "y", 0.0f } }; this.PhysicsController.ProcessControlCommand(action); } - } } } @@ -253,7 +281,6 @@ private void GetInput(out float speed) { if (m_Input.sqrMagnitude > 1) { m_Input.Normalize(); } - } public MouseLook GetMouseLook() { @@ -273,8 +300,15 @@ private void FPSInput() { // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; - Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, - m_CharacterController.height / 2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); + Physics.SphereCast( + transform.position, + m_CharacterController.radius, + Vector3.down, + out hitInfo, + m_CharacterController.height / 2f, + Physics.AllLayers, + QueryTriggerInteraction.Ignore + ); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; m_MoveDir.x = desiredMove.x * speed; @@ -288,8 +322,5 @@ private void FPSInput() { m_CharacterController.Move(m_MoveDir * Time.deltaTime); } } - - } } - diff --git a/unity/Assets/Scripts/DebugInputField.cs b/unity/Assets/Scripts/DebugInputField.cs index 537f81b9ca..0fc77e4c08 100644 --- a/unity/Assets/Scripts/DebugInputField.cs +++ b/unity/Assets/Scripts/DebugInputField.cs @@ -1,17 +1,17 @@ +using System; using System.Collections; using System.Collections.Generic; -using UnityEngine; -using UnityEngine.UI; -using System; +using System.IO; using System.Linq; -using UnityEditor; +using System.Runtime.Serialization.Formatters.Binary; +using MessagePack.Resolvers; using Newtonsoft.Json.Linq; -using Thor.Procedural.Data; using Thor.Procedural; -using System.IO; -using System.Runtime.Serialization.Formatters.Binary; +using Thor.Procedural.Data; +using UnityEditor; +using UnityEngine; using UnityEngine.AI; -using MessagePack.Resolvers; +using UnityEngine.UI; namespace UnityStandardAssets.Characters.FirstPerson { public class DebugInputField : MonoBehaviour { @@ -21,18 +21,25 @@ public class DebugInputField : MonoBehaviour { private ControlMode controlMode; #if UNITY_EDITOR - private Dictionary debugKeyToController = new Dictionary{ - {KeyCode.F1, ControlMode.DEBUG_TEXT_INPUT}, - {KeyCode.BackQuote, ControlMode.FPS}, - {KeyCode.F2, ControlMode.DISCRETE_POINT_CLICK}, - {KeyCode.F3, ControlMode.DISCRETE_HIDE_N_SEEK}, - {KeyCode.F4, ControlMode.MINIMAL_FPS} + private Dictionary debugKeyToController = new Dictionary< + KeyCode, + ControlMode + > + { + { KeyCode.F1, ControlMode.DEBUG_TEXT_INPUT }, + { KeyCode.BackQuote, ControlMode.FPS }, + { KeyCode.F2, ControlMode.DISCRETE_POINT_CLICK }, + { KeyCode.F3, ControlMode.DISCRETE_HIDE_N_SEEK }, + { KeyCode.F4, ControlMode.MINIMAL_FPS } }; #endif private bool setEnabledControlComponent(ControlMode mode, bool enabled) { Type componentType; - var success = PlayerControllers.controlModeToComponent.TryGetValue(mode, out componentType); + var success = PlayerControllers.controlModeToComponent.TryGetValue( + mode, + out componentType + ); if (success) { var previousComponent = Agent.GetComponent(componentType) as MonoBehaviour; if (previousComponent == null) { @@ -67,27 +74,31 @@ public IEnumerator moveArmHeightDebug(float height) { currentDistance = Vector3.SqrMagnitude(target - arm.transform.localPosition); } - } + public void dumpPosition(Transform to) { Debug.Log("GameObject: " + to.gameObject.name); Debug.Log( - to.position.x.ToString("0.####") + " " + - to.position.y.ToString("0.####") + " " + - to.position.z.ToString("0.####") + " " + to.position.x.ToString("0.####") + + " " + + to.position.y.ToString("0.####") + + " " + + to.position.z.ToString("0.####") + + " " ); - } public IEnumerator moveArmDebug(Vector3 targetArmBase) { - var arm = CurrentActiveController().GetComponentInChildren(); // var rig = arm.transform.Find("FK_IK_rig").Find("robot_arm_IK_rig").GetComponent(); // var rigBuilder = arm.transform.Find("FK_IK_rig").Find("robot_arm_IK_rig").GetComponent(); // var animator = arm.gameObject.GetComponent(); // animator.enabled = false; Debug.Log("My name is " + arm.name); - var armTarget = arm.transform.Find("robot_arm_FK_IK_rig").Find("IK_rig").Find("IK_pos_rot_manipulator"); + var armTarget = arm + .transform.Find("robot_arm_FK_IK_rig") + .Find("IK_rig") + .Find("IK_pos_rot_manipulator"); var wristCol = GameObject.Find("robot_wrist_1_tcol (11)").transform; Vector3 target = arm.transform.TransformPoint(targetArmBase); float currentDistance = Vector3.SqrMagnitude(target - armTarget.transform.position); @@ -112,7 +123,6 @@ public IEnumerator moveArmDebug(Vector3 targetArmBase) { } yield return new WaitForEndOfFrame(); Debug.Log("Ending arm movement"); - } public void setControlMode(ControlMode mode) { @@ -135,23 +145,25 @@ void SelectPlayerControl() { setControlMode(ControlMode.DEBUG_TEXT_INPUT); #endif #if UNITY_WEBGL - Debug.Log("Player Control Set To:Webgl"); - setControlMode(ControlMode.FPS); + Debug.Log("Player Control Set To:Webgl"); + setControlMode(ControlMode.FPS); #endif #if CROWDSOURCE_TASK - Debug.Log("CROWDSOURCE_TASK"); - setControlMode(ControlMode.DISCRETE_HIDE_N_SEEK); + Debug.Log("CROWDSOURCE_TASK"); + setControlMode(ControlMode.DISCRETE_HIDE_N_SEEK); #endif #if TURK_TASK - Debug.Log("Player Control Set To: TURK"); - setControlMode(ControlMode.DISCRETE_POINT_CLICK); + Debug.Log("Player Control Set To: TURK"); + setControlMode(ControlMode.DISCRETE_POINT_CLICK); #endif } void InitializeUserControl() { GameObject fpsController = GameObject.FindObjectOfType().gameObject; Agent = fpsController.gameObject; - AManager = GameObject.Find("PhysicsSceneManager").GetComponentInChildren(); + AManager = GameObject + .Find("PhysicsSceneManager") + .GetComponentInChildren(); // StochasticController = fpsController.GetComponent(); @@ -168,7 +180,6 @@ BaseFPSAgentController CurrentActiveController() { private PhysicsRemoteFPSAgentController PhysicsController { get => (PhysicsRemoteFPSAgentController)this.CurrentActiveController(); - } // Update is called once per frame @@ -177,7 +188,6 @@ void Update() { foreach (KeyValuePair entry in debugKeyToController) { if (Input.GetKeyDown(entry.Key)) { if (controlMode != entry.Value) { - // GameObject.Find("DebugCanvasPhysics").GetComponentInChildren().setControlMode(entry.Value); setControlMode(entry.Value); break; @@ -202,11 +212,12 @@ public void HideHUD() { #if UNITY_EDITOR public string closestVisibleObjectId() { - return ((PhysicsRemoteFPSAgentController)AManager.PrimaryAgent).ObjectIdOfClosestVisibleObject(); + return ( + (PhysicsRemoteFPSAgentController)AManager.PrimaryAgent + ).ObjectIdOfClosestVisibleObject(); } public IEnumerator ExecuteBatch(List commands) { - foreach (var command in commands) { while (CurrentActiveController().IsProcessing) { yield return new WaitForEndOfFrame(); @@ -216,7 +227,6 @@ public IEnumerator ExecuteBatch(List commands) { } } - // shortcut to execute no-parameter actions private void ExecuteAction(string actionName) { Dictionary action = new Dictionary(); @@ -225,13 +235,15 @@ private void ExecuteAction(string actionName) { } public void Execute(string command) { - if (CurrentActiveController().IsProcessing) { Debug.Log("Cannot execute command while last action has not completed."); } // pass in multiple parameters separated by spaces - string[] splitcommand = command.Split(new string[] { " " }, System.StringSplitOptions.None); + string[] splitcommand = command.Split( + new string[] { " " }, + System.StringSplitOptions.None + ); switch (splitcommand[0]) { case "init": { @@ -262,14 +274,15 @@ public void Execute(string command) { // action.agentMode = "locobot"; action["fieldOfView"] = 90f; // action.cameraY = 2.0f; - + action["snapToGrid"] = true; //action["width"] = 100; //action["height"] = 100; // action.rotateStepDegrees = 45; action["action"] = "Initialize"; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action), AManager); // AgentManager am = PhysicsController.gameObject.FindObjectsOfType()[0]; // Debug.Log("Physics scene manager = ..."); // Debug.Log(physicsSceneManager); @@ -314,14 +327,14 @@ public void Execute(string command) { action["fieldOfView"] = 79; action["gridSize"] = 0.25f; - action["applyActionNoise"] = true; action["continuousMode"] = true; //action["snapToGrid"] = false; //action["action"] = "Initialize"; //action["fieldOfView"] = 90; //action["gridSize"] = 0.25f; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action), AManager); break; } case "initb1": { @@ -366,7 +379,8 @@ public void Execute(string command) { //action["action"] = "Initialize"; //action["fieldOfView"] = 90; //action["gridSize"] = 0.25f; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action), AManager); break; } case "inita": { @@ -410,7 +424,8 @@ public void Execute(string command) { // action.massThreshold = 10f; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action), AManager); // AgentManager am = PhysicsController.gameObject.FindObjectsOfType()[0]; // Debug.Log("Physics scene manager = ..."); // Debug.Log(physicsSceneManager); @@ -460,7 +475,8 @@ public void Execute(string command) { // action.massThreshold = 10f; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action), AManager); // AgentManager am = PhysicsController.gameObject.FindObjectsOfType()[0]; // Debug.Log("Physics scene manager = ..."); // Debug.Log(physicsSceneManager); @@ -522,19 +538,19 @@ public void Execute(string command) { action["procedural"] = true; ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - break; - } case "inite": { - Dictionary action = new Dictionary{ - {"action", "Initialize"}, - {"agentMode", "arm"}, - {"agentControllerType", "mid-level"} - }; + Dictionary action = new Dictionary + { + { "action", "Initialize" }, + { "agentMode", "arm" }, + { "agentControllerType", "mid-level" } + }; ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - var arm = CurrentActiveController().GetComponentInChildren(); + var arm = CurrentActiveController() + .GetComponentInChildren(); var armTarget = GameObject.Find("IK_pos_rot_manipulator"); armTarget.transform.Rotate(90f, 0f, 0f); @@ -543,497 +559,564 @@ public void Execute(string command) { var armBase = GameObject.Find("robot_arm_rig_gripper"); armBase.transform.Translate(0f, 0.27f, 0f); - CurrentActiveController().ProcessControlCommand( - new Dictionary{ - {"action", "LookDown"} - }); + CurrentActiveController() + .ProcessControlCommand( + new Dictionary { { "action", "LookDown" } } + ); break; } case "sim": { - var collisionListener = this.CurrentActiveController().GetComponent(); - Physics.Simulate(0.02f); - var l = collisionListener.StaticCollisions(); - Debug.Log("total collisions: " + l.ToArray().Length); - break; - } + var collisionListener = this.CurrentActiveController() + .GetComponent(); + Physics.Simulate(0.02f); + var l = collisionListener.StaticCollisions(); + Debug.Log("total collisions: " + l.ToArray().Length); + break; + } case "inits": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "Initialize"; - action["agentMode"] = "stretch"; - action["agentControllerType"] = "stretch"; - action["visibilityScheme"] = "Distance"; - action["renderInstanceSegmentation"] = true; - action["renderDepth"] = true; -// action["antiAliasing"] = "smaa"; - action["massThreshold"] = 10.0f; + action["action"] = "Initialize"; + action["agentMode"] = "stretch"; + action["agentControllerType"] = "stretch"; + action["visibilityScheme"] = "Distance"; + action["renderInstanceSegmentation"] = true; + action["renderDepth"] = true; + // action["antiAliasing"] = "smaa"; + action["massThreshold"] = 10.0f; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } //fpin using stretch bot as source mesh case "initpinnobody": { - Dictionary action = new Dictionary(); - - action["action"] = "Initialize"; - action["agentMode"] = "fpin"; - action["visibilityScheme"] = "Distance"; - action["renderInstanceSegmentation"] = true; - action["renderDepth"] = true; - - action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary() { - {"originOffsetX", 0.2f}, - {"originOffsetZ", 0.4f}, - {"colliderScaleRatio", new Vector3(0.8f, 1.2f, 0.5f)}, - {"useVisibleColliderBase", true}, - {"useAbsoluteSize", true} + Dictionary action = new Dictionary(); + + action["action"] = "Initialize"; + action["agentMode"] = "fpin"; + action["visibilityScheme"] = "Distance"; + action["renderInstanceSegmentation"] = true; + action["renderDepth"] = true; + + action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< + string, + object + >() + { + { "originOffsetX", 0.2f }, + { "originOffsetZ", 0.4f }, + { "colliderScaleRatio", new Vector3(0.8f, 1.2f, 0.5f) }, + { "useVisibleColliderBase", true }, + { "useAbsoluteSize", true } }; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } //fpin using stretch bot as source mesh case "initpins": { - Dictionary action = new Dictionary(); - - action["action"] = "Initialize"; - action["agentMode"] = "fpin"; - //action["useAbsoluteSize"] = true; - action["visibilityScheme"] = "Distance"; - action["renderInstanceSegmentation"] = true; - action["renderDepth"] = true; - - action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary() { - {"bodyAsset", new BodyAsset() { assetId = "StretchBotSimObj"}}, - {"originOffsetX", -0.1f}, - {"originOffsetZ", 0.1157837f}, - {"colliderScaleRatio", new Vector3(1, 1, 1)}, - {"useVisibleColliderBase", true} + Dictionary action = new Dictionary(); + + action["action"] = "Initialize"; + action["agentMode"] = "fpin"; + //action["useAbsoluteSize"] = true; + action["visibilityScheme"] = "Distance"; + action["renderInstanceSegmentation"] = true; + action["renderDepth"] = true; + + action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< + string, + object + >() + { + { + "bodyAsset", + new BodyAsset() { assetId = "StretchBotSimObj" } + }, + { "originOffsetX", -0.1f }, + { "originOffsetZ", 0.1157837f }, + { "colliderScaleRatio", new Vector3(1, 1, 1) }, + { "useVisibleColliderBase", true } }; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } case "initpinsabsolute": { - Dictionary action = new Dictionary(); - - action["action"] = "Initialize"; - action["agentMode"] = "fpin"; - //action["useAbsoluteSize"] = true; - action["visibilityScheme"] = "Distance"; - action["renderInstanceSegmentation"] = true; - action["renderDepth"] = true; - - action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary() { - {"bodyAsset", new BodyAsset() { assetId = "StretchBotSimObj"}}, - {"originOffsetX", -0.09938055f}, - {"originOffsetZ", 0.1157837f}, - {"colliderScaleRatio", new Vector3(1, 1, 1)}, - {"useAbsoluteSize", true}, - {"useVisibleColliderBase", true} + Dictionary action = new Dictionary(); + + action["action"] = "Initialize"; + action["agentMode"] = "fpin"; + //action["useAbsoluteSize"] = true; + action["visibilityScheme"] = "Distance"; + action["renderInstanceSegmentation"] = true; + action["renderDepth"] = true; + + action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< + string, + object + >() + { + { + "bodyAsset", + new BodyAsset() { assetId = "StretchBotSimObj" } + }, + { "originOffsetX", -0.09938055f }, + { "originOffsetZ", 0.1157837f }, + { "colliderScaleRatio", new Vector3(1, 1, 1) }, + { "useAbsoluteSize", true }, + { "useVisibleColliderBase", true } }; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } case "initpinsratio": { - Dictionary action = new Dictionary(); - - action["action"] = "Initialize"; - action["agentMode"] = "fpin"; - //action["useAbsoluteSize"] = true; - action["visibilityScheme"] = "Distance"; - action["renderInstanceSegmentation"] = true; - action["renderDepth"] = true; - - action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary() { - {"bodyAsset", new BodyAsset() { assetId = "StretchBotSimObj"}}, - {"originOffsetX", -0.09938055f}, - {"originOffsetZ", 0.1157837f}, - {"colliderScaleRatio", new Vector3(4, 3, 2)}, + Dictionary action = new Dictionary(); + + action["action"] = "Initialize"; + action["agentMode"] = "fpin"; + //action["useAbsoluteSize"] = true; + action["visibilityScheme"] = "Distance"; + action["renderInstanceSegmentation"] = true; + action["renderDepth"] = true; + + action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< + string, + object + >() + { + { + "bodyAsset", + new BodyAsset() { assetId = "StretchBotSimObj" } + }, + { "originOffsetX", -0.09938055f }, + { "originOffsetZ", 0.1157837f }, + { "colliderScaleRatio", new Vector3(4, 3, 2) }, }; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } //fpin using locobot as source mesh case "initpinl": { - Dictionary action = new Dictionary(); - - action["action"] = "Initialize"; - action["agentMode"] = "fpin"; - //action["useAbsoluteSize"] = true; - action["visibilityScheme"] = "Distance"; - action["renderInstanceSegmentation"] = true; - action["renderDepth"] = true; - - action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary() { - {"bodyAsset", new BodyAsset() { assetId = "LocoBotSimObj"}}, - {"originOffsetX", 0.0f}, - {"originOffsetZ", -0.025f}, - {"colliderScaleRatio", new Vector3(1, 1, 1)} + Dictionary action = new Dictionary(); + + action["action"] = "Initialize"; + action["agentMode"] = "fpin"; + //action["useAbsoluteSize"] = true; + action["visibilityScheme"] = "Distance"; + action["renderInstanceSegmentation"] = true; + action["renderDepth"] = true; + + action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< + string, + object + >() + { + { + "bodyAsset", + new BodyAsset() { assetId = "LocoBotSimObj" } + }, + { "originOffsetX", 0.0f }, + { "originOffsetZ", -0.025f }, + { "colliderScaleRatio", new Vector3(1, 1, 1) } }; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } //fpin using TOASTER!!! as source mesh case "initpint": { - Dictionary action = new Dictionary(); - - action["action"] = "Initialize"; - // AgentManager Initialize Args - action["agentMode"] = "fpin"; - action["visibilityScheme"] = "Distance"; - action["renderInstanceSegmentation"] = true; - action["renderDepth"] = true; - - // Fpin agent Initialize args - action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary() { - {"bodyAsset", new BodyAsset() { assetId = "Toaster_5"}}, - {"originOffsetX", 0.0f}, - {"originOffsetZ", 0.0f}, - {"colliderScaleRatio", new Vector3(1, 1, 1)}, - {"useAbsoluteSize", false}, + Dictionary action = new Dictionary(); + + action["action"] = "Initialize"; + // AgentManager Initialize Args + action["agentMode"] = "fpin"; + action["visibilityScheme"] = "Distance"; + action["renderInstanceSegmentation"] = true; + action["renderDepth"] = true; + + // Fpin agent Initialize args + action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< + string, + object + >() + { + { + "bodyAsset", + new BodyAsset() { assetId = "Toaster_5" } + }, + { "originOffsetX", 0.0f }, + { "originOffsetZ", 0.0f }, + { "colliderScaleRatio", new Vector3(1, 1, 1) }, + { "useAbsoluteSize", false }, }; - //action["useAbsoluteSize"] = true; + //action["useAbsoluteSize"] = true; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } //fpin using TOASTER!!! as source mesh case "initpint321": { - Dictionary action = new Dictionary(); - - action["action"] = "Initialize"; - // AgentManager Initialize Args - action["agentMode"] = "fpin"; - action["visibilityScheme"] = "Distance"; - action["renderInstanceSegmentation"] = true; - action["renderDepth"] = true; - - // Fpin agent Initialize args - action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary() { - {"bodyAsset", new BodyAsset() { assetId = "Toaster_5"}}, - {"originOffsetX", 0.0f}, - {"originOffsetZ", 0.0f}, - {"colliderScaleRatio", new Vector3(3, 2, 1f)}, - {"useAbsoluteSize", false}, - {"useVisibleColliderBase", false} + Dictionary action = new Dictionary(); + + action["action"] = "Initialize"; + // AgentManager Initialize Args + action["agentMode"] = "fpin"; + action["visibilityScheme"] = "Distance"; + action["renderInstanceSegmentation"] = true; + action["renderDepth"] = true; + + // Fpin agent Initialize args + action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< + string, + object + >() + { + { + "bodyAsset", + new BodyAsset() { assetId = "Toaster_5" } + }, + { "originOffsetX", 0.0f }, + { "originOffsetZ", 0.0f }, + { "colliderScaleRatio", new Vector3(3, 2, 1f) }, + { "useAbsoluteSize", false }, + { "useVisibleColliderBase", false } }; - //action["useAbsoluteSize"] = true; + //action["useAbsoluteSize"] = true; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } //fpin using TOASTER!!! as source mesh case "initpint321vcb": { - Dictionary action = new Dictionary(); - - action["action"] = "Initialize"; - // AgentManager Initialize Args - action["agentMode"] = "fpin"; - action["visibilityScheme"] = "Distance"; - action["renderInstanceSegmentation"] = true; - action["renderDepth"] = true; - - // Fpin agent Initialize args - action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary() { - {"bodyAsset", new BodyAsset() { assetId = "Toaster_5"}}, - {"originOffsetX", 0.0f}, - {"originOffsetZ", 0.0f}, - {"colliderScaleRatio", new Vector3(3, 2, 1f)}, - {"useAbsoluteSize", false}, - {"useVisibleColliderBase", true} + Dictionary action = new Dictionary(); + + action["action"] = "Initialize"; + // AgentManager Initialize Args + action["agentMode"] = "fpin"; + action["visibilityScheme"] = "Distance"; + action["renderInstanceSegmentation"] = true; + action["renderDepth"] = true; + + // Fpin agent Initialize args + action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< + string, + object + >() + { + { + "bodyAsset", + new BodyAsset() { assetId = "Toaster_5" } + }, + { "originOffsetX", 0.0f }, + { "originOffsetZ", 0.0f }, + { "colliderScaleRatio", new Vector3(3, 2, 1f) }, + { "useAbsoluteSize", false }, + { "useVisibleColliderBase", true } }; - //action["useAbsoluteSize"] = true; + //action["useAbsoluteSize"] = true; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } case "initpinobja": { - Dictionary action = new Dictionary(); - BodyAsset ba = null; - - if (splitcommand.Length == 2) { + Dictionary action = new Dictionary(); + BodyAsset ba = null; - var objectId = splitcommand[1]; + if (splitcommand.Length == 2) { + var objectId = splitcommand[1]; - objectId = objectId.Trim(); - var pathSplit = Application.dataPath.Split('/'); + objectId = objectId.Trim(); + var pathSplit = Application.dataPath.Split('/'); - var repoRoot = pathSplit.Reverse().Skip(2).Reverse().ToList(); - Debug.Log(string.Join("/", repoRoot)); + var repoRoot = pathSplit.Reverse().Skip(2).Reverse().ToList(); + Debug.Log(string.Join("/", repoRoot)); - var objaverseRoot = $"{string.Join("/", repoRoot)}/objaverse"; - ba = new BodyAsset() { - dynamicAsset = new LoadInUnityProceduralAsset() { - id = objectId, - dir = objaverseRoot - } - }; - } + var objaverseRoot = $"{string.Join("/", repoRoot)}/objaverse"; + ba = new BodyAsset() { + dynamicAsset = new LoadInUnityProceduralAsset() { + id = objectId, + dir = objaverseRoot + } + }; + } - action["action"] = "Initialize"; - // AgentManager Initialize Args - action["agentMode"] = "fpin"; - action["visibilityScheme"] = "Distance"; - action["renderInstanceSegmentation"] = true; - action["renderDepth"] = true; + action["action"] = "Initialize"; + // AgentManager Initialize Args + action["agentMode"] = "fpin"; + action["visibilityScheme"] = "Distance"; + action["renderInstanceSegmentation"] = true; + action["renderDepth"] = true; - Debug.Log($"--initpinobja id: {ba.dynamicAsset.id}, objadir: {ba.dynamicAsset.dir}"); + Debug.Log( + $"--initpinobja id: {ba.dynamicAsset.id}, objadir: {ba.dynamicAsset.dir}" + ); - // Fpin agent Initialize args - action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary() { - {"bodyAsset", ba}, - {"originOffsetX", 0.0f}, - {"originOffsetZ", 0.0f}, - {"colliderScaleRatio", new Vector3(1, 1, 1)} + // Fpin agent Initialize args + action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< + string, + object + >() + { + { "bodyAsset", ba }, + { "originOffsetX", 0.0f }, + { "originOffsetZ", 0.0f }, + { "colliderScaleRatio", new Vector3(1, 1, 1) } }; - //action["useAbsoluteSize"] = true; + //action["useAbsoluteSize"] = true; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } case "initbodynobody": { - - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "InitializeBody"; - action["colliderScaleRatio"] = new Vector3(1.2f, 1.3f, 1.4f); - action["originOffsetX"] = 0.0f; - action["originOffsetZ"] = 0.0f; - action["useAbsoluteSize"] = true; - action["useVisibleColliderBase"] = true; + action["action"] = "InitializeBody"; + action["colliderScaleRatio"] = new Vector3(1.2f, 1.3f, 1.4f); + action["originOffsetX"] = 0.0f; + action["originOffsetZ"] = 0.0f; + action["useAbsoluteSize"] = true; + action["useVisibleColliderBase"] = true; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } case "initbodyt": { - - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "InitializeBody"; - action["bodyAsset"] = new BodyAsset() { assetId = "Toaster_5"}; - action["colliderScaleRatio"] = new Vector3(1, 1, 1); - action["originOffsetX"] = 0.0f; - action["originOffsetZ"] = 0.0f; - //action["useAbsoluteSize"] = true; + action["action"] = "InitializeBody"; + action["bodyAsset"] = new BodyAsset() { assetId = "Toaster_5" }; + action["colliderScaleRatio"] = new Vector3(1, 1, 1); + action["originOffsetX"] = 0.0f; + action["originOffsetZ"] = 0.0f; + //action["useAbsoluteSize"] = true; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } case "initbodyorigint": { - - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "InitializeBody"; - action["bodyAsset"] = new BodyAsset() { assetId = "Toaster_5"}; - action["colliderScaleRatio"] = new Vector3(1, 1, 1); - action["originOffsetX"] = 0.05f; - action["originOffsetZ"] = 0.05f; - //action["useAbsoluteSize"] = true; + action["action"] = "InitializeBody"; + action["bodyAsset"] = new BodyAsset() { assetId = "Toaster_5" }; + action["colliderScaleRatio"] = new Vector3(1, 1, 1); + action["originOffsetX"] = 0.05f; + action["originOffsetZ"] = 0.05f; + //action["useAbsoluteSize"] = true; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } case "initbodyratiot": { - - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "InitializeBody"; - action["bodyAsset"] = new BodyAsset() { assetId = "Toaster_5"}; - action["colliderScaleRatio"] = new Vector3(2f, 4f, 2f); - action["originOffsetX"] = 0.0f; - action["originOffsetZ"] = 0.0f; - //action["useAbsoluteSize"] = true; + action["action"] = "InitializeBody"; + action["bodyAsset"] = new BodyAsset() { assetId = "Toaster_5" }; + action["colliderScaleRatio"] = new Vector3(2f, 4f, 2f); + action["originOffsetX"] = 0.0f; + action["originOffsetZ"] = 0.0f; + //action["useAbsoluteSize"] = true; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } case "initbodyabsolutet": { - - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "InitializeBody"; - action["bodyAsset"] = new BodyAsset() { assetId = "Toaster_5"}; - action["colliderScaleRatio"] = new Vector3(1f, 1f, 1f); - action["originOffsetX"] = 0.0f; - action["originOffsetZ"] = 0.0f; - action["useAbsoluteSize"] = true; + action["action"] = "InitializeBody"; + action["bodyAsset"] = new BodyAsset() { assetId = "Toaster_5" }; + action["colliderScaleRatio"] = new Vector3(1f, 1f, 1f); + action["originOffsetX"] = 0.0f; + action["originOffsetZ"] = 0.0f; + action["useAbsoluteSize"] = true; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } case "initbodyl": { - - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "InitializeBody"; - action["bodyAsset"] = new BodyAsset() { assetId = "LocoBotSimObj"}; - action["colliderScaleRatio"] = new Vector3(1, 1, 1); - action["originOffsetX"] = 0.0f; - action["originOffsetZ"] = 0.0f; - //action["useAbsoluteSize"] = true; + action["action"] = "InitializeBody"; + action["bodyAsset"] = new BodyAsset() { assetId = "LocoBotSimObj" }; + action["colliderScaleRatio"] = new Vector3(1, 1, 1); + action["originOffsetX"] = 0.0f; + action["originOffsetZ"] = 0.0f; + //action["useAbsoluteSize"] = true; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } case "initbodys": { - - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "InitializeBody"; - action["bodyAsset"] = new BodyAsset() { assetId = "StretchBotSimObj"}; - action["colliderScaleRatio"] = new Vector3(1, 1, 1); - action["originOffsetX"] = -0.1f; - action["originOffsetZ"] = 0.1157837f; - //action["useAbsoluteSize"] = true; + action["action"] = "InitializeBody"; + action["bodyAsset"] = new BodyAsset() { assetId = "StretchBotSimObj" }; + action["colliderScaleRatio"] = new Vector3(1, 1, 1); + action["originOffsetX"] = -0.1f; + action["originOffsetZ"] = 0.1157837f; + //action["useAbsoluteSize"] = true; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } case "initbodya": { - - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "InitializeBody"; - action["bodyAsset"] = new BodyAsset() { assetId = "Apple_1"}; - action["colliderScaleRatio"] = new Vector3(1, 1, 1); - action["originOffsetX"] = 0.0f; - action["originOffsetZ"] = 0.0f; - //action["useAbsoluteSize"] = true; + action["action"] = "InitializeBody"; + action["bodyAsset"] = new BodyAsset() { assetId = "Apple_1" }; + action["colliderScaleRatio"] = new Vector3(1, 1, 1); + action["originOffsetX"] = 0.0f; + action["originOffsetZ"] = 0.0f; + //action["useAbsoluteSize"] = true; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } case "initbodyc": { - - Dictionary action = new Dictionary(); - - action["action"] = "InitializeBody"; - action["bodyAsset"] = new BodyAsset() { assetId = "Chair_227_1"}; - action["colliderScaleRatio"] = new Vector3(1, 1, 1); - action["originOffsetX"] = 0.0f; - action["originOffsetZ"] = 0.0f; - //action["useAbsoluteSize"] = true; + Dictionary action = new Dictionary(); - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + action["action"] = "InitializeBody"; + action["bodyAsset"] = new BodyAsset() { assetId = "Chair_227_1" }; + action["colliderScaleRatio"] = new Vector3(1, 1, 1); + action["originOffsetX"] = 0.0f; + action["originOffsetZ"] = 0.0f; + //action["useAbsoluteSize"] = true; - break; - } + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + break; + } - //fpin using apple + //fpin using apple case "initpina": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "Initialize"; - action["agentMode"] = "fpin"; - action["visibilityScheme"] = "Distance"; + action["action"] = "Initialize"; + action["agentMode"] = "fpin"; + action["visibilityScheme"] = "Distance"; - action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary() { - {"bodyAsset", new BodyAsset() { assetId = "Apple_1"}}, - {"originOffsetX", 0.0f}, - {"originOffsetZ", 0.0f}, - {"colliderScaleRatio", new Vector3(1, 1, 1)} + action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< + string, + object + >() + { + { + "bodyAsset", + new BodyAsset() { assetId = "Apple_1" } + }, + { "originOffsetX", 0.0f }, + { "originOffsetZ", 0.0f }, + { "colliderScaleRatio", new Vector3(1, 1, 1) } }; + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - - break; - } + break; + } case "inits-cp": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "Initialize"; - action["agentMode"] = "stretch"; - action["agentControllerType"] = "stretch"; - action["renderInstanceSegmentation"] = true; + action["action"] = "Initialize"; + action["agentMode"] = "stretch"; + action["agentControllerType"] = "stretch"; + action["renderInstanceSegmentation"] = true; - action["thirdPartyCameraParameters"] = new Dictionary() { - {"SecondaryCamera", new CameraParameters() + action["thirdPartyCameraParameters"] = new Dictionary() + { + { + "SecondaryCamera", + new CameraParameters() { fieldOfView = 130f, localEulerAngles = new Vector3(-20f, 0f, 0.0f) - } + } } - }; + }; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } - case "rpanm" : { - Dictionary action = new Dictionary(); + break; + } + case "rpanm": { + Dictionary action = new Dictionary(); - action["action"] = "RandomlyPlaceAgentOnNavMesh"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + action["action"] = "RandomlyPlaceAgentOnNavMesh"; + CurrentActiveController().ProcessControlCommand(action); + break; + } case "ftele": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); action["action"] = "TeleportFull"; action["position"] = new Vector3(10.0f, 0.009f, 2.75f); action["rotation"] = new Vector3(0f, 0f, 0f); @@ -1041,124 +1124,123 @@ public void Execute(string command) { action["standing"] = true; CurrentActiveController().ProcessControlCommand(action); break; - } + } case "obig": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "PlaceObjectIntoGripper"; - action["objectId"] = "Apple|-00.47|+01.15|+00.48"; - if (splitcommand.Length > 1) { - action["objectId"] = splitcommand[1]; - } + action["action"] = "PlaceObjectIntoGripper"; + action["objectId"] = "Apple|-00.47|+01.15|+00.48"; + if (splitcommand.Length > 1) { + action["objectId"] = splitcommand[1]; + } - CurrentActiveController().ProcessControlCommand(action); - break; - } -// case "telearm": { -// Dictionary action = new Dictionary(); -// action["action"] = "TeleportArm"; -// -// CurrentActiveController().ProcessControlCommand(action); -// break; -// } + CurrentActiveController().ProcessControlCommand(action); + break; + } + // case "telearm": { + // Dictionary action = new Dictionary(); + // action["action"] = "TeleportArm"; + // + // CurrentActiveController().ProcessControlCommand(action); + // break; + // } case "mcb": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "MoveCameraBase"; - action["xPositionOffset"] = 0; - action["zPositionOffset"] = 0; - if (splitcommand.Length > 1) { - action["xPositionOffset"] = float.Parse(splitcommand[1]); - } - if (splitcommand.Length == 3) { - action["zPositionOffset"] = float.Parse(splitcommand[2]); - } - CurrentActiveController().ProcessControlCommand(action); - break; - } + action["action"] = "MoveCameraBase"; + action["xPositionOffset"] = 0; + action["zPositionOffset"] = 0; + if (splitcommand.Length > 1) { + action["xPositionOffset"] = float.Parse(splitcommand[1]); + } + if (splitcommand.Length == 3) { + action["zPositionOffset"] = float.Parse(splitcommand[2]); + } + CurrentActiveController().ProcessControlCommand(action); + break; + } case "rcb": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "RotateCameraBase"; - action["yawDegrees"] = 0; - action["rollDegrees"] = 0; - if (splitcommand.Length > 1) { - action["yawDegrees"] = float.Parse(splitcommand[1]); - } - if (splitcommand.Length == 3) { - action["rollDegrees"] = float.Parse(splitcommand[2]); + action["action"] = "RotateCameraBase"; + action["yawDegrees"] = 0; + action["rollDegrees"] = 0; + if (splitcommand.Length > 1) { + action["yawDegrees"] = float.Parse(splitcommand[1]); + } + if (splitcommand.Length == 3) { + action["rollDegrees"] = float.Parse(splitcommand[2]); + } + CurrentActiveController().ProcessControlCommand(action); + break; } - CurrentActiveController().ProcessControlCommand(action); - break; - } case "rcm": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "RotateCameraMount"; - action["degrees"] = 20.0f; - if (splitcommand.Length > 1) { - action["degrees"] = float.Parse(splitcommand[1]); - } - if (splitcommand.Length == 3) { - action["secondary"] = bool.Parse(splitcommand[2]); + action["action"] = "RotateCameraMount"; + action["degrees"] = 20.0f; + if (splitcommand.Length > 1) { + action["degrees"] = float.Parse(splitcommand[1]); + } + if (splitcommand.Length == 3) { + action["secondary"] = bool.Parse(splitcommand[2]); + } + CurrentActiveController().ProcessControlCommand(action); + break; } - CurrentActiveController().ProcessControlCommand(action); - break; - } case "render": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "RenderObjectFromAngles"; - action["objectId"] = splitcommand[1]; - action["renderResolution"] = new Vector2(512, 512); - action["angles"] = new List { 0, 90, 180, 270 }; + action["action"] = "RenderObjectFromAngles"; + action["objectId"] = splitcommand[1]; + action["renderResolution"] = new Vector2(512, 512); + action["angles"] = new List { 0, 90, 180, 270 }; - action["cameraHeightMultiplier"] = 0.0f; - if (splitcommand.Length > 2) { - action["cameraHeightMultiplier"] = float.Parse(splitcommand[2]); - } + action["cameraHeightMultiplier"] = 0.0f; + if (splitcommand.Length > 2) { + action["cameraHeightMultiplier"] = float.Parse(splitcommand[2]); + } - CurrentActiveController().ProcessControlCommand(action); - break; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } case "sgo": { - Dictionary action = new Dictionary(); - - action["action"] = "SetGripperOpenness"; - action["openness"] = 0; - if (splitcommand.Length > 1) { - action["openness"] = float.Parse(splitcommand[1]); + Dictionary action = new Dictionary(); + + action["action"] = "SetGripperOpenness"; + action["openness"] = 0; + if (splitcommand.Length > 1) { + action["openness"] = float.Parse(splitcommand[1]); + } + CurrentActiveController().ProcessControlCommand(action); + break; } - CurrentActiveController().ProcessControlCommand(action); - break; - } case "adbdol": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "SetAssetDatabaseCaching"; + action["action"] = "SetAssetDatabaseCaching"; - if (splitcommand.Length > 1) { - action["enable"] = bool.Parse(splitcommand[1]); - } - - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) { + action["enable"] = bool.Parse(splitcommand[1]); + } - } + CurrentActiveController().ProcessControlCommand(action); + break; + } case "mabd": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "MoveArmBaseDown"; - action["distance"] = 0.4f; - - CurrentActiveController().ProcessControlCommand(action); - break; - } + action["action"] = "MoveArmBaseDown"; + action["distance"] = 0.4f; + + CurrentActiveController().ProcessControlCommand(action); + break; + } case "gaom": { Dictionary action = new Dictionary(); @@ -1171,276 +1253,278 @@ public void Execute(string command) { CurrentActiveController().ProcessControlCommand(action); break; } - + case "inits-camera": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "Initialize"; - action["agentMode"] = "stretch"; - action["agentControllerType"] = "stretch"; - action["renderInstanceSegmentation"] = true; - action["cameraNearPlane"] = 0.05f; - if (splitcommand.Length >= 2) { - action["cameraNearPlane"] = float.Parse(splitcommand[1]); + action["action"] = "Initialize"; + action["agentMode"] = "stretch"; + action["agentControllerType"] = "stretch"; + action["renderInstanceSegmentation"] = true; + action["cameraNearPlane"] = 0.05f; + if (splitcommand.Length >= 2) { + action["cameraNearPlane"] = float.Parse(splitcommand[1]); + } + + action["cameraFarPlane"] = 20.0f; + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + + break; } - - action["cameraFarPlane"] = 20.0f; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } - case "getlights": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "GetLights"; + action["action"] = "GetLights"; - CurrentActiveController().ProcessControlCommand(action); + CurrentActiveController().ProcessControlCommand(action); - //ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + //ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } case "stretchtest1": { - List commands = new List(); - commands.Add("run move_stretch_arm_1"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_1"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest2": { - List commands = new List(); - commands.Add("run move_stretch_arm_2"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } - + List commands = new List(); + commands.Add("run move_stretch_arm_2"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } + case "stretchtest3": { - List commands = new List(); - commands.Add("run move_stretch_arm_3"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_3"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest4": { - List commands = new List(); - commands.Add("run move_stretch_arm_4"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_4"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest5": { - List commands = new List(); - commands.Add("run move_stretch_arm_5"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_5"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest6": { - List commands = new List(); - commands.Add("run move_stretch_arm_6"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_6"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest7": { - List commands = new List(); - commands.Add("run move_stretch_arm_7"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_7"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest8": { - List commands = new List(); - commands.Add("run move_stretch_arm_8"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } - + List commands = new List(); + commands.Add("run move_stretch_arm_8"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } + case "stretchtest9": { - List commands = new List(); - commands.Add("run move_stretch_arm_9"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_9"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest10": { - List commands = new List(); - commands.Add("run move_stretch_arm_10"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_10"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest11": { - List commands = new List(); - commands.Add("run move_stretch_arm_11"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_11"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest12": { - List commands = new List(); - commands.Add("run move_stretch_arm_12"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_12"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest13": { - List commands = new List(); - commands.Add("run move_stretch_arm_13"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_13"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest14": { - List commands = new List(); - commands.Add("run move_stretch_arm_14"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_14"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest15": { - List commands = new List(); - commands.Add("run move_stretch_arm_15"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_15"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest16": { - List commands = new List(); - commands.Add("run move_stretch_arm_16"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_16"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest17": { - List commands = new List(); - commands.Add("run move_stretch_arm_17"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_17"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtest18": { - List commands = new List(); - commands.Add("run move_stretch_arm_18"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } - + List commands = new List(); + commands.Add("run move_stretch_arm_18"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtestu": { - List commands = new List(); - commands.Add("run move_stretch_arm_u"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_u"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "stretchtestd": { - List commands = new List(); - commands.Add("run move_stretch_arm_d"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_stretch_arm_d"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "iktest1": { - List commands = new List(); - commands.Add("run move_ik_arm_1"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_ik_arm_1"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "iktest2": { - List commands = new List(); - commands.Add("run move_ik_arm_2"); - //commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + List commands = new List(); + commands.Add("run move_ik_arm_2"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } case "parent": { - Dictionary action = new Dictionary{ - {"action", "ParentObject"}, + Dictionary action = new Dictionary + { + { "action", "ParentObject" }, }; - action["parentId"] = splitcommand[1]; - action["childId"] = splitcommand[2]; + action["parentId"] = splitcommand[1]; + action["childId"] = splitcommand[2]; - CurrentActiveController().ProcessControlCommand( - action - ); - break; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } case "gohfr": { - Dictionary action = new Dictionary { - {"action", "GetObjectHitFromRaycast"}, - {"from", new Vector3(1.048016f, 1f, 9.798f) }, - {"to", new Vector3(1.048016f, 0f, 9.798f) } + Dictionary action = new Dictionary + { + { "action", "GetObjectHitFromRaycast" }, + { "from", new Vector3(1.048016f, 1f, 9.798f) }, + { "to", new Vector3(1.048016f, 0f, 9.798f) } }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } case "bboxdist": { - Dictionary action = new Dictionary { - {"action", "BBoxDistance"}, - {"objectId0", splitcommand[1]}, - {"objectId1", splitcommand[2]} + Dictionary action = new Dictionary + { + { "action", "BBoxDistance" }, + { "objectId0", splitcommand[1] }, + { "objectId1", splitcommand[2] } }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } case "adjacent": { - Dictionary action = new Dictionary { - {"action", "CheckUnobstructedPathBetweenObjectCenters"}, - {"objectId0", splitcommand[1]}, - {"objectId1", splitcommand[2]} + Dictionary action = new Dictionary + { + { "action", "CheckUnobstructedPathBetweenObjectCenters" }, + { "objectId0", splitcommand[1] }, + { "objectId1", splitcommand[2] } }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } case "whaton": { - List objectIds = new List(); + List objectIds = new List(); - for (int i = 1; i < splitcommand.Length; i++) { - objectIds.Add(splitcommand[i]); - } - Dictionary action = new Dictionary { - {"action", "CheckWhatObjectsOn"}, - {"objectIds", objectIds}, + for (int i = 1; i < splitcommand.Length; i++) { + objectIds.Add(splitcommand[i]); + } + Dictionary action = new Dictionary + { + { "action", "CheckWhatObjectsOn" }, + { "objectIds", objectIds }, }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } case "expspawn": { ServerAction action = new ServerAction(); @@ -1459,7 +1543,7 @@ public void Execute(string command) { action.action = "ReturnValidSpawnsExpRoom"; action.receptacleObjectId = "DiningTable|-00.59|+00.00|+00.33"; action.objectVariation = 0; - action.y = 120f;// UnityEngine.Random.Range(0, 360); + action.y = 120f; // UnityEngine.Random.Range(0, 360); CurrentActiveController().ProcessControlCommand(action); break; } @@ -1469,13 +1553,17 @@ public void Execute(string command) { // Example: 'run simple', where simple.json exists in unity/debug/. // This works best with Unity's Debugger for vscode (or other supported Unity IDEs). case "run": - // parse the file path + // parse the file path const string BASE_PATH = "./debug/"; string file = ""; string path; if (splitcommand.Length == 1) { // opens up a file explorer in the background - path = EditorUtility.OpenFilePanel(title: "Open JSON actions file.", directory: "debug", extension: "json"); + path = EditorUtility.OpenFilePanel( + title: "Open JSON actions file.", + directory: "debug", + extension: "json" + ); } else if (splitcommand.Length == 2) { // uses ./debug/{splitcommand[1]}[.json] file = splitcommand[1].Trim(); @@ -1484,7 +1572,9 @@ public void Execute(string command) { } path = BASE_PATH + file; } else { - Debug.LogError("Pass in a file name, like 'run simple' or open a file with 'run'."); + Debug.LogError( + "Pass in a file name, like 'run simple' or open a file with 'run'." + ); break; } @@ -1510,36 +1600,38 @@ IEnumerator executeBatch(JArray jActions) { new DynamicServerAction(action) ); } else { - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); } } } StartCoroutine(executeBatch(jActions: actions)); break; case "cwr": { - CurrentActiveController().SimObjPhysicsTypeIsReceptacle(); - var obj = CurrentActiveController().actionReturn; - var jsonResolver = new ShouldSerializeContractResolver(); - var str = Newtonsoft.Json.JsonConvert.SerializeObject( - obj, - Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { - ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, - ContractResolver = jsonResolver - }); - Debug.Log(str); + CurrentActiveController().SimObjPhysicsTypeIsReceptacle(); + var obj = CurrentActiveController().actionReturn; + var jsonResolver = new ShouldSerializeContractResolver(); + var str = Newtonsoft.Json.JsonConvert.SerializeObject( + obj, + Newtonsoft.Json.Formatting.None, + new Newtonsoft.Json.JsonSerializerSettings() { + ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, + ContractResolver = jsonResolver + } + ); + Debug.Log(str); - break; - } + break; + } case "exp": { ServerAction action = new ServerAction(); action.action = "SpawnExperimentObjAtRandom"; action.objectType = "receptacle"; - action.randomSeed = 50;// UnityEngine.Random.Range(0, 1000); + action.randomSeed = 50; // UnityEngine.Random.Range(0, 1000); action.receptacleObjectId = "DiningTable|-00.59|+00.00|+00.33"; action.objectVariation = 12; - action.y = 120f;// UnityEngine.Random.Range(0, 360); + action.y = 120f; // UnityEngine.Random.Range(0, 360); CurrentActiveController().ProcessControlCommand(action); break; } @@ -1557,7 +1649,7 @@ IEnumerator executeBatch(JArray jActions) { } else { action.objectVariation = 0; } - action.y = 0f;// UnityEngine.Random.Range(0, 360); + action.y = 0f; // UnityEngine.Random.Range(0, 360); CurrentActiveController().ProcessControlCommand(action); break; } @@ -1566,11 +1658,11 @@ IEnumerator executeBatch(JArray jActions) { ServerAction action = new ServerAction(); action.action = "SpawnExperimentObjAtPoint"; - action.objectType = "replacement";//"receptacle"; + action.objectType = "replacement"; //"receptacle"; action.receptacleObjectId = "DiningTable|-00.59|+00.00|+00.33"; action.objectVariation = 12; action.position = new Vector3(-1.4f, 0.9f, 0.1f); - action.y = 120f;// UnityEngine.Random.Range(0, 360); + action.y = 120f; // UnityEngine.Random.Range(0, 360); CurrentActiveController().ProcessControlCommand(action); break; } @@ -1708,13 +1800,13 @@ IEnumerator executeBatch(JArray jActions) { GameObject table = GameObject.FindObjectOfType().gameObject; - if(table == null) { + if (table == null) { break; } action["objectId"] = table.GetComponent().objectID; CurrentActiveController().ProcessControlCommand(action); - break; + break; } case "spawndirt": { @@ -1723,7 +1815,7 @@ IEnumerator executeBatch(JArray jActions) { GameObject table = GameObject.FindObjectOfType().gameObject; - if(table == null) { + if (table == null) { break; } @@ -1731,7 +1823,7 @@ IEnumerator executeBatch(JArray jActions) { action["howManyDirt"] = 100; action["randomSeed"] = 0; CurrentActiveController().ProcessControlCommand(action); - break; + break; } case "spawndirtarray": { @@ -1740,37 +1832,41 @@ IEnumerator executeBatch(JArray jActions) { GameObject table = GameObject.FindObjectOfType().gameObject; - if(table == null) { + if (table == null) { break; } action["objectId"] = table.GetComponent().objectID; - action["spawnPositions"] = new DirtSpawnPosition[] {new DirtSpawnPosition(){x = -1.728f, z = -0.918f}, new DirtSpawnPosition(){x = 1.728f, z = 0.918f}}; + action["spawnPositions"] = new DirtSpawnPosition[] + { + new DirtSpawnPosition() { x = -1.728f, z = -0.918f }, + new DirtSpawnPosition() { x = 1.728f, z = 0.918f } + }; action["randomSeed"] = 0; CurrentActiveController().ProcessControlCommand(action); - break; + break; } case "cleardirt": { Dictionary action = new Dictionary(); action["action"] = "ClearAllDirt"; CurrentActiveController().ProcessControlCommand(action); - break; + break; } case "sponge": { Dictionary action = new Dictionary(); action["action"] = "ActivateSponge"; CurrentActiveController().ProcessControlCommand(action); - break; - } + break; + } case "getsponge": { Dictionary action = new Dictionary(); action["action"] = "GetSpongeScale"; CurrentActiveController().ProcessControlCommand(action); - break; - } + break; + } case "setsponge": { Dictionary action = new Dictionary(); action["action"] = "SetSpongeScale"; @@ -1778,36 +1874,36 @@ IEnumerator executeBatch(JArray jActions) { action["y"] = 3.0f; action["z"] = 3.0f; CurrentActiveController().ProcessControlCommand(action); - break; - } + break; + } case "pen": { Dictionary action = new Dictionary(); action["action"] = "ActivatePen"; CurrentActiveController().ProcessControlCommand(action); - break; - } + break; + } case "getspongemeta": { Dictionary action = new Dictionary(); action["action"] = "GetSpongeMeta"; CurrentActiveController().ProcessControlCommand(action); break; - } + } case "getpenmeta": { Dictionary action = new Dictionary(); action["action"] = "GetPenMeta"; CurrentActiveController().ProcessControlCommand(action); break; - } + } case "getdirtmeta": { Dictionary action = new Dictionary(); action["action"] = "GetDirtMeta"; CurrentActiveController().ProcessControlCommand(action); break; - } + } case "getdoorhinge": { Dictionary action = new Dictionary(); @@ -1815,7 +1911,7 @@ IEnumerator executeBatch(JArray jActions) { action["objectId"] = "door|1|3"; CurrentActiveController().ProcessControlCommand(action); break; - } + } case "getdoorhandle": { Dictionary action = new Dictionary(); @@ -1823,14 +1919,14 @@ IEnumerator executeBatch(JArray jActions) { action["objectId"] = "door|1|3"; CurrentActiveController().ProcessControlCommand(action); break; - } + } case "getpenmarkmeta": { Dictionary action = new Dictionary(); action["action"] = "GetPenMarkMeta"; CurrentActiveController().ProcessControlCommand(action); break; - } + } // initialize drone mode case "initd": { @@ -1865,7 +1961,7 @@ IEnumerator executeBatch(JArray jActions) { break; } - + case "geo": { var action = new Dictionary() { ["action"] = "GetInSceneAssetGeometry", @@ -1877,9 +1973,7 @@ IEnumerator executeBatch(JArray jActions) { } case "des": { - var action = new Dictionary() { - ["action"] = "DestroyHouse" - }; + var action = new Dictionary() { ["action"] = "DestroyHouse" }; CurrentActiveController().ProcessControlCommand(action); break; } @@ -1902,7 +1996,7 @@ IEnumerator executeBatch(JArray jActions) { CurrentActiveController().ProcessControlCommand(action); break; } - + case "sbc": { var action = new Dictionary() { ["action"] = "UpdateAgentBoxCollider", @@ -1942,7 +2036,7 @@ IEnumerator executeBatch(JArray jActions) { CurrentActiveController().ProcessControlCommand(action); break; } - + case "sbca": { var action = new Dictionary() { ["action"] = "UpdateAgentBoxCollider", @@ -1952,7 +2046,7 @@ IEnumerator executeBatch(JArray jActions) { CurrentActiveController().ProcessControlCommand(action); break; } - + case "sbca2": { var action = new Dictionary() { ["action"] = "UpdateAgentBoxCollider", @@ -1962,7 +2056,7 @@ IEnumerator executeBatch(JArray jActions) { CurrentActiveController().ProcessControlCommand(action); break; } - + case "dbc": { var action = new Dictionary() { ["action"] = "DestroyAgentBoxCollider", @@ -1975,20 +2069,23 @@ IEnumerator executeBatch(JArray jActions) { // materials, and you'll have to call "git restore *.mat *maT" // to revert the materials. case "dangerouslyChangeColor": - CurrentActiveController().ProcessControlCommand(new Dictionary() { - ["action"] = "RandomizeColors" - }); + CurrentActiveController() + .ProcessControlCommand( + new Dictionary() { ["action"] = "RandomizeColors" } + ); break; case "resetColor": - CurrentActiveController().ProcessControlCommand(new Dictionary() { - ["action"] = "ResetColors" - }); + CurrentActiveController() + .ProcessControlCommand( + new Dictionary() { ["action"] = "ResetColors" } + ); break; case "getMaterials": - CurrentActiveController().ProcessControlCommand(new Dictionary() { - ["action"] = "GetMaterials" - }); + CurrentActiveController() + .ProcessControlCommand( + new Dictionary() { ["action"] = "GetMaterials" } + ); break; // This is dangerous because it will modify the underlying // materials, and you'll have to call "git restore *.mat *maT" @@ -2000,15 +2097,19 @@ IEnumerator executeBatch(JArray jActions) { excludedObjectIds.Add(splitcommand[1]); } - CurrentActiveController().ProcessControlCommand(new Dictionary() { - ["action"] = "RandomizeMaterials", - ["excludedObjectIds"] = excludedObjectIds - }); + CurrentActiveController() + .ProcessControlCommand( + new Dictionary() { + ["action"] = "RandomizeMaterials", + ["excludedObjectIds"] = excludedObjectIds + } + ); break; case "resetMaterial": - CurrentActiveController().ProcessControlCommand(new Dictionary() { - ["action"] = "ResetMaterials" - }); + CurrentActiveController() + .ProcessControlCommand( + new Dictionary() { ["action"] = "ResetMaterials" } + ); break; case "light": { @@ -2065,10 +2166,10 @@ IEnumerator executeBatch(JArray jActions) { } } - action.anywhere = false;// false, only recepatcle objects in viewport used - // action.minDistance = 1.8f; - // action.maxDistance = 2.5f; - // action.objectId = "Floor|+00.00|+00.00|+00.00"; + action.anywhere = false; // false, only recepatcle objects in viewport used + // action.minDistance = 1.8f; + // action.maxDistance = 2.5f; + // action.objectId = "Floor|+00.00|+00.00|+00.00"; CurrentActiveController().ProcessControlCommand(action); break; } @@ -2143,20 +2244,47 @@ IEnumerator executeBatch(JArray jActions) { } case "debugarm": { - var arm = CurrentActiveController().GetComponentInChildren(); + var arm = CurrentActiveController() + .GetComponentInChildren(); ArmMetadata armmeta = arm.GenerateMetadata(); Debug.Log("last joint position"); Vector3 rrpos = armmeta.joints[armmeta.joints.Length - 1].rootRelativePosition; - Debug.Log("Root Relative Arm Position - x:" + rrpos.x.ToString("0.###") + " y:" + rrpos.y.ToString("0.###") + " z:" + rrpos.z.ToString("0.###")); + Debug.Log( + "Root Relative Arm Position - x:" + + rrpos.x.ToString("0.###") + + " y:" + + rrpos.y.ToString("0.###") + + " z:" + + rrpos.z.ToString("0.###") + ); break; } case "debugstretcharmjoints": { - var arm = CurrentActiveController().GetComponentInChildren(); + var arm = CurrentActiveController() + .GetComponentInChildren(); ArmMetadata armmeta = arm.GenerateMetadata(); foreach (JointMetadata jm in armmeta.joints) { - Debug.Log(jm.name + " position: (" + jm.position.x + ", " + jm.position.y + ", " + jm.position.z + ")"); - Debug.Log(jm.name + " root-relative position: (" + jm.rootRelativePosition.x + ", " + jm.rootRelativePosition.y + ", " + jm.rootRelativePosition.z + ")"); + Debug.Log( + jm.name + + " position: (" + + jm.position.x + + ", " + + jm.position.y + + ", " + + jm.position.z + + ")" + ); + Debug.Log( + jm.name + + " root-relative position: (" + + jm.rootRelativePosition.x + + ", " + + jm.rootRelativePosition.y + + ", " + + jm.rootRelativePosition.z + + ")" + ); Debug.Log(jm.name + " rotation: " + jm.rotation); Debug.Log(jm.name + " root-relative rotation: " + jm.rootRelativeRotation); Debug.Log(jm.name + " local rotation: " + jm.localRotation); @@ -2165,11 +2293,30 @@ IEnumerator executeBatch(JArray jActions) { } case "debugarmjoints": { - var arm = CurrentActiveController().GetComponentInChildren(); + var arm = CurrentActiveController() + .GetComponentInChildren(); ArmMetadata armmeta = arm.GenerateMetadata(); foreach (JointMetadata jm in armmeta.joints) { - Debug.Log(jm.name + " position: (" + jm.position.x + ", " + jm.position.y + ", " + jm.position.z + ")"); - Debug.Log(jm.name + " root-relative position: (" + jm.rootRelativePosition.x + ", " + jm.rootRelativePosition.y + ", " + jm.rootRelativePosition.z + ")"); + Debug.Log( + jm.name + + " position: (" + + jm.position.x + + ", " + + jm.position.y + + ", " + + jm.position.z + + ")" + ); + Debug.Log( + jm.name + + " root-relative position: (" + + jm.rootRelativePosition.x + + ", " + + jm.rootRelativePosition.y + + ", " + + jm.rootRelativePosition.z + + ")" + ); Debug.Log(jm.name + " rotation: " + jm.rotation); Debug.Log(jm.name + " root-relative rotation: " + jm.rootRelativeRotation); Debug.Log(jm.name + " local rotation: " + jm.localRotation); @@ -2178,8 +2325,12 @@ IEnumerator executeBatch(JArray jActions) { } case "posarm1": { - var arm = CurrentActiveController().GetComponentInChildren(); - var armTarget = arm.transform.Find("robot_arm_FK_IK_rig").Find("IK_rig").Find("IK_pos_rot_manipulator"); + var arm = CurrentActiveController() + .GetComponentInChildren(); + var armTarget = arm + .transform.Find("robot_arm_FK_IK_rig") + .Find("IK_rig") + .Find("IK_pos_rot_manipulator"); armTarget.transform.position = new Vector3(-0.72564f, 0.901f, 0.72564f); break; } @@ -2202,7 +2353,6 @@ IEnumerator executeBatch(JArray jActions) { break; } - case "slide3": { List commands = new List(); commands.Add("inita"); @@ -2344,7 +2494,9 @@ IEnumerator executeBatch(JArray jActions) { commands.Add("mmlah 1 1 True True"); commands.Add("telefull"); commands.Add("mmlah 0.5203709825292535 2 True True"); - commands.Add("mmla 0.01000303 -1.63912773e-06 0.558107364 2 armBase True False True"); + commands.Add( + "mmla 0.01000303 -1.63912773e-06 0.558107364 2 armBase True False True" + ); StartCoroutine(ExecuteBatch(commands)); break; } @@ -2491,7 +2643,8 @@ IEnumerator executeBatch(JArray jActions) { ["agentPositionRelativeCoordinates"] = true }; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action), AManager); break; } @@ -2505,7 +2658,8 @@ IEnumerator executeBatch(JArray jActions) { ["agentPositionRelativeCoordinates"] = true }; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action), AManager); break; } @@ -2518,7 +2672,8 @@ IEnumerator executeBatch(JArray jActions) { //["agentPositionRelativeCoordinates"] = false }; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action), AManager); break; } @@ -2581,7 +2736,9 @@ IEnumerator executeBatch(JArray jActions) { case "putr": { Dictionary action = new Dictionary(); action["action"] = "PutObject"; - action["objectId"] = ((PhysicsRemoteFPSAgentController)CurrentActiveController()).ObjectIdOfClosestReceptacleObject(); + action["objectId"] = ( + (PhysicsRemoteFPSAgentController)CurrentActiveController() + ).ObjectIdOfClosestReceptacleObject(); action["randomSeed"] = int.Parse(splitcommand[1]); // set this to false if we want to place it and let physics resolve by having it fall a short distance into position @@ -2676,7 +2833,7 @@ IEnumerator executeBatch(JArray jActions) { case "gip": { Dictionary action = new Dictionary(); action["action"] = "GetInteractablePoses"; - if(splitcommand.Length == 2) { + if (splitcommand.Length == 2) { action["objectId"] = splitcommand[1].ToString(); } else { action["objectId"] = "Fridge|-02.10|+00.00|+01.07"; @@ -2752,7 +2909,6 @@ IEnumerator executeBatch(JArray jActions) { action["forceVisible"] = false; action["numPlacementAttempts"] = 5; } - // should objects be spawned only in immediately visible areas? else if (splitcommand.Length == 3) { action["randomSeed"] = int.Parse(splitcommand[1]); @@ -2778,7 +2934,7 @@ IEnumerator executeBatch(JArray jActions) { action["numPlacementAttempts"] = int.Parse(splitcommand[3]); } else { action["randomSeed"] = 0; - action["forceVisible"] = false;// true; + action["forceVisible"] = false; // true; action["numPlacementAttempts"] = 20; } @@ -2793,7 +2949,7 @@ IEnumerator executeBatch(JArray jActions) { excludeThese[0] = "CounterTop"; action["excludedReceptacles"] = excludeThese; - action["placeStationary"] = false;// set to false to spawn with kinematic = false, set to true to spawn everything kinematic true and they won't roll around + action["placeStationary"] = false; // set to false to spawn with kinematic = false, set to true to spawn everything kinematic true and they won't roll around CurrentActiveController().ProcessControlCommand(action); break; @@ -2808,12 +2964,11 @@ IEnumerator executeBatch(JArray jActions) { action.objectType = splitcommand[1]; objectVariation = int.Parse(splitcommand[2]); } else { - action.objectType = "Tomato";// default to spawn debug tomato - + action.objectType = "Tomato"; // default to spawn debug tomato } action.action = "CreateObject"; - action.randomizeObjectAppearance = false;// pick randomly from available or not? - action.objectVariation = objectVariation;// if random false, which version of the object to spawn? (there are only 3 of each type atm) + action.randomizeObjectAppearance = false; // pick randomly from available or not? + action.objectVariation = objectVariation; // if random false, which version of the object to spawn? (there are only 3 of each type atm) CurrentActiveController().ProcessControlCommand(action); @@ -2843,9 +2998,7 @@ IEnumerator executeBatch(JArray jActions) { ServerAction action = new ServerAction(); action.action = "RotateUniverseAroundAgent"; - action.rotation = new Vector3( - 0f, float.Parse(splitcommand[1]), 0f - ); + action.rotation = new Vector3(0f, float.Parse(splitcommand[1]), 0f); CurrentActiveController().ProcessControlCommand(action); break; } @@ -2874,20 +3027,27 @@ IEnumerator executeBatch(JArray jActions) { if (splitcommand.Length > 1) { action.objectType = splitcommand[1]; - action.position = new Vector3(float.Parse(splitcommand[2]), float.Parse(splitcommand[3]), float.Parse(splitcommand[4])); - action.rotation = new Vector3(float.Parse(splitcommand[5]), float.Parse(splitcommand[6]), float.Parse(splitcommand[7])); + action.position = new Vector3( + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]), + float.Parse(splitcommand[4]) + ); + action.rotation = new Vector3( + float.Parse(splitcommand[5]), + float.Parse(splitcommand[6]), + float.Parse(splitcommand[7]) + ); // action.rotation? } - // default to zeroed out rotation tomato else { - action.objectType = "Tomato";// default to spawn debug tomato + action.objectType = "Tomato"; // default to spawn debug tomato action.position = Vector3.zero; action.rotation = Vector3.zero; } action.action = "CreateObjectAtLocation"; - action.randomizeObjectAppearance = false;// pick randomly from available or not? + action.randomizeObjectAppearance = false; // pick randomly from available or not? action.objectVariation = 1; // if random false, which version of the object to spawn? (there are only 3 of each type atm) CurrentActiveController().ProcessControlCommand(action); @@ -2999,7 +3159,6 @@ IEnumerator executeBatch(JArray jActions) { action.objectVariation = int.Parse(splitcommand[2]); } else { action.objectType = "Tomato"; // default to spawn debug tomato - } action.x = 0.3f; action.z = 0.3f; @@ -3012,7 +3171,7 @@ IEnumerator executeBatch(JArray jActions) { comm["action"] = "ChangeFOV"; comm["fieldOfView"] = float.Parse(splitcommand[1]); if (splitcommand.Length > 2) { - comm["camera"] = splitcommand[2]; + comm["camera"] = splitcommand[2]; } CurrentActiveController().ProcessControlCommand(comm); @@ -3097,7 +3256,7 @@ IEnumerator executeBatch(JArray jActions) { CurrentActiveController().ProcessControlCommand(action); break; } - + case "stretchmovebaseup": { Dictionary action = new Dictionary(); action["action"] = "MoveArmBaseUp"; @@ -3108,7 +3267,7 @@ IEnumerator executeBatch(JArray jActions) { //action["fixedDeltaTime"] = 5.0f; CurrentActiveController().ProcessControlCommand(action); break; - } + } case "stretchmovebasedown": { Dictionary action = new Dictionary(); @@ -3120,7 +3279,7 @@ IEnumerator executeBatch(JArray jActions) { //action["fixedDeltaTime"] = 5.0f; CurrentActiveController().ProcessControlCommand(action); break; - } + } // move ahead case "ma": { @@ -3131,7 +3290,9 @@ IEnumerator executeBatch(JArray jActions) { if (splitcommand.Length > 1) { action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { action["moveMagnitude"] = 0.25f; } + } else { + action["moveMagnitude"] = 0.25f; + } CurrentActiveController().ProcessControlCommand(action); break; } @@ -3145,7 +3306,9 @@ IEnumerator executeBatch(JArray jActions) { if (splitcommand.Length > 1) { action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { action["moveMagnitude"] = 0.25f; } + } else { + action["moveMagnitude"] = 0.25f; + } CurrentActiveController().ProcessControlCommand(action); break; } @@ -3157,7 +3320,9 @@ IEnumerator executeBatch(JArray jActions) { if (splitcommand.Length > 1) { action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { action["moveMagnitude"] = 0.25f; } + } else { + action["moveMagnitude"] = 0.25f; + } CurrentActiveController().ProcessControlCommand(action); break; } @@ -3169,7 +3334,9 @@ IEnumerator executeBatch(JArray jActions) { if (splitcommand.Length > 1) { action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { action["moveMagnitude"] = 0.25f; } + } else { + action["moveMagnitude"] = 0.25f; + } CurrentActiveController().ProcessControlCommand(action); break; } @@ -3429,7 +3596,7 @@ IEnumerator executeBatch(JArray jActions) { // action.manualInteract = true; CurrentActiveController().ProcessControlCommand(action); break; - } + } // pickup object case "pu": { @@ -3500,9 +3667,8 @@ IEnumerator executeBatch(JArray jActions) { CurrentActiveController().ProcessControlCommand(action); break; } - case "dirtyrec" : { - - Dictionary action = new Dictionary(); + case "dirtyrec": { + Dictionary action = new Dictionary(); action["action"] = "MakeReceptacleDirty"; action["density"] = 0.1f; action["scale"] = new Vector3(0.3f, 0.3f, 0.2f); @@ -3510,13 +3676,12 @@ IEnumerator executeBatch(JArray jActions) { action["objectId"] = splitcommand[1]; } if (splitcommand.Length > 2) { - action["density"] = float.Parse(splitcommand[1]); + action["density"] = float.Parse(splitcommand[1]); } - CurrentActiveController().ProcessControlCommand(action); - break; - - } + CurrentActiveController().ProcessControlCommand(action); + break; + } case "cleanobject": { ServerAction action = new ServerAction(); action.action = "CleanObject"; @@ -3685,7 +3850,7 @@ IEnumerator executeBatch(JArray jActions) { CurrentActiveController().ProcessControlCommand(action); break; - } + } // move hand ahead, forward relative to agent's facing // pass in move magnitude or default is 0.25 units @@ -3713,7 +3878,6 @@ IEnumerator executeBatch(JArray jActions) { Dictionary action = new Dictionary(); action["action"] = "MoveHandBack"; - if (splitcommand.Length > 1) { action["moveMagnitude"] = float.Parse(splitcommand[1]); } else { @@ -3879,7 +4043,7 @@ IEnumerator executeBatch(JArray jActions) { if (splitcommand.Length > 1 && splitcommand.Length < 3) { action.objectId = splitcommand[1]; - action.moveMagnitude = 200f;// 4000f; + action.moveMagnitude = 200f; // 4000f; } else if (splitcommand.Length > 2) { action.objectId = splitcommand[1]; action.moveMagnitude = float.Parse(splitcommand[2]); @@ -3901,12 +4065,14 @@ IEnumerator executeBatch(JArray jActions) { if (splitcommand.Length > 1 && splitcommand.Length < 3) { action.objectId = splitcommand[1]; - action.moveMagnitude = 200f;// 4000f; + action.moveMagnitude = 200f; // 4000f; } else if (splitcommand.Length > 2) { action.objectId = splitcommand[1]; action.moveMagnitude = float.Parse(splitcommand[2]); } else { - action.objectId = ((PhysicsRemoteFPSAgentController)AManager.PrimaryAgent).ObjectIdOfClosestPickupableOrMoveableObject(); + action.objectId = ( + (PhysicsRemoteFPSAgentController)AManager.PrimaryAgent + ).ObjectIdOfClosestPickupableOrMoveableObject(); } // action.moveMagnitude = 200f;// 4000f; @@ -3923,7 +4089,7 @@ IEnumerator executeBatch(JArray jActions) { if (splitcommand.Length > 1 && splitcommand.Length < 3) { action.objectId = splitcommand[1]; - action.moveMagnitude = 10f;// 4000f; + action.moveMagnitude = 10f; // 4000f; } else if (splitcommand.Length > 2) { action.objectId = splitcommand[1]; action.moveMagnitude = float.Parse(splitcommand[2]); @@ -4009,7 +4175,6 @@ IEnumerator executeBatch(JArray jActions) { action.objectPoses[0].position = new Vector3(0, 0, 0); action.objectPoses[0].rotation = new Vector3(0, 0, 0); - CurrentActiveController().ProcessControlCommand(action); break; @@ -4094,7 +4259,6 @@ IEnumerator executeBatch(JArray jActions) { break; } - //***************************************************************************** // MASS SCALE ACTIONS HERE //***************************************************************************** @@ -4186,10 +4350,13 @@ IEnumerator executeBatch(JArray jActions) { if (splitcommand.Length == 2) { // ID of spawner action["objectId"] = splitcommand[1]; - } - else if (splitcommand.Length >= 4) { + } else if (splitcommand.Length >= 4) { // Target position - action["position"] = new Vector3(float.Parse(splitcommand[1]), float.Parse(splitcommand[2]), float.Parse(splitcommand[3])); + action["position"] = new Vector3( + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]) + ); } CurrentActiveController().ProcessControlCommand(action); break; @@ -4205,7 +4372,11 @@ IEnumerator executeBatch(JArray jActions) { //action["position"] = new Vector3(7.149451732635498f, 0.9009996652603146f, -2.4680588245391846f); //for bowl on FloorPlan_Train1_3 - action["position"] = new Vector3(5.039496421813965f, 0.9009997248649597f, -3.127098560333252f); + action["position"] = new Vector3( + 5.039496421813965f, + 0.9009997248649597f, + -3.127098560333252f + ); // pass in a min range, max range, delay if (splitcommand.Length > 1) { @@ -4234,8 +4405,8 @@ IEnumerator executeBatch(JArray jActions) { action["action"] = "GetShortestPath"; action["objectId"] = "Apple|surface|2|0"; - action["position"] = new Vector3(x: 3.0f, y: 0.9009921550750732f,z: 1.75f); - action["rotation"] = new Vector3(-0.0f, 0.0f, 0.0f); + action["position"] = new Vector3(x: 3.0f, y: 0.9009921550750732f, z: 1.75f); + action["rotation"] = new Vector3(-0.0f, 0.0f, 0.0f); action["agentId"] = agentId; CurrentActiveController().ProcessControlCommand(action); @@ -4291,17 +4462,20 @@ IEnumerator executeBatch(JArray jActions) { action["allowedError"] = float.Parse(splitcommand[7]); } - if (splitcommand.Length < 4) { - throw new ArgumentException("need to provide 6 floats, first 3 source position second 3 target position"); + throw new ArgumentException( + "need to provide 6 floats, first 3 source position second 3 target position" + ); } } else { - throw new ArgumentException("need to provide at least 3 floats for target position"); + throw new ArgumentException( + "need to provide at least 3 floats for target position" + ); } CurrentActiveController().ProcessControlCommand(action); break; } - case "shortest_path_p": { + case "shortest_path_p": { Dictionary action = new Dictionary(); action["action"] = "GetShortestPathToPointN"; @@ -4311,11 +4485,14 @@ IEnumerator executeBatch(JArray jActions) { // action.objectId = splitcommand[1]; if (splitcommand.Length >= 4) { - - var target = new Vector3(float.Parse(splitcommand[1]), float.Parse(splitcommand[2]), float.Parse(splitcommand[3])); + var target = new Vector3( + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]) + ); action["target"] = target; } - + if (splitcommand.Length > 4) { action["allowedError"] = float.Parse(splitcommand[4]); } @@ -4324,12 +4501,15 @@ IEnumerator executeBatch(JArray jActions) { action["agentId"] = int.Parse(splitcommand[5]); } - if (splitcommand.Length < 4) { - throw new ArgumentException("need to provide 6 floats, first 3 source position second 3 target position"); + throw new ArgumentException( + "need to provide 6 floats, first 3 source position second 3 target position" + ); } } else { - throw new ArgumentException("need to provide at least 3 floats for target position"); + throw new ArgumentException( + "need to provide at least 3 floats for target position" + ); } CurrentActiveController().ProcessControlCommand(action); break; @@ -4337,10 +4517,11 @@ IEnumerator executeBatch(JArray jActions) { case "visualize_path": { Dictionary action = new Dictionary() { ["action"] = "VisualizePath", - ["positions"] = new List() { - new Vector3(4.258f, 1.0f, -1.69f), - new Vector3(6.3f, 1.0f, -3.452f) - } + ["positions"] = new List() + { + new Vector3(4.258f, 1.0f, -1.69f), + new Vector3(6.3f, 1.0f, -3.452f) + } }; CurrentActiveController().ProcessControlCommand(action); @@ -4349,10 +4530,11 @@ IEnumerator executeBatch(JArray jActions) { case "visualize_path2": { Dictionary action = new Dictionary() { ["action"] = "VisualizePath", - ["positions"] = new List() { - new Vector3(4.258f, 1.0f, -1.69f), - new Vector3(8.3f, 1.0f, 3.452f) - } + ["positions"] = new List() + { + new Vector3(4.258f, 1.0f, -1.69f), + new Vector3(8.3f, 1.0f, 3.452f) + } }; CurrentActiveController().ProcessControlCommand(action); @@ -4409,8 +4591,7 @@ IEnumerator executeBatch(JArray jActions) { break; } case "vpf": { - - ServerAction action = new ServerAction(); + ServerAction action = new ServerAction(); action.action = "VisualizeShortestPaths"; action.objectType = "Dog Bed"; @@ -4420,20 +4601,20 @@ IEnumerator executeBatch(JArray jActions) { action.objectType = splitcommand[1]; } - Debug.Log($"vpf --- call {splitcommand.Length}"); - - + Debug.Log($"vpf --- call {splitcommand.Length}"); var fpin = CurrentActiveController() as FpinAgentController; var pos = fpin.SamplePointsOnNavMesh(200, 0.1f); action.positions = pos.Take(20).ToList(); - Debug.Log($"Debug input field {action.positions} null? {action.positions == null}"); + Debug.Log( + $"Debug input field {action.positions} null? {action.positions == null}" + ); action.grid = true; CurrentActiveController().ProcessControlCommand(action); - break; - } + break; + } case "vw": { Dictionary action = new Dictionary(); action["action"] = "VisualizeWaypoints"; @@ -4446,7 +4627,11 @@ IEnumerator executeBatch(JArray jActions) { var pos = PhysicsController.getReachablePositions().Shuffle(); var positions = pos.Take(num).ToList(); - action["waypoints"] = positions.Select(p => new Waypoint() {position = p, color = SerializableColor.fromUnityColor(UnityEngine.Random.ColorHSV()), radius = 0.5f}); + action["waypoints"] = positions.Select(p => new Waypoint() { + position = p, + color = SerializableColor.fromUnityColor(UnityEngine.Random.ColorHSV()), + radius = 0.5f + }); // action.pathGradient = new Gradient() { // colorKeys = new GradientColorKey[]{ // new GradientColorKey(Color.white, 0.0f), @@ -4467,7 +4652,7 @@ IEnumerator executeBatch(JArray jActions) { CurrentActiveController().ProcessControlCommand(action); break; - } + } case "visualize_shortest_path": { ServerAction action = new ServerAction(); action.action = "VisualizeShortestPaths"; @@ -4485,7 +4670,10 @@ IEnumerator executeBatch(JArray jActions) { ); } else { // var pos = PhysicsController.getReachablePositions().Shuffle(); - action.positions = new List() { PhysicsController.transform.position }; + action.positions = new List() + { + PhysicsController.transform.position + }; action.grid = true; } } @@ -4515,10 +4703,10 @@ IEnumerator executeBatch(JArray jActions) { // action.returnToStart = true; if (splitcommand.Length > 4) { action.position = new Vector3( - float.Parse(splitcommand[1]), - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]) - ); + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]) + ); if (splitcommand.Length >= 5) { action.speed = float.Parse(splitcommand[4]); @@ -4539,7 +4727,6 @@ IEnumerator executeBatch(JArray jActions) { if (splitcommand.Length >= 9) { action.disableRendering = bool.Parse(splitcommand[8]); } - } else { Debug.LogError("Target x y z args needed for command"); } @@ -4556,10 +4743,10 @@ IEnumerator executeBatch(JArray jActions) { // action.returnToStart = true; if (splitcommand.Length > 4) { action.position = new Vector3( - float.Parse(splitcommand[1]), - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]) - ); + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]) + ); if (splitcommand.Length >= 5) { action.speed = float.Parse(splitcommand[4]); @@ -4593,10 +4780,10 @@ IEnumerator executeBatch(JArray jActions) { if (splitcommand.Length >= 4) { Debug.Log("4 >"); action["offset"] = new Vector3( - float.Parse(splitcommand[1]), - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]) - ); + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]) + ); if (splitcommand.Length >= 5) { action["speed"] = float.Parse(splitcommand[4]); @@ -4660,7 +4847,7 @@ IEnumerator executeBatch(JArray jActions) { case "abextendarm": { Dictionary action = new Dictionary(); action["action"] = "MoveArm"; - action["position"] = new Vector3(0,0, 0.5f); + action["position"] = new Vector3(0, 0, 0.5f); action["speed"] = 5.0f; action["disableRendering"] = false; action["useLimits"] = true; @@ -4677,7 +4864,7 @@ IEnumerator executeBatch(JArray jActions) { case "abretractarm": { Dictionary action = new Dictionary(); action["action"] = "MoveArm"; - action["position"] = new Vector3(0,0, -0.5f); + action["position"] = new Vector3(0, 0, -0.5f); action["speed"] = 5.0f; action["disableRendering"] = false; action["useLimits"] = true; @@ -4685,7 +4872,7 @@ IEnumerator executeBatch(JArray jActions) { if (splitcommand.Length > 1) { action["position"] = new Vector3(0, 0, float.Parse(splitcommand[1])); } - + //action["fixedDeltaTime"] = 5.0f; CurrentActiveController().ProcessControlCommand(action); break; @@ -4707,7 +4894,7 @@ IEnumerator executeBatch(JArray jActions) { Dictionary action = new Dictionary(); action["action"] = "PickupObject"; if (splitcommand.Length > 1) { - List objectIds = new List(); + List objectIds = new List(); objectIds.Add(splitcommand[1]); action["objectIdCandidates"] = objectIds; } @@ -4750,7 +4937,9 @@ IEnumerator executeBatch(JArray jActions) { action["y"] = 0.9009995460510254f; action["z"] = 1.5f; Vector3 rotation = new Vector3(0, 135.0f, 0); - float horizon = Agent.GetComponent().AgentCamera.transform.eulerAngles.x; + float horizon = Agent + .GetComponent() + .AgentCamera.transform.eulerAngles.x; bool standing = true; if (splitcommand.Length > 1 && splitcommand.Length < 6) { @@ -4780,7 +4969,7 @@ IEnumerator executeBatch(JArray jActions) { CurrentActiveController().ProcessControlCommand(action); break; - } + } case "expfit": { Dictionary action = new Dictionary(); @@ -4819,12 +5008,11 @@ IEnumerator executeBatch(JArray jActions) { break; } case "mc": { - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); action["action"] = "MoveAgent"; - action["speed"] = 1; + action["speed"] = 1; if (splitcommand.Length > 2) { - - action["ahead"] = float.Parse(splitcommand[1]); + action["ahead"] = float.Parse(splitcommand[1]); action["right"] = float.Parse(splitcommand[2]); if (splitcommand.Length > 3) { @@ -4832,9 +5020,11 @@ IEnumerator executeBatch(JArray jActions) { } } - action["physicsSimulationParams"] = new PhysicsSimulationParams() { autoSimulation = false}; + action["physicsSimulationParams"] = new PhysicsSimulationParams() { + autoSimulation = false + }; action["returnToStart"] = true; - + CurrentActiveController().ProcessControlCommand(action); break; } @@ -4842,19 +5032,19 @@ IEnumerator executeBatch(JArray jActions) { Dictionary action = new Dictionary(); action["action"] = "RotateAgent"; // if (splitcommand.Length > 2) { - action["degrees"] = float.Parse(splitcommand[1]); + action["degrees"] = float.Parse(splitcommand[1]); - // if (splitcommand.Length >= 3) { - // action.speed = float.Parse(splitcommand[2]); - // } + // if (splitcommand.Length >= 3) { + // action.speed = float.Parse(splitcommand[2]); + // } - // if (splitcommand.Length >= 4) { - // action.disableRendering = bool.Parse(splitcommand[3]); - // } + // if (splitcommand.Length >= 4) { + // action.disableRendering = bool.Parse(splitcommand[3]); + // } - // if (splitcommand.Length >= 5) { - // action.returnToStart = bool.Parse(splitcommand[4]); - // } + // if (splitcommand.Length >= 5) { + // action.returnToStart = bool.Parse(splitcommand[4]); + // } // } CurrentActiveController().ProcessControlCommand(action); @@ -4888,10 +5078,10 @@ IEnumerator executeBatch(JArray jActions) { if (splitcommand.Length > 4) { action.rotation = new Vector3( - float.Parse(splitcommand[1]), - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]) - ); + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]) + ); if (splitcommand.Length >= 5) { action.speed = float.Parse(splitcommand[4]); @@ -4906,7 +5096,11 @@ IEnumerator executeBatch(JArray jActions) { case "pumlh": { Dictionary action = new Dictionary(); action["action"] = "PickUpMidLevelHand"; - action["objectIds"] = new List { "Bread|-00.52|+01.17|-00.03", "Apple|-00.54|+01.15|+00.18" }; + action["objectIds"] = new List + { + "Bread|-00.52|+01.17|-00.03", + "Apple|-00.54|+01.15|+00.18" + }; CurrentActiveController().ProcessControlCommand(action); break; } @@ -4914,10 +5108,7 @@ IEnumerator executeBatch(JArray jActions) { case "smooth": { Dictionary action = new Dictionary(); action["action"] = "RandomizeSmoothness"; - action["objectIds"] = new string[] { - "small|room|14", - "Sofa1" - }; + action["objectIds"] = new string[] { "small|room|14", "Sofa1" }; CurrentActiveController().ProcessControlCommand(action); break; } @@ -4940,7 +5131,6 @@ IEnumerator executeBatch(JArray jActions) { break; } case "cr": { - // dynamic action = new JObject(); Dictionary action = new Dictionary(); @@ -4951,7 +5141,11 @@ IEnumerator executeBatch(JArray jActions) { path = ""; if (splitcommand.Length == 1) { // opens up a file explorer in the background - path = EditorUtility.OpenFilePanel(title: "Open JSON actions file.", directory: "Resources", extension: "json"); + path = EditorUtility.OpenFilePanel( + title: "Open JSON actions file.", + directory: "Resources", + extension: "json" + ); } else if (splitcommand.Length == 2) { // uses ./debug/{splitcommand[1]}[.json] file = splitcommand[1].Trim(); @@ -4973,7 +5167,6 @@ IEnumerator executeBatch(JArray jActions) { JObject obj = JObject.Parse(jsonStr); - // var k = JObject.Parse(jsonStr); // JArray wallsJson = k["walls"]; @@ -4997,8 +5190,8 @@ IEnumerator executeBatch(JArray jActions) { action["wallMaterialId"] = "DrywallOrange"; action["floorMaterialId"] = "DarkWoodFloors"; action["ceilingMaterialId"] = ""; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); // CurrentActiveController().CreateRoom( // new Wall[] { @@ -5034,30 +5227,31 @@ IEnumerator executeBatch(JArray jActions) { break; // public void CreateRoom(Wall[] walls, float wallHeight, string wallMaterialId, string floorMaterialId, string ceilingMaterialId, float wallThickness = 0.0f, string namePostFix = "") { - } case "newScene": { - UnityEngine.SceneManagement.SceneManager.LoadScene("FloorPlan402_physics"); - break; - } + UnityEngine.SceneManagement.SceneManager.LoadScene("FloorPlan402_physics"); + break; + } case "newScene2": { - UnityEngine.SceneManagement.SceneManager.LoadScene("Procedural"); - break; - } + UnityEngine.SceneManagement.SceneManager.LoadScene("Procedural"); + break; + } case "ch": { - Dictionary action = new Dictionary(); // AssetDatabase.Refresh(); action["action"] = "CreateHouse"; - var jsonStr = System.IO.File.ReadAllText(Application.dataPath + "/Resources/rooms/house.json"); + var jsonStr = System.IO.File.ReadAllText( + Application.dataPath + "/Resources/rooms/house.json" + ); Debug.Log($"jjson: {jsonStr}"); JObject obj = JObject.Parse(jsonStr); action["house"] = obj; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); // CurrentActiveController().CreateHouse( // new House() { @@ -5162,7 +5356,6 @@ IEnumerator executeBatch(JArray jActions) { } case "chp": { - Dictionary action = new Dictionary(); // AssetDatabase.Refresh(); @@ -5186,12 +5379,12 @@ IEnumerator executeBatch(JArray jActions) { JObject obj = JObject.Parse(jsonStr); action["house"] = obj; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); break; } - case "chp_direct": { - + case "chp_direct": { Dictionary action = new Dictionary(); // AssetDatabase.Refresh(); @@ -5216,11 +5409,13 @@ IEnumerator executeBatch(JArray jActions) { action["house"] = obj; // CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - ProceduralTools.CreateHouse(obj.ToObject(), ProceduralTools.GetMaterials()); + ProceduralTools.CreateHouse( + obj.ToObject(), + ProceduralTools.GetMaterials() + ); break; } case "chpt_direct": { - Dictionary action = new Dictionary(); // AssetDatabase.Refresh(); @@ -5242,10 +5437,12 @@ IEnumerator executeBatch(JArray jActions) { JObject obj = JObject.Parse(jsonStr); - var house = Thor.Procedural.Templates.createHouseFromTemplate(obj.ToObject()); + var house = Thor.Procedural.Templates.createHouseFromTemplate( + obj.ToObject() + ); // var house = CurrentActiveController().actionReturn; - + action.Clear(); action["action"] = "CreateHouse"; @@ -5253,27 +5450,28 @@ IEnumerator executeBatch(JArray jActions) { var jsonResolver = new ShouldSerializeContractResolver(); var houseString = Newtonsoft.Json.JsonConvert.SerializeObject( - house, - Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { - ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, - ContractResolver = jsonResolver - } - ); + house, + Newtonsoft.Json.Formatting.None, + new Newtonsoft.Json.JsonSerializerSettings() { + ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, + ContractResolver = jsonResolver + } + ); - Debug.Log("House: " + houseString); - string destination = path = Application.dataPath + ROOM_BASE_PATH + "template-out-house.json"; - + Debug.Log("House: " + houseString); + string destination = path = + Application.dataPath + ROOM_BASE_PATH + "template-out-house.json"; System.IO.File.WriteAllText(destination, houseString); - - ProceduralTools.CreateHouse(JObject.FromObject(house).ToObject(), ProceduralTools.GetMaterials()); + ProceduralTools.CreateHouse( + JObject.FromObject(house).ToObject(), + ProceduralTools.GetMaterials() + ); break; } case "chpt": { - Dictionary action = new Dictionary(); // AssetDatabase.Refresh(); @@ -5296,10 +5494,10 @@ IEnumerator executeBatch(JArray jActions) { JObject obj = JObject.Parse(jsonStr); - action["template"] = obj; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); var house = CurrentActiveController().actionReturn; @@ -5312,20 +5510,20 @@ IEnumerator executeBatch(JArray jActions) { var jsonResolver = new ShouldSerializeContractResolver(); var houseString = Newtonsoft.Json.JsonConvert.SerializeObject( - house, - Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { - ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, - ContractResolver = jsonResolver - } - ); - string destination = path = Application.dataPath + ROOM_BASE_PATH + "template-out-house.json"; - + house, + Newtonsoft.Json.Formatting.None, + new Newtonsoft.Json.JsonSerializerSettings() { + ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, + ContractResolver = jsonResolver + } + ); + string destination = path = + Application.dataPath + ROOM_BASE_PATH + "template-out-house.json"; System.IO.File.WriteAllText(destination, houseString); - - - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); break; } @@ -5335,26 +5533,33 @@ IEnumerator executeBatch(JArray jActions) { // AssetDatabase.Refresh(); action["action"] = "GetAssetDatabase"; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); // var assetMetadata = (List)CurrentActiveController().actionReturn as List; // Debug.Log($"assetDb: {string.Join("\n", assetMetadata.Select(m => $"{m.id}|{m.type}|box: {m.boundingBox.min}, {m.boundingBox.max}, {m.primaryProperty}"))}"); break; } case "gadt": { - CurrentActiveController().GetAssetDatabase(); - var assetMetadata = (List)CurrentActiveController().actionReturn as List; + CurrentActiveController().GetAssetDatabase(); + var assetMetadata = + (List)CurrentActiveController().actionReturn + as List; - break; - } + break; + } case "soirr": { Dictionary action = new Dictionary(); action["action"] = "SpawnObjectInReceptacleRandomly"; action["prefabName"] = "Coffee_Table_211_1"; action["objectId"] = "THISISATABLE"; action["targetReceptacle"] = "Floor|+00.00|+00.00|+00.00"; - action["rotation"] = new FlexibleRotation() { axis = new Vector3(0, 1, 0), degrees = 45 }; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + action["rotation"] = new FlexibleRotation() { + axis = new Vector3(0, 1, 0), + degrees = 45 + }; + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); break; } case "soir": { @@ -5364,19 +5569,22 @@ IEnumerator executeBatch(JArray jActions) { action["objectId"] = "THISISATABLE"; action["targetReceptacle"] = "Floor|+00.00|+00.00|+00.00"; action["position"] = new Vector3(5f, 0.0006076097f, 8.15f); - action["rotation"] = new FlexibleRotation() { axis = new Vector3(0, 1, 0), degrees = 45 }; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + action["rotation"] = new FlexibleRotation() { + axis = new Vector3(0, 1, 0), + degrees = 45 + }; + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); break; } case "bnm": { Dictionary action = new Dictionary(); action["action"] = "BakeNavMesh"; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); break; - } case "va": { - Dictionary action = new Dictionary(); action["action"] = "SpawnAsset"; action["assetId"] = "Dining_Table_16_1"; @@ -5387,30 +5595,32 @@ IEnumerator executeBatch(JArray jActions) { action["assetId"] = splitcommand[1]; } - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); break; } case "ra": { - Dictionary action = new Dictionary(); action["action"] = "RotateObject"; action["objectId"] = "asset_0"; if (splitcommand.Length > 4) { action["angleAxisRotation"] = new FlexibleRotation() { - axis = new Vector3(float.Parse(splitcommand[1]), float.Parse(splitcommand[2]), float.Parse(splitcommand[3])), + axis = new Vector3( + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]) + ), degrees = float.Parse(splitcommand[4]) }; } if (splitcommand.Length == 6) { - action["absolute"] = bool.Parse(splitcommand[5]); - } - - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); break; } case "laoc": { @@ -5422,7 +5632,8 @@ IEnumerator executeBatch(JArray jActions) { action["objectId"] = splitcommand[1]; } - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); break; } case "sky": { @@ -5436,99 +5647,89 @@ IEnumerator executeBatch(JArray jActions) { float.Parse(splitcommand[3]), float.Parse(splitcommand[4]) ); - } - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); break; } case "g3d": { - Dictionary action = new Dictionary(); action["action"] = "GetAsset3DGeometry"; if (splitcommand.Length == 2) { action["assetId"] = splitcommand[1]; - } - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - var geos = (List)CurrentActiveController().actionReturn as List; + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + var geos = + (List)CurrentActiveController().actionReturn + as List; Debug.Log($"Geo count: {geos.Count}"); var geo = geos.First(); - Debug.Log($"Geometry. vertexCount: {geo.vertices.Length}, triangleCount: {geo.triangleIndices.Length / 3}, some: {string.Join(", ", geo.triangleIndices.Take(12))}"); + Debug.Log( + $"Geometry. vertexCount: {geo.vertices.Length}, triangleCount: {geo.triangleIndices.Length / 3}, some: {string.Join(", ", geo.triangleIndices.Take(12))}" + ); break; } case "ca_msg": { + if (splitcommand.Length == 2) { + var objectId = splitcommand[1]; - if (splitcommand.Length == 2) { + var fname = objectId.Trim(); + // if (!fname.EndsWith(".json")) { + // fname += ".msgpack.gz"; + // } - var objectId = splitcommand[1]; + var pathSplit = Application.dataPath.Split('/'); - var fname = objectId.Trim(); - // if (!fname.EndsWith(".json")) { - // fname += ".msgpack.gz"; - // } - - var pathSplit = Application.dataPath.Split('/'); + var repoRoot = pathSplit.Reverse().Skip(2).Reverse().ToList(); + Debug.Log(string.Join("/", repoRoot)); - var repoRoot = pathSplit.Reverse().Skip(2).Reverse().ToList(); - Debug.Log(string.Join("/", repoRoot)); + var objaverseRoot = $"{string.Join("/", repoRoot)}/objaverse"; + var objectDir = $"{objaverseRoot}/{objectId}"; + var objectPath = $"{objectDir}/{fname}"; - var objaverseRoot = $"{string.Join("/", repoRoot)}/objaverse"; - var objectDir = $"{objaverseRoot}/{objectId}"; - var objectPath = $"{objectDir}/{fname}"; + // var filename = Path.GetFileName(objectPath); - - - // var filename = Path.GetFileName(objectPath); + //var pathOut = Application.dataPath + $"/Resources/msgpack_test/{objectId}.json"; - //var pathOut = Application.dataPath + $"/Resources/msgpack_test/{objectId}.json"; + var af = CurrentActiveController().CreateRuntimeAsset(fname, objaverseRoot); + Debug.Log($"ActionFinished {af.success} {af.errorMessage}"); + } - var af = CurrentActiveController().CreateRuntimeAsset( - fname, - objaverseRoot - ); - Debug.Log($"ActionFinished {af.success} {af.errorMessage}"); + break; } - - break; - } case "caid_msg": { - - + if (splitcommand.Length == 2) { + var objectId = splitcommand[1]; - if (splitcommand.Length == 2) { + var fname = objectId.Trim(); + if (!fname.EndsWith(".json")) { + fname += ".msgpack.gz"; + } - var objectId = splitcommand[1]; + var pathSplit = Application.dataPath.Split('/'); - var fname = objectId.Trim(); - if (!fname.EndsWith(".json")) { - fname += ".msgpack.gz"; - } - - var pathSplit = Application.dataPath.Split('/'); + var repoRoot = pathSplit.Reverse().Skip(2).Reverse().ToList(); + Debug.Log(string.Join("/", repoRoot)); - var repoRoot = pathSplit.Reverse().Skip(2).Reverse().ToList(); - Debug.Log(string.Join("/", repoRoot)); + var objaverseRoot = $"{string.Join("/", repoRoot)}/objaverse"; + var objectDir = $"{objaverseRoot}/{objectId}"; + var objectPath = $"{objectDir}/{fname}"; + var dir = Application.persistentDataPath; - var objaverseRoot = $"{string.Join("/", repoRoot)}/objaverse"; - var objectDir = $"{objaverseRoot}/{objectId}"; - var objectPath = $"{objectDir}/{fname}"; - var dir = Application.persistentDataPath; - - var filename = Path.GetFileName(objectPath); + var filename = Path.GetFileName(objectPath); - var pathOut = Application.dataPath + $"/Resources/msgpack_test/{objectId}.json"; + var pathOut = + Application.dataPath + $"/Resources/msgpack_test/{objectId}.json"; - CurrentActiveController().CreateRuntimeAsset( - objectId, - dir - ); + CurrentActiveController().CreateRuntimeAsset(objectId, dir); + } + + break; } - - break; - } case "proc_mats": { var mats = ProceduralTools.GetMaterials(); @@ -5557,68 +5758,71 @@ IEnumerator executeBatch(JArray jActions) { break; } case "nma": { - var navMeshAgent = GameObject.FindObjectOfType(); - Debug.Log($"Navmeshagent typeID: {navMeshAgent.agentTypeID}"); - break; - } + var navMeshAgent = GameObject.FindObjectOfType(); + Debug.Log($"Navmeshagent typeID: {navMeshAgent.agentTypeID}"); + break; + } case "tadfa": { Dictionary action = new Dictionary(); action["action"] = "TestActionDispatchFindAmbiguous"; - action["typeName"] = "UnityStandardAssets.Characters.FirstPerson.PhysicsRemoteFPSAgentController"; + action["typeName"] = + "UnityStandardAssets.Characters.FirstPerson.PhysicsRemoteFPSAgentController"; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); var obj = (List)(CurrentActiveController().actionReturn); Debug.Log($"{string.Join(",", obj)}"); break; - } + } case "proc_arr": { - var arr = new int[][] { - new int[]{2, 2, 2, 2}, - new int[]{2, 1, 1, 2}, - new int[]{2, 1, 1, 2}, - new int[]{2, 1, 1, 2}, - new int[]{2, 2, 2, 2}, - }; - - + var arr = new int[][] + { + new int[] { 2, 2, 2, 2 }, + new int[] { 2, 1, 1, 2 }, + new int[] { 2, 1, 1, 2 }, + new int[] { 2, 1, 1, 2 }, + new int[] { 2, 2, 2, 2 }, + }; - - var layout = $@" + var layout = + $@" 2 2 2 2 2 1 1 2 2 1 1 2 2 2 2 2 "; - - var doors = @" + var doors = + @" 2 = 2 2 2 = 1 2 2 1 1 2 2 2 2 2"; - var objects = @" + var objects = + @" 2 2 2 2 2 1 1 2 2 * 1 2 2 2 2 +"; - // var arr = new int[][] { - // new int[]{0, 0, 0}, - // new int[]{0, 1, 0}, - // new int[]{0, 0, 0} - // }; - - // 2: [ (0, 0),(0, 1),(0, 2),(0, 3),(1, 3),(2, 3),(3, 3) ] - // 1: [ (1, 1),(1, 2),(2, 2),(3, 2),(3, 1),(2, 1) ] - - // 1: [ ((0, 0), (1, 1)),((1, 1), (1, 2)),((0, 0), (1, 2)),((1, 2), (2, 2)),((0, 0), (2, 2)),((2, 2), (2, 1)),((0, 0), (2, 1)),((2, 1), (1, 1)) ] - - var house = Templates.createHouseFromTemplate( - new HouseTemplate() { - id = "house_0", - layout = $@" + // var arr = new int[][] { + // new int[]{0, 0, 0}, + // new int[]{0, 1, 0}, + // new int[]{0, 0, 0} + // }; + + // 2: [ (0, 0),(0, 1),(0, 2),(0, 3),(1, 3),(2, 3),(3, 3) ] + // 1: [ (1, 1),(1, 2),(2, 2),(3, 2),(3, 1),(2, 1) ] + + // 1: [ ((0, 0), (1, 1)),((1, 1), (1, 2)),((0, 0), (1, 2)),((1, 2), (2, 2)),((0, 0), (2, 2)),((2, 2), (2, 1)),((0, 0), (2, 1)),((2, 1), (1, 1)) ] + + var house = Templates.createHouseFromTemplate( + new HouseTemplate() { + id = "house_0", + layout = + $@" 0 0 0 0 0 0 0 2 2 2 2 0 0 2 2 2 2 0 @@ -5626,7 +5830,8 @@ 0 1 1 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 ", - objectsLayouts = new List() { + objectsLayouts = new List() + { $@" 0 0 0 0 0 0 0 2 2 2 2 0 @@ -5634,8 +5839,7 @@ 0 2 2 2 2 0 0 1 * 1 = 0 0 1 1 1 + 0 0 0 0 0 0 0 - " - , + ", $@" 0 0 0 0 0 0 0 2 2 2 2 0 @@ -5644,91 +5848,135 @@ 0 1 1 1 1 0 0 1 1 1 $ 0 0 0 0 0 0 0 " - }, - // layout = $@" - // 2 2 2 2 2 - // 2 2 2 2 2 - // 2 2 1 1 2 - // 2 2 1 1 2 - // 2 2 2 2 2 - // ", - // objectsLayouts = new List() { - // $@" - // 2 2 2 2 2 - // 2 2 = 2 2 - // 2 2 = 1 2 - // 2 2 * 1 2 - // 2 2 2 2 + - // " - // , - // $@" - // 2 2 2 2 2 - // 2 2 2 2 2 - // 2 2 1 1 2 - // 2 2 1 1 2 - // 2 2 2 2 $ - // " - // }, - rooms = new Dictionary() { - {"1", new RoomTemplate(){ - wallTemplate = new Thor.Procedural.Data.PolygonWall() { - material = new MaterialProperties() { - color = SerializableColor.fromUnityColor(Color.red), - unlit = true - } - }, - floorTemplate = new Thor.Procedural.Data.RoomHierarchy() { - floorMaterial = new MaterialProperties() { name = "DarkWoodFloors"}, - roomType = "Bedroom" - }, - wallHeight = 3.0f - }}, - {"2", new RoomTemplate(){ - wallTemplate = new Thor.Procedural.Data.PolygonWall() { - material = new MaterialProperties() { - color = SerializableColor.fromUnityColor(Color.blue), - unlit = true + }, + // layout = $@" + // 2 2 2 2 2 + // 2 2 2 2 2 + // 2 2 1 1 2 + // 2 2 1 1 2 + // 2 2 2 2 2 + // ", + // objectsLayouts = new List() { + // $@" + // 2 2 2 2 2 + // 2 2 = 2 2 + // 2 2 = 1 2 + // 2 2 * 1 2 + // 2 2 2 2 + + // " + // , + // $@" + // 2 2 2 2 2 + // 2 2 2 2 2 + // 2 2 1 1 2 + // 2 2 1 1 2 + // 2 2 2 2 $ + // " + // }, + rooms = new Dictionary() + { + { + "1", + new RoomTemplate() + { + wallTemplate = new Thor.Procedural.Data.PolygonWall() + { + material = new MaterialProperties() + { + color = SerializableColor.fromUnityColor(Color.red), + unlit = true + } + }, + floorTemplate = new Thor.Procedural.Data.RoomHierarchy() + { + floorMaterial = new MaterialProperties() + { + name = "DarkWoodFloors" + }, + roomType = "Bedroom" + }, + wallHeight = 3.0f + } + }, + { + "2", + new RoomTemplate() + { + wallTemplate = new Thor.Procedural.Data.PolygonWall() + { + material = new MaterialProperties() + { + color = SerializableColor.fromUnityColor( + Color.blue + ), + unlit = true + } + }, + floorTemplate = new Thor.Procedural.Data.RoomHierarchy() + { + floorMaterial = new MaterialProperties() + { + name = "RedBrick" + }, + roomType = "LivingRoom" + }, + wallHeight = 3.0f + } + } + }, + doors = new Dictionary() + { + { + "=", + new Thor.Procedural.Data.Door() + { + openness = 1.0f, + assetId = "Doorway_1", + room0 = "1" + } + } + }, + objects = new Dictionary() + { + { + "*", + new Thor.Procedural.Data.HouseObject() + { + assetId = "RoboTHOR_side_table_strind", + rotation = new FlexibleRotation() + { + axis = new Vector3(0, 1, 0), + degrees = 90 } - }, - floorTemplate = new Thor.Procedural.Data.RoomHierarchy() { - floorMaterial = new MaterialProperties() { name ="RedBrick" }, - roomType = "LivingRoom" - }, - wallHeight = 3.0f - }} - }, - doors = new Dictionary() { - {"=", new Thor.Procedural.Data.Door(){ - openness = 1.0f, - assetId = "Doorway_1", - room0 = "1" - - }} - }, - objects = new Dictionary() { - {"*", new Thor.Procedural.Data.HouseObject(){ - assetId = "RoboTHOR_side_table_strind", - rotation = new FlexibleRotation() { axis = new Vector3(0, 1, 0), degrees = 90} - }}, - {"+", new Thor.Procedural.Data.HouseObject(){ - assetId = "Chair_007_1" - }}, - {"$", new Thor.Procedural.Data.HouseObject(){ - assetId = "Apple_4", - position = new Vector3(0.1f, 1.5f, 0) - }} - }, - proceduralParameters = new ProceduralParameters() { - ceilingMaterial = new MaterialProperties() { name = "ps_mat" }, - floorColliderThickness = 1.0f, - receptacleHeight = 0.7f, - skyboxId = "Sky1", + } + }, + { + "+", + new Thor.Procedural.Data.HouseObject() + { + assetId = "Chair_007_1" + } + }, + { + "$", + new Thor.Procedural.Data.HouseObject() + { + assetId = "Apple_4", + position = new Vector3(0.1f, 1.5f, 0) + } + } + }, + proceduralParameters = new ProceduralParameters() { + ceilingMaterial = new MaterialProperties() { name = "ps_mat" }, + floorColliderThickness = 1.0f, + receptacleHeight = 0.7f, + skyboxId = "Sky1", + } } - } - - ); + ); - var temp = @" + var temp = + @" { 'rooms': { '1': { @@ -5750,40 +5998,37 @@ 0 0 0 0 0 0 } "; + var jsonResolver = new ShouldSerializeContractResolver(); + var houseString = Newtonsoft.Json.JsonConvert.SerializeObject( + house, + Newtonsoft.Json.Formatting.None, + new Newtonsoft.Json.JsonSerializerSettings() { + ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, + ContractResolver = jsonResolver + } + ); + Debug.Log("####### HOUSE\n" + houseString); + ProceduralTools.CreateHouse(house, ProceduralTools.GetMaterials()); - var jsonResolver = new ShouldSerializeContractResolver(); - var houseString = Newtonsoft.Json.JsonConvert.SerializeObject( - house, - Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { - ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, - ContractResolver = jsonResolver - } - ); - Debug.Log("####### HOUSE\n" + houseString); - - ProceduralTools.CreateHouse(house, ProceduralTools.GetMaterials()); - - Debug.Log("####### HOUSE Created \n"); - + Debug.Log("####### HOUSE Created \n"); - Dictionary action = new Dictionary(); + Dictionary action = new Dictionary(); - action["action"] = "TeleportFull"; - action["position"] = new Vector3(3.0f, 1.0f, 2.0f); - action["rotation"] = new Vector3(0, 0, 0); - action["horizon"] = 0.0f; - action["standing"] = true; - action["forceAction"] = true; + action["action"] = "TeleportFull"; + action["position"] = new Vector3(3.0f, 1.0f, 2.0f); + action["rotation"] = new Vector3(0, 0, 0); + action["horizon"] = 0.0f; + action["standing"] = true; + action["forceAction"] = true; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - break; - } + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + break; + } } // StartCoroutine(CheckIfactionCompleteWasSetToTrueAfterWaitingALittleBit(splitcommand[0])); - } #endif @@ -5799,7 +6044,10 @@ public static void CopyToClipboard(string s) { // used to show what's currently visible on the top left of the screen void OnGUI() { - if (CurrentActiveController().VisibleSimObjPhysics != null && this.controlMode != ControlMode.MINIMAL_FPS) { + if ( + CurrentActiveController().VisibleSimObjPhysics != null + && this.controlMode != ControlMode.MINIMAL_FPS + ) { if (CurrentActiveController().VisibleSimObjPhysics.Length > 10) { int horzIndex = -1; GUILayout.BeginHorizontal(); @@ -5810,7 +6058,11 @@ void OnGUI() { GUILayout.BeginHorizontal(); horzIndex = 0; } - GUILayout.Button(o.ObjectID, UnityEditor.EditorStyles.miniButton, GUILayout.MaxWidth(200f)); + GUILayout.Button( + o.ObjectID, + UnityEditor.EditorStyles.miniButton, + GUILayout.MaxWidth(200f) + ); } GUILayout.EndHorizontal(); @@ -5839,7 +6091,13 @@ void OnGUI() { // } - if (GUILayout.Button(o.ObjectID + suffix, UnityEditor.EditorStyles.miniButton, GUILayout.MinWidth(100f))) { + if ( + GUILayout.Button( + o.ObjectID + suffix, + UnityEditor.EditorStyles.miniButton, + GUILayout.MinWidth(100f) + ) + ) { CopyToClipboard(o.ObjectID); } } @@ -5847,7 +6105,5 @@ void OnGUI() { } } #endif - } } - diff --git a/unity/Assets/Scripts/DecalCollision.cs b/unity/Assets/Scripts/DecalCollision.cs index 963e66050c..07734ba8fe 100644 --- a/unity/Assets/Scripts/DecalCollision.cs +++ b/unity/Assets/Scripts/DecalCollision.cs @@ -12,28 +12,31 @@ public class DecalCollision : Break { // If true Guarantees that other spawn planes under the same parent will have the same stencil value [SerializeField] private bool sameStencilAsSiblings = false; + [SerializeField] private int stencilWriteValue = 1; + [SerializeField] private GameObject[] decals = null; + [SerializeField] private float nextDecalWaitTimeSeconds = 1; + [SerializeField] private Vector3 decalScale = new Vector3(0.3f, 0.3f, 0.2f); + [SerializeField] private bool transparent = false; [SerializeField] - protected bool stencilSet = false; + // In local space private Vector3 transparentDecalSpawnOffset = new Vector3(0, 0, 0); private float prevTime; private static int currentStencilId = 0; - - void OnEnable() { breakType = BreakType.Decal; prevTime = Time.time; @@ -44,12 +47,16 @@ void OnEnable() { if (!sameStencilAsSiblings) { setStencilWriteValue(mr); } else { - var otherPlanes = this.transform.parent.gameObject.GetComponentsInChildren(); + var otherPlanes = + this.transform.parent.gameObject.GetComponentsInChildren(); // var otherPlanes = this.gameObject.GetComponentsInParent(); // Debug.Log("other planes id " + this.stencilWriteValue + " len " + otherPlanes.Length); foreach (var spawnPlane in otherPlanes) { - - if (spawnPlane.isActiveAndEnabled && spawnPlane.stencilSet && spawnPlane.sameStencilAsSiblings) { + if ( + spawnPlane.isActiveAndEnabled + && spawnPlane.stencilSet + && spawnPlane.sameStencilAsSiblings + ) { this.stencilWriteValue = spawnPlane.stencilWriteValue; this.stencilSet = true; mr.material.SetInt("_StencilRef", this.stencilWriteValue); @@ -66,7 +73,6 @@ void OnEnable() { mr.material.SetInt("_StencilRef", this.stencilWriteValue); } } - } private void setStencilWriteValue(MeshRenderer mr) { @@ -96,7 +102,12 @@ protected override void BreakForDecalType(Collision collision) { // Maybe factor the other object size somehow but not directly, also first collider that hits somtimes has size 0 :( // decalCopy.transform.localScale = scale + new Vector3(0.0f, 0.0f, 0.02f); - spawnDecal(contact.point, this.transform.rotation, decalScale, DecalRotationAxis.FORWARD); + spawnDecal( + contact.point, + this.transform.rotation, + decalScale, + DecalRotationAxis.FORWARD + ); break; } } @@ -104,7 +115,6 @@ protected override void BreakForDecalType(Collision collision) { spawnDecal(transform.position, this.transform.rotation, decalScale * 2); } } else { - if (collision != null) { foreach (ContactPoint contact in collision.contacts) { Debug.Log("Decal pre for " + this.stencilWriteValue); @@ -124,29 +134,53 @@ protected override void BreakForDecalType(Collision collision) { var forwardNormalized = this.transform.forward.normalized; var proyOnForward = Vector3.Dot(forwardNormalized, planeToCollision); var proyectedPoint = contact.point - forwardNormalized * proyOnForward; - spawnDecal(proyectedPoint, this.transform.rotation, decalScale, DecalRotationAxis.FORWARD); + spawnDecal( + proyectedPoint, + this.transform.rotation, + decalScale, + DecalRotationAxis.FORWARD + ); break; } } } else { // Debug.Log("Spawn decal break " + this.transform.rotation + " final " + this.transform.rotation * Quaternion.Euler(-90, 0, 0)); // spawnDecal(this.transform.position, this.transform.rotation * Quaternion.Euler(-90, 0, 0), decalScale * 2); - spawnDecal(this.transform.position + this.transform.rotation * transparentDecalSpawnOffset, this.transform.rotation, this.transform.localScale); + spawnDecal( + this.transform.position + this.transform.rotation * transparentDecalSpawnOffset, + this.transform.rotation, + this.transform.localScale + ); } } } - public void SpawnDecal(Vector3 position, bool worldSpace = false, Vector3? scale = null, DecalRotationAxis randomRotationAxis = DecalRotationAxis.NONE) { - + public void SpawnDecal( + Vector3 position, + bool worldSpace = false, + Vector3? scale = null, + DecalRotationAxis randomRotationAxis = DecalRotationAxis.NONE + ) { // var pos = this.transform.InverseTransformPoint(worldPos); var pos = position; if (worldSpace) { - pos = this.transform.InverseTransformPoint(position); + pos = this.transform.InverseTransformPoint(position); } - spawnDecal(pos, this.transform.rotation, scale.GetValueOrDefault(this.decalScale), randomRotationAxis); + spawnDecal( + pos, + this.transform.rotation, + scale.GetValueOrDefault(this.decalScale), + randomRotationAxis + ); } - private void spawnDecal(Vector3 position, Quaternion rotation, Vector3 scale, DecalRotationAxis randomRotationAxis = DecalRotationAxis.NONE, int index = -1) { + private void spawnDecal( + Vector3 position, + Quaternion rotation, + Vector3 scale, + DecalRotationAxis randomRotationAxis = DecalRotationAxis.NONE, + int index = -1 + ) { var minimumScale = this.transform.localScale; var decalScale = scale; if (minimumScale.x < scale.x || minimumScale.y < scale.y) { @@ -166,7 +200,12 @@ private void spawnDecal(Vector3 position, Quaternion rotation, Vector3 scale, De randomRotation = Quaternion.AngleAxis(randomAngle, Vector3.right); } - var decalCopy = Object.Instantiate(decals[selectIndex], position, rotation * randomRotation, this.transform.parent); + var decalCopy = Object.Instantiate( + decals[selectIndex], + position, + rotation * randomRotation, + this.transform.parent + ); decalCopy.transform.localScale = decalScale; var mr = decalCopy.GetComponent(); diff --git a/unity/Assets/Scripts/DecalSpawner.cs b/unity/Assets/Scripts/DecalSpawner.cs index 8021c8397d..4688455ea6 100644 --- a/unity/Assets/Scripts/DecalSpawner.cs +++ b/unity/Assets/Scripts/DecalSpawner.cs @@ -2,9 +2,11 @@ using System.Collections.Generic; using UnityEngine; - public class DirtCoordinateBounds { - public float minX, maxX, minZ, maxZ; + public float minX, + maxX, + minZ, + maxZ; } public class DirtSpawnPosition { @@ -12,33 +14,35 @@ public class DirtSpawnPosition { public float z; } -public class DecalSpawner : MonoBehaviour -{ - // If true Guarantees that other spawn planes under the same parent will have the same stencil value +public class DecalSpawner : MonoBehaviour { + // If true Guarantees that other spawn planes under the same parent will have the same stencil value [SerializeField] private bool sameStencilAsSiblings = false; + [SerializeField] private int stencilWriteValue = 1; + [SerializeField] private GameObject[] decals = null; + [SerializeField] private float nextDecalWaitTimeSeconds = 1; + [SerializeField] private Vector3 decalScale = new Vector3(0.3f, 0.3f, 0.2f); + [SerializeField] private bool transparent = false; [SerializeField] - protected bool stencilSet = false; + // In local space private Vector3 transparentDecalSpawnOffset = new Vector3(0, 0, 0); private float prevTime; private static int currentStencilId = 0; - - void OnEnable() { //breakType = BreakType.Decal; prevTime = Time.time; @@ -49,12 +53,16 @@ void OnEnable() { if (!sameStencilAsSiblings) { setStencilWriteValue(mr); } else { - var otherPlanes = this.transform.parent.gameObject.GetComponentsInChildren(); + var otherPlanes = + this.transform.parent.gameObject.GetComponentsInChildren(); // var otherPlanes = this.gameObject.GetComponentsInParent(); // Debug.Log("other planes id " + this.stencilWriteValue + " len " + otherPlanes.Length); foreach (var spawnPlane in otherPlanes) { - - if (spawnPlane.isActiveAndEnabled && spawnPlane.stencilSet && spawnPlane.sameStencilAsSiblings) { + if ( + spawnPlane.isActiveAndEnabled + && spawnPlane.stencilSet + && spawnPlane.sameStencilAsSiblings + ) { this.stencilWriteValue = spawnPlane.stencilWriteValue; this.stencilSet = true; mr.material.SetInt("_StencilRef", this.stencilWriteValue); @@ -73,17 +81,15 @@ void OnEnable() { } } - public void Update() { - - } - + public void Update() { } public DirtCoordinateBounds GetDirtCoordinateBounds() { - DirtCoordinateBounds coords = new DirtCoordinateBounds(); SimObjPhysics myParentSimObj = this.transform.GetComponentInParent(); - Vector3[] spawnPointsArray = myParentSimObj.FindMySpawnPointsFromTriggerBoxInLocalSpace().ToArray(); + Vector3[] spawnPointsArray = myParentSimObj + .FindMySpawnPointsFromTriggerBoxInLocalSpace() + .ToArray(); coords.minX = spawnPointsArray[0].x; coords.maxX = spawnPointsArray[0].x; @@ -108,19 +114,22 @@ public DirtCoordinateBounds GetDirtCoordinateBounds() { } } - #if UNITY_EDITOR +#if UNITY_EDITOR Debug.Log($"minX: {coords.minX}"); Debug.Log($"minZ: {coords.minZ}"); Debug.Log($"maxX: {coords.maxX}"); Debug.Log($"maxZ: {coords.maxZ}"); - #endif +#endif return coords; } - public void SpawnDirt(int howMany = 1, int randomSeed = 0, DirtSpawnPosition[] spawnPointsArray = null) { - - if(spawnPointsArray == null) { + public void SpawnDirt( + int howMany = 1, + int randomSeed = 0, + DirtSpawnPosition[] spawnPointsArray = null + ) { + if (spawnPointsArray == null) { DirtCoordinateBounds c = GetDirtCoordinateBounds(); Random.InitState(randomSeed); @@ -131,16 +140,23 @@ public void SpawnDirt(int howMany = 1, int randomSeed = 0, DirtSpawnPosition[] s var randomZ = Random.Range(c.minZ, c.maxZ); //generate random scale cause dirt - var randomScale = new Vector3(Random.Range(0.1f, 0.4f), Random.Range(0.1f, 0.4f), 0.2f); + var randomScale = new Vector3( + Random.Range(0.1f, 0.4f), + Random.Range(0.1f, 0.4f), + 0.2f + ); //this decalPosition is in local space relative to the trigger box - Vector3 decalPosition = new Vector3(randomX, 0.0f , randomZ); + Vector3 decalPosition = new Vector3(randomX, 0.0f, randomZ); //spawnDecal expects coordinates in world space, so TransformPoint - spawnDecal(this.transform.parent.transform.TransformPoint(decalPosition) + this.transform.rotation * transparentDecalSpawnOffset - , this.transform.rotation, - randomScale, DecalRotationAxis.FORWARD); + spawnDecal( + this.transform.parent.transform.TransformPoint(decalPosition) + + this.transform.rotation * transparentDecalSpawnOffset, + this.transform.rotation, + randomScale, + DecalRotationAxis.FORWARD + ); } } - //instead pass in exact coordinates you want to spawn decals //note this ignores the howMany variable, instead will spawn //decals based on exactly what spawn points are passed in via spawnPointsArray @@ -148,10 +164,23 @@ public void SpawnDirt(int howMany = 1, int randomSeed = 0, DirtSpawnPosition[] s Random.InitState(randomSeed); for (int i = 0; i < spawnPointsArray.Length; i++) { - var randomScale = new Vector3(Random.Range(0.1f, 0.4f), Random.Range(0.1f, 0.4f), 0.2f); - Vector3 decalPosition = new Vector3(spawnPointsArray[i].x, 0.0f, spawnPointsArray[i].z); - spawnDecal(this.transform.parent.transform.TransformPoint(decalPosition) + this.transform.rotation * transparentDecalSpawnOffset - , this.transform.rotation, randomScale, DecalRotationAxis.FORWARD); + var randomScale = new Vector3( + Random.Range(0.1f, 0.4f), + Random.Range(0.1f, 0.4f), + 0.2f + ); + Vector3 decalPosition = new Vector3( + spawnPointsArray[i].x, + 0.0f, + spawnPointsArray[i].z + ); + spawnDecal( + this.transform.parent.transform.TransformPoint(decalPosition) + + this.transform.rotation * transparentDecalSpawnOffset, + this.transform.rotation, + randomScale, + DecalRotationAxis.FORWARD + ); } } } @@ -168,16 +197,31 @@ private void setStencilWriteValue(MeshRenderer mr) { this.stencilSet = true; } - public void SpawnDecal(Vector3 position, bool worldSpace = false, Vector3? scale = null, DecalRotationAxis randomRotationAxis = DecalRotationAxis.NONE) { - + public void SpawnDecal( + Vector3 position, + bool worldSpace = false, + Vector3? scale = null, + DecalRotationAxis randomRotationAxis = DecalRotationAxis.NONE + ) { var pos = position; if (worldSpace) { - pos = this.transform.InverseTransformPoint(position); + pos = this.transform.InverseTransformPoint(position); } - spawnDecal(pos, this.transform.rotation, scale.GetValueOrDefault(this.decalScale), randomRotationAxis); + spawnDecal( + pos, + this.transform.rotation, + scale.GetValueOrDefault(this.decalScale), + randomRotationAxis + ); } - private void spawnDecal(Vector3 position, Quaternion rotation, Vector3 scale, DecalRotationAxis randomRotationAxis = DecalRotationAxis.NONE, int index = -1) { + private void spawnDecal( + Vector3 position, + Quaternion rotation, + Vector3 scale, + DecalRotationAxis randomRotationAxis = DecalRotationAxis.NONE, + int index = -1 + ) { var minimumScale = this.transform.localScale; var decalScale = scale; if (minimumScale.x < scale.x || minimumScale.y < scale.y) { @@ -197,7 +241,12 @@ private void spawnDecal(Vector3 position, Quaternion rotation, Vector3 scale, De randomRotation = Quaternion.AngleAxis(randomAngle, Vector3.right); } - var decalCopy = Object.Instantiate(decals[selectIndex], position, rotation * randomRotation, this.transform.parent); + var decalCopy = Object.Instantiate( + decals[selectIndex], + position, + rotation * randomRotation, + this.transform.parent + ); decalCopy.transform.localScale = decalScale; var mr = decalCopy.GetComponent(); diff --git a/unity/Assets/Scripts/DeferredDecal.cs b/unity/Assets/Scripts/DeferredDecal.cs index 7c5cc1a658..901600a3b7 100644 --- a/unity/Assets/Scripts/DeferredDecal.cs +++ b/unity/Assets/Scripts/DeferredDecal.cs @@ -1,8 +1,8 @@ using System.Collections; using System.Collections.Generic; +using System.Linq; using UnityEngine; using UnityEngine.Rendering; -using System.Linq; public enum DecalType { DIFFUSE_ONLY, @@ -13,13 +13,15 @@ public enum DecalType { } public class DeferredDecal : MonoBehaviour { - [SerializeField] public Material material; + [SerializeField] private Mesh cubeMesh = null; + [SerializeField] private DecalType type = DecalType.DIFFUSE_ONLY; + [SerializeField] private CameraEvent atRenderEvent = CameraEvent.BeforeLighting; private CommandBuffer buffer; @@ -35,12 +37,13 @@ void Start() { // This doesn't work as `agents` only has SecondaryCamera for stretch, bug to rework agentmanager // this.cameras = manager.agents.Select(a => a.gameObject.GetComponentInChildren()).ToList();//.Concat(manager.thirdPartyCameras).ToList(); // Debug.Log($"agents { manager.agents.Count} names { string.Join(", ", manager.agents.Select(a => a.gameObject.name))} cams {string.Join(", ", cameras.Select(a => a.gameObject.name))}" ); - - this.cameras = new List() {manager.primaryAgent.m_Camera}.Concat(manager.thirdPartyCameras).ToList(); + + this.cameras = new List() { manager.primaryAgent.m_Camera } + .Concat(manager.thirdPartyCameras) + .ToList(); foreach (var cam in cameras) { cam.AddCommandBuffer(atRenderEvent, buffer); } - } public void OnWillRenderObject() { @@ -53,43 +56,66 @@ public void OnWillRenderObject() { if (type == DecalType.EMISSIVE_SPECULAR) { // Diffuse + specular decals - RenderTargetIdentifier[] multipleRenderTargets = { BuiltinRenderTextureType.GBuffer0, BuiltinRenderTextureType.GBuffer1, BuiltinRenderTextureType.GBuffer3 }; + RenderTargetIdentifier[] multipleRenderTargets = + { + BuiltinRenderTextureType.GBuffer0, + BuiltinRenderTextureType.GBuffer1, + BuiltinRenderTextureType.GBuffer3 + }; buffer.SetRenderTarget(multipleRenderTargets, BuiltinRenderTextureType.CameraTarget); } else if (type == DecalType.NORMAL_DIFFUSE) { // For decals that have normals - RenderTargetIdentifier[] multipleRenderTargets = { BuiltinRenderTextureType.GBuffer0, BuiltinRenderTextureType.GBuffer2 }; + RenderTargetIdentifier[] multipleRenderTargets = + { + BuiltinRenderTextureType.GBuffer0, + BuiltinRenderTextureType.GBuffer2 + }; buffer.SetRenderTarget(multipleRenderTargets, BuiltinRenderTextureType.CameraTarget); } else if (type == DecalType.EMISSIVE_SPECULAR) { // All render targets - RenderTargetIdentifier[] multipleRenderTargets = { BuiltinRenderTextureType.GBuffer0, BuiltinRenderTextureType.GBuffer1, BuiltinRenderTextureType.GBuffer2, BuiltinRenderTextureType.GBuffer3 }; + RenderTargetIdentifier[] multipleRenderTargets = + { + BuiltinRenderTextureType.GBuffer0, + BuiltinRenderTextureType.GBuffer1, + BuiltinRenderTextureType.GBuffer2, + BuiltinRenderTextureType.GBuffer3 + }; buffer.SetRenderTarget(multipleRenderTargets, BuiltinRenderTextureType.CameraTarget); } else if (type == DecalType.DIFFUSE_ONLY) { // Diffuse only, no MTR - buffer.SetRenderTarget(BuiltinRenderTextureType.GBuffer0, BuiltinRenderTextureType.CameraTarget); + buffer.SetRenderTarget( + BuiltinRenderTextureType.GBuffer0, + BuiltinRenderTextureType.CameraTarget + ); } else if (type == DecalType.FORWARD) { - buffer.SetRenderTarget(BuiltinRenderTextureType.CurrentActive, BuiltinRenderTextureType.CameraTarget); + buffer.SetRenderTarget( + BuiltinRenderTextureType.CurrentActive, + BuiltinRenderTextureType.CameraTarget + ); } buffer.DrawMesh(this.cubeMesh, this.transform.localToWorldMatrix, this.material); - - } - private void OnDisable() - { + private void OnDisable() { foreach (var cam in cameras) { - cam.RemoveCommandBuffer(atRenderEvent, buffer); } } - void OnDrawGizmos() { + void OnDrawGizmos() { Gizmos.color = new Color(1, 0.92f, 0.016f, 0.2f); - Gizmos.DrawMesh(this.cubeMesh, this.transform.position, this.transform.rotation, this.transform.localScale); + Gizmos.DrawMesh( + this.cubeMesh, + this.transform.position, + this.transform.rotation, + this.transform.localScale + ); Gizmos.color = new Color(1, 0.92f, 0.016f, 0.6f); - Vector3[] basePoints = { + Vector3[] basePoints = + { new Vector3(-0.5f, -0.5f, -0.5f), new Vector3(-0.5f, +0.5f, +0.5f), new Vector3(+0.5f, +0.5f, -0.5f), @@ -109,4 +135,4 @@ void OnDrawGizmos() { } } } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/DirtAndWrite.cs b/unity/Assets/Scripts/DirtAndWrite.cs index c5c0d94c4c..dd9476eaaa 100644 --- a/unity/Assets/Scripts/DirtAndWrite.cs +++ b/unity/Assets/Scripts/DirtAndWrite.cs @@ -1,27 +1,19 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using UnityEngine; -using UnityStandardAssets.Characters.FirstPerson; using UnityEngine.SceneManagement; -using System.Linq; - +using UnityStandardAssets.Characters.FirstPerson; #if UNITY_EDITOR using UnityEditor; using UnityEditor.SceneManagement; #endif -public class DirtAndWrite : MonoBehaviour -{ +public class DirtAndWrite : MonoBehaviour { // Start is called before the first frame update - void Start() - { - - } + void Start() { } // Update is called once per frame - void Update() - { - - } + void Update() { } } diff --git a/unity/Assets/Scripts/Dirty.cs b/unity/Assets/Scripts/Dirty.cs index 9900602136..92db8bf9d8 100644 --- a/unity/Assets/Scripts/Dirty.cs +++ b/unity/Assets/Scripts/Dirty.cs @@ -3,24 +3,30 @@ using UnityEngine; public class Dirty : MonoBehaviour { - [SerializeField] public SwapObjList[] MaterialSwapObjects; // put objects that need amterial swaps here, use OnMaterials for Dirty, OffMaterials for Clean [SerializeField] public GameObject[] ObjectsToEnableIfClean; // for things like bed sheets, decals etc. that need to toggle on and off the entire game object + [SerializeField] public GameObject[] ObjectsToEnableIfDirty; + [SerializeField] protected bool isDirty = false; public bool IsDirty() { return isDirty; } + // Start is called before the first frame update void Start() { #if UNITY_EDITOR - if (!gameObject.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeDirty)) { + if ( + !gameObject + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeDirty) + ) { Debug.LogError(gameObject.name + " is missing the CanBeDirty secondary property!"); } #endif @@ -40,7 +46,8 @@ public void ToggleCleanOrDirty() { // swap all material swap objects to OnMaterials if (MaterialSwapObjects.Length > 0) { for (int i = 0; i < MaterialSwapObjects.Length; i++) { - MaterialSwapObjects[i].MyObject.GetComponent().materials = MaterialSwapObjects[i].OnMaterials; + MaterialSwapObjects[i].MyObject.GetComponent().materials = + MaterialSwapObjects[i].OnMaterials; } } @@ -60,13 +67,13 @@ public void ToggleCleanOrDirty() { isDirty = true; } - // if dirt, make clean else { // swap all material swap object to OffMaterials if (MaterialSwapObjects.Length > 0) { for (int i = 0; i < MaterialSwapObjects.Length; i++) { - MaterialSwapObjects[i].MyObject.GetComponent().materials = MaterialSwapObjects[i].OffMaterials; + MaterialSwapObjects[i].MyObject.GetComponent().materials = + MaterialSwapObjects[i].OffMaterials; } } diff --git a/unity/Assets/Scripts/DiscreteHidenSeekAgentController.cs b/unity/Assets/Scripts/DiscreteHidenSeekAgentController.cs index d4e89d9906..354b1045a5 100644 --- a/unity/Assets/Scripts/DiscreteHidenSeekAgentController.cs +++ b/unity/Assets/Scripts/DiscreteHidenSeekAgentController.cs @@ -10,8 +10,10 @@ public class ObjectSpanwMetadata { public string objectType; public int objectVariation; } + public class DiscreteHidenSeekgentController : MonoBehaviour { - [SerializeField] private float HandMoveMagnitude = 0.1f; + [SerializeField] + private float HandMoveMagnitude = 0.1f; public PhysicsRemoteFPSAgentController PhysicsController = null; private GameObject InputMode_Text = null; private ObjectHighlightController highlightController = null; @@ -21,9 +23,12 @@ public class DiscreteHidenSeekgentController : MonoBehaviour { private bool hidingPhase = false; public string onlyPickableObjectId = null; public bool disableCollistionWithPickupObject = false; + void Start() { var Debug_Canvas = GameObject.Find("DebugCanvasPhysics"); - AgentManager agentManager = GameObject.Find("PhysicsSceneManager").GetComponentInChildren(); + AgentManager agentManager = GameObject + .Find("PhysicsSceneManager") + .GetComponentInChildren(); agentManager.SetUpPhysicsController(); PhysicsController = (PhysicsRemoteFPSAgentController)agentManager.PrimaryAgent; @@ -31,7 +36,15 @@ void Start() { Cursor.lockState = CursorLockMode.None; Debug_Canvas.GetComponent().enabled = true; - highlightController = new ObjectHighlightController(PhysicsController, PhysicsController.maxVisibleDistance, true, false, 0, 0, true); + highlightController = new ObjectHighlightController( + PhysicsController, + PhysicsController.maxVisibleDistance, + true, + false, + 0, + 0, + true + ); highlightController.SetDisplayTargetText(false); // SpawnObjectToHide("{\"objectType\": \"Plunger\", \"objectVariation\": 1}"); @@ -62,7 +75,6 @@ public void OnDisable() { } public void SpawnObjectToHide(string objectMeta) { - var objectData = new ObjectSpanwMetadata(); Debug.Log(objectMeta); JsonUtility.FromJsonOverwrite(objectMeta, objectData); @@ -154,7 +166,6 @@ void Update() { action.action = "MoveAhead"; action.moveMagnitude = WalkMagnitude; PhysicsController.ProcessControlCommand(action); - } if (Input.GetKeyDown(KeyCode.S)) { @@ -162,7 +173,6 @@ void Update() { action.action = "MoveBack"; action.moveMagnitude = WalkMagnitude; PhysicsController.ProcessControlCommand(action); - } if (Input.GetKeyDown(KeyCode.A)) { @@ -170,7 +180,6 @@ void Update() { action.action = "MoveLeft"; action.moveMagnitude = WalkMagnitude; PhysicsController.ProcessControlCommand(action); - } if (Input.GetKeyDown(KeyCode.D)) { @@ -178,10 +187,9 @@ void Update() { action.action = "MoveRight"; action.moveMagnitude = WalkMagnitude; PhysicsController.ProcessControlCommand(action); - } - if (Input.GetKeyDown(KeyCode.LeftArrow))//|| Input.GetKeyDown(KeyCode.J)) + if (Input.GetKeyDown(KeyCode.LeftArrow)) //|| Input.GetKeyDown(KeyCode.J)) { ServerAction action = new ServerAction(); // action.action = "RotateLeft"; @@ -190,7 +198,7 @@ void Update() { PhysicsController.ProcessControlCommand(action); } - if (Input.GetKeyDown(KeyCode.RightArrow))//|| Input.GetKeyDown(KeyCode.L)) + if (Input.GetKeyDown(KeyCode.RightArrow)) //|| Input.GetKeyDown(KeyCode.L)) { ServerAction action = new ServerAction(); // action.action = "RotateRight"; @@ -200,8 +208,6 @@ void Update() { } } - - if (this.PhysicsController.WhatAmIHolding() != null && handMode) { var actionName = "MoveHandForce"; var localPos = new Vector3(0, 0, 0); @@ -239,7 +245,9 @@ void Update() { } } else if (handMode) { if (Input.GetKeyDown(KeyCode.Space)) { - var withinReach = PhysicsController.FindObjectInVisibleSimObjPhysics(onlyPickableObjectId) != null; + var withinReach = + PhysicsController.FindObjectInVisibleSimObjPhysics(onlyPickableObjectId) + != null; if (withinReach) { ServerAction action = new ServerAction(); action.objectId = onlyPickableObjectId; @@ -248,7 +256,13 @@ void Update() { } } } - if ((Input.GetKeyDown(KeyCode.LeftControl) || Input.GetKeyDown(KeyCode.C) || Input.GetKeyDown(KeyCode.RightControl)) && PhysicsController.ReadyForCommand) { + if ( + ( + Input.GetKeyDown(KeyCode.LeftControl) + || Input.GetKeyDown(KeyCode.C) + || Input.GetKeyDown(KeyCode.RightControl) + ) && PhysicsController.ReadyForCommand + ) { ServerAction action = new ServerAction(); if (this.PhysicsController.isStanding()) { action.action = "Crouch"; @@ -257,13 +271,10 @@ void Update() { action.action = "Stand"; PhysicsController.ProcessControlCommand(action); } - - } if (PhysicsController.WhatAmIHolding() != null) { if (Input.GetKeyDown(KeyCode.Space) && !hidingPhase && !handMode) { - SetObjectVisible(!visibleObject); } } @@ -285,5 +296,4 @@ private static void SetLayerRecursively(GameObject obj, int newLayer) { } } } - -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/DiscretePointClickAgentController.cs b/unity/Assets/Scripts/DiscretePointClickAgentController.cs index c1566f901c..f6f0dfb8d9 100644 --- a/unity/Assets/Scripts/DiscretePointClickAgentController.cs +++ b/unity/Assets/Scripts/DiscretePointClickAgentController.cs @@ -5,15 +5,19 @@ namespace UnityStandardAssets.Characters.FirstPerson { public class DiscretePointClickAgentController : MonoBehaviour { - [SerializeField] private float HandMoveMagnitude = 0.1f; + [SerializeField] + private float HandMoveMagnitude = 0.1f; public PhysicsRemoteFPSAgentController PhysicsController = null; private GameObject InputMode_Text = null; private ObjectHighlightController highlightController = null; private GameObject throwForceBar = null; private bool handMode = false; + void Start() { var Debug_Canvas = GameObject.Find("DebugCanvasPhysics"); - AgentManager agentManager = GameObject.Find("PhysicsSceneManager").GetComponentInChildren(); + AgentManager agentManager = GameObject + .Find("PhysicsSceneManager") + .GetComponentInChildren(); agentManager.SetUpPhysicsController(); PhysicsController = agentManager.PrimaryAgent as PhysicsRemoteFPSAgentController; @@ -21,7 +25,12 @@ void Start() { Cursor.lockState = CursorLockMode.None; Debug_Canvas.GetComponent().enabled = true; - highlightController = new ObjectHighlightController(PhysicsController, PhysicsController.maxVisibleDistance, true, false); + highlightController = new ObjectHighlightController( + PhysicsController, + PhysicsController.maxVisibleDistance, + true, + false + ); } public void OnEnable() { @@ -33,7 +42,7 @@ public void OnEnable() { if (throwForceBar) { throwForceBar.SetActive(false); } - + // InputFieldObj = GameObject.Find("DebugCanvasPhysics/InputField"); // TODO: move debug input field script from, Input Field and disable here } @@ -89,12 +98,12 @@ void Update() { executeAction("LookDown"); } - if (Input.GetKeyDown(KeyCode.LeftArrow))//|| Input.GetKeyDown(KeyCode.J)) + if (Input.GetKeyDown(KeyCode.LeftArrow)) //|| Input.GetKeyDown(KeyCode.J)) { executeAction("RotateLeft"); } - if (Input.GetKeyDown(KeyCode.RightArrow))//|| Input.GetKeyDown(KeyCode.L)) + if (Input.GetKeyDown(KeyCode.RightArrow)) //|| Input.GetKeyDown(KeyCode.L)) { executeAction("RotateRight"); } diff --git a/unity/Assets/Scripts/Door.cs b/unity/Assets/Scripts/Door.cs index 4e266dac72..e7a7cdae46 100644 --- a/unity/Assets/Scripts/Door.cs +++ b/unity/Assets/Scripts/Door.cs @@ -1,10 +1,9 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; [ExecuteInEditMode] public class Door : MonoBehaviour { - public SimObj ParentObj; public Vector3 OpenRotation; public Vector3 ClosedRotation; @@ -21,7 +20,8 @@ void OnEnable() { Animator a = ParentObj.gameObject.GetComponent(); if (a == null) { a = ParentObj.gameObject.AddComponent(); - a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; + a.runtimeAnimatorController = + Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; } } } diff --git a/unity/Assets/Scripts/DraggablePoint.cs b/unity/Assets/Scripts/DraggablePoint.cs index 1ef4824374..43861b29ec 100644 --- a/unity/Assets/Scripts/DraggablePoint.cs +++ b/unity/Assets/Scripts/DraggablePoint.cs @@ -4,36 +4,37 @@ using UnityEditor; #endif -public class DraggablePoint : PropertyAttribute {} - +public class DraggablePoint : PropertyAttribute { } #if UNITY_EDITOR // [CustomEditor(typeof(MonoBehaviour), true)] public class DraggablePointDrawer : Editor { + readonly GUIStyle style = new GUIStyle(); - readonly GUIStyle style = new GUIStyle(); - - void OnEnable(){ - style.fontStyle = FontStyle.Bold; - style.normal.textColor = Color.white; - } + void OnEnable() { + style.fontStyle = FontStyle.Bold; + style.normal.textColor = Color.white; + } - public void OnSceneGUI () { - var property = serializedObject.GetIterator (); - while (property.Next (true)) { - if (property.propertyType == SerializedPropertyType.Vector3) { - var field = serializedObject.targetObject.GetType ().GetField (property.name); - if (field == null) { - continue; + public void OnSceneGUI() { + var property = serializedObject.GetIterator(); + while (property.Next(true)) { + if (property.propertyType == SerializedPropertyType.Vector3) { + var field = serializedObject.targetObject.GetType().GetField(property.name); + if (field == null) { + continue; + } + var draggablePoints = field.GetCustomAttributes(typeof(DraggablePoint), false); + if (draggablePoints.Length > 0) { + Handles.Label(property.vector3Value, property.name); + property.vector3Value = Handles.PositionHandle( + property.vector3Value, + Quaternion.identity + ); + serializedObject.ApplyModifiedProperties(); + } + } } - var draggablePoints = field.GetCustomAttributes (typeof(DraggablePoint), false); - if (draggablePoints.Length > 0) { - Handles.Label(property.vector3Value, property.name); - property.vector3Value = Handles.PositionHandle (property.vector3Value, Quaternion.identity); - serializedObject.ApplyModifiedProperties (); - } - } } - } } -#endif \ No newline at end of file +#endif diff --git a/unity/Assets/Scripts/DroneBasket.cs b/unity/Assets/Scripts/DroneBasket.cs index 33d4f7b988..1353c6fdf3 100644 --- a/unity/Assets/Scripts/DroneBasket.cs +++ b/unity/Assets/Scripts/DroneBasket.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; - #if UNITY_EDITOR using UnityEditor; #endif @@ -11,7 +10,8 @@ public class DroneBasket : MonoBehaviour { public GameObject myParent = null; private PhysicsSceneManager psManager; - [SerializeField] protected List CurrentlyContains = new List(); + [SerializeField] + protected List CurrentlyContains = new List(); // Use this for initialization void Start() { @@ -19,15 +19,12 @@ void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } public void OnTriggerStay(Collider other) { // from the collider, see if the thing hit is a sim object physics // don't detect other trigger colliders to prevent nested objects from containing each other if (other.GetComponentInParent() && !other.isTrigger) { - SimObjPhysics sop = other.GetComponentInParent(); // don't add any parent objects in case this is a child sim object @@ -36,7 +33,7 @@ public void OnTriggerStay(Collider other) { } // check each "other" object, see if it is currently in the CurrentlyContains list, and make sure it is NOT one of this object's doors/drawer - if (!CurrentlyContains.Contains(sop))//&& !MyObjects.Contains(sop.transform.gameObject)) + if (!CurrentlyContains.Contains(sop)) //&& !MyObjects.Contains(sop.transform.gameObject)) { CurrentlyContains.Add(sop); @@ -50,7 +47,6 @@ public void OnTriggerStay(Collider other) { psManager.RemoveFromRBSInScene(rb); Destroy(rb); - } sop.enabled = false; @@ -59,5 +55,4 @@ public void OnTriggerStay(Collider other) { } } } - } diff --git a/unity/Assets/Scripts/DroneFPSAgentController.cs b/unity/Assets/Scripts/DroneFPSAgentController.cs index 60d6fa8b73..6a916cce30 100644 --- a/unity/Assets/Scripts/DroneFPSAgentController.cs +++ b/unity/Assets/Scripts/DroneFPSAgentController.cs @@ -1,9 +1,9 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; -using UnityEngine; -using System; using System.Linq; using RandomExtensions; +using UnityEngine; using UnityEngine.AI; using UnityEngine.Rendering.PostProcessing; @@ -13,18 +13,27 @@ public class DroneFPSAgentController : BaseFPSAgentController { public GameObject basket; public GameObject basketTrigger; public List caught_object = new List(); - private bool hasFixedUpdateHappened = true;// track if the fixed physics update has happened + private bool hasFixedUpdateHappened = true; // track if the fixed physics update has happened protected Vector3 thrust; public float dronePositionRandomNoiseSigma = 0f; + // count of fixed updates for use in droneCurrentTime public float fixupdateCnt = 0f; - // Update is called once per frame - public DroneFPSAgentController(BaseAgentComponent baseAgentComponent, AgentManager agentManager) : base(baseAgentComponent, agentManager) { } + // Update is called once per frame + public DroneFPSAgentController( + BaseAgentComponent baseAgentComponent, + AgentManager agentManager + ) + : base(baseAgentComponent, agentManager) { } protected override void resumePhysics() { - if (Time.timeScale == 0 && !Physics.autoSimulation && physicsSceneManager.physicsSimulationPaused) { + if ( + Time.timeScale == 0 + && !Physics.autoSimulation + && physicsSceneManager.physicsSimulationPaused + ) { Time.timeScale = this.autoResetTimeScale; Physics.autoSimulation = true; physicsSceneManager.physicsSimulationPaused = false; @@ -62,7 +71,6 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { return ActionFinished.Success; } - public void MoveLeft(ServerAction action) { moveCharacter(action, 270); } @@ -130,9 +138,12 @@ public override void FixedUpdate() { if (thrust.magnitude > 0.0001 && Time.timeScale != 0) { if (dronePositionRandomNoiseSigma > 0) { - var noiseX = (float)systemRandom.NextGaussian(0.0f, dronePositionRandomNoiseSigma / 3.0f); - var noiseY = (float)systemRandom.NextGaussian(0.0f, dronePositionRandomNoiseSigma / 3.0f); - var noiseZ = (float)systemRandom.NextGaussian(0.0f, dronePositionRandomNoiseSigma / 3.0f); + var noiseX = (float) + systemRandom.NextGaussian(0.0f, dronePositionRandomNoiseSigma / 3.0f); + var noiseY = (float) + systemRandom.NextGaussian(0.0f, dronePositionRandomNoiseSigma / 3.0f); + var noiseZ = (float) + systemRandom.NextGaussian(0.0f, dronePositionRandomNoiseSigma / 3.0f); Vector3 noise = new Vector3(noiseX, noiseY, noiseZ); m_CharacterController.Move((thrust * Time.fixedDeltaTime) + noise); } else { @@ -143,11 +154,14 @@ public override void FixedUpdate() { if (this.agentState == AgentState.PendingFixedUpdate) { this.agentState = AgentState.ActionComplete; } - } // generates object metadata based on sim object's properties - public override ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics simObj, bool isVisible, bool isInteractable) { + public override ObjectMetadata ObjectMetadataFromSimObjPhysics( + SimObjPhysics simObj, + bool isVisible, + bool isInteractable + ) { DroneObjectMetadata objMeta = new DroneObjectMetadata(); objMeta.isCaught = this.isObjectCaught(simObj); objMeta.numSimObjHits = simObj.numSimObjHit; @@ -231,8 +245,8 @@ public override ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics sim // object temperature to string objMeta.temperature = simObj.CurrentObjTemp.ToString(); - objMeta.pickupable = simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup;// can this object be picked up? - objMeta.isPickedUp = simObj.isPickedUp;// returns true for if this object is currently being held by the agent + objMeta.pickupable = simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup; // can this object be picked up? + objMeta.isPickedUp = simObj.isPickedUp; // returns true for if this object is currently being held by the agent objMeta.moveable = simObj.PrimaryProperty == SimObjPrimaryProperty.Moveable; @@ -246,7 +260,7 @@ public override ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics sim //note using forceAction=True will ignore the isInteractable requirement objMeta.isInteractable = isInteractable; - objMeta.isMoving = simObj.inMotion;// keep track of if this object is actively moving + objMeta.isMoving = simObj.inMotion; // keep track of if this object is actively moving objMeta.objectOrientedBoundingBox = simObj.ObjectOrientedBoundingBox; @@ -265,7 +279,7 @@ public override MetadataWrapper generateMetadataWrapper() { // TODO: clean this up with reflection. // it works, but will not update when something changes to AgentMetadata - // metadata.agent = new + // metadata.agent = new AgentMetadata baseAgent = metadata.agent; DroneAgentMetadata droneMeta = new DroneAgentMetadata(); @@ -299,7 +313,6 @@ public Vector3 GetFlyingOrientation(float moveMagnitude, int targetOrientation) if (actionOrientation.ContainsKey(delta)) { m = actionOrientation[delta]; - } else { actionOrientation = new Dictionary(); actionOrientation.Add(0, transform.forward); @@ -326,7 +339,9 @@ public Vector3[] SeekTwoPos(Vector3[] shuffledCurrentlyReachable) { // if(Mathf.Abs(p.x-p2.x) < 0.5*Mathf.Abs(p.z-p2.z)){ // if(Mathf.Abs(p.x-p2.x) == 0){ if (Mathf.Abs(p.x - p2.x) <= 0.5) { - float y = y_candidates.OrderBy(x => systemRandom.Next()).ToArray()[0]; + float y = y_candidates.OrderBy(x => systemRandom.Next()).ToArray()[ + 0 + ]; output[0] = new Vector3(p.x, 1.0f, p.z); output[1] = new Vector3(p2.x, y, p2.z); return output; @@ -345,21 +360,39 @@ public void ChangeAutoResetTimeScale(float timeScale) { } public void Teleport( - Vector3? position = null, Vector3? rotation = null, float? horizon = null, bool forceAction = false + Vector3? position = null, + Vector3? rotation = null, + float? horizon = null, + bool forceAction = false ) { - base.teleport(position: position, rotation: rotation, horizon: horizon, forceAction: forceAction); + base.teleport( + position: position, + rotation: rotation, + horizon: horizon, + forceAction: forceAction + ); actionFinished(success: true); } public void TeleportFull( - Vector3? position, Vector3? rotation, float? horizon, bool forceAction = false + Vector3? position, + Vector3? rotation, + float? horizon, + bool forceAction = false ) { - base.teleportFull(position: position, rotation: rotation, horizon: horizon, forceAction: forceAction); + base.teleportFull( + position: position, + rotation: rotation, + horizon: horizon, + forceAction: forceAction + ); actionFinished(success: true); } public void FlyRandomStart(float y) { - Vector3[] shuffledCurrentlyReachable = getReachablePositions().OrderBy(x => systemRandom.Next()).ToArray(); + Vector3[] shuffledCurrentlyReachable = getReachablePositions() + .OrderBy(x => systemRandom.Next()) + .ToArray(); Vector3[] Random_output = SeekTwoPos(shuffledCurrentlyReachable); var thrust_dt_drone = Random_output[0]; @@ -436,7 +469,14 @@ public void FlyDown(float moveMagnitude) { // for use with the Drone to be able to launch an object into the air // Launch an object at a given Force (action.moveMagnitude), and angle (action.rotation) - public void LaunchDroneObject(float moveMagnitude, string objectName, bool objectRandom, float x, float y, float z) { + public void LaunchDroneObject( + float moveMagnitude, + string objectName, + bool objectRandom, + float x, + float y, + float z + ) { Launch(moveMagnitude, objectName, objectRandom, x, y, z); actionFinished(true); fixupdateCnt = 0f; @@ -444,7 +484,6 @@ public void LaunchDroneObject(float moveMagnitude, string objectName, bool objec // spawn a launcher object at action.position coordinates public void SpawnDroneLauncher(Vector3 position) { - SpawnLauncher(position); actionFinished(true); } @@ -485,7 +524,14 @@ public bool isObjectCaught(SimObjPhysics check_obj) { return caught_object_bool; } - public void Launch(float moveMagnitude, string objectName, bool objectRandom, float x, float y, float z) { + public void Launch( + float moveMagnitude, + string objectName, + bool objectRandom, + float x, + float y, + float z + ) { Vector3 LaunchAngle = new Vector3(x, y, z); DroneObjectLauncher.Launch(this, moveMagnitude, LaunchAngle, objectName, objectRandom); } @@ -501,6 +547,5 @@ public Vector3 GetLauncherPosition() { public void SpawnLauncher(Vector3 position) { UnityEngine.Object.Instantiate(DroneObjectLauncher, position, Quaternion.identity); } - } } diff --git a/unity/Assets/Scripts/DroneObjectLauncher.cs b/unity/Assets/Scripts/DroneObjectLauncher.cs index e7772f48f0..9bfd4ac392 100644 --- a/unity/Assets/Scripts/DroneObjectLauncher.cs +++ b/unity/Assets/Scripts/DroneObjectLauncher.cs @@ -1,24 +1,21 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using UnityEngine; -using System; using UnityStandardAssets.Characters.FirstPerson; public class DroneObjectLauncher : MonoBehaviour { - [SerializeField] public GameObject[] prefabsToLaunch; + [SerializeField] + public GameObject[] prefabsToLaunch; // keep track of what objects were launched already private HashSet launch_object = new HashSet(); // Use this for initialization - void Start() { - - } + void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } public bool HasLaunch(SimObjPhysics obj) { return launch_object.Contains(obj); @@ -48,10 +45,19 @@ public GameObject GetGameObject(string objectType, bool randomize, int variation return candidates[variation]; } - public void Launch(DroneFPSAgentController agent, float magnitude, Vector3 direction, string objectName, bool randomize) { - + public void Launch( + DroneFPSAgentController agent, + float magnitude, + Vector3 direction, + string objectName, + bool randomize + ) { GameObject toLaunch = GetGameObject(objectName, randomize, 0); - GameObject fireaway = Instantiate(toLaunch, this.transform.position, this.transform.rotation); + GameObject fireaway = Instantiate( + toLaunch, + this.transform.position, + this.transform.rotation + ); GameObject topObject = GameObject.Find("Objects"); fireaway.transform.SetParent(topObject.transform); diff --git a/unity/Assets/Scripts/EditorSetupSimObjPhysics.cs b/unity/Assets/Scripts/EditorSetupSimObjPhysics.cs index 2825fcb8c6..41124c7702 100644 --- a/unity/Assets/Scripts/EditorSetupSimObjPhysics.cs +++ b/unity/Assets/Scripts/EditorSetupSimObjPhysics.cs @@ -8,23 +8,24 @@ public class EditorSetupSimObjPhysics : MonoBehaviour { public SimObjPrimaryProperty Primary; public SimObjSecondaryProperty[] Secondary; - // Use this for initialization - void Start() { - - } + void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } public void Mirror() { // SimObjSecondaryProperty[] MirrorSecondary = new SimObjSecondaryProperty[]{SimObjSecondaryProperty.CanBeCleanedGlass}; // Setup(SimObjType.Mirror, SimObjPrimaryProperty.Static, MirrorSecondary); } - public void Setup(SimObjType type, SimObjPrimaryProperty primaryProperty, SimObjSecondaryProperty[] secondaryProperties, string tag, int layer) { + public void Setup( + SimObjType type, + SimObjPrimaryProperty primaryProperty, + SimObjSecondaryProperty[] secondaryProperties, + string tag, + int layer + ) { // SimObjPhysics sop = gameObject.GetComponent(); // sop.Type = type; diff --git a/unity/Assets/Scripts/ExpRoom/ArmAgentController_partial_ExpRoom.cs b/unity/Assets/Scripts/ExpRoom/ArmAgentController_partial_ExpRoom.cs index 26e5b7cb19..411498983b 100644 --- a/unity/Assets/Scripts/ExpRoom/ArmAgentController_partial_ExpRoom.cs +++ b/unity/Assets/Scripts/ExpRoom/ArmAgentController_partial_ExpRoom.cs @@ -5,17 +5,16 @@ using System.IO; using System.Linq; using Priority_Queue; +using RandomExtensions; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.ImageEffects; using UnityStandardAssets.Utility; -using RandomExtensions; namespace UnityStandardAssets.Characters.FirstPerson { public partial class KinovaArmAgentController : ArmAgentController { - public void AttachObjectToArmWithFixedJoint(string objectId) { if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { errorMessage = $"Cannot find object with id {objectId}."; @@ -30,6 +29,5 @@ public void AttachObjectToArmWithFixedJoint(string objectId) { public void BreakFixedJoints() { actionFinished(getArmImplementation().BreakFixedJoints()); } - } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/ExpRoom/IK_Robot_Arm_Controller_partial_ExpRoom.cs b/unity/Assets/Scripts/ExpRoom/IK_Robot_Arm_Controller_partial_ExpRoom.cs index 04fc730df6..8616af0013 100644 --- a/unity/Assets/Scripts/ExpRoom/IK_Robot_Arm_Controller_partial_ExpRoom.cs +++ b/unity/Assets/Scripts/ExpRoom/IK_Robot_Arm_Controller_partial_ExpRoom.cs @@ -5,16 +5,15 @@ using System.IO; using System.Linq; using Priority_Queue; +using RandomExtensions; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.ImageEffects; using UnityStandardAssets.Utility; -using RandomExtensions; public partial class IK_Robot_Arm_Controller : ArmController { - public bool AttachObjectToArmWithFixedJoint(SimObjPhysics target) { foreach (FixedJoint fj in magnetSphere.gameObject.GetComponents()) { if (fj.connectedBody.gameObject == target.gameObject) { @@ -37,5 +36,4 @@ public bool BreakFixedJoints() { } return true; } - -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/ExpRoom/PhysicsRemoteFPSAgentController_partial_ExpRoom.cs b/unity/Assets/Scripts/ExpRoom/PhysicsRemoteFPSAgentController_partial_ExpRoom.cs index 14e4397102..ef6f0130a5 100644 --- a/unity/Assets/Scripts/ExpRoom/PhysicsRemoteFPSAgentController_partial_ExpRoom.cs +++ b/unity/Assets/Scripts/ExpRoom/PhysicsRemoteFPSAgentController_partial_ExpRoom.cs @@ -5,13 +5,13 @@ using System.IO; using System.Linq; using Priority_Queue; +using RandomExtensions; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.ImageEffects; using UnityStandardAssets.Utility; -using RandomExtensions; namespace UnityStandardAssets.Characters.FirstPerson { public partial class PhysicsRemoteFPSAgentController : BaseFPSAgentController { @@ -49,7 +49,8 @@ public static void emptyEnumerator(IEnumerator enumerator) { } public void WhichContainersDoesAvailableObjectFitIn( - string objectName, int? thirdPartyCameraIndex = null + string objectName, + int? thirdPartyCameraIndex = null ) { Camera camera = m_Camera; if (thirdPartyCameraIndex.HasValue) { @@ -58,7 +59,8 @@ public void WhichContainersDoesAvailableObjectFitIn( PhysicsSceneManager.StartPhysicsCoroutine( startCoroutineUsing: this.baseAgentComponent, enumerator: whichContainersDoesAvailableObjectFitIn( - objectName: objectName, visibilityCheckCamera: camera + objectName: objectName, + visibilityCheckCamera: camera ) ); } @@ -97,12 +99,14 @@ Camera visibilityCheckCamera activateSop(toCover); - if (!PlaceObjectAtPoint( - target: toCover, - position: middleOfTable, - rotation: null, - forceKinematic: true - )) { + if ( + !PlaceObjectAtPoint( + target: toCover, + position: middleOfTable, + rotation: null, + forceKinematic: true + ) + ) { deactivateSop(toCover); errorMessage = $"{toCover.name} failed to place"; actionFinished(false); @@ -115,9 +119,9 @@ Camera visibilityCheckCamera int numberFit = 0; foreach ( - SimObjPhysics cover in availableExpRoomContainersDict.OrderBy( - kvp => kvp.Key - ).Select(kvp => kvp.Value) + SimObjPhysics cover in availableExpRoomContainersDict + .OrderBy(kvp => kvp.Key) + .Select(kvp => kvp.Value) ) { if (cover.GetComponent()) { cover.GetComponent().Unbreakable = true; @@ -137,23 +141,27 @@ SimObjPhysics cover in availableExpRoomContainersDict.OrderBy( float lastScale = 1.0f; Func tryScale = (scale) => { - emptyEnumerator(scaleObject( - scale: scale / lastScale, - target: cover, - scaleOverSeconds: 0f, - skipActionFinished: true - )); + emptyEnumerator( + scaleObject( + scale: scale / lastScale, + target: cover, + scaleOverSeconds: 0f, + skipActionFinished: true + ) + ); lastScale = scale; Physics.SyncTransforms(); - if (!PlaceObjectAtPoint( - target: cover, - position: rightOfTable, - rotation: null, - forceKinematic: true, - includeErrorMessage: true - )) { + if ( + !PlaceObjectAtPoint( + target: cover, + position: rightOfTable, + rotation: null, + forceKinematic: true, + includeErrorMessage: true + ) + ) { #if UNITY_EDITOR Debug.Log($"{cover.name} failed to place: {errorMessage}"); #endif @@ -172,9 +180,8 @@ SimObjPhysics cover in availableExpRoomContainersDict.OrderBy( Physics.SyncTransforms(); - Collider coverCollidingWith = UtilityFunctions.firstColliderObjectCollidingWith( - go: cover.gameObject - ); + Collider coverCollidingWith = + UtilityFunctions.firstColliderObjectCollidingWith(go: cover.gameObject); if (coverCollidingWith != null) { //Debug.Log($"{cover.name} colliding with {coverCollidingWith.transform.parent.name}"); return false; @@ -205,12 +212,14 @@ SimObjPhysics cover in availableExpRoomContainersDict.OrderBy( numberFit += 1; } - emptyEnumerator(scaleObject( - scale: 1.0f / lastScale, - target: cover, - scaleOverSeconds: 0f, - skipActionFinished: true - )); + emptyEnumerator( + scaleObject( + scale: 1.0f / lastScale, + target: cover, + scaleOverSeconds: 0f, + skipActionFinished: true + ) + ); deactivateSop(cover); } @@ -309,7 +318,9 @@ public void ToggleObjectIsKinematic(string objectId, bool? isKinematic = null) { return; } - Rigidbody rb = physicsSceneManager.ObjectIdToSimObjPhysics[objectId].GetComponent(); + Rigidbody rb = physicsSceneManager + .ObjectIdToSimObjPhysics[objectId] + .GetComponent(); if (isKinematic.HasValue) { rb.isKinematic = isKinematic.Value; } else { @@ -360,9 +371,7 @@ public void SetRigidbodyConstraints( actionFinished(true); } - public List pointOnObjectsCollidersClosestToPoint( - string objectId, Vector3 point - ) { + public List pointOnObjectsCollidersClosestToPoint(string objectId, Vector3 point) { if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { errorMessage = $"Cannot find object with id {objectId}."; return null; @@ -375,17 +384,21 @@ public List pointOnObjectsCollidersClosestToPoint( // on certain collider types. We fall back to using the object's bounding box (see below) // if there are no colliders of the supported types. if ( - c.enabled && !c.isTrigger && ( - c is BoxCollider || - c is SphereCollider || - c is CapsuleCollider || - (c is MeshCollider && ((MeshCollider) c).convex) + c.enabled + && !c.isTrigger + && ( + c is BoxCollider + || c is SphereCollider + || c is CapsuleCollider + || (c is MeshCollider && ((MeshCollider)c).convex) ) ) { closePoints.Add(c.ClosestPoint(point)); #if UNITY_EDITOR Vector3 closePoint = closePoints[closePoints.Count - 1]; - Debug.Log($"For collider {c}, {closePoint} has dist {Vector3.Distance(closePoint, point)}"); + Debug.Log( + $"For collider {c}, {closePoint} has dist {Vector3.Distance(closePoint, point)}" + ); #endif } } @@ -398,8 +411,8 @@ c is CapsuleCollider || #if UNITY_EDITOR Vector3 closePoint = closePoints[closePoints.Count - 1]; Debug.Log( - $"Could not find any usable colliders in {objectId}. Instead using the bounding box," + - $" for the bounding box {closePoint} has dist {Vector3.Distance(closePoint, point)}" + $"Could not find any usable colliders in {objectId}. Instead using the bounding box," + + $" for the bounding box {closePoint} has dist {Vector3.Distance(closePoint, point)}" ); #endif } @@ -407,7 +420,6 @@ c is CapsuleCollider || return closePoints; } - /// /// Finds the points on an object's colliders that are closest to a specified point in space. /// @@ -430,16 +442,15 @@ c is CapsuleCollider || /// /// In the Unity Editor, this method also logs the distance from the closest points to the specified point, aiding in debugging and visualization. /// - public void PointOnObjectsCollidersClosestToPoint( - string objectId, Vector3 point - ) { - List closePoints = pointOnObjectsCollidersClosestToPoint(objectId: objectId, point: point); + public void PointOnObjectsCollidersClosestToPoint(string objectId, Vector3 point) { + List closePoints = pointOnObjectsCollidersClosestToPoint( + objectId: objectId, + point: point + ); actionFinishedEmit(closePoints != null, closePoints); } - public void PointOnObjectsMeshClosestToPoint( - string objectId, Vector3 point - ) { + public void PointOnObjectsMeshClosestToPoint(string objectId, Vector3 point) { if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); @@ -463,9 +474,7 @@ public void PointOnObjectsMeshClosestToPoint( actionFinishedEmit(true, points); } - public void ProportionOfObjectVisible( - string objectId, int? thirdPartyCameraIndex = null - ) { + public void ProportionOfObjectVisible(string objectId, int? thirdPartyCameraIndex = null) { if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); @@ -479,7 +488,9 @@ public void ProportionOfObjectVisible( Transform[] visPoints = target.VisibilityPoints; int visPointCount = 0; - Camera camera = thirdPartyCameraIndex.HasValue ? agentManager.thirdPartyCameras[thirdPartyCameraIndex.Value] : m_Camera; + Camera camera = thirdPartyCameraIndex.HasValue + ? agentManager.thirdPartyCameras[thirdPartyCameraIndex.Value] + : m_Camera; foreach (Transform point in visPoints) { // if this particular point is in view... @@ -573,9 +584,7 @@ public void AddClippingPlaneToObject( actionFinished(true, toReturn); } - public void AddClippingPlaneToObjectToExcludeBox( - string objectId, List boxCorners - ) { + public void AddClippingPlaneToObjectToExcludeBox(string objectId, List boxCorners) { if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); @@ -599,8 +608,8 @@ public void AddClippingPlaneToObjectToExcludeBox( toReturn["normal"] = planeGo.transform.up; if (!(bool)toReturn["enabled"]) { errorMessage = ( - "Clipping plane was placed on object but is disabled as the" + - " input bounding box contained no points on the object's mesh." + "Clipping plane was placed on object but is disabled as the" + + " input bounding box contained no points on the object's mesh." ); actionFinished(false, toReturn); } else { @@ -618,7 +627,8 @@ public void GetClippingPlane(string objectId) { Ronja.ClippingPlane clipPlane = target.GetComponentInChildren(); if (clipPlane == null) { - errorMessage = $"Object with id {objectId} does not have a clipping plane associated with it."; + errorMessage = + $"Object with id {objectId} does not have a clipping plane associated with it."; actionFinishedEmit(false); return; } @@ -631,9 +641,7 @@ public void GetClippingPlane(string objectId) { actionFinishedEmit(true, toReturn); } - public void ToggleClippingPlane( - string objectId, bool? enabled = null - ) { + public void ToggleClippingPlane(string objectId, bool? enabled = null) { if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); @@ -643,7 +651,8 @@ public void ToggleClippingPlane( Ronja.ClippingPlane clipPlane = target.GetComponentInChildren(); if (clipPlane == null) { - errorMessage = $"Object with id {objectId} does not have a clipping plane associated with it."; + errorMessage = + $"Object with id {objectId} does not have a clipping plane associated with it."; actionFinished(false); return; } @@ -689,7 +698,8 @@ protected List cornersOfBounds(Bounds b) { } public GameObject addClippingPlaneToObjectToExcludeBox( - SimObjPhysics target, float[][] boxCorners + SimObjPhysics target, + float[][] boxCorners ) { List boxCornersV3 = new List(); for (int i = 0; i < boxCorners.Length; i++) { @@ -699,7 +709,8 @@ public GameObject addClippingPlaneToObjectToExcludeBox( } public GameObject addClippingPlaneToObjectToExcludeBox( - SimObjPhysics target, List boxCorners + SimObjPhysics target, + List boxCorners ) { GameObject clipPlaneGo = addClippingPlaneToObject(target); @@ -739,26 +750,26 @@ public GameObject addClippingPlaneToObjectToExcludeBox( clipPlaneGo.transform.LookAt(lookOffset + startPos); clipPlaneGo.transform.Rotate(new Vector3(90f, 0f, 0f)); if (lookOffset.x > 0f) { - clipPlaneGo.transform.position = new Vector3( - boundsOfVerticesToExclude.min.x - startPos.x, 0f, 0f - ) + startPos; + clipPlaneGo.transform.position = + new Vector3(boundsOfVerticesToExclude.min.x - startPos.x, 0f, 0f) + + startPos; } else { - clipPlaneGo.transform.position = new Vector3( - boundsOfVerticesToExclude.max.x - startPos.x, 0f, 0f - ) + startPos; + clipPlaneGo.transform.position = + new Vector3(boundsOfVerticesToExclude.max.x - startPos.x, 0f, 0f) + + startPos; } } else { Vector3 lookOffset = new Vector3(0f, 0f, Mathf.Sign(direction.z)); clipPlaneGo.transform.LookAt(lookOffset + startPos); clipPlaneGo.transform.Rotate(new Vector3(90f, 0f, 0f)); if (lookOffset.z > 0f) { - clipPlaneGo.transform.position = new Vector3( - 0f, 0f, boundsOfVerticesToExclude.min.z - startPos.z - ) + startPos; + clipPlaneGo.transform.position = + new Vector3(0f, 0f, boundsOfVerticesToExclude.min.z - startPos.z) + + startPos; } else { - clipPlaneGo.transform.position = new Vector3( - 0f, 0f, boundsOfVerticesToExclude.max.z - startPos.z - ) + startPos; + clipPlaneGo.transform.position = + new Vector3(0f, 0f, boundsOfVerticesToExclude.max.z - startPos.z) + + startPos; } } @@ -771,9 +782,15 @@ public GameObject addClippingPlaneToObjectToExcludeBox( // grid will be a 2n+1 by n grid in the orientation of agent right/left by agent forward public void GetReceptacleCoordinatesExpRoom(float gridSize, int maxStepCount) { var agent = this.agentManager.agents[0]; - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); // good defaults would be gridSize 0.1m, maxStepCount 20 to cover the room - var ret = ersm.ValidGrid(agent.AgentHand.transform.position, gridSize, maxStepCount, agent); + var ret = ersm.ValidGrid( + agent.AgentHand.transform.position, + gridSize, + maxStepCount, + agent + ); // var ret = ersm.ValidGrid(agent.AgentHand.transform.position, action.gridSize, action.maxStepCount, agent); actionFinished(true, ret); } @@ -788,13 +805,15 @@ public void SpawnExperimentObjAtPoint( int objectVariation = 0 ) { if (receptacleObjectId == null) { - errorMessage = "please give valid receptacleObjectId for SpawnExperimentReceptacleAtPoint action"; + errorMessage = + "please give valid receptacleObjectId for SpawnExperimentReceptacleAtPoint action"; actionFinished(false); return; } if (objectType == null) { - errorMessage = "please use either 'receptacle' or 'screen' to specify which experiment object to spawn"; + errorMessage = + "please use either 'receptacle' or 'screen' to specify which experiment object to spawn"; actionFinished(false); return; } @@ -808,14 +827,26 @@ public void SpawnExperimentObjAtPoint( } if (target == null) { - errorMessage = "no receptacle object with id: " + - receptacleObjectId + " could not be found during SpawnExperimentReceptacleAtPoint"; + errorMessage = + "no receptacle object with id: " + + receptacleObjectId + + " could not be found during SpawnExperimentReceptacleAtPoint"; actionFinished(false); return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); - if (ersm.SpawnExperimentObjAtPoint(this, objectType, objectVariation, target, position, rotation)) { + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); + if ( + ersm.SpawnExperimentObjAtPoint( + this, + objectType, + objectVariation, + target, + position, + rotation + ) + ) { actionFinished(true); } else { errorMessage = $"Experiment object could not be placed on {receptacleObjectId}"; @@ -833,13 +864,15 @@ public void SpawnExperimentObjAtRandom( int objectVariation = 0 ) { if (receptacleObjectId == null) { - errorMessage = "please give valid receptacleObjectId for SpawnExperimentReceptacleAtRandom action"; + errorMessage = + "please give valid receptacleObjectId for SpawnExperimentReceptacleAtRandom action"; actionFinished(false); return; } if (objectType == null) { - errorMessage = "please use either 'receptacle' or 'screen' to specify which experiment object to spawn"; + errorMessage = + "please use either 'receptacle' or 'screen' to specify which experiment object to spawn"; actionFinished(false); return; } @@ -853,14 +886,26 @@ public void SpawnExperimentObjAtRandom( } if (target == null) { - errorMessage = "no receptacle object with id: " + - receptacleObjectId + " could not be found during SpawnExperimentReceptacleAtRandom"; + errorMessage = + "no receptacle object with id: " + + receptacleObjectId + + " could not be found during SpawnExperimentReceptacleAtRandom"; actionFinished(false); return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); - if (ersm.SpawnExperimentObjAtRandom(this, objectType, objectVariation, randomSeed, target, rotation)) { + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); + if ( + ersm.SpawnExperimentObjAtRandom( + this, + objectType, + objectVariation, + randomSeed, + target, + rotation + ) + ) { actionFinished(true); } else { errorMessage = "Experiment object could not be placed on " + receptacleObjectId; @@ -892,24 +937,23 @@ public void ChangeScreenMaterialExpRoom(string objectId, int objectVariation) { } if (target == null) { - errorMessage = "no object with id: " + - objectId + " could be found during ChangeScreenMaterialExpRoom"; + errorMessage = + "no object with id: " + + objectId + + " could be found during ChangeScreenMaterialExpRoom"; actionFinished(false); return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); ersm.ChangeScreenMaterial(target, objectVariation); actionFinished(true); } // specify a screen in exp room by objectId and change material color to rgb public void ChangeScreenColorExpRoom(string objectId, float r, float g, float b) { - if ( - r < 0 || r > 255 || - g < 0 || g > 255 || - b < 0 || b > 255 - ) { + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) { errorMessage = "rgb values must be [0-255]"; actionFinished(false); return; @@ -924,13 +968,16 @@ public void ChangeScreenColorExpRoom(string objectId, float r, float g, float b) } if (target == null) { - errorMessage = "no object with id: " + - objectId + " could not be found during ChangeScreenColorExpRoom"; + errorMessage = + "no object with id: " + + objectId + + " could not be found during ChangeScreenColorExpRoom"; actionFinished(false); return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); ersm.ChangeScreenColor(target, r, g, b); actionFinished(true); } @@ -944,24 +991,22 @@ public void ChangeWallMaterialExpRoom(int objectVariation) { return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); ersm.ChangeWallMaterial(objectVariation); actionFinished(true); } // change wall color to rgb (0-255, 0-255, 0-255) public void ChangeWallColorExpRoom(float r, float g, float b) { - if ( - r < 0 || r > 255 || - g < 0 || g > 255 || - b < 0 || b > 255 - ) { + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) { errorMessage = "rgb values must be [0-255]"; actionFinished(false); return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); ersm.ChangeWallColor(r, g, b); actionFinished(true); } @@ -975,41 +1020,36 @@ public void ChangeFloorMaterialExpRoom(int objectVariation) { return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); ersm.ChangeFloorMaterial(objectVariation); actionFinished(true); } // change wall color to rgb (0-255, 0-255, 0-255) public void ChangeFloorColorExpRoom(float r, float g, float b) { - if ( - r < 0 || r > 255 || - g < 0 || g > 255 || - b < 0 || b > 255 - ) { + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) { errorMessage = "rgb values must be [0-255]"; actionFinished(false); return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); ersm.ChangeFloorColor(r, g, b); actionFinished(true); } // change color of ceiling lights in exp room to rgb (0-255, 0-255, 0-255) public void ChangeLightColorExpRoom(float r, float g, float b) { - if ( - r < 0 || r > 255 || - g < 0 || g > 255 || - b < 0 || b > 255 - ) { + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) { errorMessage = "rgb values must be [0-255]"; actionFinished(false); return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); ersm.ChangeLightColor(r, g, b); actionFinished(true); } @@ -1024,7 +1064,8 @@ public void ChangeLightIntensityExpRoom(float intensity) { return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); ersm.ChangeLightIntensity(intensity); actionFinished(true); } @@ -1037,23 +1078,21 @@ public void ChangeTableTopMaterialExpRoom(int objectVariation) { return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); ersm.ChangeTableTopMaterial(objectVariation); actionFinished(true); } public void ChangeTableTopColorExpRoom(float r, float g, float b) { - if ( - r < 0 || r > 255 || - g < 0 || g > 255 || - b < 0 || b > 255 - ) { + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) { errorMessage = "rgb values must be [0-255]"; actionFinished(false); return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); ersm.ChangeTableTopColor(r, g, b); actionFinished(true); } @@ -1066,23 +1105,21 @@ public void ChangeTableLegMaterialExpRoom(int objectVariation) { return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); ersm.ChangeTableLegMaterial(objectVariation); actionFinished(true); } public void ChangeTableLegColorExpRoom(float r, float g, float b) { - if ( - r < 0 || r > 255 || - g < 0 || g > 255 || - b < 0 || b > 255 - ) { + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) { errorMessage = "rgb values must be [0-255]"; actionFinished(false); return; } - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); ersm.ChangeTableLegColor(r, g, b); actionFinished(true); } @@ -1090,15 +1127,22 @@ public void ChangeTableLegColorExpRoom(float r, float g, float b) { // returns valid spawn points for spawning an object on a receptacle in the experiment room // checks if at rotation can spawn without falling off // table - public void ReturnValidSpawnsExpRoom(string objectType, string receptacleObjectId, float rotation, int objectVariation = 0) { + public void ReturnValidSpawnsExpRoom( + string objectType, + string receptacleObjectId, + float rotation, + int objectVariation = 0 + ) { if (receptacleObjectId == null) { - errorMessage = "please give valid receptacleObjectId for ReturnValidSpawnsExpRoom action"; + errorMessage = + "please give valid receptacleObjectId for ReturnValidSpawnsExpRoom action"; actionFinished(false); return; } if (objectType == null) { - errorMessage = "please use either 'receptacle' or 'screen' to specify which experiment object to spawn"; + errorMessage = + "please use either 'receptacle' or 'screen' to specify which experiment object to spawn"; actionFinished(false); return; } @@ -1111,8 +1155,12 @@ public void ReturnValidSpawnsExpRoom(string objectType, string receptacleObjectI SimObjPhysics target = physicsSceneManager.ObjectIdToSimObjPhysics[receptacleObjectId]; // return all valid spawn coordinates - ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); - actionFinished(true, ersm.ReturnValidSpawns(this, objectType, objectVariation, target, rotation)); + ExperimentRoomSceneManager ersm = + physicsSceneManager.GetComponent(); + actionFinished( + true, + ersm.ReturnValidSpawns(this, objectType, objectVariation, target, rotation) + ); } } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/ExperimentRoomSceneManager.cs b/unity/Assets/Scripts/ExperimentRoomSceneManager.cs index f25a11abbd..677c4aa389 100644 --- a/unity/Assets/Scripts/ExperimentRoomSceneManager.cs +++ b/unity/Assets/Scripts/ExperimentRoomSceneManager.cs @@ -1,31 +1,42 @@ -using System.Collections; -using System; +using System; +using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; public class ExperimentRoomSceneManager : MonoBehaviour { public GameObject[] replacementObjectsToSpawn = null; + // set of experiment receptacle objects public GameObject[] receptaclesToSpawn = null; + // screens to place on table public GameObject[] screensToSpawn = null; + // reference to wall renderer public Renderer wall; + // wall materials to swap between public Material[] wallMaterials = null; + // reference to floor renderer public Renderer floor; + // floor materials to swap between public Material[] floorMaterials = null; + // reference to table renderer, material[0] is top, material [1] are legs public Renderer table; + // table top materials to swap between public Material[] tableTopMaterials = null; + // reference to table leg renderer public Material[] tableLegMaterials = null; + // reference to lights in screen public GameObject[] allOfTheLights; + // material screen options public Material[] screenMaterials = null; @@ -44,9 +55,7 @@ void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } #if UNITY_EDITOR List debugCoords = new List(); @@ -58,7 +67,12 @@ void Update() { // the y value will be wherever the agent's hand currently is // gridIncrement- size between grid points in meters // count - casts a grid forward <2 * count + 1> by - public List ValidGrid(Vector3 origin, float gridIncrement, int count, BaseFPSAgentController agent) { + public List ValidGrid( + Vector3 origin, + float gridIncrement, + int count, + BaseFPSAgentController agent + ) { // start from origin which will be agent's hand List pointsOnGrid = new List(); @@ -114,8 +128,8 @@ public List ValidGrid(Vector3 origin, float gridIncrement, int count, B // ok we now have grid points in a grid, now raycast down from each of those and see if we hit a receptacle... return actualPoints; - } + // change specified screen object's material to color rgb public void ChangeScreenColor(SimObjPhysics screen, float r, float g, float b) { List renderers = GetAllRenderersOfObject(screen); @@ -207,7 +221,13 @@ public void ChangeFloorColor(float r, float g, float b) { // return spawn coordinates above the that the will fit at a given rotation // excludes coordinates that would cause object to fall off the table - public List ReturnValidSpawns(PhysicsRemoteFPSAgentController agent, string objType, int variation, SimObjPhysics targetReceptacle, float yRot = 0) { + public List ReturnValidSpawns( + PhysicsRemoteFPSAgentController agent, + string objType, + int variation, + SimObjPhysics targetReceptacle, + float yRot = 0 + ) { toSpawn = null; if (objType == "screen") { @@ -218,7 +238,11 @@ public List ReturnValidSpawns(PhysicsRemoteFPSAgentController agent, st toSpawn = receptaclesToSpawn[variation].GetComponent(); } - SimObjPhysics spawned = GameObject.Instantiate(toSpawn, initialSpawnPosition, Quaternion.identity); + SimObjPhysics spawned = GameObject.Instantiate( + toSpawn, + initialSpawnPosition, + Quaternion.identity + ); Rigidbody rb = spawned.GetComponent(); // apply rotation to object, default quaternion.identity @@ -268,9 +292,16 @@ public List ReturnValidSpawns(PhysicsRemoteFPSAgentController agent, st } // Note: always run ReturnValidSpawns - to get the current scene state's set of useable coordinates for the objType and Variation - // spawn receptacle/screen of index [variation] on table object at coordinate + // spawn receptacle/screen of index [variation] on table object at coordinate // a valid should be generated from the ReturnValidSpawns() return - public bool SpawnExperimentObjAtPoint(PhysicsRemoteFPSAgentController agent, string objType, int variation, SimObjPhysics targetReceptacle, Vector3 point, float yRot = 0) { + public bool SpawnExperimentObjAtPoint( + PhysicsRemoteFPSAgentController agent, + string objType, + int variation, + SimObjPhysics targetReceptacle, + Vector3 point, + float yRot = 0 + ) { toSpawn = null; bool success = false; @@ -288,7 +319,11 @@ public bool SpawnExperimentObjAtPoint(PhysicsRemoteFPSAgentController agent, str } // instantiate the prefab toSpawn away from every other object - SimObjPhysics spawned = GameObject.Instantiate(toSpawn, initialSpawnPosition, Quaternion.identity); + SimObjPhysics spawned = GameObject.Instantiate( + toSpawn, + initialSpawnPosition, + Quaternion.identity + ); Rigidbody rb = spawned.GetComponent(); // make sure object doesn't fall until we are done preparing to reposition it on the target receptacle rb.isKinematic = true; @@ -336,9 +371,15 @@ public bool SpawnExperimentObjAtPoint(PhysicsRemoteFPSAgentController agent, str return success; } - // spawn receptacle/screen of index [variation] on table object using random seed to pick which spawn coordinate used - public bool SpawnExperimentObjAtRandom(PhysicsRemoteFPSAgentController agent, string objType, int variation, int seed, SimObjPhysics targetReceptacle, float yRot = 0) { + public bool SpawnExperimentObjAtRandom( + PhysicsRemoteFPSAgentController agent, + string objType, + int variation, + int seed, + SimObjPhysics targetReceptacle, + float yRot = 0 + ) { toSpawn = null; bool success = false; @@ -358,7 +399,11 @@ public bool SpawnExperimentObjAtRandom(PhysicsRemoteFPSAgentController agent, st spawnCoordinates.Shuffle_(seed); // instantiate the prefab toSpawn away from every other object - SimObjPhysics spawned = GameObject.Instantiate(toSpawn, initialSpawnPosition, Quaternion.identity); + SimObjPhysics spawned = GameObject.Instantiate( + toSpawn, + initialSpawnPosition, + Quaternion.identity + ); Rigidbody rb = spawned.GetComponent(); // make sure object doesn't fall until we are done preparing to reposition it on the target receptacle rb.isKinematic = true; @@ -429,21 +474,53 @@ private List GetCorners(SimObjPhysics sop) { // keep track of all 8 corners of the OverlapBox List corners = new List(); // bottom forward right - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f + ) + ); // bottom forward left - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f + ) + ); // bottom back left - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f + ) + ); // bottom back right - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f + ) + ); // top forward right - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f + ) + ); // top forward left - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f + ) + ); // top back left - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f + ) + ); // top back right - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f + ) + ); return corners; } diff --git a/unity/Assets/Scripts/Extensions.cs b/unity/Assets/Scripts/Extensions.cs index 33c7df5357..5049372db3 100644 --- a/unity/Assets/Scripts/Extensions.cs +++ b/unity/Assets/Scripts/Extensions.cs @@ -1,28 +1,29 @@ +using System; using System.Collections.Generic; +using System.IO; using System.Linq; -using System; - using System.Runtime.Serialization.Formatters.Binary; - using System.IO; -using MessagePack.Resolvers; -using MessagePack.Formatters; +using System.Runtime.Serialization.Formatters.Binary; using MessagePack; +using MessagePack.Formatters; +using MessagePack.Resolvers; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; public static class ExtensionMethods { - public static T DeepClone(this T obj) - { + public static T DeepClone(this T obj) { // Don't serialize a null object, simply return the default for that object if (ReferenceEquals(obj, null)) { return default; - } + } // initialize inner objects individually // for example in default constructor some list property initialized with some values, // but in 'source' these items are cleaned - // without ObjectCreationHandling.Replace default constructor values will be added to result - var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace}; + var deserializeSettings = new JsonSerializerSettings { + ObjectCreationHandling = ObjectCreationHandling.Replace + }; var jsonResolver = new ShouldSerializeContractResolver(); var str = Newtonsoft.Json.JsonConvert.SerializeObject( @@ -39,26 +40,29 @@ public static T DeepClone(this T obj) return jObj.ToObject(); } - public static TValue GetValueOrDefault(this Dictionary dictionary, TKey key, TValue defaultValue = default(TValue)) - { + public static TValue GetValueOrDefault( + this Dictionary dictionary, + TKey key, + TValue defaultValue = default(TValue) + ) { TValue value; return dictionary.TryGetValue(key, out value) ? value : defaultValue; } - public static int AddCount(this Dictionary dictionary, TKey key, int count = 1) - { + public static int AddCount(this Dictionary dictionary, TKey key, int count = 1) { int value; dictionary.TryGetValue(key, out value); if (dictionary.ContainsKey(key)) { dictionary[key] = dictionary[key] + count; - } - else { + } else { dictionary[key] = count; } return dictionary[key]; } - public static IEnumerable> CartesianProduct(this IEnumerable> sequences) { + public static IEnumerable> CartesianProduct( + this IEnumerable> sequences + ) { IEnumerable> emptyProduct = new[] { Enumerable.Empty() }; return sequences.Aggregate( emptyProduct, @@ -66,6 +70,6 @@ public static IEnumerable> CartesianProduct(this IEnumerable FormMap = new Dictionary{ - {"image", FieldType.RGBImage}, - {"image_depth", FieldType.DepthImage}, - {"image_normals", FieldType.NormalsImage}, - {"image_classes", FieldType.ClassesImage}, - {"image_flow", FieldType.FlowsImage}, - {"image_ids", FieldType.IDsImage}, - {"image-thirdParty-camera", FieldType.ThirdPartyCameraImage}, - {"image_thirdParty_depth", FieldType.ThirdPartyDepth}, - {"image_thirdParty_normals", FieldType.ThirdPartyNormals}, - {"image_thirdParty_classes", FieldType.ThirdPartyClasses}, - {"image_thirdParty_image_ids", FieldType.ThirdPartyImageIds}, - {"image_thirdParty_flow", FieldType.ThirdPartyFlow} - + public static Dictionary FormMap = new Dictionary + { + { "image", FieldType.RGBImage }, + { "image_depth", FieldType.DepthImage }, + { "image_normals", FieldType.NormalsImage }, + { "image_classes", FieldType.ClassesImage }, + { "image_flow", FieldType.FlowsImage }, + { "image_ids", FieldType.IDsImage }, + { "image-thirdParty-camera", FieldType.ThirdPartyCameraImage }, + { "image_thirdParty_depth", FieldType.ThirdPartyDepth }, + { "image_thirdParty_normals", FieldType.ThirdPartyNormals }, + { "image_thirdParty_classes", FieldType.ThirdPartyClasses }, + { "image_thirdParty_image_ids", FieldType.ThirdPartyImageIds }, + { "image_thirdParty_flow", FieldType.ThirdPartyFlow } }; - static public int UnpackNetworkBytes(byte[] data, int offset = 0) { + public static int UnpackNetworkBytes(byte[] data, int offset = 0) { int networkInt = System.BitConverter.ToInt32(data, offset); return IPAddress.NetworkToHostOrder(networkInt); } - static public byte[] PackNetworkBytes(int val) { + public static byte[] PackNetworkBytes(int val) { int networkInt = IPAddress.HostToNetworkOrder(val); return System.BitConverter.GetBytes(networkInt); } public string ReceiveMessage() { if (clientPipe == null) { - this.clientPipe = new FileStream(this.clientPipePath, FileMode.Open, FileAccess.Read); + this.clientPipe = new FileStream( + this.clientPipePath, + FileMode.Open, + FileAccess.Read + ); } string action = null; while (true) { byte[] header = new byte[headerLength]; int bytesRead = clientPipe.Read(header, 0, header.Length); if (bytesRead == 0) { - throw new EndOfStreamException("zero bytes read trying to read header; assuming disconnect"); + throw new EndOfStreamException( + "zero bytes read trying to read header; assuming disconnect" + ); } FieldType fieldType = (FieldType)header[0]; if (fieldType == FieldType.EndOfMessage) { @@ -66,7 +70,9 @@ public string ReceiveMessage() { bytesRead = clientPipe.Read(body, totalBytesRead, body.Length - totalBytesRead); // didn't read anything new, assume that we have a disconnect if (bytesRead == 0) { - throw new EndOfStreamException("number of bytes read did not change during body read; assuming disconnect"); + throw new EndOfStreamException( + "number of bytes read did not change during body read; assuming disconnect" + ); } totalBytesRead += bytesRead; } @@ -90,7 +96,11 @@ public void SendEOM() { public void SendMessage(FieldType t, byte[] body) { if (this.serverPipe == null) { - this.serverPipe = new FileStream(this.serverPipePath, FileMode.Open, FileAccess.Write); + this.serverPipe = new FileStream( + this.serverPipePath, + FileMode.Open, + FileAccess.Write + ); } // Console.WriteLine("server pipe + connected " + this.serverPipe.IsConnected ); byte[] header = new byte[headerLength]; @@ -100,8 +110,6 @@ public void SendMessage(FieldType t, byte[] body) { serverPipe.Write(body, 0, body.Length); } - - private Client(string serverPipePath, string clientPipePath) { this.serverPipePath = serverPipePath; this.clientPipePath = clientPipePath; @@ -109,15 +117,12 @@ private Client(string serverPipePath, string clientPipePath) { this.eomHeader[0] = (byte)FieldType.EndOfMessage; } - public static Client GetInstance(string serverPipePath, string clientPipePath) { if (singletonClient == null) { singletonClient = new Client(serverPipePath, clientPipePath); } return singletonClient; } - - } public enum FieldType : byte { @@ -139,6 +144,4 @@ public enum FieldType : byte { ThirdPartyFlow = 0x10, EndOfMessage = 0xff } - - } diff --git a/unity/Assets/Scripts/Fill.cs b/unity/Assets/Scripts/Fill.cs index 4150723476..4121486184 100644 --- a/unity/Assets/Scripts/Fill.cs +++ b/unity/Assets/Scripts/Fill.cs @@ -1,7 +1,7 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using UnityEngine; -using System; using Random = UnityEngine.Random; public class Fill : MonoBehaviour { @@ -31,7 +31,11 @@ public string FilledLiquid() { void Awake() { #if UNITY_EDITOR - if (!gameObject.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeFilled)) { + if ( + !gameObject + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeFilled) + ) { Debug.LogError(gameObject.name + " is missing the CanBeFilled secondary property!"); } #endif @@ -76,9 +80,7 @@ public void FillObject(string whichLiquid) { // check if this object has whichLiquid setup as fillable: If the object has a null reference this object // is not setup for that liquid if (Liquids[whichLiquid] == null) { - throw new ArgumentException( - $"The liquid {whichLiquid} is not setup for this object." - ); + throw new ArgumentException($"The liquid {whichLiquid} is not setup for this object."); } Liquids[whichLiquid].transform.gameObject.SetActive(true); @@ -101,7 +103,7 @@ public void FillObject(string whichLiquid) { public void EmptyObject() { // for each thing in Liquids, if it exists set it to false and then set bools appropriately foreach (KeyValuePair gogogo in Liquids) { - // if the value field is not null and has a reference to a liquid object + // if the value field is not null and has a reference to a liquid object if (gogogo.Value != null) { gogogo.Value.SetActive(false); } diff --git a/unity/Assets/Scripts/FirstPersonCharacterCull.cs b/unity/Assets/Scripts/FirstPersonCharacterCull.cs index 605bceeccb..ce83224dd9 100644 --- a/unity/Assets/Scripts/FirstPersonCharacterCull.cs +++ b/unity/Assets/Scripts/FirstPersonCharacterCull.cs @@ -1,5 +1,5 @@ -using UnityEngine; -using System.Collections.Generic; +using System.Collections.Generic; +using UnityEngine; using UnityEngine.Rendering; using UnityStandardAssets.Characters.FirstPerson; @@ -8,12 +8,8 @@ public class FirstPersonCharacterCull : MonoBehaviour { private bool _stopCullingThingsForASecond = false; public bool StopCullingThingsForASecond { - get { - return this._stopCullingThingsForASecond; - } - set { - this._stopCullingThingsForASecond = value; - } + get { return this._stopCullingThingsForASecond; } + set { this._stopCullingThingsForASecond = value; } } public MeshRenderer[] RenderersToHide; // Mesh renderer that you want this script's camera to cull @@ -28,13 +24,11 @@ public void SwitchRenderersToHide(GameObject visibilityCapsule) { } RenderersToHide = renderers.ToArray(); - } void OnPreRender() // Just before this camera starts to render... { if (!StopCullingThingsForASecond) { - if ( FPSController != null && FPSController.agent != null @@ -46,7 +40,6 @@ void OnPreRender() // Just before this camera starts to render... } } } - } void OnPostRender() // Immediately after this camera renders... @@ -58,12 +51,10 @@ void OnPostRender() // Immediately after this camera renders... && (RenderersToHide != null || RenderersToHide.Length != 0) && FPSController.agent.IsVisible ) { // only do this if visibility capsule is toggled on - foreach (MeshRenderer mr in RenderersToHide) { mr.enabled = true; // Turn it back on } } } } - -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/Flame.cs b/unity/Assets/Scripts/Flame.cs index 4c77e5e127..28abb12afd 100644 --- a/unity/Assets/Scripts/Flame.cs +++ b/unity/Assets/Scripts/Flame.cs @@ -13,14 +13,10 @@ public class Flame : MonoBehaviour { public GameObject MyObject; // Start is called before the first frame update - void Start() { - - } + void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } // if this touches water and it's on, it is put out. Fire safety is important! public void OnTriggerStay(Collider MagiciansRed) { diff --git a/unity/Assets/Scripts/FpinAgentController.cs b/unity/Assets/Scripts/FpinAgentController.cs index 20e43a4da6..9571325c7e 100644 --- a/unity/Assets/Scripts/FpinAgentController.cs +++ b/unity/Assets/Scripts/FpinAgentController.cs @@ -1,18 +1,17 @@ +using System; using System.Collections; using System.Collections.Generic; -using UnityEngine; -using System; using System.Linq; +using MessagePack; using RandomExtensions; +using Thor.Procedural; +using Thor.Procedural.Data; +using UnityEngine; using UnityEngine.AI; using UnityEngine.Rendering.PostProcessing; using UnityEngine.UIElements; -using Thor.Procedural.Data; -using Thor.Procedural; -using MessagePack; namespace UnityStandardAssets.Characters.FirstPerson { - public class BoxBounds { public Vector3 worldCenter; public Vector3 agentRelativeCenter; @@ -28,16 +27,16 @@ public class LoadInUnityProceduralAsset { public ObjectAnnotations annotations = null; } - #nullable enable +#nullable enable [Serializable] [MessagePackObject(keyAsPropertyName: true)] public class BodyAsset { public string? assetId = null; public LoadInUnityProceduralAsset? dynamicAsset = null; public ProceduralAsset? asset = null; - } - #nullable disable + +#nullable disable [Serializable] [MessagePackObject(keyAsPropertyName: true)] @@ -65,8 +64,7 @@ public class BackwardsCompatibleInitializeParams { public string visibilityScheme = VisibilityScheme.Collider.ToString(); } - public class FpinAgentController : PhysicsRemoteFPSAgentController{ - + public class FpinAgentController : PhysicsRemoteFPSAgentController { private static readonly Vector3 agentSpawnOffset = new Vector3(100.0f, 100.0f, 100.0f); private FpinMovableContinuous fpinMovable; public BoxCollider spawnedBoxCollider = null; @@ -77,42 +75,52 @@ public class FpinAgentController : PhysicsRemoteFPSAgentController{ public BoxBounds boxBounds = null; public BoxBounds BoxBounds { get { - if(spawnedBoxCollider != null) { + if (spawnedBoxCollider != null) { BoxBounds currentBounds = new BoxBounds(); - currentBounds.worldCenter = spawnedBoxCollider.transform.TransformPoint(spawnedBoxCollider.center); + currentBounds.worldCenter = spawnedBoxCollider.transform.TransformPoint( + spawnedBoxCollider.center + ); currentBounds.size = GetTrueSizeOfBoxCollider(spawnedBoxCollider); - currentBounds.agentRelativeCenter = this.transform.InverseTransformPoint(currentBounds.worldCenter); + currentBounds.agentRelativeCenter = this.transform.InverseTransformPoint( + currentBounds.worldCenter + ); boxBounds = currentBounds; // Debug.Log($"world center: {boxBounds.worldCenter}"); // Debug.Log($"size: {boxBounds.size}"); // Debug.Log($"agentRelativeCenter: {boxBounds.agentRelativeCenter}"); - } else { + } else { // Debug.Log("why is it nullll"); return null; } return boxBounds; } - set { - boxBounds = value; - } + set { boxBounds = value; } } public CollisionListener collisionListener; - - public FpinAgentController(BaseAgentComponent baseAgentComponent, AgentManager agentManager) : base(baseAgentComponent, agentManager) { - } + + public FpinAgentController(BaseAgentComponent baseAgentComponent, AgentManager agentManager) + : base(baseAgentComponent, agentManager) { } public void Start() { //put stuff we need here when we need it maybe } - public override RaycastHit[] CastBodyTrayectory(Vector3 startPosition, Vector3 direction, float skinWidth, float moveMagnitude, int layerMask, CapsuleData cachedCapsule) { - - Vector3 startPositionBoxCenter = startPosition + this.transform.TransformDirection(this.boxBounds.agentRelativeCenter); + public override RaycastHit[] CastBodyTrayectory( + Vector3 startPosition, + Vector3 direction, + float skinWidth, + float moveMagnitude, + int layerMask, + CapsuleData cachedCapsule + ) { + Vector3 startPositionBoxCenter = + startPosition + + this.transform.TransformDirection(this.boxBounds.agentRelativeCenter); return Physics.BoxCastAll( center: startPositionBoxCenter, @@ -134,8 +142,7 @@ public Vector3 GetTrueSizeOfBoxCollider(BoxCollider collider) { Transform currentTransform = collider.transform; // Apply the scale from the collider's transform and all parent transforms - while (currentTransform != null) - { + while (currentTransform != null) { trueSize.x *= currentTransform.localScale.x; trueSize.y *= currentTransform.localScale.y; trueSize.z *= currentTransform.localScale.z; @@ -147,13 +154,11 @@ public Vector3 GetTrueSizeOfBoxCollider(BoxCollider collider) { return trueSize; } - //override so we can access to fpin specific stuff public override MetadataWrapper generateMetadataWrapper() { - //get all the usual stuff from base agent's implementation MetadataWrapper metaWrap = base.generateMetadataWrapper(); - + //here's the fpin specific stuff if (boxBounds != null) { //get from BoxBounds as box world center will update as agent moves so we can't cache it @@ -167,9 +172,7 @@ public override MetadataWrapper generateMetadataWrapper() { return metaWrap; } - public List SamplePointsOnNavMesh( - int sampleCount, float maxDistance - ) { + public List SamplePointsOnNavMesh(int sampleCount, float maxDistance) { float minX = agentManager.SceneBounds.min.x; float minZ = agentManager.SceneBounds.min.z; float maxX = agentManager.SceneBounds.max.x; @@ -177,20 +180,21 @@ public List SamplePointsOnNavMesh( Debug.Log($"Scene bounds: X: {minX} z: {minZ} max x: {maxX} z: {maxZ}"); - int n = (int) Mathf.Ceil(Mathf.Sqrt(sampleCount)); + int n = (int)Mathf.Ceil(Mathf.Sqrt(sampleCount)); List initPoints = new List(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { - initPoints.Add(new Vector3( - Mathf.Lerp(minX, maxX, (i + 0.5f) / n), - 0f, - Mathf.Lerp(minZ, maxZ, (j + 0.5f) / n) - )); + initPoints.Add( + new Vector3( + Mathf.Lerp(minX, maxX, (i + 0.5f) / n), + 0f, + Mathf.Lerp(minZ, maxZ, (j + 0.5f) / n) + ) + ); } } initPoints.Shuffle_(); - List pointsOnMesh = new List(); for (int i = 0; i < initPoints.Count; i++) { @@ -202,7 +206,12 @@ public List SamplePointsOnNavMesh( Vector3 randomPoint = initPoints[i]; if (NavMesh.SamplePosition(randomPoint, out hit, maxDistance, NavMesh.AllAreas)) { # if UNITY_EDITOR - Debug.DrawLine(hit.position, hit.position + new Vector3(0f, 0.1f, 0f), Color.cyan, 15f); + Debug.DrawLine( + hit.position, + hit.position + new Vector3(0f, 0.1f, 0f), + Color.cyan, + 15f + ); # endif pointsOnMesh.Add(hit.position); } @@ -223,7 +232,7 @@ public void RandomlyPlaceAgentOnNavMesh(int n = 200, float maxDistance = 0.1f) { foreach (Collider c in GetComponentsInChildren()) { b.Encapsulate(c.bounds); } - + //Debug.Log($"current transform.position.y: {transform.position.y}"); float yOffset = 0.001f + transform.position.y - b.min.y; //Debug.Log($"yOffset is: {yOffset}"); @@ -248,15 +257,14 @@ public void RandomlyPlaceAgentOnNavMesh(int n = 200, float maxDistance = 0.1f) { } public void spawnAgentBoxCollider( - GameObject agent, + GameObject agent, Type agentType, Vector3 originalPosition, Quaternion originalRotation, Bounds agentBounds, bool useVisibleColliderBase = false, bool spawnCollidersWithoutMesh = false - ) { - + ) { //create colliders based on the agent bounds var col = new GameObject("fpinCollider", typeof(BoxCollider)); col.layer = LayerMask.NameToLayer("Agent"); @@ -267,24 +275,31 @@ public void spawnAgentBoxCollider( tCol.layer = LayerMask.NameToLayer("Agent"); spawnedTriggerBoxCollider = tCol.GetComponent(); spawnedTriggerBoxCollider.isTrigger = true; - + //move both of these colliders to the bounds center - spawnedBoxCollider.transform.position = spawnedTriggerBoxCollider.transform.position = agentBounds.center; - spawnedBoxCollider.transform.rotation = spawnedTriggerBoxCollider.transform.rotation = Quaternion.identity; + spawnedBoxCollider.transform.position = spawnedTriggerBoxCollider.transform.position = + agentBounds.center; + spawnedBoxCollider.transform.rotation = spawnedTriggerBoxCollider.transform.rotation = + Quaternion.identity; //parent these colliders to the viscap really quick, so if we scale the fpinVisibilityCapsule later it all stays the same - spawnedBoxCollider.transform.parent = spawnedTriggerBoxCollider.transform.parent = fpinVisibilityCapsule.transform; - + spawnedBoxCollider.transform.parent = spawnedTriggerBoxCollider.transform.parent = + fpinVisibilityCapsule.transform; + //calculate collider size based on what the size of the bounds of the mesh are - Vector3 colliderSize = new Vector3(agentBounds.size.x, agentBounds.size.y, agentBounds.size.z); + Vector3 colliderSize = new Vector3( + agentBounds.size.x, + agentBounds.size.y, + agentBounds.size.z + ); spawnedBoxCollider.size = spawnedTriggerBoxCollider.size = colliderSize; - + return; } //helper function to remove the currently generated agent box collider //make sure to follow this up with a subsequent generation so BoxBounds isn't left null - public void destroyAgentBoxCollider(){ + public void destroyAgentBoxCollider() { GameObject visibleBox = GameObject.Find("VisibleBox"); if (spawnedBoxCollider != null) { UnityEngine.Object.DestroyImmediate(spawnedBoxCollider.transform.gameObject); @@ -297,12 +312,12 @@ public void destroyAgentBoxCollider(){ if (visibleBox != null) { UnityEngine.Object.DestroyImmediate(visibleBox); } - #if UNITY_EDITOR +#if UNITY_EDITOR GameObject visualizedBoxCollider = GameObject.Find("VisualizedBoxCollider"); if (visualizedBoxCollider != null) { UnityEngine.Object.DestroyImmediate(visualizedBoxCollider); } - #endif +#endif //clear out any leftover values for BoxBounds just in case BoxBounds = null; @@ -311,7 +326,11 @@ public void destroyAgentBoxCollider(){ return; } - private Transform CopyMeshChildrenRecursive(Transform sourceTransform, Transform targetTransform, bool isTopMost = true) { + private Transform CopyMeshChildrenRecursive( + Transform sourceTransform, + Transform targetTransform, + bool isTopMost = true + ) { Transform thisTransform = null; foreach (Transform child in sourceTransform) { GameObject copiedChild = null; @@ -323,7 +342,10 @@ private Transform CopyMeshChildrenRecursive(Transform sourceTransform, Transform // Process children only if necessary (i.e., they contain MeshFilters) if (HasMeshInChildrenOrSelf(child)) { - Transform parentForChildren = (copiedChild != null) ? copiedChild.transform : CreateContainerForHierarchy(child, targetTransform).transform; + Transform parentForChildren = + (copiedChild != null) + ? copiedChild.transform + : CreateContainerForHierarchy(child, targetTransform).transform; CopyMeshChildrenRecursive(child, parentForChildren, false); if (isTopMost) { thisTransform = parentForChildren; @@ -371,7 +393,7 @@ private bool HasMeshInChildrenOrSelf(Transform transform) { return true; } } - + if (transform.GetComponent() != null) { return true; } @@ -388,7 +410,10 @@ private GameObject CreateContainerForHierarchy(Transform child, Transform target return container; } - private HashSet TransformedMeshRendererVertices(MeshRenderer mr, bool returnFirstVertexOnly = false) { + private HashSet TransformedMeshRendererVertices( + MeshRenderer mr, + bool returnFirstVertexOnly = false + ) { MeshFilter mf = mr.gameObject.GetComponent(); Matrix4x4 localToWorld = mr.transform.localToWorldMatrix; HashSet vertices = new HashSet(mf.sharedMesh.vertices); @@ -400,24 +425,22 @@ private HashSet TransformedMeshRendererVertices(MeshRenderer mr, bool r } public ActionFinished GetBoxBounds() { - return new ActionFinished() { - success = true, - actionReturn = this.BoxBounds - }; + return new ActionFinished() { success = true, actionReturn = this.BoxBounds }; } - public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles) - { + public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angles) { // Move the point to the pivot's origin - Vector3 dir = point - pivot; + Vector3 dir = point - pivot; // Rotate it - dir = Quaternion.Euler(angles) * dir; + dir = Quaternion.Euler(angles) * dir; // Move it back - point = dir + pivot; + point = dir + pivot; return point; } - - public ActionFinished BackwardsCompatibleInitialize(BackwardsCompatibleInitializeParams args) { + + public ActionFinished BackwardsCompatibleInitialize( + BackwardsCompatibleInitializeParams args + ) { Debug.Log("RUNNING BackCompatInitialize from FpinAgentController.cs"); // limit camera from looking too far down/up //default max are 30 up and 60 down, different agent types may overwrite this @@ -483,28 +506,33 @@ public ActionFinished BackwardsCompatibleInitialize(BackwardsCompatibleInitializ this.rotateStepDegrees = args.rotateStepDegrees; } - if (args.snapToGrid && !ValidRotateStepDegreesWithSnapToGrid(args.rotateStepDegrees)) { - errorMessage = $"Invalid values 'rotateStepDegrees': ${args.rotateStepDegrees} and 'snapToGrid':${args.snapToGrid}. 'snapToGrid': 'True' is not supported when 'rotateStepDegrees' is different from grid rotation steps of 0, 90, 180, 270 or 360."; + if (args.snapToGrid && !ValidRotateStepDegreesWithSnapToGrid(args.rotateStepDegrees)) { + errorMessage = + $"Invalid values 'rotateStepDegrees': ${args.rotateStepDegrees} and 'snapToGrid':${args.snapToGrid}. 'snapToGrid': 'True' is not supported when 'rotateStepDegrees' is different from grid rotation steps of 0, 90, 180, 270 or 360."; Debug.Log(errorMessage); return new ActionFinished(success: false, errorMessage: errorMessage); } - if(args.maxDownwardLookAngle < 0) { + if (args.maxDownwardLookAngle < 0) { errorMessage = "maxDownwardLookAngle must be a non-negative float"; Debug.Log(errorMessage); return new ActionFinished(success: false, errorMessage: errorMessage); } - if(args.maxUpwardLookAngle < 0) { + if (args.maxUpwardLookAngle < 0) { errorMessage = "maxUpwardLookAngle must be a non-negative float"; Debug.Log(errorMessage); return new ActionFinished(success: false, errorMessage: errorMessage); } - this.snapToGrid = args.snapToGrid; - if (args.renderDepthImage || args.renderSemanticSegmentation || args.renderInstanceSegmentation || args.renderNormalsImage) { + if ( + args.renderDepthImage + || args.renderSemanticSegmentation + || args.renderInstanceSegmentation + || args.renderNormalsImage + ) { this.updateImageSynthesis(true); } @@ -518,7 +546,11 @@ public ActionFinished BackwardsCompatibleInitialize(BackwardsCompatibleInitializ if (collider != null && navmeshAgent != null) { navmeshAgent.radius = collider.radius; navmeshAgent.height = collider.height; - navmeshAgent.transform.localPosition = new Vector3(navmeshAgent.transform.localPosition.x, navmeshAgent.transform.localPosition.y, collider.center.z); + navmeshAgent.transform.localPosition = new Vector3( + navmeshAgent.transform.localPosition.x, + navmeshAgent.transform.localPosition.y, + collider.center.z + ); } // navmeshAgent.radius = @@ -539,17 +571,22 @@ public ActionFinished BackwardsCompatibleInitialize(BackwardsCompatibleInitializ // Debug.Log("Object " + action.controllerInitialization.ToString() + " dict " + (action.controllerInitialization.variableInitializations == null));//+ string.Join(";", action.controllerInitialization.variableInitializations.Select(x => x.Key + "=" + x.Value).ToArray())); - this.visibilityScheme = ServerAction.GetVisibilitySchemeFromString(args.visibilityScheme); + this.visibilityScheme = ServerAction.GetVisibilitySchemeFromString( + args.visibilityScheme + ); // this.originalLightingValues = null; // Physics.autoSimulation = true; // Debug.Log("True if physics is auto-simulating: " + Physics.autoSimulation); this.AgentHand.gameObject.SetActive(false); - return new ActionFinished(success: true, actionReturn: new InitializeReturn { - cameraNearPlane = m_Camera.nearClipPlane, - cameraFarPlane = m_Camera.farClipPlane - }); + return new ActionFinished( + success: true, + actionReturn: new InitializeReturn { + cameraNearPlane = m_Camera.nearClipPlane, + cameraFarPlane = m_Camera.farClipPlane + } + ); } public ActionFinished Initialize( @@ -557,11 +594,10 @@ public ActionFinished Initialize( // TODO: do we want to allow non relative to the box offsets? float originOffsetX = 0.0f, float originOffsetZ = 0.0f, - Vector3? colliderScaleRatio = null, - bool useAbsoluteSize = false, + Vector3? colliderScaleRatio = null, + bool useAbsoluteSize = false, bool useVisibleColliderBase = false ) { - this.visibilityScheme = VisibilityScheme.Distance; var actionFinished = this.InitializeBody( bodyAsset: bodyAsset, @@ -585,12 +621,12 @@ public ActionFinished InitializeBody( bool useVisibleColliderBase = false ) { // if using no source body mesh, we default to using absolute size via the colliderScaleRatio - // since a non absolute size doesn't make sense if we have no default mesh size to base the scale + // since a non absolute size doesn't make sense if we have no default mesh size to base the scale // ratio on Vector3 meshScaleRatio = colliderScaleRatio.GetValueOrDefault(Vector3.one); bool noMesh = false; - if(bodyAsset == null) { + if (bodyAsset == null) { useAbsoluteSize = true; noMesh = true; } @@ -598,7 +634,7 @@ public ActionFinished InitializeBody( // Store the current rotation Vector3 originalPosition = this.transform.position; Quaternion originalRotation = this.transform.rotation; - + // Move the agent to a safe place and temporarily align the agent's rotation with the world coordinate system (i.e. zero it out) this.transform.position = originalPosition + agentSpawnOffset; this.transform.rotation = Quaternion.identity; @@ -612,7 +648,7 @@ public ActionFinished InitializeBody( var spawnAssetActionFinished = new ActionFinished(); Bounds meshBoundsWorld = new Bounds(this.transform.position, Vector3.zero); - if(bodyAsset != null) { + if (bodyAsset != null) { //spawn in a default mesh in an out-of-the-way location (currently 200,200,200) to base the new bounds on spawnAssetActionFinished = spawnBodyAsset(bodyAsset, out GameObject spawnedMesh); // Return early if spawn failed @@ -621,14 +657,18 @@ public ActionFinished InitializeBody( } // duplicate the entire mesh hierarchy from "agentMesh" to "FPSController" (with all of the local-transforms intact), and return top-level transform - topMeshTransform = CopyMeshChildrenRecursive(sourceTransform: spawnedMesh.transform, targetTransform: this.transform); + topMeshTransform = CopyMeshChildrenRecursive( + sourceTransform: spawnedMesh.transform, + targetTransform: this.transform + ); // get unscaled bounds of mesh // we need a bounds-center to start from that is guaranteed to fall inside of the mesh's geometry, // so we'll take the bounds-center of the first meshRenderer - MeshRenderer[] meshRenderers = topMeshTransform.gameObject.GetComponentsInChildren(); - foreach(MeshRenderer mr in meshRenderers) { + MeshRenderer[] meshRenderers = + topMeshTransform.gameObject.GetComponentsInChildren(); + foreach (MeshRenderer mr in meshRenderers) { // No need to run TransformedMeshRendererVertices if the meshRenderer's GameObject isn't rotated if (mr.transform.eulerAngles.magnitude < 1e-4f) { meshBoundsWorld.Encapsulate(mr.bounds); @@ -646,15 +686,19 @@ public ActionFinished InitializeBody( topMeshTransform.GetChild(0).position = currentTopMeshTransformChildPos; if (useAbsoluteSize) { - topMeshTransform.localScale = new Vector3(meshScaleRatio.x / meshBoundsWorld.size.x, - meshScaleRatio.y / meshBoundsWorld.size.y, - meshScaleRatio.z / meshBoundsWorld.size.z); + topMeshTransform.localScale = new Vector3( + meshScaleRatio.x / meshBoundsWorld.size.x, + meshScaleRatio.y / meshBoundsWorld.size.y, + meshScaleRatio.z / meshBoundsWorld.size.z + ); meshBoundsWorld.size = meshScaleRatio; } else { topMeshTransform.localScale = meshScaleRatio; - meshBoundsWorld.size = new Vector3(meshScaleRatio.x * meshBoundsWorld.size.x, - meshScaleRatio.y * meshBoundsWorld.size.y, - meshScaleRatio.z * meshBoundsWorld.size.z); + meshBoundsWorld.size = new Vector3( + meshScaleRatio.x * meshBoundsWorld.size.x, + meshScaleRatio.y * meshBoundsWorld.size.y, + meshScaleRatio.z * meshBoundsWorld.size.z + ); } // Move the topMeshTransform by a Vector3 that closes the distance between the current bounds-center's @@ -663,7 +707,8 @@ public ActionFinished InitializeBody( // Move topMeshTransform so its bounds-footprint is centered on the FPSAgentController-origin topMeshTransform.position += Vector3.up * meshBoundsWorld.extents.y; // Now that meshBoundsWorld's position is no longer accurate, update it - meshBoundsWorld.center = this.transform.position + Vector3.up * meshBoundsWorld.extents.y; + meshBoundsWorld.center = + this.transform.position + Vector3.up * meshBoundsWorld.extents.y; // remove the spawned mesh cause we are done with it foreach (var sop in spawnedMesh.GetComponentsInChildren()) { @@ -674,7 +719,10 @@ public ActionFinished InitializeBody( UnityEngine.Object.DestroyImmediate(spawnedMesh); } } else { - meshBoundsWorld = new Bounds(this.transform.position + (Vector3.up * meshScaleRatio.y / 2), meshScaleRatio); + meshBoundsWorld = new Bounds( + this.transform.position + (Vector3.up * meshScaleRatio.y / 2), + meshScaleRatio + ); } // Create new "viscap" object to hold all the meshes and use it as the new pivot poitn for them @@ -698,7 +746,7 @@ public ActionFinished InitializeBody( agentBounds: meshBoundsWorld, useVisibleColliderBase: useVisibleColliderBase, spawnCollidersWithoutMesh: noMesh //if noMesh is true, we have no mesh so we need to spawn colliders without a mesh - ); + ); // spawn the visible collider base if we need to if (useVisibleColliderBase) { @@ -713,13 +761,18 @@ public ActionFinished InitializeBody( meshBoundsWorld.size.z ); // get the y-offset for how low we need to move the visible collider base so it is flush with the bottomost extents of the spawnedBoxCollider - float yOffset = visibleBase.GetComponent().bounds.min.y - meshBoundsWorld.min.y; + float yOffset = + visibleBase.GetComponent().bounds.min.y - meshBoundsWorld.min.y; // we have the offset now so lets set the local position for the visible base as needed visibleBase.transform.localPosition -= yOffset * Vector3.up; } // now lets reposition the agent origin with originOffsetX and originOffsetZ - fpinVisibilityCapsule.transform.position += new Vector3(-originOffsetX, 0, -originOffsetZ); + fpinVisibilityCapsule.transform.position += new Vector3( + -originOffsetX, + 0, + -originOffsetZ + ); // now that meshBoundsWorld's position is no longer accurate, update it meshBoundsWorld.center += new Vector3(-originOffsetX, 0, -originOffsetZ); @@ -729,7 +782,10 @@ public ActionFinished InitializeBody( characterController.center = boxCenter; // set the radius to fit inside the box, considering the smallest length, width, or height - float minRadius = Mathf.Min(Mathf.Min(meshBoundsWorld.extents.x, meshBoundsWorld.extents.z), meshBoundsWorld.extents.y); + float minRadius = Mathf.Min( + Mathf.Min(meshBoundsWorld.extents.x, meshBoundsWorld.extents.z), + meshBoundsWorld.extents.y + ); characterController.radius = minRadius; // adjust the capsule size based on the size of the bounds @@ -743,14 +799,22 @@ public ActionFinished InitializeBody( // ok recalibrate navmesh child component based on the new agent capsule now that its updated var navmeshchild = this.transform.GetComponentInChildren(); - navmeshchild.transform.localPosition = new Vector3(meshBoundsWorld.center.x - this.transform.position.x, 0.0f, meshBoundsWorld.center.z - this.transform.position.z); + navmeshchild.transform.localPosition = new Vector3( + meshBoundsWorld.center.x - this.transform.position.x, + 0.0f, + meshBoundsWorld.center.z - this.transform.position.z + ); navmeshchild.baseOffset = 0.0f; navmeshchild.height = boxHeight; navmeshchild.radius = minRadius; // ok now check if we were to teleport back to our original position and rotation.... // will our current box colliders clip with anything? If so, send a failure message - Vector3 boxCenterAtInitialTransform = RotatePointAroundPivot(meshBoundsWorld.center - agentSpawnOffset, originalPosition, originalRotation.eulerAngles); + Vector3 boxCenterAtInitialTransform = RotatePointAroundPivot( + meshBoundsWorld.center - agentSpawnOffset, + originalPosition, + originalRotation.eulerAngles + ); #if UNITY_EDITOR // ///////////////////////////////////////////////// @@ -761,7 +825,7 @@ public ActionFinished InitializeBody( cube.transform.rotation = originalRotation; cube.transform.localScale = meshBoundsWorld.size; cube.GetComponent().enabled = false; - + var material = cube.GetComponent().material; material.SetColor("_Color", new Color(1.0f, 0.0f, 0.0f, 0.4f)); // Set transparency XD ... @@ -777,17 +841,31 @@ public ActionFinished InitializeBody( #endif // used to check if there is enough free space given the generated colliders for the agent to return to its original pose - int checkBoxLayerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int checkBoxLayerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); // check if we were to teleport our agent back to its starting position, will the new box colliders generated clip with anything? // if we do clip with something, leave the agent where it is, and send a message saying there is clipping actively happening - // the reccomended thing to do here is either reset the scene entirely and load in with a new agent, or try and use `InitializeBody` with + // the reccomended thing to do here is either reset the scene entirely and load in with a new agent, or try and use `InitializeBody` with // a smaller mesh size that would potentially fit here Debug.Log($"{boxCenterAtInitialTransform:F5} and {meshBoundsWorld.extents:F5}"); - if (Physics.CheckBox(boxCenterAtInitialTransform, meshBoundsWorld.extents, originalRotation, checkBoxLayerMask)) { + if ( + Physics.CheckBox( + boxCenterAtInitialTransform, + meshBoundsWorld.extents, + originalRotation, + checkBoxLayerMask + ) + ) { this.transform.position = originalPosition; this.transform.rotation = originalRotation; - string error = "Spawned box collider is colliding with other objects. Cannot spawn box collider."; + string error = + "Spawned box collider is colliding with other objects. Cannot spawn box collider."; actionReturn = error; errorMessage = error; throw new InvalidOperationException(error); @@ -805,24 +883,29 @@ public ActionFinished InitializeBody( fpinMovable = new FpinMovableContinuous(this.GetComponentInParent()); // we had a body asset used, so actionFinished returns info related to that - if(bodyAsset != null){ + if (bodyAsset != null) { return new ActionFinished(spawnAssetActionFinished) { // TODO: change to a proper class once metadata return is defined - actionReturn = new Dictionary() { + actionReturn = new Dictionary() + { //objectSphereBounds... how is this being used??? currently if we scale the mesh asset this value may not be correct - {"objectSphereBounds", spawnAssetActionFinished.actionReturn as ObjectSphereBounds}, - {"BoxBounds", this.BoxBounds}, - {"cameraNearPlane", m_Camera.nearClipPlane}, - {"cameraFarPlane", m_Camera.farClipPlane} + { + "objectSphereBounds", + spawnAssetActionFinished.actionReturn as ObjectSphereBounds + }, + { "BoxBounds", this.BoxBounds }, + { "cameraNearPlane", m_Camera.nearClipPlane }, + { "cameraFarPlane", m_Camera.farClipPlane } } }; } else { return new ActionFinished() { // TODO: change to a proper class once metadata return is defined - actionReturn = new Dictionary() { - {"BoxBounds", this.BoxBounds}, - {"cameraNearPlane", m_Camera.nearClipPlane}, - {"cameraFarPlane", m_Camera.farClipPlane} + actionReturn = new Dictionary() + { + { "BoxBounds", this.BoxBounds }, + { "cameraNearPlane", m_Camera.nearClipPlane }, + { "cameraFarPlane", m_Camera.farClipPlane } } }; } @@ -831,18 +914,32 @@ public ActionFinished InitializeBody( private ActionFinished spawnBodyAsset(BodyAsset bodyAsset, out GameObject spawnedMesh) { if (bodyAsset == null) { throw new ArgumentNullException("bodyAsset is null"); + } else if ( + bodyAsset.assetId == null + && bodyAsset.dynamicAsset == null + && bodyAsset.asset == null + ) { + throw new ArgumentNullException( + "`bodyAsset.assetId`, `bodyAsset.dynamicAsset` or `bodyAsset.asset` must be provided all are null." + ); } - else if (bodyAsset.assetId == null && bodyAsset.dynamicAsset == null && bodyAsset.asset == null) { - throw new ArgumentNullException("`bodyAsset.assetId`, `bodyAsset.dynamicAsset` or `bodyAsset.asset` must be provided all are null."); - } - ActionFinished actionFinished = new ActionFinished(success: false, errorMessage: "No body specified"); + ActionFinished actionFinished = new ActionFinished( + success: false, + errorMessage: "No body specified" + ); spawnedMesh = null; - - if ( (bodyAsset.dynamicAsset != null || bodyAsset.asset != null) && bodyAsset.assetId == null) { - var id = bodyAsset.dynamicAsset != null ? bodyAsset.dynamicAsset.id : bodyAsset.asset.name; + + if ( + (bodyAsset.dynamicAsset != null || bodyAsset.asset != null) + && bodyAsset.assetId == null + ) { + var id = + bodyAsset.dynamicAsset != null + ? bodyAsset.dynamicAsset.id + : bodyAsset.asset.name; var assetMap = ProceduralTools.getAssetMap(); - // Check if asset is in AssetDatabase already + // Check if asset is in AssetDatabase already if (assetMap.ContainsKey(id)) { Debug.Log("------- Already contains key"); bodyAsset.assetId = id; @@ -850,11 +947,13 @@ private ActionFinished spawnBodyAsset(BodyAsset bodyAsset, out GameObject spawne } if (bodyAsset.assetId != null) { - actionFinished = SpawnAsset(bodyAsset.assetId, "agentMesh", new Vector3(200f, 200f, 200f)); + actionFinished = SpawnAsset( + bodyAsset.assetId, + "agentMesh", + new Vector3(200f, 200f, 200f) + ); spawnedMesh = GameObject.Find("agentMesh"); - } - - else if (bodyAsset.dynamicAsset != null) { + } else if (bodyAsset.dynamicAsset != null) { actionFinished = this.CreateRuntimeAsset( id: bodyAsset.dynamicAsset.id, dir: bodyAsset.dynamicAsset.dir, @@ -863,18 +962,22 @@ private ActionFinished spawnBodyAsset(BodyAsset bodyAsset, out GameObject spawne serializable: true ); spawnedMesh = GameObject.Find("mesh"); - } - else if (bodyAsset.asset != null) { + } else if (bodyAsset.asset != null) { bodyAsset.asset.serializable = true; - actionFinished = this.CreateRuntimeAsset( - asset: bodyAsset.asset - ); + actionFinished = this.CreateRuntimeAsset(asset: bodyAsset.asset); } - if (bodyAsset.assetId == null && (bodyAsset.dynamicAsset != null || bodyAsset.asset != null)) { - - var id = bodyAsset.dynamicAsset != null ? bodyAsset.dynamicAsset.id : bodyAsset.asset.name; - Debug.Log($"-- checks {bodyAsset.assetId == null} {bodyAsset.dynamicAsset != null} {bodyAsset.asset != null} "); + if ( + bodyAsset.assetId == null + && (bodyAsset.dynamicAsset != null || bodyAsset.asset != null) + ) { + var id = + bodyAsset.dynamicAsset != null + ? bodyAsset.dynamicAsset.id + : bodyAsset.asset.name; + Debug.Log( + $"-- checks {bodyAsset.assetId == null} {bodyAsset.dynamicAsset != null} {bodyAsset.asset != null} " + ); if (!actionFinished.success || actionFinished.actionReturn == null) { return new ActionFinished( success: false, @@ -883,16 +986,20 @@ private ActionFinished spawnBodyAsset(BodyAsset bodyAsset, out GameObject spawne } var assetData = actionFinished.actionReturn as Dictionary; Debug.Log($"-- dynamicAsset id: {id} keys {string.Join(", ", assetData.Keys)}"); - spawnedMesh = assetData["gameObject"] as GameObject;//.transform.Find("mesh").gameObject; + spawnedMesh = assetData["gameObject"] as GameObject; //.transform.Find("mesh").gameObject; } return actionFinished; } - protected override LayerMask GetVisibilityRaycastLayerMask(bool withSimObjInvisible = false) { // No agent because camera can be in the path of colliders - string[] layers = new string[] { - "SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0" //, "Agent" + string[] layers = new string[] + { + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" //, "Agent" }; if (withSimObjInvisible) { layers = layers.Append("SimObjInvisible").ToArray(); @@ -923,21 +1030,35 @@ protected override void teleportFull( bool forceAction ) { //Debug.Log($"what even is the position passed in at the start? {position:F8}"); - if (rotation.HasValue && (!Mathf.Approximately(rotation.Value.x, 0f) || !Mathf.Approximately(rotation.Value.z, 0f))) { + if ( + rotation.HasValue + && ( + !Mathf.Approximately(rotation.Value.x, 0f) + || !Mathf.Approximately(rotation.Value.z, 0f) + ) + ) { throw new ArgumentOutOfRangeException( - "No agents currently can change in pitch or roll. So, you must set rotation(x=0, y=yaw, z=0)." + - $" You gave {rotation.Value.ToString("F6")}." + "No agents currently can change in pitch or roll. So, you must set rotation(x=0, y=yaw, z=0)." + + $" You gave {rotation.Value.ToString("F6")}." ); } // recall that horizon=60 is look down 60 degrees and horizon=-30 is look up 30 degrees - if (!forceAction && horizon.HasValue && (horizon.Value > maxDownwardLookAngle || horizon.Value < -maxUpwardLookAngle)) { + if ( + !forceAction + && horizon.HasValue + && (horizon.Value > maxDownwardLookAngle || horizon.Value < -maxUpwardLookAngle) + ) { throw new ArgumentOutOfRangeException( $"Each horizon must be in [{-maxUpwardLookAngle}:{maxDownwardLookAngle}]. You gave {horizon}." ); } - if (!forceAction && position.HasValue && !agentManager.SceneBounds.Contains(position.Value)) { + if ( + !forceAction + && position.HasValue + && !agentManager.SceneBounds.Contains(position.Value) + ) { throw new ArgumentOutOfRangeException( $"Teleport position {position.Value.ToString("F6")} out of scene bounds! Ignore this by setting forceAction=true." ); @@ -968,11 +1089,17 @@ bool forceAction ); //we teleported the agent a little bit above the ground just so we are clear, now snap agent flush with the floor - this.assertTeleportedNearGround(targetPosition: position.GetValueOrDefault(transform.position)); + this.assertTeleportedNearGround( + targetPosition: position.GetValueOrDefault(transform.position) + ); if (!forceAction) { - - if (isAgentCapsuleColliding(collidersToIgnore: collidersToIgnoreDuringMovement, includeErrorMessage: true)) { + if ( + isAgentCapsuleColliding( + collidersToIgnore: collidersToIgnoreDuringMovement, + includeErrorMessage: true + ) + ) { transform.position = oldPosition; transform.rotation = oldRotation; autoSyncTransforms(); @@ -980,10 +1107,13 @@ bool forceAction throw new InvalidOperationException(errorMessage); } - if (isAgentBoxColliding( - transformWithBoxCollider: spawnedBoxCollider.transform, - collidersToIgnore: collidersToIgnoreDuringMovement, - includeErrorMessage: true)) { + if ( + isAgentBoxColliding( + transformWithBoxCollider: spawnedBoxCollider.transform, + collidersToIgnore: collidersToIgnoreDuringMovement, + includeErrorMessage: true + ) + ) { transform.position = oldPosition; transform.rotation = oldRotation; autoSyncTransforms(); @@ -991,7 +1121,7 @@ bool forceAction throw new InvalidOperationException(errorMessage); } } - + actionFinished(success: true); } @@ -1006,15 +1136,17 @@ protected override void assertTeleportedNearGround(Vector3? targetPosition) { // move otherwise the agent will end up in a different // location from the targetPosition autoSyncTransforms(); - m_CharacterController.Move(new Vector3(0f, Physics.gravity.y * this.m_GravityMultiplier, 0f)); + m_CharacterController.Move( + new Vector3(0f, Physics.gravity.y * this.m_GravityMultiplier, 0f) + ); autoSyncTransforms(); // perhaps like y=2 was specified, with an agent's standing height of 0.9 if (Mathf.Abs(transform.position.y - pos.y) > 1.0f) { throw new InvalidOperationException( - "After teleporting and adjusting agent position to floor, there was too large a change." + - " This may be due to the target teleport coordinates causing the agent to fall through the floor." + - $"({Mathf.Abs(transform.position.y - pos.y)} > 1.0f) in the y position." + "After teleporting and adjusting agent position to floor, there was too large a change." + + " This may be due to the target teleport coordinates causing the agent to fall through the floor." + + $"({Mathf.Abs(transform.position.y - pos.y)} > 1.0f) in the y position." ); } } diff --git a/unity/Assets/Scripts/FpinMovableContinuous.cs b/unity/Assets/Scripts/FpinMovableContinuous.cs index b811e0d9a5..fabefa08fb 100644 --- a/unity/Assets/Scripts/FpinMovableContinuous.cs +++ b/unity/Assets/Scripts/FpinMovableContinuous.cs @@ -3,48 +3,48 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public class FpinMovableContinuous: MovableContinuous { - public CollisionListener collisionListener { - get; - private set; - } - public FpinMovableContinuous(CollisionListener collisionListener) { - this.collisionListener = collisionListener; - } - public string GetHaltMessage() { - var staticCollisions = collisionListener?.StaticCollisions().ToList(); +public class FpinMovableContinuous : MovableContinuous { + public CollisionListener collisionListener { get; private set; } + + public FpinMovableContinuous(CollisionListener collisionListener) { + this.collisionListener = collisionListener; + } - if (staticCollisions.Count > 0) { - var sc = staticCollisions[0]; + public string GetHaltMessage() { + var staticCollisions = collisionListener?.StaticCollisions().ToList(); - // if we hit a sim object - if (sc.isSimObj) { - return "Collided with static/kinematic sim object: '" + sc.simObjPhysics.name + "', could not reach target."; - } + if (staticCollisions.Count > 0) { + var sc = staticCollisions[0]; - // if we hit a structural object that isn't a sim object but still has static collision - if (!sc.isSimObj) { - return "Collided with static structure in scene: '" + sc.gameObject.name + "', could not reach target."; - } + // if we hit a sim object + if (sc.isSimObj) { + return "Collided with static/kinematic sim object: '" + + sc.simObjPhysics.name + + "', could not reach target."; } - return ""; - } - public virtual bool ShouldHalt() { - return collisionListener.ShouldHalt(); + // if we hit a structural object that isn't a sim object but still has static collision + if (!sc.isSimObj) { + return "Collided with static structure in scene: '" + + sc.gameObject.name + + "', could not reach target."; + } } + return ""; + } - public virtual void ContinuousUpdate(float fixedDeltaTime) { - // Here would go the arm manipulation - } - - public virtual ActionFinished FinishContinuousMove(BaseFPSAgentController controller) { - bool actionSuccess = !this.ShouldHalt(); - string errorMessage = this.GetHaltMessage(); - - return new ActionFinished() { - success = actionSuccess, - errorMessage = errorMessage - }; - } - } \ No newline at end of file + public virtual bool ShouldHalt() { + return collisionListener.ShouldHalt(); + } + + public virtual void ContinuousUpdate(float fixedDeltaTime) { + // Here would go the arm manipulation + } + + public virtual ActionFinished FinishContinuousMove(BaseFPSAgentController controller) { + bool actionSuccess = !this.ShouldHalt(); + string errorMessage = this.GetHaltMessage(); + + return new ActionFinished() { success = actionSuccess, errorMessage = errorMessage }; + } +} diff --git a/unity/Assets/Scripts/FrameCollider.cs b/unity/Assets/Scripts/FrameCollider.cs index 16bacb9c04..b8287ff850 100644 --- a/unity/Assets/Scripts/FrameCollider.cs +++ b/unity/Assets/Scripts/FrameCollider.cs @@ -2,11 +2,10 @@ using System.Collections.Generic; using UnityEngine; - // Maintains rotation based on the myObject object, which is the door of the sim object. This ensures that for any given -// cabinet shape, the cabinet can remain "visible" even when the door is out of frame. +// cabinet shape, the cabinet can remain "visible" even when the door is out of frame. -// to use: Put this prefab in the "TriggerColliders" section of the cabinet +// to use: Put this prefab in the "TriggerColliders" section of the cabinet // rotate the CabinetDoor main sim object to an open position, and then rotate this object to that same position but opposite sign (ie:90, -90) // Move the four fCol objects so that the camera of the agent can raycast to them when the door is open and out of frame. These fCol objects should @@ -14,19 +13,21 @@ public class FrameCollider : MonoBehaviour { public Transform myObject; + // Use this for initialization void Start() { myObject = gameObject.GetComponentInParent().transform; - } // Update is called once per frame void Update() { - // so we need to constantly update the rotation of this object so that the colliders stay in the right place. - // unforunately we couldnt' just unparent them from the door because the door has the rigidbody, and if they were unparented then the + // unforunately we couldnt' just unparent them from the door because the door has the rigidbody, and if they were unparented then the // compound box collider would not propogate up to the rigidbody for visibility detection, so here we are this seems to work! - gameObject.transform.localEulerAngles = new Vector3(0, -myObject.transform.localEulerAngles.y, 0); - + gameObject.transform.localEulerAngles = new Vector3( + 0, + -myObject.transform.localEulerAngles.y, + 0 + ); } } diff --git a/unity/Assets/Scripts/FreezeObject.cs b/unity/Assets/Scripts/FreezeObject.cs index 415c2b525e..7cfe23f2d5 100644 --- a/unity/Assets/Scripts/FreezeObject.cs +++ b/unity/Assets/Scripts/FreezeObject.cs @@ -1,6 +1,5 @@ -using UnityEngine; using System.Collections; - +using UnityEngine; [ExecuteInEditMode] public class FreezeObject : MonoBehaviour { @@ -8,17 +7,18 @@ public class FreezeObject : MonoBehaviour { public bool FreezePosition = false; public bool FreezeRotation = false; - private Space m_OldSpace = Space.World; private bool m_OldFreezePosition = false; private bool m_OldFreezeRotation = false; private Vector3 m_Position = Vector3.zero; private Quaternion m_Rotation = Quaternion.identity; + void Awake() { if (Application.isPlaying) { Destroy(this); } } + void Update() { if (!Application.isEditor) { Destroy(this); @@ -54,5 +54,4 @@ void Update() { m_OldFreezePosition = FreezePosition; m_OldFreezeRotation = FreezeRotation; } - -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/Fridge.cs b/unity/Assets/Scripts/Fridge.cs index d77f4f87e7..36893251aa 100644 --- a/unity/Assets/Scripts/Fridge.cs +++ b/unity/Assets/Scripts/Fridge.cs @@ -1,9 +1,8 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; public class Fridge : MonoBehaviour { - public SimObj ParentObj; public Transform[] Doors; @@ -47,13 +46,27 @@ void Update() { Quaternion doorStartRotation = Doors[i].rotation; Doors[i].localEulerAngles = doorTargetRotation; doorTargetRotation = Doors[i].localEulerAngles; - Doors[i].rotation = Quaternion.RotateTowards(doorStartRotation, Doors[i].rotation, Time.deltaTime * SimUtil.SmoothAnimationSpeed * 25); - distanceToTarget = Mathf.Max(distanceToTarget, Vector3.Distance(Doors[i].localEulerAngles, doorTargetRotation)); + Doors[i].rotation = Quaternion.RotateTowards( + doorStartRotation, + Doors[i].rotation, + Time.deltaTime * SimUtil.SmoothAnimationSpeed * 25 + ); + distanceToTarget = Mathf.Max( + distanceToTarget, + Vector3.Distance(Doors[i].localEulerAngles, doorTargetRotation) + ); } for (int i = 0; i < Drawers.Length; i++) { drawerTargetPosition = open ? OpenPositions[i] : ClosedPositions[i]; - Drawers[i].localPosition = Vector3.Lerp(Drawers[i].localPosition, drawerTargetPosition, Time.deltaTime * SimUtil.SmoothAnimationSpeed); - distanceToTarget = Mathf.Max(distanceToTarget, Vector3.Distance(Doors[i].localPosition, drawerTargetPosition)); + Drawers[i].localPosition = Vector3.Lerp( + Drawers[i].localPosition, + drawerTargetPosition, + Time.deltaTime * SimUtil.SmoothAnimationSpeed + ); + distanceToTarget = Mathf.Max( + distanceToTarget, + Vector3.Distance(Doors[i].localPosition, drawerTargetPosition) + ); } if (distanceToTarget >= 360f) { diff --git a/unity/Assets/Scripts/GenerateRoboTHOR.cs b/unity/Assets/Scripts/GenerateRoboTHOR.cs index 72e5dfdb91..9d925df97f 100644 --- a/unity/Assets/Scripts/GenerateRoboTHOR.cs +++ b/unity/Assets/Scripts/GenerateRoboTHOR.cs @@ -38,16 +38,15 @@ public class GenerateRoboTHOR : MonoBehaviour { protected WallCell[,] wallCells; protected int cellsVisited; - protected int xWalls, zWalls; + protected int xWalls, + zWalls; protected int boundaryPadding; protected Transform wallParent; protected Transform floorParent; protected Transform structure; protected float[] validStartingAgentRotations = new float[] { 0, 90, 180, 270 }; - protected string[] validOrientations = new string[] { - "left", "right", "top", "bottom" - }; + protected string[] validOrientations = new string[] { "left", "right", "top", "bottom" }; protected class WallCell { public bool visited; @@ -57,13 +56,7 @@ protected class WallCell { * Walls are null if they are boundary walls. That is, * they are unable to be toggled on or off. */ - public WallCell( - bool visited, - bool? left, - bool? right, - bool? top, - bool? bottom - ) { + public WallCell(bool visited, bool? left, bool? right, bool? top, bool? bottom) { this.visited = visited; this.walls = new Dictionary { ["left"] = left, @@ -78,9 +71,13 @@ public WallCell( // null if all neighbors have been visited. protected (int, int)? VisitCell(int xGridCell, int zGridCell) { if (xGridCell < 0 || xGridCell >= xWalls) { - throw new ArgumentOutOfRangeException($"xGridCell must be in [0:xWalls), not {xGridCell}"); + throw new ArgumentOutOfRangeException( + $"xGridCell must be in [0:xWalls), not {xGridCell}" + ); } else if (zGridCell < 0 || zGridCell >= zWalls) { - throw new ArgumentOutOfRangeException($"zGridCell must be in [0:zWalls), not {zGridCell}"); + throw new ArgumentOutOfRangeException( + $"zGridCell must be in [0:zWalls), not {zGridCell}" + ); } if (!wallCells[xGridCell, zGridCell].visited) { @@ -128,9 +125,13 @@ public WallCell( */ protected (int, int)? GetNeighbor(int xGridCell, int zGridCell, string orientation) { if (xGridCell < 0 || xGridCell >= xWalls) { - throw new ArgumentOutOfRangeException($"xGridCell must be in [0:xWalls), not {xGridCell}"); + throw new ArgumentOutOfRangeException( + $"xGridCell must be in [0:xWalls), not {xGridCell}" + ); } else if (zGridCell < 0 || zGridCell >= zWalls) { - throw new ArgumentOutOfRangeException($"zGridCell must be in [0:zWalls), not {zGridCell}"); + throw new ArgumentOutOfRangeException( + $"zGridCell must be in [0:zWalls), not {zGridCell}" + ); } if (!wallCells[xGridCell, zGridCell].walls[orientation].HasValue) { @@ -168,7 +169,11 @@ public WallCell( /** * Returns the position of the neighbor. If the neighbor is out of bounds, null is returned. */ - protected (int, int)? RemoveNeighborWallBoundary(int xGridCell, int zGridCell, string orientation) { + protected (int, int)? RemoveNeighborWallBoundary( + int xGridCell, + int zGridCell, + string orientation + ) { (int, int)? neighbor = GetNeighbor( xGridCell: xGridCell, zGridCell: zGridCell, @@ -202,27 +207,27 @@ public WallCell( */ protected Vector3 GetWallGridPointCenter(int xGridCell, int zGridCell) { if (xGridCell < 0 || xGridCell >= xWalls) { - throw new ArgumentOutOfRangeException($"xGridCell must be in [0:xWalls), not {xGridCell}"); + throw new ArgumentOutOfRangeException( + $"xGridCell must be in [0:xWalls), not {xGridCell}" + ); } else if (zGridCell < 0 || zGridCell >= zWalls) { - throw new ArgumentOutOfRangeException($"zGridCell must be in [0:zWalls), not {zGridCell}"); + throw new ArgumentOutOfRangeException( + $"zGridCell must be in [0:zWalls), not {zGridCell}" + ); } float xPos = ( xWalls % 2 == 1 - ? wallCenterX + wallPanelWidth * (xGridCell - xWalls / 2) - wallPanelWidth / 2 - : wallCenterX + wallPanelWidth * (xGridCell - (xWalls - 1) / 2 - 1) + ? wallCenterX + wallPanelWidth * (xGridCell - xWalls / 2) - wallPanelWidth / 2 + : wallCenterX + wallPanelWidth * (xGridCell - (xWalls - 1) / 2 - 1) ); float zPos = ( zWalls % 2 == 1 - ? wallCenterZ - wallPanelWidth * (zGridCell - zWalls / 2) + wallPanelWidth / 2 - : wallCenterZ - wallPanelWidth * (zGridCell - (zWalls - 1) / 2 - 1) + ? wallCenterZ - wallPanelWidth * (zGridCell - zWalls / 2) + wallPanelWidth / 2 + : wallCenterZ - wallPanelWidth * (zGridCell - (zWalls - 1) / 2 - 1) ); - return new Vector3( - x: xPos, - y: wallCenterY, - z: zPos - ); + return new Vector3(x: xPos, y: wallCenterY, z: zPos); } /** @@ -231,9 +236,13 @@ protected Vector3 GetWallGridPointCenter(int xGridCell, int zGridCell) { */ protected Vector3 GetAgentGridPointCenter(int xGridCell, int zGridCell) { if (xGridCell < 0 || xGridCell >= xWalls) { - throw new ArgumentOutOfRangeException($"xGridCell must be in [0:xWalls), not {xGridCell}"); + throw new ArgumentOutOfRangeException( + $"xGridCell must be in [0:xWalls), not {xGridCell}" + ); } else if (zGridCell < 0 || zGridCell >= zWalls) { - throw new ArgumentOutOfRangeException($"zGridCell must be in [0:zWalls), not {zGridCell}"); + throw new ArgumentOutOfRangeException( + $"zGridCell must be in [0:zWalls), not {zGridCell}" + ); } float agentCenterX = 5.387f; @@ -241,22 +250,22 @@ protected Vector3 GetAgentGridPointCenter(int xGridCell, int zGridCell) { float xPos = ( xWalls % 2 == 1 - ? agentCenterX + wallPanelWidth * (xGridCell - xWalls / 2) - : agentCenterX + wallPanelWidth * (xGridCell - (xWalls - 1) / 2 - 1) + wallPanelWidth / 2 + ? agentCenterX + wallPanelWidth * (xGridCell - xWalls / 2) + : agentCenterX + + wallPanelWidth * (xGridCell - (xWalls - 1) / 2 - 1) + + wallPanelWidth / 2 ); float zPos = ( zWalls % 2 == 1 - ? agentCenterZ - wallPanelWidth * (zGridCell - zWalls / 2) - : agentCenterZ - wallPanelWidth * (zGridCell - (zWalls - 1) / 2 - 1) - wallPanelWidth / 2 + ? agentCenterZ - wallPanelWidth * (zGridCell - zWalls / 2) + : agentCenterZ + - wallPanelWidth * (zGridCell - (zWalls - 1) / 2 - 1) + - wallPanelWidth / 2 ); // These are the empirical center position of the agent. // They don't need to be super precise because the position is rounded. - return new Vector3( - x: xPos, - y: 0.9009997f, - z: zPos - ); + return new Vector3(x: xPos, y: 0.9009997f, z: zPos); } /** @@ -298,7 +307,10 @@ protected void PlaceWall(Vector3 gridPointCenter, string orientation) { * Place a single wall at a position and orientation. */ protected void PlaceWall(int xGridCell, int zGridCell, string orientation) { - Vector3 gridPointCenter = GetWallGridPointCenter(xGridCell: xGridCell, zGridCell: zGridCell); + Vector3 gridPointCenter = GetWallGridPointCenter( + xGridCell: xGridCell, + zGridCell: zGridCell + ); PlaceWall(gridPointCenter: gridPointCenter, orientation: orientation); } @@ -329,16 +341,17 @@ protected void AddOuterWalls() { GameObject wall; // side 1 - wall = Instantiate( - original: outerWallPrefab, - parent: floorParent, - position: new Vector3( - x: wallCenterX, - y: 1.298f, - z: wallCenterZ + (float)(zWalls + boundaryPadding * 2) / 2 - ), - rotation: Quaternion.identity - ) as GameObject; + wall = + Instantiate( + original: outerWallPrefab, + parent: floorParent, + position: new Vector3( + x: wallCenterX, + y: 1.298f, + z: wallCenterZ + (float)(zWalls + boundaryPadding * 2) / 2 + ), + rotation: Quaternion.identity + ) as GameObject; wall.transform.localScale = new Vector3( x: xWalls + boundaryPadding * 2, y: wall.transform.localScale.y, @@ -346,16 +359,17 @@ protected void AddOuterWalls() { ); // side 2 - wall = Instantiate( - original: outerWallPrefab, - parent: floorParent, - position: new Vector3( - x: wallCenterX, - y: 1.298f, - z: wallCenterZ - (float)(zWalls + boundaryPadding * 2) / 2 - ), - rotation: Quaternion.Euler(0, 180, 0) - ) as GameObject; + wall = + Instantiate( + original: outerWallPrefab, + parent: floorParent, + position: new Vector3( + x: wallCenterX, + y: 1.298f, + z: wallCenterZ - (float)(zWalls + boundaryPadding * 2) / 2 + ), + rotation: Quaternion.Euler(0, 180, 0) + ) as GameObject; wall.transform.localScale = new Vector3( x: xWalls + boundaryPadding * 2, y: wall.transform.localScale.y, @@ -363,16 +377,17 @@ protected void AddOuterWalls() { ); // side 3 - wall = Instantiate( - original: outerWallPrefab, - parent: floorParent, - position: new Vector3( - x: wallCenterX - (float)(xWalls + boundaryPadding * 2) / 2, - y: 1.298f, - z: wallCenterZ - ), - rotation: Quaternion.Euler(0, -90, 0) - ) as GameObject; + wall = + Instantiate( + original: outerWallPrefab, + parent: floorParent, + position: new Vector3( + x: wallCenterX - (float)(xWalls + boundaryPadding * 2) / 2, + y: 1.298f, + z: wallCenterZ + ), + rotation: Quaternion.Euler(0, -90, 0) + ) as GameObject; wall.transform.localScale = new Vector3( x: zWalls + boundaryPadding * 2, y: wall.transform.localScale.y, @@ -380,16 +395,17 @@ protected void AddOuterWalls() { ); // side 4 - wall = Instantiate( - original: outerWallPrefab, - parent: floorParent, - position: new Vector3( - x: wallCenterX + (float)(xWalls + boundaryPadding * 2) / 2, - y: 1.298f, - z: wallCenterZ - ), - rotation: Quaternion.Euler(0, 90, 0) - ) as GameObject; + wall = + Instantiate( + original: outerWallPrefab, + parent: floorParent, + position: new Vector3( + x: wallCenterX + (float)(xWalls + boundaryPadding * 2) / 2, + y: 1.298f, + z: wallCenterZ + ), + rotation: Quaternion.Euler(0, 90, 0) + ) as GameObject; wall.transform.localScale = new Vector3( x: zWalls + boundaryPadding * 2, y: wall.transform.localScale.y, @@ -408,9 +424,13 @@ protected void PlaceCeilings() { original: ceilingPrefab, parent: structure, position: new Vector3( - x: ceilingCenterX + ceilingSizeX * (x - (float)xCeilings / 2) + ceilingSizeX / 2, + x: ceilingCenterX + + ceilingSizeX * (x - (float)xCeilings / 2) + + ceilingSizeX / 2, y: ceilingCenterY, - z: ceilingCenterZ + ceilingSizeZ * (z - (float)zCeilings / 2) + ceilingSizeZ / 2 + z: ceilingCenterZ + + ceilingSizeZ * (z - (float)zCeilings / 2) + + ceilingSizeZ / 2 ), rotation: Quaternion.identity ); @@ -520,13 +540,18 @@ public void GenerateConfig( int agentXCell = Random.Range(0, xWalls); int agentZCell = Random.Range(0, zWalls); Vector3 agentPosition = GetAgentGridPointCenter( - xGridCell: agentXCell, zGridCell: agentZCell + xGridCell: agentXCell, + zGridCell: agentZCell ); agentPosition.y = agentTransform.position.y; agentTransform.position = agentPosition; // change agent rotation int startRotationI = Random.Range(0, validStartingAgentRotations.Length); - agentTransform.localEulerAngles = new Vector3(0, validStartingAgentRotations[startRotationI], 0); + agentTransform.localEulerAngles = new Vector3( + 0, + validStartingAgentRotations[startRotationI], + 0 + ); } } diff --git a/unity/Assets/Scripts/GetAllScenesInstanceCount.cs b/unity/Assets/Scripts/GetAllScenesInstanceCount.cs index df3107b5a1..c6e5633e88 100644 --- a/unity/Assets/Scripts/GetAllScenesInstanceCount.cs +++ b/unity/Assets/Scripts/GetAllScenesInstanceCount.cs @@ -1,9 +1,8 @@ using System; using System.Collections.Generic; +using System.IO; using UnityEngine; using UnityEngine.SceneManagement; -using System.IO; - #if UNITY_EDITOR using UnityEditor; using UnityEditor.SceneManagement; @@ -122,4 +121,4 @@ public class GetAllScenesInstanceCount : MonoBehaviour { // } // } } -#endif \ No newline at end of file +#endif diff --git a/unity/Assets/Scripts/GroupCommand.cs b/unity/Assets/Scripts/GroupCommand.cs index 0cd040c283..a1047ba412 100644 --- a/unity/Assets/Scripts/GroupCommand.cs +++ b/unity/Assets/Scripts/GroupCommand.cs @@ -19,4 +19,4 @@ private static void GroupSelected() { Selection.activeGameObject = go; } } -#endif \ No newline at end of file +#endif diff --git a/unity/Assets/Scripts/HeatZone.cs b/unity/Assets/Scripts/HeatZone.cs index 94c6f9690a..ada873db22 100644 --- a/unity/Assets/Scripts/HeatZone.cs +++ b/unity/Assets/Scripts/HeatZone.cs @@ -8,14 +8,10 @@ public class HeatZone : MonoBehaviour { public bool CanToastBread = true; // Start is called before the first frame update - void Start() { - - } + void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } public void OnTriggerStay(Collider other) { if (other.GetComponentInParent()) { @@ -40,7 +36,6 @@ public void OnTriggerStay(Collider other) { sopcook.Cook(); } } - // oh it's not bread, no worries just cook it now else if (sop.Type != SimObjType.BreadSliced) { if (!sopcook.IsCooked()) { @@ -48,8 +43,6 @@ public void OnTriggerStay(Collider other) { } } } - - } } } diff --git a/unity/Assets/Scripts/HoleMetadata.cs b/unity/Assets/Scripts/HoleMetadata.cs index 287906cfd6..d62d5abcb5 100644 --- a/unity/Assets/Scripts/HoleMetadata.cs +++ b/unity/Assets/Scripts/HoleMetadata.cs @@ -1,69 +1,69 @@ using System.Collections; using System.Collections.Generic; -using UnityEngine; using System.Linq; +using UnityEngine; -public class HoleMetadata : MonoBehaviour -{ - [DraggablePoint] public Vector3 Min; - [DraggablePoint] public Vector3 Max; - public Vector3 Margin; +public class HoleMetadata : MonoBehaviour { + [DraggablePoint] + public Vector3 Min; - - -void OnDrawGizmos() { + [DraggablePoint] + public Vector3 Max; + public Vector3 Margin; - // Box collider green - //Gizmos.color = new Color(145.0f/255.0f, 245.0f/255.0f, 139/255.0f, 1.0f); + void OnDrawGizmos() { + // Box collider green + //Gizmos.color = new Color(145.0f/255.0f, 245.0f/255.0f, 139/255.0f, 1.0f); - // Red - Gizmos.color = new Color(243.0f/255.0f, 77.0f/255.0f, 44/255.0f, 1.0f); + // Red + Gizmos.color = new Color(243.0f / 255.0f, 77.0f / 255.0f, 44 / 255.0f, 1.0f); - var halfSize = (Max-Min)/2.0f; - var halfSizeLocal = transform.TransformPoint(halfSize); + var halfSize = (Max - Min) / 2.0f; + var halfSizeLocal = transform.TransformPoint(halfSize); - var bottomLeft = Min; - var size = Max-Min; + var bottomLeft = Min; + var size = Max - Min; - var k = new List(){ - Vector3.zero, - new Vector3(0, 0, size.z) - }; + var k = new List() { Vector3.zero, new Vector3(0, 0, size.z) }; - var corners = new List> { - new List(){ - Vector3.zero, - new Vector3(size.x, 0, 0) - }, - new List(){ - Vector3.zero, - new Vector3(0, size.y, 0) - }, - new List(){ - Vector3.zero, - new Vector3(0, 0, size.z) - } - }.CartesianProduct().Select(x => x.Aggregate(bottomLeft, (acc, v) => acc + v)).ToList(); - - var tmp = corners[3]; - corners[3] = corners[2]; - corners[2] = tmp; + var corners = new List> + { + new List() { Vector3.zero, new Vector3(size.x, 0, 0) }, + new List() { Vector3.zero, new Vector3(0, size.y, 0) }, + new List() { Vector3.zero, new Vector3(0, 0, size.z) } + } + .CartesianProduct() + .Select(x => x.Aggregate(bottomLeft, (acc, v) => acc + v)) + .ToList(); - tmp = corners[7]; - corners[7] = corners[6]; - corners[6] = tmp; + var tmp = corners[3]; + corners[3] = corners[2]; + corners[2] = tmp; - corners = corners.Select(c => this.transform.TransformPoint(c)).ToList(); + tmp = corners[7]; + corners[7] = corners[6]; + corners[6] = tmp; - var sides = new List>() { corners.Take(4).ToList(), corners.Skip(4).ToList() }; + corners = corners.Select(c => this.transform.TransformPoint(c)).ToList(); - foreach (var q in sides) { + var sides = new List>() + { + corners.Take(4).ToList(), + corners.Skip(4).ToList() + }; - foreach (var (first, second) in q.Zip(q.Skip(3).Concat(q.Take(3)), (first, second) => (first, second)).Concat(sides[0].Zip(sides[1], (first, second)=> (first, second)))) { - Gizmos.DrawLine(first, second); + foreach (var q in sides) { + foreach ( + var (first, second) in q.Zip( + q.Skip(3).Concat(q.Take(3)), + (first, second) => (first, second) + ) + .Concat(sides[0].Zip(sides[1], (first, second) => (first, second))) + ) { + Gizmos.DrawLine(first, second); + } } - } - - //Gizmos.DrawCube (Min+halfSize, Max-Min); - } + + //Gizmos.DrawCube (Min+halfSize, Max-Min); + } } diff --git a/unity/Assets/Scripts/IK_Robot_Arm_Controller.cs b/unity/Assets/Scripts/IK_Robot_Arm_Controller.cs index f842263a99..d468cbadb3 100644 --- a/unity/Assets/Scripts/IK_Robot_Arm_Controller.cs +++ b/unity/Assets/Scripts/IK_Robot_Arm_Controller.cs @@ -1,20 +1,24 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -using System.Linq; public partial class IK_Robot_Arm_Controller : ArmController { [SerializeField] - private Transform armBase, elbowTarget, handCameraTransform, FirstJoint; + private Transform armBase, + elbowTarget, + handCameraTransform, + FirstJoint; public PhysicsRemoteFPSAgentController PhysicsController; // dict to track which picked up object has which set of trigger colliders // which we have to parent and reparent in order for arm collision to detect [SerializeField] - public new Dictionary> heldObjects = new Dictionary>(); + public new Dictionary> heldObjects = + new Dictionary>(); // private bool StopMotionOnContact = false; // Start is called before the first frame update @@ -29,13 +33,15 @@ public override GameObject GetArmTarget() { return armTarget.gameObject; } - public override Transform pickupParent() { + public override Transform pickupParent() { return magnetSphere.transform; } - public override Vector3 wristSpaceOffsetToWorldPos(Vector3 offset) { - return handCameraTransform.TransformPoint(offset) - handCameraTransform.TransformPoint(Vector3.zero); + public override Vector3 wristSpaceOffsetToWorldPos(Vector3 offset) { + return handCameraTransform.TransformPoint(offset) + - handCameraTransform.TransformPoint(Vector3.zero); } + public override Vector3 armBaseSpaceOffsetToWorldPos(Vector3 offset) { return this.transform.TransformPoint(offset) - this.transform.TransformPoint(Vector3.zero); } @@ -43,6 +49,7 @@ public override Vector3 armBaseSpaceOffsetToWorldPos(Vector3 offset) { public override Vector3 pointToWristSpace(Vector3 point) { return handCameraTransform.TransformPoint(point); } + public override Vector3 pointToArmBaseSpace(Vector3 point) { return this.transform.Find("robot_arm_FK_IK_rig").transform.TransformPoint(point); } @@ -56,7 +63,6 @@ public GameObject GetArmBase() { return armBase.gameObject; } - public GameObject GetElbowTarget() { return elbowTarget.gameObject; } @@ -77,13 +83,11 @@ protected override void lastStepCallback() { // return ActionFinished.Success; // } - + void Start() { // calculating based on distance from origin of arm to the 2nd joint, which will always be constant this.originToShoulderLength = Vector3.Distance( - this.transform.FirstChildOrDefault( - x => x.name == "robot_arm_2_jnt" - ).position, + this.transform.FirstChildOrDefault(x => x.name == "robot_arm_2_jnt").position, this.transform.position ); @@ -144,7 +148,7 @@ public IEnumerator rotateWristAroundPoint( Vector3 rotatePoint, Quaternion rotation, float degreesPerSecond, - float fixedDeltaTime, + float fixedDeltaTime, bool returnToStartPositionIfFailed = false ) { collisionListener.Reset(); @@ -242,7 +246,12 @@ public override ArmMetadata GenerateMetadata() { if (currentRotation != new Quaternion(0, 0, 0, -1)) { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); - jointMeta.rotation = new Vector4(vectorRot.x, vectorRot.y, vectorRot.z, ConvertAngleToZeroCentricRange(angleRot)); + jointMeta.rotation = new Vector4( + vectorRot.x, + vectorRot.y, + vectorRot.z, + ConvertAngleToZeroCentricRange(angleRot) + ); } else { jointMeta.rotation = new Vector4(1, 0, 0, 0); } @@ -256,7 +265,12 @@ public override ArmMetadata GenerateMetadata() { // Check that root-relative rotation is angle-axis-notation-compatible if (currentRotation != new Quaternion(0, 0, 0, -1)) { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); - jointMeta.rootRelativeRotation = new Vector4(vectorRot.x, vectorRot.y, vectorRot.z, ConvertAngleToZeroCentricRange(angleRot)); + jointMeta.rootRelativeRotation = new Vector4( + vectorRot.x, + vectorRot.y, + vectorRot.z, + ConvertAngleToZeroCentricRange(angleRot) + ); } else { jointMeta.rootRelativeRotation = new Vector4(1, 0, 0, 0); } @@ -266,12 +280,19 @@ public override ArmMetadata GenerateMetadata() { parentJoint = joint.parent; // Grab rotation of current joint's angler relative to parent joint's angler - currentRotation = Quaternion.Inverse(parentJoint.GetChild(0).rotation) * joint.GetChild(0).rotation; + currentRotation = + Quaternion.Inverse(parentJoint.GetChild(0).rotation) + * joint.GetChild(0).rotation; // Check that parent-relative rotation is angle-axis-notation-compatible if (currentRotation != new Quaternion(0, 0, 0, -1)) { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); - jointMeta.localRotation = new Vector4(vectorRot.x, vectorRot.y, vectorRot.z, ConvertAngleToZeroCentricRange(angleRot)); + jointMeta.localRotation = new Vector4( + vectorRot.x, + vectorRot.y, + vectorRot.z, + ConvertAngleToZeroCentricRange(angleRot) + ); } else { jointMeta.localRotation = new Vector4(1, 0, 0, 0); } @@ -302,22 +323,23 @@ public override ArmMetadata GenerateMetadata() { meta.handSphereCenter = magnetSphere.transform.TransformPoint(magnetSphere.center); meta.handSphereRadius = magnetSphere.radius; List objectsInMagnet = WhatObjectsAreInsideMagnetSphereAsSOP(false); - meta.pickupableObjects = objectsInMagnet.Where( - x => x.PrimaryProperty == SimObjPrimaryProperty.CanPickup - ).Select(x => x.ObjectID).ToList(); + meta.pickupableObjects = objectsInMagnet + .Where(x => x.PrimaryProperty == SimObjPrimaryProperty.CanPickup) + .Select(x => x.ObjectID) + .ToList(); meta.touchedNotHeldObjects = objectsInMagnet.Select(x => x.ObjectID).ToList(); return meta; } -float ConvertAngleToZeroCentricRange(float degrees) { - if (degrees < 0) { - degrees = (degrees % 360f) + 360f; - } - if (degrees > 180f) { - degrees = (degrees % 360f) - 360f; + float ConvertAngleToZeroCentricRange(float degrees) { + if (degrees < 0) { + degrees = (degrees % 360f) + 360f; + } + if (degrees > 180f) { + degrees = (degrees % 360f) - 360f; + } + return degrees; } - return degrees; -} #if UNITY_EDITOR public class GizmoDrawCapsule { diff --git a/unity/Assets/Scripts/IgnoreCollision.cs b/unity/Assets/Scripts/IgnoreCollision.cs index 58ea4e0c8e..31a92009b3 100644 --- a/unity/Assets/Scripts/IgnoreCollision.cs +++ b/unity/Assets/Scripts/IgnoreCollision.cs @@ -13,9 +13,7 @@ void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } public void SetupIgnoreCollision() { if (gameObject.GetComponentInParent() && myColliders.Length == 0) { @@ -28,19 +26,28 @@ public void SetupIgnoreCollision() { if (objectToIgnoreCollisionsWith != null) { // do this if we are ignoring a sim object like a dresser with drawers in it if (objectToIgnoreCollisionsWith.GetComponent()) { - otherCollidersToIgnore = objectToIgnoreCollisionsWith.GetComponent().MyColliders; + otherCollidersToIgnore = objectToIgnoreCollisionsWith + .GetComponent() + .MyColliders; } // do this if we are ignoring the agent if (objectToIgnoreCollisionsWith.GetComponent()) { - otherCollidersToIgnore = new Collider[] { objectToIgnoreCollisionsWith.GetComponent().GetComponent() }; + otherCollidersToIgnore = new Collider[] + { + objectToIgnoreCollisionsWith + .GetComponent() + .GetComponent() + }; } - } - #if UNITY_EDITOR else { - Debug.LogError("IgnoreCollision on " + gameObject.transform.name + " is missing an objectToIgnoreCollisionsWith!"); + Debug.LogError( + "IgnoreCollision on " + + gameObject.transform.name + + " is missing an objectToIgnoreCollisionsWith!" + ); } #endif // // otherwise, default to finding the SimObjPhysics component in the nearest parent to use as the object to ignore diff --git a/unity/Assets/Scripts/ImageSynthesis/ColorEncoding.cs b/unity/Assets/Scripts/ImageSynthesis/ColorEncoding.cs index 8d304c2043..0932090dcb 100644 --- a/unity/Assets/Scripts/ImageSynthesis/ColorEncoding.cs +++ b/unity/Assets/Scripts/ImageSynthesis/ColorEncoding.cs @@ -1,7 +1,5 @@ -using UnityEngine; -using System.Security.Cryptography; - - +using System.Security.Cryptography; +using UnityEngine; public class ColorEncoding { public static byte ReverseBits(byte value) { @@ -24,9 +22,9 @@ public static Color EncodeIDAsColor(int instanceId) { } var sid = - (SparsifyBits((byte)(uid >> 16), 3) << 2) | - (SparsifyBits((byte)(uid >> 8), 3) << 1) | - SparsifyBits((byte)(uid), 3); + (SparsifyBits((byte)(uid >> 16), 3) << 2) + | (SparsifyBits((byte)(uid >> 8), 3) << 1) + | SparsifyBits((byte)(uid), 3); // Debug.Log(uid + " >>> " + System.Convert.ToString(sid, 2).PadLeft(24, '0')); var r = (byte)(sid >> 8); @@ -39,12 +37,10 @@ public static Color EncodeIDAsColor(int instanceId) { public static Color EncodeTagAsColor(string tag) { using (MD5 md5 = MD5.Create()) { - byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(tag)); return new Color32(data[0], data[1], data[2], data[3]); } - } public static Color EncodeLayerAsColor(int layer) { @@ -56,15 +52,25 @@ public static Color EncodeLayerAsColor(int layer) { // Unity supports up to 32 layers in total // Lets create palette of unique 16 colors - var uniqueColors = new Color[] { - new Color(1,1,1,1), new Color(z,z,z,1), // 0 - new Color(1,1,z,1), new Color(1,z,1,1), new Color(z,1,1,1), // - new Color(1,z,0,1), new Color(z,0,1,1), new Color(0,1,z,1), // 7 - - new Color(1,0,0,1), new Color(0,1,0,1), new Color(0,0,1,1), // 8 - new Color(1,1,0,1), new Color(1,0,1,1), new Color(0,1,1,1), // - new Color(1,z,z,1), new Color(z,1,z,1) // 15 - }; + var uniqueColors = new Color[] + { + new Color(1, 1, 1, 1), + new Color(z, z, z, 1), // 0 + new Color(1, 1, z, 1), + new Color(1, z, 1, 1), + new Color(z, 1, 1, 1), // + new Color(1, z, 0, 1), + new Color(z, 0, 1, 1), + new Color(0, 1, z, 1), // 7 + new Color(1, 0, 0, 1), + new Color(0, 1, 0, 1), + new Color(0, 0, 1, 1), // 8 + new Color(1, 1, 0, 1), + new Color(1, 0, 1, 1), + new Color(0, 1, 1, 1), // + new Color(1, z, z, 1), + new Color(z, 1, z, 1) // 15 + }; // Create as many colors as necessary by using base 16 color palette // To create more than 16 - will simply adjust brightness with 'divider' diff --git a/unity/Assets/Scripts/ImageSynthesis/ExampleUI.cs b/unity/Assets/Scripts/ImageSynthesis/ExampleUI.cs index 8d25710a96..09ff92d09c 100644 --- a/unity/Assets/Scripts/ImageSynthesis/ExampleUI.cs +++ b/unity/Assets/Scripts/ImageSynthesis/ExampleUI.cs @@ -1,11 +1,10 @@ using System.Collections; using System.Collections.Generic; -using UnityEngine.SceneManagement; using UnityEngine; +using UnityEngine.SceneManagement; [RequireComponent(typeof(ImageSynthesis))] public class ExampleUI : MonoBehaviour { - public int width = 320; public int height = 200; private int imageCounter = 1; @@ -15,7 +14,8 @@ void OnGUI() { var sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; // NOTE: due to per-camera / per-object motion being calculated late in the frame and after Update() // capturing is moved into LateUpdate (see ImageSynthesis.cs Known Issues) - GetComponent().Save(sceneName + "_" + imageCounter++, width, height); + GetComponent() + .Save(sceneName + "_" + imageCounter++, width, height); } } } diff --git a/unity/Assets/Scripts/ImageSynthesis/ImageSynthesis.cs b/unity/Assets/Scripts/ImageSynthesis/ImageSynthesis.cs index 6101fede7b..e72c6f766b 100644 --- a/unity/Assets/Scripts/ImageSynthesis/ImageSynthesis.cs +++ b/unity/Assets/Scripts/ImageSynthesis/ImageSynthesis.cs @@ -1,9 +1,9 @@ -using UnityEngine; -using UnityEngine.Rendering; using System; -using System.IO; using System.Collections; using System.Collections.Generic; +using System.IO; +using UnityEngine; +using UnityEngine.Rendering; // @TODO: // . support custom color wheels in optical flow via lookup textures @@ -19,29 +19,38 @@ [RequireComponent(typeof(Camera))] public class ImageSynthesis : MonoBehaviour { - private bool initialized = false; // pass configuration - private CapturePass[] capturePasses = new CapturePass[] { + private CapturePass[] capturePasses = new CapturePass[] + { new CapturePass() { name = "_img" }, new CapturePass() { name = "_depth" }, new CapturePass() { name = "_id", supportsAntialiasing = false }, new CapturePass() { name = "_class", supportsAntialiasing = false }, - new CapturePass() { name = "_normals"}, - new CapturePass() { name = "_flow", supportsAntialiasing = false, needsRescale = true }, // (see issue with Motion Vectors in @KNOWN ISSUES) - - - // new CapturePass() { name = "_position" }, + new CapturePass() { name = "_normals" }, + new CapturePass() + { + name = "_flow", + supportsAntialiasing = false, + needsRescale = true + }, // (see issue with Motion Vectors in @KNOWN ISSUES) - }; + // new CapturePass() { name = "_position" }, + }; struct CapturePass { // configuration public string name; public bool supportsAntialiasing; public bool needsRescale; - public CapturePass(string name_) { name = name_; supportsAntialiasing = true; needsRescale = false; camera = null; } + + public CapturePass(string name_) { + name = name_; + supportsAntialiasing = true; + needsRescale = false; + camera = null; + } // impl public Camera camera; @@ -67,6 +76,7 @@ public void updateCameraStatuses(bool enabled) { private Shader uberReplacementShader; private Shader opticalFlowShader; private Shader depthShader; + // public Shader positionShader; public Dictionary colorIds; @@ -85,8 +95,8 @@ public void updateCameraStatuses(bool enabled) { public Texture2D tex; public void OnEnable() { - // This initialization code MUST live in OnEnable and not Start as we instantiate ThirdPartyCameras - // programatically in other functions and need them to be initialized immediately. + // This initialization code MUST live in OnEnable and not Start as we instantiate ThirdPartyCameras + // programatically in other functions and need them to be initialized immediately. if (!initialized) { // XXXXXXXXXXX************ // Remember, adding any new Shaders requires them to be included in Project Settings->Graphics->Always Included Shaders @@ -109,8 +119,8 @@ public void OnEnable() { depthShader = Shader.Find("Hidden/DepthBW"); } #else - if (!depthShader) - depthShader = Shader.Find("Hidden/Depth"); + if (!depthShader) + depthShader = Shader.Find("Hidden/Depth"); #endif @@ -147,7 +157,7 @@ void LateUpdate() { private Camera CreateHiddenCamera(string name) { var go = new GameObject(name, typeof(Camera)); #if !UNITY_EDITOR // Useful to be able to see these cameras in the editor - go.hideFlags = HideFlags.HideAndDontSave; + go.hideFlags = HideFlags.HideAndDontSave; #endif go.transform.parent = transform; @@ -157,16 +167,17 @@ private Camera CreateHiddenCamera(string name) { if (go.transform.parent.GetComponent()) // add the FirstPersonCharacterCull so this camera's agent is not rendered- other agents when multi agent is enabled should still be rendered { - go.AddComponent(go.transform.parent.GetComponent()); + go.AddComponent( + go.transform.parent.GetComponent() + ); } var newCamera = go.GetComponent(); - newCamera.cullingMask = 1;// render everything, including PlaceableSurfaces + newCamera.cullingMask = 1; // render everything, including PlaceableSurfaces return newCamera; } - - static private void SetupCameraWithReplacementShader(Camera cam, Shader shader) { + private static void SetupCameraWithReplacementShader(Camera cam, Shader shader) { var cb = new CommandBuffer(); cam.AddCommandBuffer(CameraEvent.BeforeForwardOpaque, cb); cam.AddCommandBuffer(CameraEvent.BeforeFinalPass, cb); @@ -175,11 +186,20 @@ static private void SetupCameraWithReplacementShader(Camera cam, Shader shader) cam.clearFlags = CameraClearFlags.SolidColor; } - static private void SetupCameraWithReplacementShader(Camera cam, Shader shader, ReplacelementModes mode) { + private static void SetupCameraWithReplacementShader( + Camera cam, + Shader shader, + ReplacelementModes mode + ) { SetupCameraWithReplacementShader(cam, shader, mode, Color.blue); } - static private void SetupCameraWithReplacementShader(Camera cam, Shader shader, ReplacelementModes mode, Color clearColor) { + private static void SetupCameraWithReplacementShader( + Camera cam, + Shader shader, + ReplacelementModes mode, + Color clearColor + ) { var cb = new CommandBuffer(); cb.SetGlobalFloat("_OutputMode", (int)mode); // @TODO: CommandBuffer is missing SetGlobalInt() method cam.renderingPath = RenderingPath.Forward; @@ -190,7 +210,11 @@ static private void SetupCameraWithReplacementShader(Camera cam, Shader shader, cam.clearFlags = CameraClearFlags.SolidColor; } - static private void SetupCameraWithPostShader(Camera cam, Material material, DepthTextureMode depthTextureMode = DepthTextureMode.None) { + private static void SetupCameraWithPostShader( + Camera cam, + Material material, + DepthTextureMode depthTextureMode = DepthTextureMode.None + ) { var cb = new CommandBuffer(); cb.Blit(null, BuiltinRenderTextureType.CurrentActive, material); cam.AddCommandBuffer(CameraEvent.AfterEverything, cb); @@ -251,11 +275,26 @@ public void OnCameraChange() { // SetupCameraWithReplacementShader(capturePasses[1].camera, uberReplacementShader, ReplacelementModes.DepthMultichannel); SetupCameraWithPostShader(capturePasses[1].camera, depthMaterial, DepthTextureMode.Depth); - - SetupCameraWithReplacementShader(capturePasses[2].camera, uberReplacementShader, ReplacelementModes.ObjectId); - SetupCameraWithReplacementShader(capturePasses[3].camera, uberReplacementShader, ReplacelementModes.CatergoryId); - SetupCameraWithReplacementShader(capturePasses[4].camera, uberReplacementShader, ReplacelementModes.Normals); - SetupCameraWithPostShader(capturePasses[5].camera, opticalFlowMaterial, DepthTextureMode.Depth | DepthTextureMode.MotionVectors); + SetupCameraWithReplacementShader( + capturePasses[2].camera, + uberReplacementShader, + ReplacelementModes.ObjectId + ); + SetupCameraWithReplacementShader( + capturePasses[3].camera, + uberReplacementShader, + ReplacelementModes.CatergoryId + ); + SetupCameraWithReplacementShader( + capturePasses[4].camera, + uberReplacementShader, + ReplacelementModes.Normals + ); + SetupCameraWithPostShader( + capturePasses[5].camera, + opticalFlowMaterial, + DepthTextureMode.Depth | DepthTextureMode.MotionVectors + ); #if UNITY_EDITOR for (int i = 0; i < capturePasses.Length; i++) { @@ -265,12 +304,10 @@ public void OnCameraChange() { #endif /* - SetupCameraWithReplacementShader(capturePasses[6].camera, positionShader); - */ - + SetupCameraWithReplacementShader(capturePasses[6].camera, positionShader); + */ } - public string MD5Hash(string input) { byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(input)); // Create string representation @@ -281,10 +318,9 @@ public string MD5Hash(string input) { return sb.ToString(); } - private string getObjectId(GameObject gameObject) { // the object id is generated this way to handle the edge case - // where a non-simobject could get moved from its initial position + // where a non-simobject could get moved from its initial position // during a simulation. This forces the objectId to get generated once // on scene startup int key = gameObject.GetInstanceID(); @@ -292,13 +328,13 @@ private string getObjectId(GameObject gameObject) { return nonSimObjObjectIds[key]; } else { Transform t = gameObject.transform; - string objectId = gameObject.name + "|" + t.position.x + "|" + t.position.y + "|" + t.position.z; + string objectId = + gameObject.name + "|" + t.position.x + "|" + t.position.y + "|" + t.position.z; nonSimObjObjectIds[key] = objectId; return objectId; } } - public void OnSceneChange() { sentColorCorrespondence = false; var renderers = UnityEngine.Object.FindObjectsOfType(); @@ -382,7 +418,16 @@ public byte[] Encode( foreach (var pass in capturePasses) { if (pass.name == passName) { - return Encode(pass.camera, width, height, pass.supportsAntialiasing, pass.needsRescale, jpg, format, textureReadMode); + return Encode( + pass.camera, + width, + height, + pass.supportsAntialiasing, + pass.needsRescale, + jpg, + format, + textureReadMode + ); } } @@ -406,17 +451,35 @@ public void Save(string filename, int width = -1, int height = -1, string path = // execute as coroutine to wait for the EndOfFrame before starting capture StartCoroutine( - WaitForEndOfFrameAndSave(pathWithoutExtension, filenameExtension, width, height)); + WaitForEndOfFrameAndSave(pathWithoutExtension, filenameExtension, width, height) + ); } - private IEnumerator WaitForEndOfFrameAndSave(string filenameWithoutExtension, string filenameExtension, int width, int height) { + private IEnumerator WaitForEndOfFrameAndSave( + string filenameWithoutExtension, + string filenameExtension, + int width, + int height + ) { yield return new WaitForEndOfFrame(); Save(filenameWithoutExtension, filenameExtension, width, height); } - private void Save(string filenameWithoutExtension, string filenameExtension, int width, int height) { + private void Save( + string filenameWithoutExtension, + string filenameExtension, + int width, + int height + ) { foreach (var pass in capturePasses) { - Save(pass.camera, filenameWithoutExtension + pass.name + filenameExtension, width, height, pass.supportsAntialiasing, pass.needsRescale); + Save( + pass.camera, + filenameWithoutExtension + pass.name + filenameExtension, + width, + height, + pass.supportsAntialiasing, + pass.needsRescale + ); } } @@ -435,10 +498,25 @@ private byte[] Encode( var readWrite = textureReadMode; var antiAliasing = (supportsAntialiasing) ? Mathf.Max(1, QualitySettings.antiAliasing) : 1; - var finalRT = - RenderTexture.GetTemporary(width, height, depth, format, readWrite, antiAliasing); - var renderRT = (!needsRescale) ? finalRT : - RenderTexture.GetTemporary(mainCamera.pixelWidth, mainCamera.pixelHeight, depth, format, readWrite, antiAliasing); + var finalRT = RenderTexture.GetTemporary( + width, + height, + depth, + format, + readWrite, + antiAliasing + ); + var renderRT = + (!needsRescale) + ? finalRT + : RenderTexture.GetTemporary( + mainCamera.pixelWidth, + mainCamera.pixelHeight, + depth, + format, + readWrite, + antiAliasing + ); if (tex == null) { tex = new Texture2D(width, height, TextureFormat.RGBA32, false); } @@ -483,14 +561,19 @@ private byte[] Encode( cam.targetTexture = prevCameraRT; RenderTexture.active = prevActiveRT; - - // UnityEngine.Object.Destroy(tex); RenderTexture.ReleaseTemporary(finalRT); return bytes; } - private void Save(Camera cam, string filename, int width, int height, bool supportsAntialiasing, bool needsRescale) { + private void Save( + Camera cam, + string filename, + int width, + int height, + bool supportsAntialiasing, + bool needsRescale + ) { byte[] bytes = Encode(cam, width, height, supportsAntialiasing, needsRescale); File.WriteAllBytes(filename, bytes); } @@ -499,10 +582,11 @@ private void Save(Camera cam, string filename, int width, int height, bool suppo private GameObject lastSelectedGO; private int lastSelectedGOLayer = -1; private string lastSelectedGOTag = "unknown"; + private bool DetectPotentialSceneChangeInEditor() { bool change = false; // there is no callback in Unity Editor to automatically detect changes in scene objects - // as a workaround lets track selected objects and check, if properties that are + // as a workaround lets track selected objects and check, if properties that are // interesting for us (layer or tag) did not change since the last frame if (UnityEditor.Selection.transforms.Length > 1) { // multiple objects are selected, all bets are off! @@ -512,7 +596,8 @@ private bool DetectPotentialSceneChangeInEditor() { } else if (UnityEditor.Selection.activeGameObject) { var go = UnityEditor.Selection.activeGameObject; // check if layer or tag of a selected object have changed since the last frame - var potentialChangeHappened = lastSelectedGOLayer != go.layer || lastSelectedGOTag != go.tag; + var potentialChangeHappened = + lastSelectedGOLayer != go.layer || lastSelectedGOTag != go.tag; if (go == lastSelectedGO && potentialChangeHappened) { change = true; } diff --git a/unity/Assets/Scripts/InstantiatePrefabTest.cs b/unity/Assets/Scripts/InstantiatePrefabTest.cs index 09c6855ed7..8b539258cf 100644 --- a/unity/Assets/Scripts/InstantiatePrefabTest.cs +++ b/unity/Assets/Scripts/InstantiatePrefabTest.cs @@ -1,9 +1,9 @@ -using UnityEngine; +using System; using System.Collections; using System.Collections.Generic; -using System; -using UnityStandardAssets.Characters.FirstPerson; using System.Linq; +using UnityEngine; +using UnityStandardAssets.Characters.FirstPerson; // this script manages the spawning/placing of sim objects in the scene public class InstantiatePrefabTest : MonoBehaviour { @@ -17,7 +17,6 @@ public class InstantiatePrefabTest : MonoBehaviour { Quaternion gizmoquaternion; #endif - private float yoffset = 0.005f; // y axis offset of placing objects, useful to allow objects to fall just a tiny bit to allow physics to resolve consistently private List SpawnCorners = new List(); @@ -45,15 +44,33 @@ public SimObjPhysics Spawn(string prefabType, string objectId, Vector3 position) return null; } - public SimObjPhysics SpawnObject(string objectType, bool randomize, int variation, Vector3 position, Vector3 rotation, bool spawningInHand) { - return SpawnObject(objectType, randomize, variation, position, rotation, spawningInHand, false); + public SimObjPhysics SpawnObject( + string objectType, + bool randomize, + int variation, + Vector3 position, + Vector3 rotation, + bool spawningInHand + ) { + return SpawnObject( + objectType, + randomize, + variation, + position, + rotation, + spawningInHand, + false + ); } public Bounds BoundsOfObject(string objectType, int variation) { // GameObject topObject = GameObject.Find("Objects"); List candidates = new List(); foreach (GameObject go in prefabs) { - if (go.GetComponent().Type == (SimObjType)Enum.Parse(typeof(SimObjType), objectType)) { + if ( + go.GetComponent().Type + == (SimObjType)Enum.Parse(typeof(SimObjType), objectType) + ) { candidates.Add(go); } } @@ -77,14 +94,25 @@ public Bounds BoundsOfObject(string objectType, int variation) { // spawningInHand - adjusts layermask depending on if the object is going to spawn directly in the agent's hand vs spawning in the environment // ignoreChecks - bool to ignore checks and spawn anyway //-- - public SimObjPhysics SpawnObject(string objectType, bool randomize, int variation, Vector3 position, Vector3 rotation, bool spawningInHand, bool ignoreChecks) { + public SimObjPhysics SpawnObject( + string objectType, + bool randomize, + int variation, + Vector3 position, + Vector3 rotation, + bool spawningInHand, + bool ignoreChecks + ) { GameObject topObject = GameObject.Find("Objects"); List candidates = new List(); foreach (GameObject go in prefabs) { // does a prefab of objectType exist in the current array of prefabs to spawn? - if (go.GetComponent().Type == (SimObjType)Enum.Parse(typeof(SimObjType), objectType)) { + if ( + go.GetComponent().Type + == (SimObjType)Enum.Parse(typeof(SimObjType), objectType) + ) { candidates.Add(go); } } @@ -102,14 +130,29 @@ public SimObjPhysics SpawnObject(string objectType, bool randomize, int variatio Quaternion quat = Quaternion.Euler(rotation); - if (ignoreChecks || CheckSpawnArea(candidates[variation].GetComponent(), position, quat, spawningInHand)) { + if ( + ignoreChecks + || CheckSpawnArea( + candidates[variation].GetComponent(), + position, + quat, + spawningInHand + ) + ) { GameObject prefab = Instantiate(candidates[variation], position, quat) as GameObject; if (!ignoreChecks) { - if (UtilityFunctions.isObjectColliding( - prefab, - new List(from agent in GameObject.FindObjectsOfType() select agent.gameObject)) + if ( + UtilityFunctions.isObjectColliding( + prefab, + new List( + from agent in GameObject.FindObjectsOfType() + select agent.gameObject + ) + ) ) { - Debug.Log("On spawning object the area was not clear despite CheckSpawnArea saying it was."); + Debug.Log( + "On spawning object the area was not clear despite CheckSpawnArea saying it was." + ); prefab.SetActive(false); return null; } @@ -140,11 +183,13 @@ public bool PlaceObjectReceptacle( bool PlaceStationary, int maxPlacementAttempts, int degreeIncrement, - bool AlwaysPlaceUpright) { - + bool AlwaysPlaceUpright + ) { if (rsps == null) { #if UNITY_EDITOR - Debug.Log("Null list of points to check, please pass in populated list of ?"); + Debug.Log( + "Null list of points to check, please pass in populated list of ?" + ); #endif return false; // uh, there was nothing in the List for some reason, so failed to spawn } @@ -156,8 +201,13 @@ public bool PlaceObjectReceptacle( // only add spawn points to try if the point's parent is not an object specific receptacle, that is handled in RandomSpawnRequiredSceneObjects foreach (ReceptacleSpawnPoint p in rsps) { - if (!p.ParentSimObjPhys.GetComponent().DoesThisObjectHaveThisSecondaryProperty - (SimObjSecondaryProperty.ObjectSpecificReceptacle)) { + if ( + !p + .ParentSimObjPhys.GetComponent() + .DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.ObjectSpecificReceptacle + ) + ) { goodRsps.Add(p); } } @@ -180,11 +230,20 @@ public bool PlaceObjectReceptacle( // same as PlaceObjectReceptacle but instead only succeeds if final placed object is within viewport - public bool PlaceObjectReceptacleInViewport(PhysicsRemoteFPSAgentController agent, List rsps, SimObjPhysics sop, bool PlaceStationary, int maxPlacementAttempts, int degreeIncrement, bool AlwaysPlaceUpright) { - + public bool PlaceObjectReceptacleInViewport( + PhysicsRemoteFPSAgentController agent, + List rsps, + SimObjPhysics sop, + bool PlaceStationary, + int maxPlacementAttempts, + int degreeIncrement, + bool AlwaysPlaceUpright + ) { if (rsps == null) { #if UNITY_EDITOR - Debug.Log("Null list of points to check, please pass in populated list of ?"); + Debug.Log( + "Null list of points to check, please pass in populated list of ?" + ); #endif return false; // uh, there was nothing in the List for some reason, so failed to spawn } @@ -195,8 +254,13 @@ public bool PlaceObjectReceptacleInViewport(PhysicsRemoteFPSAgentController agen List goodRsps = new List(); foreach (ReceptacleSpawnPoint p in rsps) { - if (!p.ParentSimObjPhys.GetComponent().DoesThisObjectHaveThisSecondaryProperty - (SimObjSecondaryProperty.ObjectSpecificReceptacle)) { + if ( + !p + .ParentSimObjPhys.GetComponent() + .DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.ObjectSpecificReceptacle + ) + ) { goodRsps.Add(p); } } @@ -224,7 +288,6 @@ public bool PlaceObjectReceptacleInViewport(PhysicsRemoteFPSAgentController agen return false; } - // use this to keep track of a Rotation and Distance for use in PlaceObject public class RotationAndDistanceValues { public float distance; @@ -236,7 +299,6 @@ public RotationAndDistanceValues(float d, Quaternion r) { } } - public bool PlaceObject( SimObjPhysics sop, ReceptacleSpawnPoint rsp, @@ -265,7 +327,6 @@ bool AlwaysPlaceUpright sopRB.velocity = Vector3.zero; sopRB.angularVelocity = Vector3.zero; - // set 360 degree increment to only check one angle, set smaller increments to check more angles when trying to place (warning THIS WILL GET SLOWER) int HowManyRotationsToCheck = 360 / degreeIncrement; Plane BoxBottom; @@ -282,19 +343,39 @@ bool AlwaysPlaceUpright sop.transform.Rotate(new Vector3(0, degreeIncrement, 0), Space.Self); // ToCheck[i].rotation = sop.transform.rotation; - Vector3 Offset = oabb.ClosestPoint(oabb.transform.TransformPoint(oabb.center) + -rsp.ReceptacleBox.transform.up * 10); + Vector3 Offset = oabb.ClosestPoint( + oabb.transform.TransformPoint(oabb.center) + + -rsp.ReceptacleBox.transform.up * 10 + ); BoxBottom = new Plane(rsp.ReceptacleBox.transform.up, Offset); - DistanceFromBoxBottomTosop = Math.Abs(BoxBottom.GetDistanceToPoint(sop.transform.position)); - - ToCheck.Add(new RotationAndDistanceValues(DistanceFromBoxBottomTosop, sop.transform.rotation)); + DistanceFromBoxBottomTosop = Math.Abs( + BoxBottom.GetDistanceToPoint(sop.transform.position) + ); + + ToCheck.Add( + new RotationAndDistanceValues( + DistanceFromBoxBottomTosop, + sop.transform.rotation + ) + ); } else { // no rotate change just yet, check the first position - Vector3 Offset = oabb.ClosestPoint(oabb.transform.TransformPoint(oabb.center) + -rsp.ReceptacleBox.transform.up * 10); // was using rsp.point + Vector3 Offset = oabb.ClosestPoint( + oabb.transform.TransformPoint(oabb.center) + + -rsp.ReceptacleBox.transform.up * 10 + ); // was using rsp.point BoxBottom = new Plane(rsp.ReceptacleBox.transform.up, Offset); - DistanceFromBoxBottomTosop = Math.Abs(BoxBottom.GetDistanceToPoint(sop.transform.position)); - - ToCheck.Add(new RotationAndDistanceValues(DistanceFromBoxBottomTosop, sop.transform.rotation)); + DistanceFromBoxBottomTosop = Math.Abs( + BoxBottom.GetDistanceToPoint(sop.transform.position) + ); + + ToCheck.Add( + new RotationAndDistanceValues( + DistanceFromBoxBottomTosop, + sop.transform.rotation + ) + ); } oabb.enabled = false; @@ -315,11 +396,21 @@ bool AlwaysPlaceUpright for (int j = 0; j < HowManyRotationsToCheck; j++) { sop.transform.Rotate(new Vector3(degreeIncrement, 0, 0), Space.Self); - Vector3 Offset = oabb.ClosestPoint(oabb.transform.TransformPoint(oabb.center) + -rsp.ReceptacleBox.transform.up * 10); + Vector3 Offset = oabb.ClosestPoint( + oabb.transform.TransformPoint(oabb.center) + + -rsp.ReceptacleBox.transform.up * 10 + ); BoxBottom = new Plane(rsp.ReceptacleBox.transform.up, Offset); - DistanceFromBoxBottomTosop = Math.Abs(BoxBottom.GetDistanceToPoint(sop.transform.position)); - - ToCheck.Add(new RotationAndDistanceValues(DistanceFromBoxBottomTosop, sop.transform.rotation)); + DistanceFromBoxBottomTosop = Math.Abs( + BoxBottom.GetDistanceToPoint(sop.transform.position) + ); + + ToCheck.Add( + new RotationAndDistanceValues( + DistanceFromBoxBottomTosop, + sop.transform.rotation + ) + ); } sop.transform.rotation = oldRotation; @@ -328,28 +419,43 @@ bool AlwaysPlaceUpright for (int j = 0; j < HowManyRotationsToCheck; j++) { sop.transform.Rotate(new Vector3(0, 0, degreeIncrement), Space.Self); - Vector3 Offset = oabb.ClosestPoint(oabb.transform.TransformPoint(oabb.center) + -rsp.ReceptacleBox.transform.up * 10); + Vector3 Offset = oabb.ClosestPoint( + oabb.transform.TransformPoint(oabb.center) + + -rsp.ReceptacleBox.transform.up * 10 + ); BoxBottom = new Plane(rsp.ReceptacleBox.transform.up, Offset); - DistanceFromBoxBottomTosop = Math.Abs(BoxBottom.GetDistanceToPoint(sop.transform.position)); - - ToCheck.Add(new RotationAndDistanceValues(DistanceFromBoxBottomTosop, sop.transform.rotation)); + DistanceFromBoxBottomTosop = Math.Abs( + BoxBottom.GetDistanceToPoint(sop.transform.position) + ); + + ToCheck.Add( + new RotationAndDistanceValues( + DistanceFromBoxBottomTosop, + sop.transform.rotation + ) + ); } sop.transform.rotation = oldRotation; - } oabb.enabled = false; } } - foreach (RotationAndDistanceValues quat in ToCheck) { // if spawn area is clear, spawn it and return true that we spawned it - if (CheckSpawnArea(sop, rsp.Point + rsp.ParentSimObjPhys.transform.up * (quat.distance + yoffset), quat.rotation, false)) { - + if ( + CheckSpawnArea( + sop, + rsp.Point + rsp.ParentSimObjPhys.transform.up * (quat.distance + yoffset), + quat.rotation, + false + ) + ) { // translate position of the target sim object to the rsp.Point and offset in local y up - sop.transform.position = rsp.Point + rsp.ReceptacleBox.transform.up * (quat.distance + yoffset);// rsp.Point + sop.transform.up * DistanceFromBottomOfBoxToTransform; + sop.transform.position = + rsp.Point + rsp.ReceptacleBox.transform.up * (quat.distance + yoffset); // rsp.Point + sop.transform.up * DistanceFromBottomOfBoxToTransform; sop.transform.rotation = quat.rotation; //ensure transforms are synced @@ -373,7 +479,11 @@ bool AlwaysPlaceUpright HowManyCornersToCheck = 8; } - if (ReceptacleRestrictions.InReceptaclesThatOnlyCheckBottomFourCorners.Contains(rsp.ParentSimObjPhys.ObjType)) { + if ( + ReceptacleRestrictions.InReceptaclesThatOnlyCheckBottomFourCorners.Contains( + rsp.ParentSimObjPhys.ObjType + ) + ) { // only check bottom 4 corners even though the action is PlaceIn HowManyCornersToCheck = 4; } @@ -384,22 +494,25 @@ bool AlwaysPlaceUpright // now check the corner count for either the 4 lowest corners, or all 8 corners depending on Corner Count // attmpt to sort corners so that first four corners are the corners closest to the spawn point we are checking against - SpawnCorners.Sort(delegate (Vector3 p1, Vector3 p2) { - // sort by making a plane where rsp.point is, find the four corners closest to that point - // return rspPlane.GetDistanceToPoint(p1).CompareTo(rspPlane.GetDistanceToPoint(p2)); - //^ this ended up not working because if something is placed at an angle this no longer makes sense... - - return Vector3.Distance(p1, rsp.Point).CompareTo(Vector3.Distance(p2, rsp.Point)); - - // return Vector3.Distance(new Vector3(0, p1.y, 0), new Vector3(0, rsp.Point.y, 0)).CompareTo( - // Vector3.Distance(new Vector3(0, p2.y, 0), new Vector3(0, rsp.Point.y, 0))); - - }); + SpawnCorners.Sort( + delegate (Vector3 p1, Vector3 p2) { + // sort by making a plane where rsp.point is, find the four corners closest to that point + // return rspPlane.GetDistanceToPoint(p1).CompareTo(rspPlane.GetDistanceToPoint(p2)); + //^ this ended up not working because if something is placed at an angle this no longer makes sense... + + return Vector3 + .Distance(p1, rsp.Point) + .CompareTo(Vector3.Distance(p2, rsp.Point)); + + // return Vector3.Distance(new Vector3(0, p1.y, 0), new Vector3(0, rsp.Point.y, 0)).CompareTo( + // Vector3.Distance(new Vector3(0, p2.y, 0), new Vector3(0, rsp.Point.y, 0))); + } + ); // ok so this is just checking if there are enough corners in the Receptacle Zone to consider it placed correctly. // originally this looped up to i < HowManyCornersToCheck, but if we just check all the corners, regardless of // sort order, it seems to bypass the issue above of how to sort the corners to find the "bottom" 4 corners, so uh - // i guess this might just work without fancy sorting to determine the bottom 4 corners... especially since the "bottom corners" starts to lose meaning as objects are rotated + // i guess this might just work without fancy sorting to determine the bottom 4 corners... especially since the "bottom corners" starts to lose meaning as objects are rotated for (int i = 0; i < 8; i++) { if (rsp.Script.CheckIfPointIsInsideReceptacleTriggerBox(SpawnCorners[i])) { CornerCount++; @@ -427,12 +540,16 @@ bool AlwaysPlaceUpright // if false, once placed the object will resolve with physics (if placed on uneven surface object might slide or roll) if (PlaceStationary) { // if the target receptacle is a pickupable receptacle, set it to kinematic true as will since we are placing stationary - if (rsp.ParentSimObjPhys.PrimaryProperty == SimObjPrimaryProperty.CanPickup || rsp.ParentSimObjPhys.PrimaryProperty == SimObjPrimaryProperty.Moveable) { + if ( + rsp.ParentSimObjPhys.PrimaryProperty == SimObjPrimaryProperty.CanPickup + || rsp.ParentSimObjPhys.PrimaryProperty == SimObjPrimaryProperty.Moveable + ) { rsp.ParentSimObjPhys.GetComponent().isKinematic = true; } // make object being placed kinematic true - sop.GetComponent().collisionDetectionMode = CollisionDetectionMode.Discrete; + sop.GetComponent().collisionDetectionMode = + CollisionDetectionMode.Discrete; sop.GetComponent().isKinematic = true; // check if the parent sim object is one that moves like a drawer - and would require this to be parented @@ -440,11 +557,14 @@ bool AlwaysPlaceUpright sop.transform.SetParent(rsp.ParentSimObjPhys.transform); // if this object is a receptacle and it has other objects inside it, drop them all together - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.Receptacle + ) + ) { sop.DropContainedObjectsStationary(); // use stationary version so that colliders are turned back on, but kinematics remain true } } - // place stationary false, let physics drop everything too else { // if not placing stationary, put all objects under Objects game object @@ -456,11 +576,18 @@ bool AlwaysPlaceUpright rb.isKinematic = false; rb.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic; // if this object is a receptacle and it has other objects inside it, drop them all together - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { - sop.DropContainedObjects(reparentContainedObjects: true, forceKinematic: false); + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.Receptacle + ) + ) { + sop.DropContainedObjects( + reparentContainedObjects: true, + forceKinematic: false + ); } } - sop.isInAgentHand = false;// set agent hand flag + sop.isInAgentHand = false; // set agent hand flag return true; } @@ -478,7 +605,10 @@ bool AlwaysPlaceUpright //"Edit Collider" button if you need to change the size // this assumes that the BoundingBox transform is zeroed out according to the root transform of the prefab public Collider ColliderHitByObjectInSpawnArea( - SimObjPhysics simObj, Vector3 position, Quaternion rotation, bool spawningInHand + SimObjPhysics simObj, + Vector3 position, + Quaternion rotation, + bool spawningInHand ) { int layermask; @@ -486,10 +616,23 @@ public Collider ColliderHitByObjectInSpawnArea( // if spawning in the agent's hand, ignore collisions with the Agent if (spawningInHand) { - layermask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + layermask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); } else { // oh we are spawning it somewhere in the environment, we do need to make sure not to spawn inside the agent or the environment - layermask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent"); + layermask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent" + ); } // get list of all active colliders of sim object, then toggle them off for now @@ -524,22 +667,54 @@ public Collider ColliderHitByObjectInSpawnArea( // keep track of all 8 corners of the OverlapBox List corners = new List(); // bottom forward right - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f + ) + ); // bottom forward left - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f + ) + ); // bottom back left - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f + ) + ); // bottom back right - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f + ) + ); // top forward right - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f + ) + ); // top forward left - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f + ) + ); // top back left - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f + ) + ); // top back right - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f + ) + ); SpawnCorners = corners; @@ -585,10 +760,19 @@ public Collider ColliderHitByObjectInSpawnArea( // nothing was hit, we are good! return null; } + public bool CheckSpawnArea( - SimObjPhysics simObj, Vector3 position, Quaternion rotation, bool spawningInHand + SimObjPhysics simObj, + Vector3 position, + Quaternion rotation, + bool spawningInHand ) { - var hitColliders = ColliderHitByObjectInSpawnArea(simObj, position, rotation, spawningInHand); + var hitColliders = ColliderHitByObjectInSpawnArea( + simObj, + position, + rotation, + spawningInHand + ); // Debug.Log("Colliders " + hitColliders.gameObject.name); return null == hitColliders; } @@ -620,5 +804,4 @@ void OnDrawGizmos() { } } #endif - } diff --git a/unity/Assets/Scripts/JavaScriptInterface.cs b/unity/Assets/Scripts/JavaScriptInterface.cs index 5bd87203e6..e4da39e082 100644 --- a/unity/Assets/Scripts/JavaScriptInterface.cs +++ b/unity/Assets/Scripts/JavaScriptInterface.cs @@ -1,15 +1,14 @@ using System; -using UnityEngine; using System.Runtime.InteropServices; +using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; - public class JavaScriptInterface : MonoBehaviour { - // IL2CPP throws exceptions about SendMetadata and Init not existing // so the body is only used for WebGL #if UNITY_WEBGL private AgentManager agentManager; + // private DebugInputField inputField; // inputField.setControlMode no longer used in SetController [DllImport("__Internal")] @@ -18,9 +17,9 @@ public class JavaScriptInterface : MonoBehaviour { [DllImport("__Internal")] private static extern void SendMetadata(string str); -/* - metadata: serialized metadata, commonly an instance of MultiAgentMetadata - */ + /* + metadata: serialized metadata, commonly an instance of MultiAgentMetadata + */ public void SendActionMetadata(string metadata) { SendMetadata(metadata); @@ -28,9 +27,11 @@ public void SendActionMetadata(string metadata) void Start() { - this.agentManager = GameObject.Find("PhysicsSceneManager").GetComponentInChildren(); + this.agentManager = GameObject + .Find("PhysicsSceneManager") + .GetComponentInChildren(); this.agentManager.SetUpPhysicsController(); - + // inputField = GameObject.Find("DebugCanvasPhysics").GetComponentInChildren();// FindObjectOfType(); // GameObject.Find("DebugCanvas").GetComponentInChildren(); Init(); @@ -43,18 +44,24 @@ public void GetRenderPath() SendMetadata("" + GetComponentInChildren().actualRenderingPath); } - public void SetController(string controlModeEnumString) + public void SetController(string controlModeEnumString) { - ControlMode controlMode = (ControlMode) Enum.Parse(typeof(ControlMode), controlModeEnumString, true); + ControlMode controlMode = (ControlMode) + Enum.Parse(typeof(ControlMode), controlModeEnumString, true); // inputField.setControlMode(controlMode); Type componentType; - var success = PlayerControllers.controlModeToComponent.TryGetValue(controlMode, out componentType); + var success = PlayerControllers.controlModeToComponent.TryGetValue( + controlMode, + out componentType + ); var Agent = CurrentActiveController().gameObject; - if (success) { + if (success) + { var previousComponent = Agent.GetComponent(componentType) as MonoBehaviour; - if (previousComponent == null) { - previousComponent = Agent.AddComponent(componentType) as MonoBehaviour; + if (previousComponent == null) + { + previousComponent = Agent.AddComponent(componentType) as MonoBehaviour; } previousComponent.enabled = true; } @@ -65,7 +72,8 @@ public void Step(string jsonAction) this.agentManager.ProcessControlCommand(new DynamicServerAction(jsonAction)); } - private BaseFPSAgentController CurrentActiveController() { + private BaseFPSAgentController CurrentActiveController() + { return this.agentManager.PrimaryAgent; } diff --git a/unity/Assets/Scripts/KinovaArmAgentController.cs b/unity/Assets/Scripts/KinovaArmAgentController.cs index 9675db433e..831dccb339 100644 --- a/unity/Assets/Scripts/KinovaArmAgentController.cs +++ b/unity/Assets/Scripts/KinovaArmAgentController.cs @@ -1,16 +1,18 @@ +using System; using System.Collections; using System.Collections.Generic; -using UnityEngine; -using System; using System.Linq; using RandomExtensions; +using UnityEngine; using UnityEngine.AI; namespace UnityStandardAssets.Characters.FirstPerson { - public partial class KinovaArmAgentController : ArmAgentController { - public KinovaArmAgentController(BaseAgentComponent baseAgentComponent, AgentManager agentManager) : base(baseAgentComponent, agentManager) { - } + public KinovaArmAgentController( + BaseAgentComponent baseAgentComponent, + AgentManager agentManager + ) + : base(baseAgentComponent, agentManager) { } public override ActionFinished InitializeBody(ServerAction initializeAction) { base.InitializeBody(initializeAction); @@ -18,7 +20,10 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { IKArm.SetActive(true); Arm = this.GetComponentInChildren(); Arm.PhysicsController = this; - var armTarget = Arm.transform.Find("robot_arm_FK_IK_rig").Find("IK_rig").Find("IK_pos_rot_manipulator"); + var armTarget = Arm + .transform.Find("robot_arm_FK_IK_rig") + .Find("IK_rig") + .Find("IK_pos_rot_manipulator"); Vector3 pos = armTarget.transform.localPosition; pos.z = 0.4f; // pulls the arm in from being fully extended armTarget.transform.localPosition = pos; @@ -32,8 +37,8 @@ private IK_Robot_Arm_Controller getArmImplementation() { IK_Robot_Arm_Controller arm = GetComponentInChildren(); if (arm == null) { throw new InvalidOperationException( - "Agent does not have kinematic arm or is not enabled.\n" + - $"Make sure there is a '{typeof(IK_Robot_Arm_Controller).Name}' component as a child of this agent." + "Agent does not have kinematic arm or is not enabled.\n" + + $"Make sure there is a '{typeof(IK_Robot_Arm_Controller).Name}' component as a child of this agent." ); } return arm; @@ -52,17 +57,24 @@ public void TeleportArm( bool forceAction = false ) { GameObject heightManip = this.GetComponent().IKArm; - GameObject posRotManip = this.GetComponent().IKArm.GetComponent().GetArmTarget(); - GameObject elbowManip = this.GetComponent().IKArm.GetComponent().GetElbowTarget(); + GameObject posRotManip = this.GetComponent() + .IKArm.GetComponent() + .GetArmTarget(); + GameObject elbowManip = this.GetComponent() + .IKArm.GetComponent() + .GetElbowTarget(); // cache old values in case there's a failure Vector3 oldLocalPosition = posRotManip.transform.localPosition; float oldLocalRotationAngle; Vector3 oldLocalRotationAxis; - posRotManip.transform.localRotation.ToAngleAxis(angle: out oldLocalRotationAngle, axis: out oldLocalRotationAxis); + posRotManip.transform.localRotation.ToAngleAxis( + angle: out oldLocalRotationAngle, + axis: out oldLocalRotationAxis + ); float oldArmHeight = heightManip.transform.localPosition.y; float oldElbowOrientation = elbowManip.transform.localEulerAngles.z; - + // establish defaults in the absence of inputs if (position == null) { position = new Vector3(0f, 0f, 0.4f); @@ -89,17 +101,17 @@ public void TeleportArm( // teleport arm-elements if (!worldRelative) { - posRotManip.transform.localPosition = (Vector3)position; - posRotManip.transform.localRotation = Quaternion.AngleAxis( - ((Vector4)rotation).w % 360, - new Vector3(((Vector4)rotation).x, ((Vector4)rotation).y, ((Vector4)rotation).z) - ); + posRotManip.transform.localPosition = (Vector3)position; + posRotManip.transform.localRotation = Quaternion.AngleAxis( + ((Vector4)rotation).w % 360, + new Vector3(((Vector4)rotation).x, ((Vector4)rotation).y, ((Vector4)rotation).z) + ); } else { - posRotManip.transform.position = (Vector3)position; - posRotManip.transform.rotation = Quaternion.AngleAxis( - ((Vector4)rotation).w % 360, - new Vector3(((Vector4)rotation).x, ((Vector4)rotation).y, ((Vector4)rotation).z) - ); + posRotManip.transform.position = (Vector3)position; + posRotManip.transform.rotation = Quaternion.AngleAxis( + ((Vector4)rotation).w % 360, + new Vector3(((Vector4)rotation).x, ((Vector4)rotation).y, ((Vector4)rotation).z) + ); } elbowManip.transform.localEulerAngles = new Vector3( @@ -113,13 +125,18 @@ public void TeleportArm( heightManip.transform.localPosition = new Vector3( heightManip.transform.localPosition.x, oldArmHeight, - heightManip.transform.localPosition.z); + heightManip.transform.localPosition.z + ); posRotManip.transform.localPosition = oldLocalPosition; - posRotManip.transform.localRotation = Quaternion.AngleAxis(oldLocalRotationAngle, oldLocalRotationAxis); + posRotManip.transform.localRotation = Quaternion.AngleAxis( + oldLocalRotationAngle, + oldLocalRotationAxis + ); elbowManip.transform.localEulerAngles = new Vector3( elbowManip.transform.localEulerAngles.x, elbowManip.transform.localEulerAngles.y, - oldElbowOrientation); + oldElbowOrientation + ); actionFinished(false); } else { actionFinished(true); @@ -162,8 +179,8 @@ public void RotateWristAroundHeldObject( } else { actionFinished( success: false, - errorMessage: $"Cannot RotateWristAroundHeldObject when holding" + - $" != 1 objects, currently holding {arm.heldObjects.Count} objects." + errorMessage: $"Cannot RotateWristAroundHeldObject when holding" + + $" != 1 objects, currently holding {arm.heldObjects.Count} objects." ); } } @@ -203,11 +220,7 @@ to prevent self-collisions. In particular we need to account for the hierarchy of rigidbodies of each arm joint and determine how to detect collision between a given arm joint and other arm joints. */ - public void RotateElbowRelative( - float degrees, - float speed = 10f, - bool returnToStart = true - ) { + public void RotateElbowRelative(float degrees, float speed = 10f, bool returnToStart = true) { IK_Robot_Arm_Controller arm = getArmImplementation(); arm.rotateElbowRelative( @@ -222,11 +235,7 @@ public void RotateElbowRelative( /* Same as RotateElbowRelative but rotates the elbow to a given angle directly. */ - public void RotateElbow( - float degrees, - float speed = 10f, - bool returnToStart = true - ) { + public void RotateElbow(float degrees, float speed = 10f, bool returnToStart = true) { IK_Robot_Arm_Controller arm = getArmImplementation(); arm.rotateElbow( diff --git a/unity/Assets/Scripts/Lamp.cs b/unity/Assets/Scripts/Lamp.cs index 2b1de0c4c6..929b3270d5 100644 --- a/unity/Assets/Scripts/Lamp.cs +++ b/unity/Assets/Scripts/Lamp.cs @@ -1,10 +1,9 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; [ExecuteInEditMode] public class Lamp : MonoBehaviour { - public SimObj ParentObj; public bool EditorOn = false; public bool OnByDefault = true; @@ -24,7 +23,8 @@ void OnEnable() { Animator a = ParentObj.gameObject.GetComponent(); if (a == null) { a = ParentObj.gameObject.AddComponent(); - a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; + a.runtimeAnimatorController = + Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; } } else { if (OnByDefault) { @@ -40,7 +40,12 @@ void Update() { } // lights.length was == null - if (LampshadeRenderer == null || OnMaterial == null || OffMaterial == null || Lights.Length == 0) { + if ( + LampshadeRenderer == null + || OnMaterial == null + || OffMaterial == null + || Lights.Length == 0 + ) { Debug.LogError("Required item null in lamp " + name); return; } diff --git a/unity/Assets/Scripts/Laptop.cs b/unity/Assets/Scripts/Laptop.cs index 8e36325456..4d30401009 100644 --- a/unity/Assets/Scripts/Laptop.cs +++ b/unity/Assets/Scripts/Laptop.cs @@ -1,10 +1,9 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; [ExecuteInEditMode] public class Laptop : MonoBehaviour { - public SimObj SimObjParent; public Transform[] PivotTransforms; public Renderer[] ScreenRenderers; diff --git a/unity/Assets/Scripts/LightSwitch.cs b/unity/Assets/Scripts/LightSwitch.cs index a397b1e085..5933a1e353 100644 --- a/unity/Assets/Scripts/LightSwitch.cs +++ b/unity/Assets/Scripts/LightSwitch.cs @@ -1,10 +1,9 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; [ExecuteInEditMode] public class LightSwitch : MonoBehaviour { - public SimObj ParentObj; public bool OnByDefault = true; public bool EditorOn = false; @@ -31,7 +30,8 @@ void OnEnable() { Animator a = ParentObj.gameObject.GetComponent(); if (a == null) { a = ParentObj.gameObject.AddComponent(); - a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; + a.runtimeAnimatorController = + Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; } } else { if (OnByDefault) { @@ -59,8 +59,12 @@ void Update() { SourceRenderers[i].sharedMaterials = sharedMats; } - RenderSettings.ambientEquatorColor = on ? equatorColor : Color.Lerp(equatorColor, Color.black, 0.5f); + RenderSettings.ambientEquatorColor = on + ? equatorColor + : Color.Lerp(equatorColor, Color.black, 0.5f); RenderSettings.ambientSkyColor = on ? skyColor : Color.Lerp(skyColor, Color.black, 0.5f); - RenderSettings.ambientGroundColor = on ? groundColor : Color.Lerp(groundColor, Color.black, 0.5f); + RenderSettings.ambientGroundColor = on + ? groundColor + : Color.Lerp(groundColor, Color.black, 0.5f); } } diff --git a/unity/Assets/Scripts/ListExtensions.cs b/unity/Assets/Scripts/ListExtensions.cs index 3cdeee001e..f0b95d93f9 100644 --- a/unity/Assets/Scripts/ListExtensions.cs +++ b/unity/Assets/Scripts/ListExtensions.cs @@ -1,17 +1,17 @@ // MIT License -// +// // Copyright (c) 2017 Justin Larrabee -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,11 +20,11 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Linq; +using UnityEngine; public static class ListExtensions { public static IList Shuffle(this IList list) { diff --git a/unity/Assets/Scripts/LocobotFPSAgentController.cs b/unity/Assets/Scripts/LocobotFPSAgentController.cs index fe3585d64a..4d0048b96d 100644 --- a/unity/Assets/Scripts/LocobotFPSAgentController.cs +++ b/unity/Assets/Scripts/LocobotFPSAgentController.cs @@ -1,18 +1,17 @@ - using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; +using RandomExtensions; using UnityEngine; using UnityEngine.Rendering; +using UnityEngine.Rendering.PostProcessing; using UnityEngine.SceneManagement; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.ImageEffects; using UnityStandardAssets.Utility; -using RandomExtensions; -using UnityEngine.Rendering.PostProcessing; namespace UnityStandardAssets.Characters.FirstPerson { public class LocobotFPSAgentController : BaseFPSAgentController { @@ -23,8 +22,11 @@ public class LocobotFPSAgentController : BaseFPSAgentController { protected float rotateGaussianSigma = 0.5f; protected bool allowHorizontalMovement = false; - public LocobotFPSAgentController(BaseAgentComponent baseAgentComponent, AgentManager agentManager) : base(baseAgentComponent, agentManager) { - } + public LocobotFPSAgentController( + BaseAgentComponent baseAgentComponent, + AgentManager agentManager + ) + : base(baseAgentComponent, agentManager) { } public override ActionFinished InitializeBody(ServerAction initializeAction) { // toggle FirstPersonCharacterCull @@ -50,7 +52,8 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { // set camera stand/crouch local positions for Tall mode standingLocalCameraPosition = m_Camera.transform.localPosition; - crouchingLocalCameraPosition = m_Camera.transform.localPosition + new Vector3(0, -0.2206f, 0);// smaller y offset if Bot + crouchingLocalCameraPosition = + m_Camera.transform.localPosition + new Vector3(0, -0.2206f, 0); // smaller y offset if Bot // limit camera from looking too far down/up if (Mathf.Approximately(initializeAction.maxUpwardLookAngle, 0.0f)) { @@ -87,8 +90,12 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { } #if UNITY_EDITOR - Debug.Log("MoveNoise: " + movementGaussianMu + " mu, " + movementGaussianSigma + " sigma"); - Debug.Log("RotateNoise: " + rotateGaussianMu + " mu, " + rotateGaussianSigma + " sigma"); + Debug.Log( + "MoveNoise: " + movementGaussianMu + " mu, " + movementGaussianSigma + " sigma" + ); + Debug.Log( + "RotateNoise: " + rotateGaussianMu + " mu, " + rotateGaussianSigma + " sigma" + ); Debug.Log("applynoise:" + applyActionNoise); #endif @@ -97,7 +104,8 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "FloorPlan_Train_Generated" ) { - GenerateRoboTHOR colorChangeComponent = physicsSceneManager.GetComponent(); + GenerateRoboTHOR colorChangeComponent = + physicsSceneManager.GetComponent(); colorChangeComponent.GenerateConfig(agentTransform: transform); } } @@ -116,7 +124,6 @@ public void MoveRelative( float noise = 0f, bool forceAction = false ) { - if (!moveMagnitude.HasValue) { moveMagnitude = gridSize; } else if (moveMagnitude.Value <= 0f) { @@ -124,7 +131,9 @@ public void MoveRelative( } if (!allowHorizontalMovement && Math.Abs(x) > 0) { - throw new InvalidOperationException("Controller does not support horizontal movement. Set AllowHorizontalMovement to true on the Controller."); + throw new InvalidOperationException( + "Controller does not support horizontal movement. Set AllowHorizontalMovement to true on the Controller." + ); } var moveLocal = new Vector3(x, 0, z); @@ -132,8 +141,10 @@ public void MoveRelative( if (xzMag > 1e-5f) { // rotate a small amount with every movement since robot doesn't always move perfectly straight if (this.applyActionNoise) { - var rotateNoise = (float)systemRandom.NextGaussian(rotateGaussianMu, rotateGaussianSigma / 2.0f); - transform.rotation = transform.rotation * Quaternion.Euler(new Vector3(0.0f, rotateNoise, 0.0f)); + var rotateNoise = (float) + systemRandom.NextGaussian(rotateGaussianMu, rotateGaussianSigma / 2.0f); + transform.rotation = + transform.rotation * Quaternion.Euler(new Vector3(0.0f, rotateNoise, 0.0f)); } var moveLocalNorm = moveLocal / xzMag; @@ -142,10 +153,12 @@ public void MoveRelative( noise: noise ); - actionFinished(moveInDirection( - direction: this.transform.rotation * (moveLocalNorm * magnitudeWithNoise), - forceAction: forceAction - )); + actionFinished( + moveInDirection( + direction: this.transform.rotation * (moveLocalNorm * magnitudeWithNoise), + forceAction: forceAction + ) + ); } else { errorMessage = "either x or z must be != 0 for the MoveRelative action"; actionFinished(false); @@ -173,7 +186,10 @@ public override void LookDown(ServerAction action) { action.degrees = Mathf.Round(action.degrees * 10.0f) / 10.0f; if (!checkForUpDownAngleLimit("down", action.degrees)) { - errorMessage = "can't look down beyond " + maxDownwardLookAngle + " degrees below the forward horizon"; + errorMessage = + "can't look down beyond " + + maxDownwardLookAngle + + " degrees below the forward horizon"; errorCode = ServerActionErrorCode.LookDownCantExceedMin; actionFinished(false); return; @@ -184,7 +200,6 @@ public override void LookDown(ServerAction action) { } public override void LookUp(ServerAction action) { - // default degree increment to 30 if (action.degrees == 0) { action.degrees = 30f; @@ -199,7 +214,10 @@ public override void LookUp(ServerAction action) { action.degrees = Mathf.Round(action.degrees * 10.0f) / 10.0f; if (!checkForUpDownAngleLimit("up", action.degrees)) { - errorMessage = "can't look up beyond " + maxUpwardLookAngle + " degrees above the forward horizon"; + errorMessage = + "can't look up beyond " + + maxUpwardLookAngle + + " degrees above the forward horizon"; errorCode = ServerActionErrorCode.LookDownCantExceedMin; actionFinished(false); return; @@ -219,12 +237,14 @@ public void Rotate(Vector3 rotation, float noise, bool manualInteract = false) { DefaultAgentHand(); } - float rotateAmountDegrees = GetRotateMagnitudeWithNoise(rotation: rotation, noise: noise); + float rotateAmountDegrees = GetRotateMagnitudeWithNoise( + rotation: rotation, + noise: noise + ); // multiply quaternions to apply rotation based on rotateAmountDegrees transform.rotation = ( - transform.rotation - * Quaternion.Euler(new Vector3(0.0f, rotateAmountDegrees, 0.0f)) + transform.rotation * Quaternion.Euler(new Vector3(0.0f, rotateAmountDegrees, 0.0f)) ); actionFinished(true); } @@ -253,20 +273,38 @@ public void RotateLeft(ServerAction action) { //////////////// TELEPORT ///////////////// /////////////////////////////////////////// - [ObsoleteAttribute(message: "This action is deprecated. Call Teleport(position, ...) instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call Teleport(position, ...) instead.", + error: false + )] public void Teleport( - float x, float y, float z, - Vector3? rotation = null, float? horizon = null, bool forceAction = false + float x, + float y, + float z, + Vector3? rotation = null, + float? horizon = null, + bool forceAction = false ) { Teleport( - position: new Vector3(x, y, z), rotation: rotation, horizon: horizon, forceAction: forceAction + position: new Vector3(x, y, z), + rotation: rotation, + horizon: horizon, + forceAction: forceAction ); } public void Teleport( - Vector3? position = null, Vector3? rotation = null, float? horizon = null, bool forceAction = false + Vector3? position = null, + Vector3? rotation = null, + float? horizon = null, + bool forceAction = false ) { - base.teleport(position: position, rotation: rotation, horizon: horizon, forceAction: forceAction); + base.teleport( + position: position, + rotation: rotation, + horizon: horizon, + forceAction: forceAction + ); base.assertTeleportedNearGround(targetPosition: position); actionFinished(success: true); } @@ -275,17 +313,38 @@ public void Teleport( ////////////// TELEPORT FULL ////////////// /////////////////////////////////////////// - [ObsoleteAttribute(message: "This action is deprecated. Call TeleportFull(position, ...) instead.", error: false)] - public void TeleportFull(float x, float y, float z, Vector3? rotation, float? horizon, bool forceAction = false) { + [ObsoleteAttribute( + message: "This action is deprecated. Call TeleportFull(position, ...) instead.", + error: false + )] + public void TeleportFull( + float x, + float y, + float z, + Vector3? rotation, + float? horizon, + bool forceAction = false + ) { TeleportFull( - position: new Vector3(x, y, z), rotation: rotation, horizon: horizon, forceAction: forceAction + position: new Vector3(x, y, z), + rotation: rotation, + horizon: horizon, + forceAction: forceAction ); } public void TeleportFull( - Vector3? position, Vector3? rotation, float? horizon, bool forceAction = false + Vector3? position, + Vector3? rotation, + float? horizon, + bool forceAction = false ) { - base.teleportFull(position: position, rotation: rotation, horizon: horizon, forceAction: forceAction); + base.teleportFull( + position: position, + rotation: rotation, + horizon: horizon, + forceAction: forceAction + ); base.assertTeleportedNearGround(targetPosition: transform.position); actionFinished(success: true); } @@ -322,7 +381,9 @@ public void MoveRight( bool forceAction = false ) { if (!allowHorizontalMovement) { - throw new InvalidOperationException("Controller does not support horizontal movement by default. Set AllowHorizontalMovement to true on the Controller."); + throw new InvalidOperationException( + "Controller does not support horizontal movement by default. Set AllowHorizontalMovement to true on the Controller." + ); } MoveRelative( x: 1.0f, @@ -338,7 +399,9 @@ public void MoveLeft( bool forceAction = false ) { if (!allowHorizontalMovement) { - throw new InvalidOperationException("Controller does not support horizontal movement by default. Set AllowHorizontalMovement to true on the Controller."); + throw new InvalidOperationException( + "Controller does not support horizontal movement by default. Set AllowHorizontalMovement to true on the Controller." + ); } MoveRelative( x: -1.0f, @@ -349,12 +412,16 @@ public void MoveLeft( } protected float GetMoveMagnitudeWithNoise(float moveMagnitude, float noise) { - float internalNoise = applyActionNoise ? (float)systemRandom.NextGaussian(movementGaussianMu, movementGaussianSigma) : 0; + float internalNoise = applyActionNoise + ? (float)systemRandom.NextGaussian(movementGaussianMu, movementGaussianSigma) + : 0; return moveMagnitude + noise + (float)internalNoise; } protected float GetRotateMagnitudeWithNoise(Vector3 rotation, float noise) { - float internalNoise = applyActionNoise ? (float)systemRandom.NextGaussian(rotateGaussianMu, rotateGaussianSigma) : 0; + float internalNoise = applyActionNoise + ? (float)systemRandom.NextGaussian(rotateGaussianMu, rotateGaussianSigma) + : 0; return rotation.y + noise + (float)internalNoise; } } diff --git a/unity/Assets/Scripts/Microwave.cs b/unity/Assets/Scripts/Microwave.cs index cee6b53c6c..faca2ad2f9 100644 --- a/unity/Assets/Scripts/Microwave.cs +++ b/unity/Assets/Scripts/Microwave.cs @@ -1,6 +1,6 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; //[ExecuteInEditMode] public class Microwave : MonoBehaviour { @@ -69,9 +69,16 @@ public void Update() { Door.localEulerAngles = targetDoorRotation; targetDoorRotation = Door.localEulerAngles; - Door.rotation = Quaternion.RotateTowards(doorStartRotation, Door.rotation, Time.deltaTime * SimUtil.SmoothAnimationSpeed * 25); + Door.rotation = Quaternion.RotateTowards( + doorStartRotation, + Door.rotation, + Time.deltaTime * SimUtil.SmoothAnimationSpeed * 25 + ); - float distanceToTarget = Vector3.Distance(Door.localEulerAngles, targetDoorRotation); + float distanceToTarget = Vector3.Distance( + Door.localEulerAngles, + targetDoorRotation + ); if (distanceToTarget >= 360f) { distanceToTarget -= 360f; } diff --git a/unity/Assets/Scripts/MinimalFPSController.cs b/unity/Assets/Scripts/MinimalFPSController.cs index 38c85339fd..d074dc0a22 100644 --- a/unity/Assets/Scripts/MinimalFPSController.cs +++ b/unity/Assets/Scripts/MinimalFPSController.cs @@ -1,16 +1,16 @@ // Copyright Allen Institute for Artificial Intelligence 2017 // Check Assets/Prefabs/DebugController for ReadMe on how to use this Debug Controller -using UnityEngine; -using Random = UnityEngine.Random; using System; -using System.IO; using System.Collections; using System.Collections.Generic; -using UnityStandardAssets.CrossPlatformInput; -using UnityStandardAssets.Utility; +using System.IO; +using System.Linq; +using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; -using System.Linq; +using UnityStandardAssets.CrossPlatformInput; +using UnityStandardAssets.Utility; +using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { [RequireComponent(typeof(CharacterController))] @@ -19,6 +19,7 @@ public class MinimalFPSController : DebugFPSAgentController { private GameObject Crosshair; private GameObject TargetText; private GameObject ThrowForceBar; + MinimalFPSController() { this.m_MouseLook = new MouseLook { XSensitivity = 2, @@ -69,7 +70,6 @@ public void ShowHUD() { BackgroundUI.SetActive(true); } - InputFieldObj.GetComponent().enabled = true; InputFieldObj.GetComponent().enabled = true; InputFieldObj.GetComponentsInChildren().ToList().ForEach(x => x.enabled = true); @@ -89,12 +89,10 @@ public void ShowHUD() { InputMode_Text.GetComponent().text = "FPS Mode"; } - Debug_Canvas = GameObject.Find("DebugCanvasPhysics"); Debug_Canvas.GetComponent().enabled = true; HideHUD(); - } public new void OnDisable() { @@ -116,4 +114,3 @@ public void ShowHUD() { } } } - diff --git a/unity/Assets/Scripts/Mirror.cs b/unity/Assets/Scripts/Mirror.cs index 9e743caafe..8359d471c0 100644 --- a/unity/Assets/Scripts/Mirror.cs +++ b/unity/Assets/Scripts/Mirror.cs @@ -1,10 +1,9 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; [ExecuteInEditMode] public class Mirror : MonoBehaviour { - public SimObj ParentObj; public bool EditorDirty = false; public GameObject DirtObject; @@ -20,7 +19,8 @@ void OnEnable() { Animator a = ParentObj.gameObject.GetComponent(); if (a == null) { a = ParentObj.gameObject.AddComponent(); - a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; + a.runtimeAnimatorController = + Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; } } } diff --git a/unity/Assets/Scripts/MyClass.cs b/unity/Assets/Scripts/MyClass.cs index a13df418f8..6ed7375d51 100644 --- a/unity/Assets/Scripts/MyClass.cs +++ b/unity/Assets/Scripts/MyClass.cs @@ -1,3 +1,2 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -internal class MyClass { -} \ No newline at end of file +internal class MyClass { } diff --git a/unity/Assets/Scripts/NavMeshSetup.cs b/unity/Assets/Scripts/NavMeshSetup.cs index 0f894115b9..ccb4baf4a0 100644 --- a/unity/Assets/Scripts/NavMeshSetup.cs +++ b/unity/Assets/Scripts/NavMeshSetup.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Collections.Generic; +using System.Linq; using UnityEngine; using UnityEngine.AI; using UnityStandardAssets.Characters.FirstPerson; @@ -7,18 +8,15 @@ using UnityEditor.SceneManagement; using UnityEditor; #endif -using System.Linq; public class NavMeshSetup : MonoBehaviour { public Transform goal; private UnityEngine.AI.NavMeshAgent navMeshAgent; private Transform hitPos; - // private PhysicsRemoteFPSAgentController PhysicsController = null; - void Start() { + // private PhysicsRemoteFPSAgentController PhysicsController = null; - - } + void Start() { } #if UNITY_EDITOR @@ -26,7 +24,7 @@ void Start() { public static void SaveHoudiniScenePrefabs() { var trainSceneNames = houdiniScenes(); - // These scenes were mannually adjusted so the nav mesh variables should not be set automatically and should be build manually + // These scenes were mannually adjusted so the nav mesh variables should not be set automatically and should be build manually trainSceneNames.ForEach((x) => saveSceneAsPrefab(x)); } @@ -35,8 +33,10 @@ private static void saveSceneAsPrefab(string sceneName) { GameObject sceneParent = new GameObject(); sceneParent.name = "Scene"; foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject))) { - if (obj.transform.parent == null && (obj.name == "Objects" || obj.name == "Structure" || obj.name == "Lighting")) { - + if ( + obj.transform.parent == null + && (obj.name == "Objects" || obj.name == "Structure" || obj.name == "Lighting") + ) { // create new object then destroy it GameObject copyObj = Instantiate(obj) as GameObject; copyObj.transform.parent = sceneParent.transform; @@ -47,7 +47,12 @@ private static void saveSceneAsPrefab(string sceneName) { sceneName = sceneName.Substring(sceneName.IndexOf("/") + 1); sceneName = sceneName.Substring(sceneName.IndexOf("/") + 1); - PrefabUtility.SaveAsPrefabAsset(sceneParent, "Assets/Scenes/prefab_exports/" + sceneName.Substring(0, sceneName.Length - ".unity".Length) + ".prefab"); + PrefabUtility.SaveAsPrefabAsset( + sceneParent, + "Assets/Scenes/prefab_exports/" + + sceneName.Substring(0, sceneName.Length - ".unity".Length) + + ".prefab" + ); DestroyImmediate(sceneParent); } @@ -111,12 +116,13 @@ public static void Build() { // selection.Add("Assets/Scenes/FloorPlan227_physics.unity"); - // These scenes were mannually adjusted so the nav mesh variables should not be set automatically and should be build manually - var exclude = new List() { - "Assets/Scenes/FloorPlan_Train7_1.unity", // Radius of agent made smaller to fit between table small path where reachable positions exist - "Assets/Scenes/FloorPlan_Train11_3.unity", // Unmade bed obstructs conectivity of navmesh - "Assets/Scenes/FloorPlan_Val2_3.unity", // Unmade bed obstructs conectivity of navmesh - }; + // These scenes were mannually adjusted so the nav mesh variables should not be set automatically and should be build manually + var exclude = new List() + { + "Assets/Scenes/FloorPlan_Train7_1.unity", // Radius of agent made smaller to fit between table small path where reachable positions exist + "Assets/Scenes/FloorPlan_Train11_3.unity", // Unmade bed obstructs conectivity of navmesh + "Assets/Scenes/FloorPlan_Val2_3.unity", // Unmade bed obstructs conectivity of navmesh + }; exclude.ForEach((x) => selection.Remove(x)); Debug.Log("Scenes: " + string.Join(",", selection.ToArray())); selection.ToList().ForEach(sceneName => BuildNavmeshForScene(sceneName)); @@ -125,9 +131,14 @@ public static void Build() { [UnityEditor.MenuItem("NavMesh/Build NavMesh for Active Scene")] public static void BuildForCurrentActiveScene() { BuildNavmeshForScene(EditorSceneManager.GetActiveScene().path); - } + } - private static List GetRoboSceneNames(int lastIndex, int lastSubIndex, string nameTemplate, string pathPrefix = "Assets/Scenes") { + private static List GetRoboSceneNames( + int lastIndex, + int lastSubIndex, + string nameTemplate, + string pathPrefix = "Assets/Scenes" + ) { var scenes = new List(); for (var i = 1; i <= lastIndex; i++) { for (var j = 1; j <= lastSubIndex; j++) { @@ -138,13 +149,16 @@ private static List GetRoboSceneNames(int lastIndex, int lastSubIndex, s return scenes; } - private static List GetSceneNames(int startIndex, int lastIndex, string nameTemplate = "", string pathPrefix = "Assets/Scenes") { + private static List GetSceneNames( + int startIndex, + int lastIndex, + string nameTemplate = "", + string pathPrefix = "Assets/Scenes" + ) { var scenes = new List(); for (var i = startIndex; i <= lastIndex; i++) { - var scene = pathPrefix + "/FloorPlan" + nameTemplate + i + "_physics.unity"; scenes.Add(scene); - } return scenes; } @@ -174,7 +188,7 @@ private static void BuildNavmeshForScene(string sceneName) { var navmeshAgent = agentController.GetComponentInChildren(); navmeshAgent.enabled = true; // The Editor bake interface does not take with parameters and could not be modified as of 2018.3 - //var buildSettings = + //var buildSettings = new NavMeshBuildSettings() { agentTypeID = navmeshAgent.agentTypeID, agentRadius = 0.2f, @@ -191,37 +205,57 @@ private static void BuildNavmeshForScene(string sceneName) { } public static void SetNavMeshNotWalkable(GameObject hierarchy) { - for (int i = 0; i < hierarchy.transform.childCount; i++) { var child = hierarchy.transform.GetChild(i); - child.GetComponentsInChildren().ToList().ForEach(meshRenderer => { - Debug.Log("Mesh Renderer " + meshRenderer.gameObject.name + " layer "); - UnityEditor.GameObjectUtility.SetStaticEditorFlags(meshRenderer.gameObject, UnityEditor.StaticEditorFlags.NavigationStatic); - UnityEditor.GameObjectUtility.SetNavMeshArea(meshRenderer.gameObject, NavMesh.GetAreaFromName("Not Walkable")); - }); + child + .GetComponentsInChildren() + .ToList() + .ForEach(meshRenderer => { + Debug.Log("Mesh Renderer " + meshRenderer.gameObject.name + " layer "); + UnityEditor.GameObjectUtility.SetStaticEditorFlags( + meshRenderer.gameObject, + UnityEditor.StaticEditorFlags.NavigationStatic + ); + UnityEditor.GameObjectUtility.SetNavMeshArea( + meshRenderer.gameObject, + NavMesh.GetAreaFromName("Not Walkable") + ); + }); //Debug.Log("Setting flag for " + child.gameObject.name + " layer " + NavMesh.GetAreaFromName("Not Walkable")); } } public static void SetNavMeshWalkable(GameObject hierarchy) { - // var objectHierarchy = hirerarchy.transform.FirstChildOrDefault(x => x.name.Contains("Floor")); - hierarchy.GetComponentsInChildren().ToList().ForEach(meshRenderer => { - Debug.Log("Mesh Renderer " + meshRenderer.gameObject.name + " layer "); - UnityEditor.GameObjectUtility.SetStaticEditorFlags(meshRenderer.gameObject, UnityEditor.StaticEditorFlags.NavigationStatic); - UnityEditor.GameObjectUtility.SetNavMeshArea(meshRenderer.gameObject, NavMesh.GetAreaFromName("Walkable")); - }); + hierarchy + .GetComponentsInChildren() + .ToList() + .ForEach(meshRenderer => { + Debug.Log("Mesh Renderer " + meshRenderer.gameObject.name + " layer "); + UnityEditor.GameObjectUtility.SetStaticEditorFlags( + meshRenderer.gameObject, + UnityEditor.StaticEditorFlags.NavigationStatic + ); + UnityEditor.GameObjectUtility.SetNavMeshArea( + meshRenderer.gameObject, + NavMesh.GetAreaFromName("Walkable") + ); + }); } private static GameObject SearchForSimObjectType(SimObjType sot, GameObject hierarchy) { GameObject go = null; - hierarchy.GetComponentsInChildren().ToList().ForEach(sop => { - if(sop.ObjType == sot) - go = sop.gameObject; - }); + hierarchy + .GetComponentsInChildren() + .ToList() + .ForEach(sop => { + if (sop.ObjType == sot) { + go = sop.gameObject; + } + }); return go; } #endif -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/NavMeshSurfaceExtended.cs b/unity/Assets/Scripts/NavMeshSurfaceExtended.cs index d23a263b00..c228c05f24 100644 --- a/unity/Assets/Scripts/NavMeshSurfaceExtended.cs +++ b/unity/Assets/Scripts/NavMeshSurfaceExtended.cs @@ -1,265 +1,324 @@ - using System; - using System.Collections.Generic; +using System; +using System.Collections.Generic; +using UnityEngine; using UnityEngine.AI; using UnityEngine.Scripting.APIUpdating; -using UnityEngine; #if UNITY_EDITOR using UnityEditor; using UnityEditor.SceneManagement; #endif - public class NavMeshSurfaceExtended : NavMeshSurface { - - - public NavMeshBuildSettings buildSettings { get; private set; } +public class NavMeshSurfaceExtended : NavMeshSurface { + public NavMeshBuildSettings buildSettings { get; private set; } - // static readonly List s_NavMeshSurfaces = new List(); + // static readonly List s_NavMeshSurfaces = new List(); - // /// Gets the list of all the components that are currently active in the scene. - // public static new List activeSurfaces - // { - // get { return s_NavMeshSurfaces; } - // } - // Dictionary navmeshes = new Dictionary(); - - public void BuildNavMesh(NavMeshBuildSettings buildSettings) - { - var sources = CollectSources(); - this.buildSettings = buildSettings; - - // Use unscaled bounds - this differs in behaviour from e.g. collider components. - // But is similar to reflection probe - and since navmesh data has no scaling support - it is the right choice here. - var sourcesBounds = new Bounds(center, Abs(size)); - if (collectObjects == CollectObjects.All || collectObjects == CollectObjects.Children) - { - sourcesBounds = CalculateWorldBounds(sources); - } + // /// Gets the list of all the components that are currently active in the scene. + // public static new List activeSurfaces + // { + // get { return s_NavMeshSurfaces; } + // } + // Dictionary navmeshes = new Dictionary(); - var data = NavMeshBuilder.BuildNavMeshData(buildSettings, - sources, sourcesBounds, transform.position, transform.rotation); + public void BuildNavMesh(NavMeshBuildSettings buildSettings) { + var sources = CollectSources(); + this.buildSettings = buildSettings; - if (data != null) - { - data.name = gameObject.name; - RemoveData(); - navMeshData = data; - if (isActiveAndEnabled) - AddData(); - } + // Use unscaled bounds - this differs in behaviour from e.g. collider components. + // But is similar to reflection probe - and since navmesh data has no scaling support - it is the right choice here. + var sourcesBounds = new Bounds(center, Abs(size)); + if (collectObjects == CollectObjects.All || collectObjects == CollectObjects.Children) { + sourcesBounds = CalculateWorldBounds(sources); } - /// Creates an instance of the NavMesh data and activates it in the navigation system. - /// The instance is created at the position and with the orientation of the GameObject. -// public void AddData() -// { -// #if UNITY_EDITOR -// var isInPreviewScene = EditorSceneManager.IsPreviewSceneObject(this); -// var isPrefab = isInPreviewScene || EditorUtility.IsPersistent(this); -// if (isPrefab) -// { -// //Debug.LogFormat("NavMeshData from {0}.{1} will not be added to the NavMesh world because the gameObject is a prefab.", -// // gameObject.name, name); -// return; -// } -// #endif -// if (m_NavMeshDataInstance.valid) -// return; - -// if (m_NavMeshData != null) -// { -// m_NavMeshDataInstance = NavMesh.AddNavMeshData(m_NavMeshData, transform.position, transform.rotation); -// m_NavMeshDataInstance.owner = this; -// } - -// m_LastPosition = transform.position; -// m_LastRotation = transform.rotation; -// } - - - - static Vector3 Abs(Vector3 v) - { - return new Vector3(Mathf.Abs(v.x), Mathf.Abs(v.y), Mathf.Abs(v.z)); + var data = NavMeshBuilder.BuildNavMeshData( + buildSettings, + sources, + sourcesBounds, + transform.position, + transform.rotation + ); + + if (data != null) { + data.name = gameObject.name; + RemoveData(); + navMeshData = data; + if (isActiveAndEnabled) { + AddData(); + } } - - Bounds CalculateWorldBounds(List sources) - { - // Use the unscaled matrix for the NavMeshSurface - Matrix4x4 worldToLocal = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one); - worldToLocal = worldToLocal.inverse; - - var result = new Bounds(); - foreach (var src in sources) - { - switch (src.shape) - { - case NavMeshBuildSourceShape.Mesh: - { - var m = src.sourceObject as Mesh; - result.Encapsulate(GetWorldBounds(worldToLocal * src.transform, m.bounds)); - break; - } - case NavMeshBuildSourceShape.Terrain: - { + } + + /// Creates an instance of the NavMesh data and activates it in the navigation system. + /// The instance is created at the position and with the orientation of the GameObject. + // public void AddData() + // { + // #if UNITY_EDITOR + // var isInPreviewScene = EditorSceneManager.IsPreviewSceneObject(this); + // var isPrefab = isInPreviewScene || EditorUtility.IsPersistent(this); + // if (isPrefab) + // { + // //Debug.LogFormat("NavMeshData from {0}.{1} will not be added to the NavMesh world because the gameObject is a prefab.", + // // gameObject.name, name); + // return; + // } + // #endif + // if (m_NavMeshDataInstance.valid) + // return; + + // if (m_NavMeshData != null) + // { + // m_NavMeshDataInstance = NavMesh.AddNavMeshData(m_NavMeshData, transform.position, transform.rotation); + // m_NavMeshDataInstance.owner = this; + // } + + // m_LastPosition = transform.position; + // m_LastRotation = transform.rotation; + // } + + + + static Vector3 Abs(Vector3 v) { + return new Vector3(Mathf.Abs(v.x), Mathf.Abs(v.y), Mathf.Abs(v.z)); + } + + Bounds CalculateWorldBounds(List sources) { + // Use the unscaled matrix for the NavMeshSurface + Matrix4x4 worldToLocal = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one); + worldToLocal = worldToLocal.inverse; + + var result = new Bounds(); + foreach (var src in sources) { + switch (src.shape) { + case NavMeshBuildSourceShape.Mesh: { + var m = src.sourceObject as Mesh; + result.Encapsulate(GetWorldBounds(worldToLocal * src.transform, m.bounds)); + break; + } + case NavMeshBuildSourceShape.Terrain: { #if NMC_CAN_ACCESS_TERRAIN - // Terrain pivot is lower/left corner - shift bounds accordingly - var t = src.sourceObject as TerrainData; - result.Encapsulate(GetWorldBounds(worldToLocal * src.transform, new Bounds(0.5f * t.size, t.size))); + // Terrain pivot is lower/left corner - shift bounds accordingly + var t = src.sourceObject as TerrainData; + result.Encapsulate( + GetWorldBounds( + worldToLocal * src.transform, + new Bounds(0.5f * t.size, t.size) + ) + ); #else - Debug.LogWarning("The NavMesh cannot be properly baked for the terrain because the necessary functionality is missing. Add the com.unity.modules.terrain package through the Package Manager."); + Debug.LogWarning( + "The NavMesh cannot be properly baked for the terrain because the necessary functionality is missing. Add the com.unity.modules.terrain package through the Package Manager." + ); #endif - break; - } - case NavMeshBuildSourceShape.Box: - case NavMeshBuildSourceShape.Sphere: - case NavMeshBuildSourceShape.Capsule: - case NavMeshBuildSourceShape.ModifierBox: - result.Encapsulate(GetWorldBounds(worldToLocal * src.transform, new Bounds(Vector3.zero, src.size))); break; - } + } + case NavMeshBuildSourceShape.Box: + case NavMeshBuildSourceShape.Sphere: + case NavMeshBuildSourceShape.Capsule: + case NavMeshBuildSourceShape.ModifierBox: + result.Encapsulate( + GetWorldBounds( + worldToLocal * src.transform, + new Bounds(Vector3.zero, src.size) + ) + ); + break; } - // Inflate the bounds a bit to avoid clipping co-planar sources - result.Expand(0.1f); - return result; - } - - static Bounds GetWorldBounds(Matrix4x4 mat, Bounds bounds) - { - var absAxisX = Abs(mat.MultiplyVector(Vector3.right)); - var absAxisY = Abs(mat.MultiplyVector(Vector3.up)); - var absAxisZ = Abs(mat.MultiplyVector(Vector3.forward)); - var worldPosition = mat.MultiplyPoint(bounds.center); - var worldSize = absAxisX * bounds.size.x + absAxisY * bounds.size.y + absAxisZ * bounds.size.z; - return new Bounds(worldPosition, worldSize); } - - void AppendModifierVolumes(ref List sources) - { + // Inflate the bounds a bit to avoid clipping co-planar sources + result.Expand(0.1f); + return result; + } + + static Bounds GetWorldBounds(Matrix4x4 mat, Bounds bounds) { + var absAxisX = Abs(mat.MultiplyVector(Vector3.right)); + var absAxisY = Abs(mat.MultiplyVector(Vector3.up)); + var absAxisZ = Abs(mat.MultiplyVector(Vector3.forward)); + var worldPosition = mat.MultiplyPoint(bounds.center); + var worldSize = + absAxisX * bounds.size.x + absAxisY * bounds.size.y + absAxisZ * bounds.size.z; + return new Bounds(worldPosition, worldSize); + } + + void AppendModifierVolumes(ref List sources) { #if UNITY_EDITOR - var myStage = StageUtility.GetStageHandle(gameObject); - if (!myStage.IsValid()) - return; + var myStage = StageUtility.GetStageHandle(gameObject); + if (!myStage.IsValid()) { + return; + } #endif - // Modifiers - List modifiers; - if (collectObjects == CollectObjects.Children) - { - modifiers = new List(GetComponentsInChildren()); - modifiers.RemoveAll(x => !x.isActiveAndEnabled); - } - else - { - modifiers = NavMeshModifierVolume.activeModifiers; + // Modifiers + List modifiers; + if (collectObjects == CollectObjects.Children) { + modifiers = new List( + GetComponentsInChildren() + ); + modifiers.RemoveAll(x => !x.isActiveAndEnabled); + } else { + modifiers = NavMeshModifierVolume.activeModifiers; + } + + foreach (var m in modifiers) { + if ((layerMask & (1 << m.gameObject.layer)) == 0) { + continue; } - foreach (var m in modifiers) - { - if ((layerMask & (1 << m.gameObject.layer)) == 0) - continue; - if (!m.AffectsAgentType(agentTypeID)) - continue; + if (!m.AffectsAgentType(agentTypeID)) { + continue; + } #if UNITY_EDITOR - if (!myStage.Contains(m.gameObject)) - continue; -#endif - var mcenter = m.transform.TransformPoint(m.center); - var scale = m.transform.lossyScale; - var msize = new Vector3(m.size.x * Mathf.Abs(scale.x), m.size.y * Mathf.Abs(scale.y), m.size.z * Mathf.Abs(scale.z)); - - var src = new NavMeshBuildSource(); - src.shape = NavMeshBuildSourceShape.ModifierBox; - src.transform = Matrix4x4.TRS(mcenter, m.transform.rotation, Vector3.one); - src.size = msize; - src.area = m.area; - sources.Add(src); + if (!myStage.Contains(m.gameObject)) { + continue; } +#endif + var mcenter = m.transform.TransformPoint(m.center); + var scale = m.transform.lossyScale; + var msize = new Vector3( + m.size.x * Mathf.Abs(scale.x), + m.size.y * Mathf.Abs(scale.y), + m.size.z * Mathf.Abs(scale.z) + ); + + var src = new NavMeshBuildSource(); + src.shape = NavMeshBuildSourceShape.ModifierBox; + src.transform = Matrix4x4.TRS(mcenter, m.transform.rotation, Vector3.one); + src.size = msize; + src.area = m.area; + sources.Add(src); + } + } + + public List CollectSources() { + var sources = new List(); + var markups = new List(); + + List modifiers; + if (collectObjects == CollectObjects.Children) { + modifiers = new List(GetComponentsInChildren()); + modifiers.RemoveAll(x => !x.isActiveAndEnabled); + } else { + modifiers = NavMeshModifier.activeModifiers; } - - - public List CollectSources() - { - var sources = new List(); - var markups = new List(); - - List modifiers; - if (collectObjects == CollectObjects.Children) - { - modifiers = new List(GetComponentsInChildren()); - modifiers.RemoveAll(x => !x.isActiveAndEnabled); - } - else - { - modifiers = NavMeshModifier.activeModifiers; + foreach (var m in modifiers) { + if ((layerMask & (1 << m.gameObject.layer)) == 0) { + continue; } - foreach (var m in modifiers) - { - if ((layerMask & (1 << m.gameObject.layer)) == 0) - continue; - if (!m.AffectsAgentType(agentTypeID)) - continue; - var markup = new NavMeshBuildMarkup(); - markup.root = m.transform; - markup.overrideArea = m.overrideArea; - markup.area = m.area; - markup.ignoreFromBuild = m.ignoreFromBuild; - markups.Add(markup); + if (!m.AffectsAgentType(agentTypeID)) { + continue; } + var markup = new NavMeshBuildMarkup(); + markup.root = m.transform; + markup.overrideArea = m.overrideArea; + markup.area = m.area; + markup.ignoreFromBuild = m.ignoreFromBuild; + markups.Add(markup); + } + #if UNITY_EDITOR - if (!EditorApplication.isPlaying) - { - if (collectObjects == CollectObjects.All) - { - UnityEditor.AI.NavMeshBuilder.CollectSourcesInStage( - null, layerMask, useGeometry, defaultArea, markups, gameObject.scene, sources); - } - else if (collectObjects == CollectObjects.Children) - { - UnityEditor.AI.NavMeshBuilder.CollectSourcesInStage( - transform, layerMask, useGeometry, defaultArea, markups, gameObject.scene, sources); - } - else if (collectObjects == CollectObjects.Volume) - { - Matrix4x4 localToWorld = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one); - - var worldBounds = GetWorldBounds(localToWorld, new Bounds(center, size)); - - UnityEditor.AI.NavMeshBuilder.CollectSourcesInStage( - worldBounds, layerMask, useGeometry, defaultArea, markups, gameObject.scene, sources); - } + if (!EditorApplication.isPlaying) { + if (collectObjects == CollectObjects.All) { + UnityEditor.AI.NavMeshBuilder.CollectSourcesInStage( + null, + layerMask, + useGeometry, + defaultArea, + markups, + gameObject.scene, + sources + ); + } else if (collectObjects == CollectObjects.Children) { + UnityEditor.AI.NavMeshBuilder.CollectSourcesInStage( + transform, + layerMask, + useGeometry, + defaultArea, + markups, + gameObject.scene, + sources + ); + } else if (collectObjects == CollectObjects.Volume) { + Matrix4x4 localToWorld = Matrix4x4.TRS( + transform.position, + transform.rotation, + Vector3.one + ); + + var worldBounds = GetWorldBounds(localToWorld, new Bounds(center, size)); + + UnityEditor.AI.NavMeshBuilder.CollectSourcesInStage( + worldBounds, + layerMask, + useGeometry, + defaultArea, + markups, + gameObject.scene, + sources + ); } - else + } else #endif - { - if (collectObjects == CollectObjects.All) - { - NavMeshBuilder.CollectSources(null, layerMask, useGeometry, defaultArea, markups, sources); - } - else if (collectObjects == CollectObjects.Children) - { - NavMeshBuilder.CollectSources(transform, layerMask, useGeometry, defaultArea, markups, sources); - } - else if (collectObjects == CollectObjects.Volume) - { - Matrix4x4 localToWorld = Matrix4x4.TRS(transform.position, transform.rotation, Vector3.one); - var worldBounds = GetWorldBounds(localToWorld, new Bounds(center, size)); - NavMeshBuilder.CollectSources(worldBounds, layerMask, useGeometry, defaultArea, markups, sources); - } - } - - if (ignoreNavMeshAgent) { - sources.RemoveAll((x) => (x.component != null && x.component.gameObject.GetComponent() != null)); - } - - if (ignoreNavMeshObstacle) { - sources.RemoveAll((x) => (x.component != null && x.component.gameObject.GetComponent() != null)); + { + if (collectObjects == CollectObjects.All) { + NavMeshBuilder.CollectSources( + null, + layerMask, + useGeometry, + defaultArea, + markups, + sources + ); + } else if (collectObjects == CollectObjects.Children) { + NavMeshBuilder.CollectSources( + transform, + layerMask, + useGeometry, + defaultArea, + markups, + sources + ); + } else if (collectObjects == CollectObjects.Volume) { + Matrix4x4 localToWorld = Matrix4x4.TRS( + transform.position, + transform.rotation, + Vector3.one + ); + var worldBounds = GetWorldBounds(localToWorld, new Bounds(center, size)); + NavMeshBuilder.CollectSources( + worldBounds, + layerMask, + useGeometry, + defaultArea, + markups, + sources + ); } + } - AppendModifierVolumes(ref sources); + if (ignoreNavMeshAgent) { + sources.RemoveAll( + (x) => + ( + x.component != null + && x.component.gameObject.GetComponent() != null + ) + ); + } - return sources; + if (ignoreNavMeshObstacle) { + sources.RemoveAll( + (x) => + ( + x.component != null + && x.component.gameObject.GetComponent() != null + ) + ); } - } \ No newline at end of file + AppendModifierVolumes(ref sources); + + return sources; + } +} diff --git a/unity/Assets/Scripts/ObjaverseAnnotation.cs b/unity/Assets/Scripts/ObjaverseAnnotation.cs index a933db002d..25ffcc27cd 100644 --- a/unity/Assets/Scripts/ObjaverseAnnotation.cs +++ b/unity/Assets/Scripts/ObjaverseAnnotation.cs @@ -2,19 +2,17 @@ using UnityEngine; namespace Thor.Objaverse { - public enum Dataset { Objaverse1_0, ObjaversePlus, ObjaverseXL } - public class ObjaverseAnnotation : MonoBehaviour - { - [SerializeField] public string ObjectCategory; + public class ObjaverseAnnotation : MonoBehaviour { + [SerializeField] + public string ObjectCategory; - [SerializeField] public Dataset MostSpecificDataset = Dataset.Objaverse1_0; + [SerializeField] + public Dataset MostSpecificDataset = Dataset.Objaverse1_0; } - - -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/ObjectHighlightController.cs b/unity/Assets/Scripts/ObjectHighlightController.cs index a966a17a9a..f3496b65f3 100644 --- a/unity/Assets/Scripts/ObjectHighlightController.cs +++ b/unity/Assets/Scripts/ObjectHighlightController.cs @@ -1,19 +1,18 @@ // Copyright Allen Institute for Artificial Intelligence 2017 // Check Assets/Prefabs/DebugController for ReadMe on how to use this Debug Controller -using UnityEngine; -using Random = UnityEngine.Random; using System; -using System.IO; using System.Collections; using System.Collections.Generic; -using UnityStandardAssets.CrossPlatformInput; -using UnityStandardAssets.Utility; +using System.IO; +using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; using UnityStandardAssets.Characters.FirstPerson; +using UnityStandardAssets.CrossPlatformInput; +using UnityStandardAssets.Utility; +using Random = UnityEngine.Random; namespace UnityStandardAssets.Characters.FirstPerson { - [Serializable] public class HighlightConfig { public Color TextStrongColor; @@ -25,12 +24,24 @@ public class HighlightConfig { } public class ObjectHighlightController { - [SerializeField] private Text TargetText = null; - [SerializeField] private Slider ThrowForceBarSlider = null; - [SerializeField] private float MinHighlightDistance = 5f; - [SerializeField] private float MaxChargeThrowSeconds = 1.4f; - [SerializeField] private float MaxThrowForce = 400.0f; - [SerializeField] private bool DisplayTargetText = true; + [SerializeField] + private Text TargetText = null; + + [SerializeField] + private Slider ThrowForceBarSlider = null; + + [SerializeField] + private float MinHighlightDistance = 5f; + + [SerializeField] + private float MaxChargeThrowSeconds = 1.4f; + + [SerializeField] + private float MaxThrowForce = 400.0f; + + [SerializeField] + private bool DisplayTargetText = true; + [SerializeField] private HighlightConfig HighlightParams = new HighlightConfig { TextStrongColor = new Color(1.0f, 1.0f, 1.0f, 1.0f), @@ -65,7 +76,6 @@ public class ObjectHighlightController { private bool withHighlightShader = true; - public ObjectHighlightController( PhysicsRemoteFPSAgentController physicsController, float minHighlightDistance, @@ -108,17 +118,30 @@ public void SetOnlyPickableId(string objectId, bool disableHighlightShaderForObj public void MouseControls() { // Interact action for mouse left-click when nothing is picked up if (Input.GetKeyDown(KeyCode.Mouse0)) { - if (this.PhysicsController.WhatAmIHolding() == null && this.PhysicsController.ReadyForCommand) { + if ( + this.PhysicsController.WhatAmIHolding() == null + && this.PhysicsController.ReadyForCommand + ) { var closestObj = this.highlightedObject; if (closestObj != null) { var actionName = ""; - if (closestObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup && (onlyPickableObjectId == null || onlyPickableObjectId == closestObj.objectID)) { + if ( + closestObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup + && ( + onlyPickableObjectId == null + || onlyPickableObjectId == closestObj.objectID + ) + ) { pickupState = true; actionName = "PickupObject"; } else if (closestObj.GetComponent()) { - actionName = closestObj.GetComponent().isOpen ? "CloseObject" : "OpenObject"; + actionName = closestObj.GetComponent().isOpen + ? "CloseObject" + : "OpenObject"; } else if (closestObj.GetComponent()) { - actionName = closestObj.GetComponent().isOn ? "ToggleObjectOff" : "ToggleObjectOn"; + actionName = closestObj.GetComponent().isOn + ? "ToggleObjectOff" + : "ToggleObjectOn"; } if (actionName != "") { @@ -133,12 +156,19 @@ public void MouseControls() { this.timerAtPress = Time.time; } - if (highlightWhileHolding && this.highlightedObject != null && this.PhysicsController.WhatAmIHolding() != this.highlightedObject.gameObject && this.PhysicsController.ReadyForCommand) { + if ( + highlightWhileHolding + && this.highlightedObject != null + && this.PhysicsController.WhatAmIHolding() != this.highlightedObject.gameObject + && this.PhysicsController.ReadyForCommand + ) { var closestObj = this.highlightedObject; if (closestObj != null) { var actionName = ""; if (closestObj.GetComponent()) { - actionName = closestObj.GetComponent().isOpen ? "CloseObject" : "OpenObject"; + actionName = closestObj.GetComponent().isOpen + ? "CloseObject" + : "OpenObject"; } if (actionName != "") { @@ -195,9 +225,10 @@ public void MouseControls() { var clampedForceTime = Mathf.Min(diff * diff, MaxChargeThrowSeconds); ThrowForceBarSlider.value = clampedForceTime / MaxChargeThrowSeconds; } else { - ThrowForceBarSlider.value -= ThrowForceBarSlider.value > 0.0f ? - Time.deltaTime / MaxChargeThrowSeconds : - 0.0f; + ThrowForceBarSlider.value -= + ThrowForceBarSlider.value > 0.0f + ? Time.deltaTime / MaxChargeThrowSeconds + : 0.0f; } } @@ -209,7 +240,17 @@ public void MouseControls() { var clampedForceTime = Mathf.Min(diff * diff, MaxChargeThrowSeconds); var force = clampedForceTime * MaxThrowForce / MaxChargeThrowSeconds; - if (this.PhysicsController.ReadyForCommand && (!this.highlightWhileHolding || (highlightedObject != null && this.PhysicsController.WhatAmIHolding() == highlightedObject.gameObject))) { + if ( + this.PhysicsController.ReadyForCommand + && ( + !this.highlightWhileHolding + || ( + highlightedObject != null + && this.PhysicsController.WhatAmIHolding() + == highlightedObject.gameObject + ) + ) + ) { Dictionary action = new Dictionary(); action["forceAction"] = true; @@ -232,31 +273,49 @@ public void MouseControls() { public void UpdateHighlightedObject(Vector3 screenPosition) { RaycastHit hit = new RaycastHit(); var ray = m_Camera.GetComponent().ScreenPointToRay(screenPosition); - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); Physics.Raycast(ray, out hit, this.MinHighlightDistance, layerMask); Debug.DrawLine(ray.origin, hit.point, Color.red); SimObjPhysics newHighlightedObject = null; Shader newPreviousShader = null; - if (hit.transform != null + if ( + hit.transform != null && hit.transform.tag == "SimObjPhysics" && (this.PhysicsController.WhatAmIHolding() == null || this.highlightWhileHolding) - ) { + ) { softHighlight = true; var simObj = hit.transform.GetComponent(); Func validObjectLazy = () => { - return (simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup && (this.onlyPickableObjectId == null || this.onlyPickableObjectId == simObj.objectID)) || - simObj.GetComponent() || - simObj.GetComponent(); + return ( + simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup + && ( + this.onlyPickableObjectId == null + || this.onlyPickableObjectId == simObj.objectID + ) + ) + || simObj.GetComponent() + || simObj.GetComponent(); }; if (simObj != null && validObjectLazy()) { - var withinReach = PhysicsController.FindObjectInVisibleSimObjPhysics(simObj.objectID) != null; + var withinReach = + PhysicsController.FindObjectInVisibleSimObjPhysics(simObj.objectID) != null; setTargetText(simObj.name, withinReach); newHighlightedObject = simObj; var mRenderer = newHighlightedObject.GetComponentInChildren(); - var useHighlightShader = !(disableHighlightShaderForObject && simObj.objectID == this.onlyPickableObjectId) && this.withHighlightShader; + var useHighlightShader = + !( + disableHighlightShaderForObject + && simObj.objectID == this.onlyPickableObjectId + ) && this.withHighlightShader; if (mRenderer != null && useHighlightShader) { if (this.highlightedObject != newHighlightedObject) { @@ -268,12 +327,24 @@ public void UpdateHighlightedObject(Vector3 screenPosition) { if (withinReach) { softHighlight = true; - mRenderer.sharedMaterial.SetFloat("_Outline", this.HighlightParams.WithinReachOutlineThickness); - mRenderer.sharedMaterial.SetColor("_OutlineColor", this.HighlightParams.WithinReachOutlineColor); + mRenderer.sharedMaterial.SetFloat( + "_Outline", + this.HighlightParams.WithinReachOutlineThickness + ); + mRenderer.sharedMaterial.SetColor( + "_OutlineColor", + this.HighlightParams.WithinReachOutlineColor + ); } else if (softHighlight) { softHighlight = false; - mRenderer.sharedMaterial.SetFloat("_Outline", this.HighlightParams.SoftOutlineThickness); - mRenderer.sharedMaterial.SetColor("_OutlineColor", this.HighlightParams.SoftOutlineColor); + mRenderer.sharedMaterial.SetFloat( + "_Outline", + this.HighlightParams.SoftOutlineThickness + ); + mRenderer.sharedMaterial.SetColor( + "_OutlineColor", + this.HighlightParams.SoftOutlineColor + ); } } } @@ -285,7 +356,11 @@ public void UpdateHighlightedObject(Vector3 screenPosition) { var mRenderer = this.highlightedObject.GetComponentInChildren(); setTargetText(""); - var useHighlightShader = !(disableHighlightShaderForObject && highlightedObject.objectID == this.onlyPickableObjectId) && this.withHighlightShader; + var useHighlightShader = + !( + disableHighlightShaderForObject + && highlightedObject.objectID == this.onlyPickableObjectId + ) && this.withHighlightShader; if (mRenderer != null && useHighlightShader) { mRenderer.material.shader = this.previousShader; @@ -298,7 +373,6 @@ public void UpdateHighlightedObject(Vector3 screenPosition) { this.previousShader = newPreviousShader; } - this.highlightedObject = newHighlightedObject; } @@ -307,7 +381,9 @@ private void setTargetText(string text, bool withinReach = false) { if (withinReach) { this.TargetText.color = this.HighlightParams.TextStrongColor; this.CrosshairText.text = "( + )"; - } else if (Math.Abs(this.TargetText.color.a - this.HighlightParams.TextStrongColor.a) < eps) { + } else if ( + Math.Abs(this.TargetText.color.a - this.HighlightParams.TextStrongColor.a) < eps + ) { this.TargetText.color = this.HighlightParams.TextFaintColor; this.CrosshairText.text = "+"; } @@ -316,9 +392,6 @@ private void setTargetText(string text, bool withinReach = false) { // concatenate the name so just the object type is displayed, not the ugly list of letters/numbers (the unique string) after this.TargetText.text = text.Split('_')[0]; } - } - } - } diff --git a/unity/Assets/Scripts/ObjectSpawner.cs b/unity/Assets/Scripts/ObjectSpawner.cs index f46815f9c8..179e9657a5 100644 --- a/unity/Assets/Scripts/ObjectSpawner.cs +++ b/unity/Assets/Scripts/ObjectSpawner.cs @@ -6,12 +6,8 @@ public class ObjectSpawner : MonoBehaviour { public GameObject[] PrefabToSpawn = null; // Use this for initialization - void Start() { - - } + void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } } diff --git a/unity/Assets/Scripts/ObjectSpecificReceptacle.cs b/unity/Assets/Scripts/ObjectSpecificReceptacle.cs index 569fe82b33..7a6b4fd80e 100644 --- a/unity/Assets/Scripts/ObjectSpecificReceptacle.cs +++ b/unity/Assets/Scripts/ObjectSpecificReceptacle.cs @@ -41,10 +41,17 @@ public bool isFull() { // Use this for initialization void Start() { #if UNITY_EDITOR - if (!gameObject.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.ObjectSpecificReceptacle)) { - Debug.LogError(this.name + " is missing the Secondary Property ObjectSpecificReceptacle!"); + if ( + !gameObject + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.ObjectSpecificReceptacle + ) + ) { + Debug.LogError( + this.name + " is missing the Secondary Property ObjectSpecificReceptacle!" + ); } #endif } - } diff --git a/unity/Assets/Scripts/PenDraw.cs b/unity/Assets/Scripts/PenDraw.cs index c2f6ed26d2..5abbbdf8ba 100644 --- a/unity/Assets/Scripts/PenDraw.cs +++ b/unity/Assets/Scripts/PenDraw.cs @@ -2,47 +2,61 @@ using System.Collections.Generic; using UnityEngine; -public class PenDraw : MonoBehaviour -{ +public class PenDraw : MonoBehaviour { public GameObject penDecal; public GameObject raycastOrigin; private bool shouldSpawn = true; // Start is called before the first frame update - void Start() - { - - } + void Start() { } // Update is called once per frame - void Update() - { - - } + void Update() { } void OnTriggerStay(Collider other) { - if (other.CompareTag("DecalSpawnPlane") && shouldSpawn) { RaycastHit hit; //check if we hit the spawn plane below the pencil - if (Physics.Raycast(raycastOrigin.transform.position, raycastOrigin.transform.forward, out hit, Mathf.Infinity, LayerMask.GetMask("Default"))) { - + if ( + Physics.Raycast( + raycastOrigin.transform.position, + raycastOrigin.transform.forward, + out hit, + Mathf.Infinity, + LayerMask.GetMask("Default") + ) + ) { //Debug.DrawRay(hit.point, Vector3.up * 10, Color.red); //check if we hit another pen mark, if so don't place anything because its too close if (hit.collider.tag == "Pen") { return; } - //ok so if its not a pen mark, that means we hit a dirt mark which means we can spawn on the table else { - if (Physics.Raycast(raycastOrigin.transform.position, raycastOrigin.transform.forward, out hit, Mathf.Infinity, LayerMask.GetMask("SimObjVisible"))) { + if ( + Physics.Raycast( + raycastOrigin.transform.position, + raycastOrigin.transform.forward, + out hit, + Mathf.Infinity, + LayerMask.GetMask("SimObjVisible") + ) + ) { Object.Instantiate(penDecal, hit.point, Quaternion.Euler(-90, 0, 0)); } } } else { - if (Physics.Raycast(raycastOrigin.transform.position, raycastOrigin.transform.forward, out hit, Mathf.Infinity, LayerMask.GetMask("SimObjVisible"))) { + if ( + Physics.Raycast( + raycastOrigin.transform.position, + raycastOrigin.transform.forward, + out hit, + Mathf.Infinity, + LayerMask.GetMask("SimObjVisible") + ) + ) { Object.Instantiate(penDecal, hit.point, Quaternion.Euler(-90, 0, 0)); } } diff --git a/unity/Assets/Scripts/PhysicsExtensions.cs b/unity/Assets/Scripts/PhysicsExtensions.cs index 093827cb74..9f4424231e 100644 --- a/unity/Assets/Scripts/PhysicsExtensions.cs +++ b/unity/Assets/Scripts/PhysicsExtensions.cs @@ -1,17 +1,17 @@ // MIT License -// +// // Copyright (c) 2017 Justin Larrabee -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -20,73 +20,178 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. -using UnityEngine; using System; using System.Collections; using System.Collections.Generic; +using UnityEngine; public static class PhysicsExtensions { // // Box // - public static bool BoxCast(BoxCollider box, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { - Vector3 center, halfExtents; + public static bool BoxCast( + BoxCollider box, + Vector3 direction, + float maxDistance = Mathf.Infinity, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { + Vector3 center, + halfExtents; Quaternion orientation; box.ToWorldSpaceBox(out center, out halfExtents, out orientation); - return Physics.BoxCast(center, halfExtents, direction, orientation, maxDistance, layerMask, queryTriggerInteraction); + return Physics.BoxCast( + center, + halfExtents, + direction, + orientation, + maxDistance, + layerMask, + queryTriggerInteraction + ); } - public static bool BoxCast(BoxCollider box, Vector3 direction, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { - Vector3 center, halfExtents; + public static bool BoxCast( + BoxCollider box, + Vector3 direction, + out RaycastHit hitInfo, + float maxDistance = Mathf.Infinity, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { + Vector3 center, + halfExtents; Quaternion orientation; box.ToWorldSpaceBox(out center, out halfExtents, out orientation); - return Physics.BoxCast(center, halfExtents, direction, out hitInfo, orientation, maxDistance, layerMask, queryTriggerInteraction); + return Physics.BoxCast( + center, + halfExtents, + direction, + out hitInfo, + orientation, + maxDistance, + layerMask, + queryTriggerInteraction + ); } - public static RaycastHit[] BoxCastAll(BoxCollider box, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { - Vector3 center, halfExtents; + public static RaycastHit[] BoxCastAll( + BoxCollider box, + Vector3 direction, + float maxDistance = Mathf.Infinity, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { + Vector3 center, + halfExtents; Quaternion orientation; box.ToWorldSpaceBox(out center, out halfExtents, out orientation); - return Physics.BoxCastAll(center, halfExtents, direction, orientation, maxDistance, layerMask, queryTriggerInteraction); + return Physics.BoxCastAll( + center, + halfExtents, + direction, + orientation, + maxDistance, + layerMask, + queryTriggerInteraction + ); } - public static int BoxCastNonAlloc(BoxCollider box, Vector3 direction, RaycastHit[] results, float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { - Vector3 center, halfExtents; + public static int BoxCastNonAlloc( + BoxCollider box, + Vector3 direction, + RaycastHit[] results, + float maxDistance = Mathf.Infinity, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { + Vector3 center, + halfExtents; Quaternion orientation; box.ToWorldSpaceBox(out center, out halfExtents, out orientation); - return Physics.BoxCastNonAlloc(center, halfExtents, direction, results, orientation, maxDistance, layerMask, queryTriggerInteraction); + return Physics.BoxCastNonAlloc( + center, + halfExtents, + direction, + results, + orientation, + maxDistance, + layerMask, + queryTriggerInteraction + ); } - public static bool CheckBox(BoxCollider box, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { - Vector3 center, halfExtents; + public static bool CheckBox( + BoxCollider box, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { + Vector3 center, + halfExtents; Quaternion orientation; box.ToWorldSpaceBox(out center, out halfExtents, out orientation); - return Physics.CheckBox(center, halfExtents, orientation, layerMask, queryTriggerInteraction); + return Physics.CheckBox( + center, + halfExtents, + orientation, + layerMask, + queryTriggerInteraction + ); } public static Collider[] OverlapBox( BoxCollider box, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal, - float expandBy = 0.0f) { - Vector3 center, halfExtents; + float expandBy = 0.0f + ) { + Vector3 center, + halfExtents; Quaternion orientation; box.ToWorldSpaceBox(out center, out halfExtents, out orientation); if (expandBy != 0.0f) { - halfExtents = new Vector3(expandBy + halfExtents.x, expandBy + halfExtents.y, expandBy + halfExtents.z); + halfExtents = new Vector3( + expandBy + halfExtents.x, + expandBy + halfExtents.y, + expandBy + halfExtents.z + ); } - return Physics.OverlapBox(center, halfExtents, orientation, layerMask, queryTriggerInteraction); + return Physics.OverlapBox( + center, + halfExtents, + orientation, + layerMask, + queryTriggerInteraction + ); } - public static int OverlapBoxNonAlloc(BoxCollider box, Collider[] results, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { - Vector3 center, halfExtents; + public static int OverlapBoxNonAlloc( + BoxCollider box, + Collider[] results, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { + Vector3 center, + halfExtents; Quaternion orientation; box.ToWorldSpaceBox(out center, out halfExtents, out orientation); - return Physics.OverlapBoxNonAlloc(center, halfExtents, results, orientation, layerMask, queryTriggerInteraction); + return Physics.OverlapBoxNonAlloc( + center, + halfExtents, + results, + orientation, + layerMask, + queryTriggerInteraction + ); } - public static void ToWorldSpaceBox(this BoxCollider box, out Vector3 center, out Vector3 halfExtents, out Quaternion orientation) { + public static void ToWorldSpaceBox( + this BoxCollider box, + out Vector3 center, + out Vector3 halfExtents, + out Quaternion orientation + ) { orientation = box.transform.rotation; center = box.transform.TransformPoint(box.center); var lossyScale = box.transform.lossyScale; @@ -98,39 +203,87 @@ public static void ToWorldSpaceBox(this BoxCollider box, out Vector3 center, out // Sphere // - public static bool SphereCast(SphereCollider sphere, Vector3 direction, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { + public static bool SphereCast( + SphereCollider sphere, + Vector3 direction, + out RaycastHit hitInfo, + float maxDistance = Mathf.Infinity, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); - return Physics.SphereCast(center, radius, direction, out hitInfo, maxDistance, layerMask, queryTriggerInteraction); + return Physics.SphereCast( + center, + radius, + direction, + out hitInfo, + maxDistance, + layerMask, + queryTriggerInteraction + ); } - public static RaycastHit[] SphereCastAll(SphereCollider sphere, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { + public static RaycastHit[] SphereCastAll( + SphereCollider sphere, + Vector3 direction, + float maxDistance = Mathf.Infinity, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); - return Physics.SphereCastAll(center, radius, direction, maxDistance, layerMask, queryTriggerInteraction); + return Physics.SphereCastAll( + center, + radius, + direction, + maxDistance, + layerMask, + queryTriggerInteraction + ); } - public static int SphereCastNonAlloc(SphereCollider sphere, Vector3 direction, RaycastHit[] results, float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { + public static int SphereCastNonAlloc( + SphereCollider sphere, + Vector3 direction, + RaycastHit[] results, + float maxDistance = Mathf.Infinity, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); - return Physics.SphereCastNonAlloc(center, radius, direction, results, maxDistance, layerMask, queryTriggerInteraction); + return Physics.SphereCastNonAlloc( + center, + radius, + direction, + results, + maxDistance, + layerMask, + queryTriggerInteraction + ); } - public static bool CheckSphere(SphereCollider sphere, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { + public static bool CheckSphere( + SphereCollider sphere, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); return Physics.CheckSphere(center, radius, layerMask, queryTriggerInteraction); } - public static Collider[] OverlapSphere - (SphereCollider sphere, - int layerMask = Physics.DefaultRaycastLayers, - QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal, - float expandBy = 0.0f) { + public static Collider[] OverlapSphere( + SphereCollider sphere, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal, + float expandBy = 0.0f + ) { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); @@ -138,14 +291,29 @@ public static Collider[] OverlapSphere return Physics.OverlapSphere(center, radius, layerMask, queryTriggerInteraction); } - public static int OverlapSphereNonAlloc(SphereCollider sphere, Collider[] results, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { + public static int OverlapSphereNonAlloc( + SphereCollider sphere, + Collider[] results, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); - return Physics.OverlapSphereNonAlloc(center, radius, results, layerMask, queryTriggerInteraction); + return Physics.OverlapSphereNonAlloc( + center, + radius, + results, + layerMask, + queryTriggerInteraction + ); } - public static void ToWorldSpaceSphere(this SphereCollider sphere, out Vector3 center, out float radius) { + public static void ToWorldSpaceSphere( + this SphereCollider sphere, + out Vector3 center, + out float radius + ) { center = sphere.transform.TransformPoint(sphere.center); radius = sphere.radius * MaxVec3(AbsVec3(sphere.transform.lossyScale)); } @@ -154,29 +322,83 @@ public static void ToWorldSpaceSphere(this SphereCollider sphere, out Vector3 ce // Capsule // - public static bool CapsuleCast(CapsuleCollider capsule, Vector3 direction, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { - Vector3 point0, point1; + public static bool CapsuleCast( + CapsuleCollider capsule, + Vector3 direction, + out RaycastHit hitInfo, + float maxDistance = Mathf.Infinity, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { + Vector3 point0, + point1; float radius; capsule.ToWorldSpaceCapsule(out point0, out point1, out radius); - return Physics.CapsuleCast(point0, point1, radius, direction, out hitInfo, maxDistance, layerMask, queryTriggerInteraction); + return Physics.CapsuleCast( + point0, + point1, + radius, + direction, + out hitInfo, + maxDistance, + layerMask, + queryTriggerInteraction + ); } - public static RaycastHit[] CapsuleCastAll(CapsuleCollider capsule, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { - Vector3 point0, point1; + public static RaycastHit[] CapsuleCastAll( + CapsuleCollider capsule, + Vector3 direction, + float maxDistance = Mathf.Infinity, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { + Vector3 point0, + point1; float radius; capsule.ToWorldSpaceCapsule(out point0, out point1, out radius); - return Physics.CapsuleCastAll(point0, point1, radius, direction, maxDistance, layerMask, queryTriggerInteraction); + return Physics.CapsuleCastAll( + point0, + point1, + radius, + direction, + maxDistance, + layerMask, + queryTriggerInteraction + ); } - public static int CapsuleCastNonAlloc(CapsuleCollider capsule, Vector3 direction, RaycastHit[] results, float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { - Vector3 point0, point1; + public static int CapsuleCastNonAlloc( + CapsuleCollider capsule, + Vector3 direction, + RaycastHit[] results, + float maxDistance = Mathf.Infinity, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { + Vector3 point0, + point1; float radius; capsule.ToWorldSpaceCapsule(out point0, out point1, out radius); - return Physics.CapsuleCastNonAlloc(point0, point1, radius, direction, results, maxDistance, layerMask, queryTriggerInteraction); + return Physics.CapsuleCastNonAlloc( + point0, + point1, + radius, + direction, + results, + maxDistance, + layerMask, + queryTriggerInteraction + ); } - public static bool CheckCapsule(CapsuleCollider capsule, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { - Vector3 point0, point1; + public static bool CheckCapsule( + CapsuleCollider capsule, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { + Vector3 point0, + point1; float radius; capsule.ToWorldSpaceCapsule(out point0, out point1, out radius); return Physics.CheckCapsule(point0, point1, radius, layerMask, queryTriggerInteraction); @@ -186,21 +408,47 @@ public static Collider[] OverlapCapsule( CapsuleCollider capsule, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal, - float expandBy = 0.0f) { - Vector3 point0, point1; + float expandBy = 0.0f + ) { + Vector3 point0, + point1; float radius; capsule.ToWorldSpaceCapsule(out point0, out point1, out radius); - return Physics.OverlapCapsule(point0, point1, expandBy + radius, layerMask, queryTriggerInteraction); + return Physics.OverlapCapsule( + point0, + point1, + expandBy + radius, + layerMask, + queryTriggerInteraction + ); } - public static int OverlapCapsuleNonAlloc(CapsuleCollider capsule, Collider[] results, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { - Vector3 point0, point1; + public static int OverlapCapsuleNonAlloc( + CapsuleCollider capsule, + Collider[] results, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { + Vector3 point0, + point1; float radius; capsule.ToWorldSpaceCapsule(out point0, out point1, out radius); - return Physics.OverlapCapsuleNonAlloc(point0, point1, radius, results, layerMask, queryTriggerInteraction); + return Physics.OverlapCapsuleNonAlloc( + point0, + point1, + radius, + results, + layerMask, + queryTriggerInteraction + ); } - public static void ToWorldSpaceCapsule(this CapsuleCollider capsule, out Vector3 point0, out Vector3 point1, out float radius) { + public static void ToWorldSpaceCapsule( + this CapsuleCollider capsule, + out Vector3 point0, + out Vector3 point1, + out float radius + ) { var center = capsule.transform.TransformPoint(capsule.center); radius = 0f; float height = 0f; @@ -233,7 +481,7 @@ public static void ToWorldSpaceCapsule(this CapsuleCollider capsule, out Vector3 point1 = center - dir * (height * 0.5f - radius); } - // + // // Util // @@ -250,7 +498,7 @@ public static void SortClosestToFurthest(RaycastHit[] hits, int hitCount = -1) { } // - // Private + // Private // private class AscendingDistanceComparer : IComparer { diff --git a/unity/Assets/Scripts/PhysicsRemoteFPSAgentController.cs b/unity/Assets/Scripts/PhysicsRemoteFPSAgentController.cs index 2b0bf057cc..a827d8200a 100644 --- a/unity/Assets/Scripts/PhysicsRemoteFPSAgentController.cs +++ b/unity/Assets/Scripts/PhysicsRemoteFPSAgentController.cs @@ -7,17 +7,17 @@ using System.IO; using System.Linq; using Priority_Queue; +using RandomExtensions; +using Thor.Procedural; +using Thor.Procedural.Data; using UnityEngine; -using UnityEngine.Rendering; using UnityEngine.Animations; +using UnityEngine.Rendering; +using UnityEngine.Rendering.PostProcessing; using UnityEngine.SceneManagement; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.ImageEffects; using UnityStandardAssets.Utility; -using RandomExtensions; -using Thor.Procedural; -using Thor.Procedural.Data; -using UnityEngine.Rendering.PostProcessing; namespace UnityStandardAssets.Characters.FirstPerson { public class OrientedPoint { @@ -26,14 +26,18 @@ public class OrientedPoint { } public partial class PhysicsRemoteFPSAgentController : BaseFPSAgentController { - protected Dictionary> maskedObjects = new Dictionary>(); + protected Dictionary> maskedObjects = + new Dictionary>(); bool transparentStructureObjectsHidden = false; - // face swap stuff here - public PhysicsRemoteFPSAgentController(BaseAgentComponent baseAgentComponent, AgentManager agentManager) : base(baseAgentComponent, agentManager) { + // face swap stuff here + public PhysicsRemoteFPSAgentController( + BaseAgentComponent baseAgentComponent, + AgentManager agentManager + ) + : base(baseAgentComponent, agentManager) { standingLocalCameraPosition = m_Camera.transform.localPosition; - } public override ActionFinished InitializeBody(ServerAction initializeAction) { @@ -55,10 +59,11 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { // camera FOV m_Camera.fieldOfView = 90f; - + // set camera stand/crouch local positions for Tall mode standingLocalCameraPosition = m_Camera.transform.localPosition; - crouchingLocalCameraPosition = m_Camera.transform.localPosition + new Vector3(0, -0.675f, 0); // bigger y offset if tall + crouchingLocalCameraPosition = + m_Camera.transform.localPosition + new Vector3(0, -0.675f, 0); // bigger y offset if tall return ActionFinished.Success; } @@ -86,14 +91,16 @@ public GameObject WhatAmIHolding() { public void EnableTemperatureDecay() { if (!physicsSceneManager.GetComponent().AllowDecayTemperature) { - physicsSceneManager.GetComponent().AllowDecayTemperature = true; + physicsSceneManager.GetComponent().AllowDecayTemperature = + true; } actionFinished(true); } public void DisableTemperatureDecay() { if (physicsSceneManager.GetComponent().AllowDecayTemperature) { - physicsSceneManager.GetComponent().AllowDecayTemperature = false; + physicsSceneManager.GetComponent().AllowDecayTemperature = + false; } actionFinished(true); } @@ -101,9 +108,14 @@ public void DisableTemperatureDecay() { // sets temperature decay for a single object. public void SetTemperatureDecayTime(string objectId, float decayTime) { if (decayTime < 0) { - throw new ArgumentOutOfRangeException("decayTime must be >= 0. You gave " + decayTime); + throw new ArgumentOutOfRangeException( + "decayTime must be >= 0. You gave " + decayTime + ); } - SimObjPhysics sop = getInteractableSimObjectFromId(objectId: objectId, forceAction: true); + SimObjPhysics sop = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: true + ); sop.SetHowManySecondsUntilRoomTemp(decayTime); actionFinished(true); } @@ -111,7 +123,9 @@ public void SetTemperatureDecayTime(string objectId, float decayTime) { // globally sets temperature decay for all objects. public void SetTemperatureDecayTime(float decayTime) { if (decayTime < 0) { - throw new ArgumentOutOfRangeException("decayTime must be >= 0. You gave " + decayTime); + throw new ArgumentOutOfRangeException( + "decayTime must be >= 0. You gave " + decayTime + ); } SimObjPhysics[] simObjects = GameObject.FindObjectsOfType(); foreach (SimObjPhysics sop in simObjects) { @@ -131,7 +145,10 @@ public void SetMassProperties(string objectId, float mass, float drag, float ang SimObjPhysics[] simObjects = GameObject.FindObjectsOfType(); foreach (SimObjPhysics sop in simObjects) { if (sop.objectID == objectId) { - if (sop.PrimaryProperty == SimObjPrimaryProperty.Moveable || sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup) { + if ( + sop.PrimaryProperty == SimObjPrimaryProperty.Moveable + || sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup + ) { Rigidbody rb = sop.GetComponent(); rb.mass = mass; rb.drag = drag; @@ -141,19 +158,24 @@ public void SetMassProperties(string objectId, float mass, float drag, float ang return; } - errorMessage = "object with ObjectID: " + objectId + ", is not Moveable or Pickupable, and the Mass Properties cannot be changed"; + errorMessage = + "object with ObjectID: " + + objectId + + ", is not Moveable or Pickupable, and the Mass Properties cannot be changed"; actionFinished(false); return; } } - errorMessage = "object with ObjectID: " + objectId + ", could not be found in this scene"; + errorMessage = + "object with ObjectID: " + objectId + ", could not be found in this scene"; actionFinished(false); return; } public bool isStanding() { - return (m_Camera.transform.localPosition - standingLocalCameraPosition).magnitude < 0.1f; + return (m_Camera.transform.localPosition - standingLocalCameraPosition).magnitude + < 0.1f; } public override MetadataWrapper generateMetadataWrapper() { @@ -193,7 +215,10 @@ public string ObjectIdOfClosestPickupableOrMoveableObject() { string objectID = null; foreach (SimObjPhysics o in VisibleSimObjPhysics) { - if (o.PrimaryProperty == SimObjPrimaryProperty.CanPickup || o.PrimaryProperty == SimObjPrimaryProperty.Moveable) { + if ( + o.PrimaryProperty == SimObjPrimaryProperty.CanPickup + || o.PrimaryProperty == SimObjPrimaryProperty.Moveable + ) { objectID = o.ObjectID; // print(objectID); break; @@ -243,6 +268,7 @@ public string ObjectIdOfClosestReceptacleObject() { return objectID; } #endif + ///////////////////////////////////////////////////////// // return a reference to a SimObj that is Visible (in the VisibleSimObjPhysics array) and // matches the passed in objectID @@ -257,7 +283,8 @@ public GameObject FindObjectInVisibleSimObjPhysics(string objectId) { protected Collider[] collidersWithinCapsuleCastOfAgent(float maxDistance) { CapsuleCollider agentCapsuleCollider = GetComponent(); - Vector3 point0, point1; + Vector3 point0, + point1; float radius; agentCapsuleCollider.ToWorldSpaceCapsule(out point0, out point1, out radius); if (point0.y <= point1.y) { @@ -265,10 +292,21 @@ protected Collider[] collidersWithinCapsuleCastOfAgent(float maxDistance) { } else { point0.y += maxDistance; } - return Physics.OverlapCapsule(point0, point1, maxDistance, LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"), QueryTriggerInteraction.Collide); + return Physics.OverlapCapsule( + point0, + point1, + maxDistance, + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ), + QueryTriggerInteraction.Collide + ); } - // checks if a float is a multiple of 0.1f protected bool CheckIfFloatIsMultipleOfOneTenth(float f) { if (((decimal)f % 0.1M == 0) == false) { @@ -280,7 +318,9 @@ protected bool CheckIfFloatIsMultipleOfOneTenth(float f) { public override void LookDown(ServerAction action) { if (action.degrees < 0) { - errorMessage = "LookDown action requires positive degree value. Invalid value used: " + action.degrees; + errorMessage = + "LookDown action requires positive degree value. Invalid value used: " + + action.degrees; actionFinished(false); return; } @@ -301,7 +341,10 @@ public override void LookDown(ServerAction action) { action.degrees = Mathf.Round(action.degrees * 10.0f) / 10.0f; if (!checkForUpDownAngleLimit("down", action.degrees)) { - errorMessage = "can't look down beyond " + maxDownwardLookAngle + " degrees below the forward horizon"; + errorMessage = + "can't look down beyond " + + maxDownwardLookAngle + + " degrees below the forward horizon"; errorCode = ServerActionErrorCode.LookDownCantExceedMin; actionFinished(false); return; @@ -315,16 +358,21 @@ public override void LookDown(ServerAction action) { DefaultAgentHand(); } } else { - errorMessage = "a held item: " + ItemInHand.transform.GetComponent().objectID + " will collide with something if agent rotates down " + action.degrees + " degrees"; + errorMessage = + "a held item: " + + ItemInHand.transform.GetComponent().objectID + + " will collide with something if agent rotates down " + + action.degrees + + " degrees"; actionFinished(false); } - } public override void LookUp(ServerAction action) { - if (action.degrees < 0) { - errorMessage = "LookUp action requires positive degree value. Invalid value used: " + action.degrees; + errorMessage = + "LookUp action requires positive degree value. Invalid value used: " + + action.degrees; actionFinished(false); return; } @@ -345,7 +393,10 @@ public override void LookUp(ServerAction action) { action.degrees = Mathf.Round(action.degrees * 10.0f) / 10.0f; if (!checkForUpDownAngleLimit("up", action.degrees)) { - errorMessage = "can't look up beyond " + maxUpwardLookAngle + " degrees above the forward horizon"; + errorMessage = + "can't look up beyond " + + maxUpwardLookAngle + + " degrees above the forward horizon"; errorCode = ServerActionErrorCode.LookDownCantExceedMin; actionFinished(false); return; @@ -359,7 +410,12 @@ public override void LookUp(ServerAction action) { DefaultAgentHand(); } } else { - errorMessage = "a held item: " + ItemInHand.transform.GetComponent().objectID + " will collide with something if agent rotates up " + action.degrees + " degrees"; + errorMessage = + "a held item: " + + ItemInHand.transform.GetComponent().objectID + + " will collide with something if agent rotates up " + + action.degrees + + " degrees"; actionFinished(false); } } @@ -368,11 +424,11 @@ public virtual void RotateRight( float? degrees = null, bool manualInteract = false, bool forceAction = false, - float speed = 1.0f, // TODO: Unused, remove when refactoring the controllers + float speed = 1.0f, // TODO: Unused, remove when refactoring the controllers bool waitForFixedUpdate = false, // TODO: Unused, remove when refactoring the controllers - bool returnToStart = true, // TODO: Unused, remove when refactoring the controllers - bool disableRendering = true, // TODO: Unused, remove when refactoring the controllers - float fixedDeltaTime = 0.02f // TODO: Unused, remove when refactoring the controllers + bool returnToStart = true, // TODO: Unused, remove when refactoring the controllers + bool disableRendering = true, // TODO: Unused, remove when refactoring the controllers + float fixedDeltaTime = 0.02f // TODO: Unused, remove when refactoring the controllers ) { if (!degrees.HasValue) { degrees = rotateStepDegrees; @@ -383,7 +439,6 @@ public virtual void RotateRight( } if (CheckIfAgentCanRotate("right", degrees.Value) || forceAction) { - transform.Rotate(0, degrees.Value, 0); // only default hand if not manually Interacting with things @@ -393,7 +448,8 @@ public virtual void RotateRight( actionFinished(true); } else { - errorMessage = $"a held item: {ItemInHand.transform.name} with something if agent rotates Right {degrees} degrees"; + errorMessage = + $"a held item: {ItemInHand.transform.name} with something if agent rotates Right {degrees} degrees"; actionFinished(false); } } @@ -402,11 +458,11 @@ public virtual void RotateLeft( float? degrees = null, bool manualInteract = false, bool forceAction = false, - float speed = 1.0f, // TODO: Unused, remove when refactoring the controllers + float speed = 1.0f, // TODO: Unused, remove when refactoring the controllers bool waitForFixedUpdate = false, // TODO: Unused, remove when refactoring the controllers - bool returnToStart = true, // TODO: Unused, remove when refactoring the controllers - bool disableRendering = true, // TODO: Unused, remove when refactoring the controllers - float fixedDeltaTime = 0.02f // TODO: Unused, remove when refactoring the controllers + bool returnToStart = true, // TODO: Unused, remove when refactoring the controllers + bool disableRendering = true, // TODO: Unused, remove when refactoring the controllers + float fixedDeltaTime = 0.02f // TODO: Unused, remove when refactoring the controllers ) { if (!degrees.HasValue) { degrees = rotateStepDegrees; @@ -426,24 +482,38 @@ public virtual void RotateLeft( actionFinished(true); } else { - errorMessage = $"a held item: {ItemInHand.transform.name} with something if agent rotates Left {degrees} degrees"; + errorMessage = + $"a held item: {ItemInHand.transform.name} with something if agent rotates Left {degrees} degrees"; actionFinished(false); } } - private bool checkArcForCollisions(BoxCollider bb, Vector3 origin, float degrees, int dirSign, Vector3 dirAxis) { + private bool checkArcForCollisions( + BoxCollider bb, + Vector3 origin, + float degrees, + int dirSign, + Vector3 dirAxis + ) { bool result = true; float arcIncrementDistance; Vector3 bbWorldCenter = bb.transform.TransformPoint(bb.center); Vector3 bbHalfExtents = bb.size / 2.0f; // Generate arc points in the positive y-axis rotation - OrientedPoint[] pointsOnArc = GenerateArcPoints(bbWorldCenter, bb.transform.rotation, origin, degrees, dirSign, dirAxis); + OrientedPoint[] pointsOnArc = GenerateArcPoints( + bbWorldCenter, + bb.transform.rotation, + origin, + degrees, + dirSign, + dirAxis + ); // Save the arc-distance to a value to reduce computation in the for-loop, since it's the same between every OrientedPoint arcIncrementDistance = (pointsOnArc[1].position - pointsOnArc[0].position).magnitude; - // Raycast from first point in pointsOnArc, stepwise to last point. If any collisions are hit, immediately return + // Raycast from first point in pointsOnArc, stepwise to last point. If any collisions are hit, immediately return for (int i = 0; i < pointsOnArc.Length - 1; i++) { RaycastHit hit; // do boxcasts from the first point, sequentially, to the last @@ -462,7 +532,14 @@ private bool checkArcForCollisions(BoxCollider bb, Vector3 origin, float degrees 0.5f ), arcIncrementDistance, - LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent"), + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent" + ), QueryTriggerInteraction.Ignore ) ) { @@ -470,10 +547,9 @@ private bool checkArcForCollisions(BoxCollider bb, Vector3 origin, float degrees if ( ( hit.transform.GetComponentInParent() - && hit.transform.GetComponentInParent().transform == ItemInHand.transform - ) || ( - hit.transform == this.transform - ) + && hit.transform.GetComponentInParent().transform + == ItemInHand.transform + ) || (hit.transform == this.transform) ) { // if the sim obj we hit is what we are holding, skip // don't worry about clipping the object into this agent @@ -494,13 +570,23 @@ private bool checkArcForCollisions(BoxCollider bb, Vector3 origin, float degrees rotPoint.position, bbHalfExtents, rotPoint.transform.rotation, - LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent"), + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent" + ), QueryTriggerInteraction.Ignore ); foreach (Collider col in WhatDidWeHit) { if (col.transform.GetComponentInParent()) { - if (col.transform.GetComponentInParent().transform == ItemInHand.transform) { + if ( + col.transform.GetComponentInParent().transform + == ItemInHand.transform + ) { continue; } } @@ -517,7 +603,14 @@ private bool checkArcForCollisions(BoxCollider bb, Vector3 origin, float degrees } // Returns an array of OrientedPoints along the arc of the rotation for a given starting point about an origin point for a total given angle - private OrientedPoint[] GenerateArcPoints(Vector3 startingPoint, Quaternion startingRotation, Vector3 origin, float angle, int dirSign, Vector3 dirAxis) { + private OrientedPoint[] GenerateArcPoints( + Vector3 startingPoint, + Quaternion startingRotation, + Vector3 origin, + float angle, + int dirSign, + Vector3 dirAxis + ) { float incrementAngle = angle / 10f; // divide the total amount we are rotating by 10 to get 10 points on the arc for positions OrientedPoint[] arcPoints = new OrientedPoint[11]; // we just always want 10 points in addition to our starting corner position (11 total) to check against per corner float currentIncrementAngle; @@ -549,7 +642,6 @@ private OrientedPoint[] GenerateArcPoints(Vector3 startingPoint, Quaternion star return arcPoints; } - // TODO: I dunno who was using this or for what, but it doesn't play nice with the new rotate functions so please add back functionality later // public void RotateRightSmooth(ServerAction controlCommand) { // if (CheckIfAgentCanTurn(90)) { @@ -571,7 +663,6 @@ private OrientedPoint[] GenerateArcPoints(Vector3 startingPoint, Quaternion star // checks if agent is clear to rotate left/right/up/down some number of degrees while holding an object public bool CheckIfAgentCanRotate(string direction, float degrees) { - if (ItemInHand == null) { // Debug.Log("Rotation check passed: nothing in Agent Hand"); return true; @@ -580,7 +671,9 @@ public bool CheckIfAgentCanRotate(string direction, float degrees) { bool result = true; // Get held object's bounding box - BoxCollider bb = ItemInHand.GetComponent().BoundingBox.GetComponent(); + BoxCollider bb = ItemInHand + .GetComponent() + .BoundingBox.GetComponent(); // Establish the directionality of specified rotation int dirSign = -1; @@ -593,21 +686,18 @@ public bool CheckIfAgentCanRotate(string direction, float degrees) { dirAxis = transform.up; origin = m_CharacterController.transform.position; } - // Yawing right (Rotating positively across XZ plane around CharacterController) else if (direction == "right") { dirSign = 1; dirAxis = transform.up; origin = m_CharacterController.transform.position; } - // Pitching up (Rotating negatively across YZ plane around camera) else if (direction == "up") { dirSign = -1; dirAxis = transform.right; origin = m_Camera.transform.position; } - // Pitching down (Rotating positively across YZ plane around camera) else if (direction == "down") { dirSign = 1; @@ -621,8 +711,6 @@ public bool CheckIfAgentCanRotate(string direction, float degrees) { return result; } - - // params are named x,y,z due to the action orignally using ServerAction.x,y,z public void ChangeAgentColor(float x, float y, float z) { agentManager.UpdateAgentColor(this, new Color(x, y, z, 1.0f)); @@ -636,7 +724,8 @@ protected Vector3 closestPointToObject(SimObjPhysics sop) { foreach (Collider c in sop.GetComponentsInChildren()) { Vector3 point = c.ClosestPointOnBounds(transform.position); float dist = Vector3.Distance( - transform.position, c.ClosestPointOnBounds(transform.position) + transform.position, + c.ClosestPointOnBounds(transform.position) ); if (dist < closestDist) { closestDist = dist; @@ -672,13 +761,36 @@ public void PointsOverTableWhereHandCanBe(string objectId, float x, float z) { for (int j = zStart; j < 11; j++) { DefaultAgentHand(); - Vector3 testPosition = AgentHand.transform.position + 0.1f * i * transform.right + 0.1f * j * transform.forward; + Vector3 testPosition = + AgentHand.transform.position + + 0.1f * i * transform.right + + 0.1f * j * transform.forward; RaycastHit hit; - if (Physics.Raycast(testPosition, -transform.up, out hit, 1f, LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"))) { + if ( + Physics.Raycast( + testPosition, + -transform.up, + out hit, + 1f, + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ) + ) + ) { Vector3 viewportPoint = m_Camera.WorldToViewportPoint(hit.point); - if (viewportPoint.x >= 0f && viewportPoint.x <= 1f && viewportPoint.y >= 0f && viewportPoint.y <= 1f) { - SimObjPhysics hitSop = hit.transform.gameObject.GetComponent(); + if ( + viewportPoint.x >= 0f + && viewportPoint.x <= 1f + && viewportPoint.y >= 0f + && viewportPoint.y <= 1f + ) { + SimObjPhysics hitSop = + hit.transform.gameObject.GetComponent(); if (hitSop && hitSop.ObjectID == tableId) { goodPositions.Add(hit.point); #if UNITY_EDITOR @@ -716,8 +828,8 @@ public void PlaceFixedReceptacleAtLocation(int objectVariation, float x, float y } if ( - physicsSceneManager.ManipulatorReceptacles == null || - physicsSceneManager.ManipulatorReceptacles.Length == 0 + physicsSceneManager.ManipulatorReceptacles == null + || physicsSceneManager.ManipulatorReceptacles.Length == 0 ) { errorMessage = "Scene does not have manipulator receptacles set."; actionFinished(false); @@ -748,10 +860,16 @@ public void PlaceFixedReceptacleAtLocation(int objectVariation, float x, float y actionFinished(true, receptId); } - public void PlaceBookWallAtLocation(int objectVariation, float x, float y, float z, Vector3 rotation) { + public void PlaceBookWallAtLocation( + int objectVariation, + float x, + float y, + float z, + Vector3 rotation + ) { if ( - physicsSceneManager.ManipulatorBooks == null || - physicsSceneManager.ManipulatorBooks.Length == 0 + physicsSceneManager.ManipulatorBooks == null + || physicsSceneManager.ManipulatorBooks.Length == 0 ) { errorMessage = "Scene does not have manipulator books set."; actionFinished(false); @@ -779,7 +897,11 @@ public void PlaceBookWallAtLocation(int objectVariation, float x, float y, float // ); } - GameObject allBooksObject = physicsSceneManager.ManipulatorBooks[0].transform.parent.gameObject; + GameObject allBooksObject = physicsSceneManager + .ManipulatorBooks[0] + .transform + .parent + .gameObject; allBooksObject.transform.position = new Vector3(x, y + yoffset, z); allBooksObject.transform.localRotation = Quaternion.Euler( @@ -892,17 +1014,18 @@ public void GetUnreachableSilhouetteForObject(string objectId, float z) { float objectRad = GetXZRadiusOfObject(targetObject); var sb = new System.Text.StringBuilder(); - int halfWidth = 1 + ((int)Math.Round((objectRad + z + m_CharacterController.radius) / gridSize)); + int halfWidth = + 1 + ((int)Math.Round((objectRad + z + m_CharacterController.radius) / gridSize)); for (int i = 2 * halfWidth; i >= 0; i--) { float zOffset = ((i - halfWidth) * gridSize); for (int j = 0; j < 2 * halfWidth + 1; j++) { - float xOffset = ((j - halfWidth) * gridSize); if (j != 0) { sb.Append(" "); } - transform.position = targetObject.transform.position + new Vector3(xOffset, 0f, zOffset); + transform.position = + targetObject.transform.position + new Vector3(xOffset, 0f, zOffset); if (isAgentCapsuleCollidingWith(targetObject.gameObject)) { sb.Append("1"); } else if (distanceToObject(targetObject) <= z) { @@ -949,7 +1072,9 @@ public void RandomlyCreateLiftedFurniture(ServerAction action) { SimObjPhysics objectCreated = null; try { objectCreated = randomlyCreateAndPlaceObjectOnFloor( - action.objectType, action.objectVariation, reachablePositions + action.objectType, + action.objectVariation, + reachablePositions ); } catch (Exception) { } if (objectCreated == null) { @@ -958,7 +1083,8 @@ public void RandomlyCreateLiftedFurniture(ServerAction action) { agent.transform.position = oldAgentPositions[i]; agent.transform.rotation = oldAgentRotations[i]; } - errorMessage = "Failed to create object of type " + action.objectType + " . " + errorMessage; + errorMessage = + "Failed to create object of type " + action.objectType + " . " + errorMessage; actionFinished(false); return; } @@ -988,14 +1114,21 @@ public void RandomlyCreateLiftedFurniture(ServerAction action) { if (candidatePositionsList.Count >= agentManager.agents.Count) { candidatePositionsList.Shuffle_(); - foreach (Vector3[] candidatePositions in UtilityFunctions.Combinations( - candidatePositionsList.ToArray(), agentManager.agents.Count)) { + foreach ( + Vector3[] candidatePositions in UtilityFunctions.Combinations( + candidatePositionsList.ToArray(), + agentManager.agents.Count + ) + ) { bool candidatesBad = false; for (int j = 0; j < candidatePositions.Length - 1; j++) { Vector3 p0 = candidatePositions[j]; for (int k = j + 1; k < candidatePositions.Length; k++) { Vector3 p1 = candidatePositions[k]; - if (Math.Abs(p1.x - p0.x) < 0.4999f && Math.Abs(p1.z - p0.z) < 0.4999f) { + if ( + Math.Abs(p1.x - p0.x) < 0.4999f + && Math.Abs(p1.z - p0.z) < 0.4999f + ) { candidatesBad = true; } if (candidatesBad) { @@ -1016,7 +1149,9 @@ public void RandomlyCreateLiftedFurniture(ServerAction action) { agent.transform.position = candidatePositions[j]; foreach (float r in rotations.Shuffle_()) { - agent.transform.rotation = Quaternion.Euler(new Vector3(0f, r, 0f)); + agent.transform.rotation = Quaternion.Euler( + new Vector3(0f, r, 0f) + ); if (agent.objectIsCurrentlyVisible(objectCreated, 100f)) { break; } @@ -1051,7 +1186,8 @@ public void RandomlyCreateLiftedFurniture(ServerAction action) { agent.transform.rotation = oldAgentRotations[i]; } objectCreated.gameObject.SetActive(false); - errorMessage = "Could not find a place to put the object after 10 iterations. " + errorMessage; + errorMessage = + "Could not find a place to put the object after 10 iterations. " + errorMessage; actionFinished(false); return; } @@ -1079,14 +1215,25 @@ protected bool moveObject( sop.gameObject, targetPosition - sop.transform.position, dir.magnitude, - LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent"), + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent" + ), QueryTriggerInteraction.Ignore ); if (sweepResults.Length > 0) { foreach (RaycastHit hit in sweepResults) { - if (ignoreCollisionWithTransforms == null || !ignoreCollisionWithTransforms.Contains(hit.transform)) { - errorMessage = hit.transform.name + " is in the way of moving " + sop.ObjectID; + if ( + ignoreCollisionWithTransforms == null + || !ignoreCollisionWithTransforms.Contains(hit.transform) + ) { + errorMessage = + hit.transform.name + " is in the way of moving " + sop.ObjectID; return false; } } @@ -1095,7 +1242,11 @@ protected bool moveObject( return true; } - protected bool moveLiftedObjectHelper(string objectId, Vector3 relativeDir, float maxAgentsDistance = -1.0f) { + protected bool moveLiftedObjectHelper( + string objectId, + Vector3 relativeDir, + float maxAgentsDistance = -1.0f + ) { if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { errorMessage = $"Cannot find object with id {objectId}."; return false; @@ -1105,9 +1256,14 @@ protected bool moveLiftedObjectHelper(string objectId, Vector3 relativeDir, floa if (moveObject(objectToMove, objectToMove.transform.position + relativeDir, true)) { if (maxAgentsDistance > 0.0f) { for (int i = 0; i < agentManager.agents.Count; i++) { - if (((PhysicsRemoteFPSAgentController)agentManager.agents[i]).distanceToObject(objectToMove) > maxAgentsDistance) { + if ( + ( + (PhysicsRemoteFPSAgentController)agentManager.agents[i] + ).distanceToObject(objectToMove) > maxAgentsDistance + ) { objectToMove.transform.position = oldPosition; - errorMessage = "Would move object beyond max distance from agent " + i.ToString(); + errorMessage = + "Would move object beyond max distance from agent " + i.ToString(); return false; } } @@ -1134,7 +1290,12 @@ public void CollidersObjectCollidingWith(string objectId) { } actionFinished(true, collidingWithNames); } - protected bool moveObjectWithTeleport(SimObjPhysics sop, Vector3 targetPosition, bool snapToGrid = false) { + + protected bool moveObjectWithTeleport( + SimObjPhysics sop, + Vector3 targetPosition, + bool snapToGrid = false + ) { Vector3 lastPosition = sop.transform.position; if (snapToGrid) { @@ -1157,7 +1318,11 @@ protected bool moveObjectWithTeleport(SimObjPhysics sop, Vector3 targetPosition, // This check is stupid but seems necessary to appease the unity gods // as unity doesn't realize the object collides with the agents in // the above checks in some cases. - if (((PhysicsRemoteFPSAgentController)agent).isAgentCapsuleCollidingWith(sop.gameObject)) { + if ( + ((PhysicsRemoteFPSAgentController)agent).isAgentCapsuleCollidingWith( + sop.gameObject + ) + ) { sop.transform.position = oldPosition; errorMessage = sop.ObjectID + " is colliding with an agent after movement."; return false; @@ -1226,13 +1391,26 @@ public void RotateLiftedObjectRight(ServerAction action) { return; } Quaternion oldRotation = sop.transform.rotation; - sop.transform.rotation = Quaternion.Euler(new Vector3(0.0f, (float)Math.Round((sop.transform.eulerAngles.y + 90f) % 360), 0.0f)); ; + sop.transform.rotation = Quaternion.Euler( + new Vector3( + 0.0f, + (float)Math.Round((sop.transform.eulerAngles.y + 90f) % 360), + 0.0f + ) + ); + ; if (!action.forceAction) { if (action.maxAgentsDistance > 0.0f) { for (int i = 0; i < agentManager.agents.Count; i++) { - if (((PhysicsRemoteFPSAgentController)agentManager.agents[i]).distanceToObject(sop) > action.maxAgentsDistance) { + if ( + ( + (PhysicsRemoteFPSAgentController)agentManager.agents[i] + ).distanceToObject(sop) > action.maxAgentsDistance + ) { sop.transform.rotation = oldRotation; - errorMessage = "Would move object beyond max distance from agent " + i.ToString(); + errorMessage = + "Would move object beyond max distance from agent " + + i.ToString(); actionFinished(false); return; } @@ -1248,9 +1426,14 @@ public void RotateLiftedObjectRight(ServerAction action) { // This check is silly but seems necessary to appease unity // as unity doesn't realize the object collides with the agents in // the above checks in some cases. - if (((PhysicsRemoteFPSAgentController)agent).isAgentCapsuleCollidingWith(sop.gameObject)) { + if ( + ((PhysicsRemoteFPSAgentController)agent).isAgentCapsuleCollidingWith( + sop.gameObject + ) + ) { sop.transform.rotation = oldRotation; - errorMessage = sop.ObjectID + " is colliding with an agent after rotation."; + errorMessage = + sop.ObjectID + " is colliding with an agent after rotation."; actionFinished(false); return; } @@ -1260,7 +1443,11 @@ public void RotateLiftedObjectRight(ServerAction action) { } } - public bool moveAgentsWithObject(SimObjPhysics objectToMove, Vector3 d, bool snapToGrid = true) { + public bool moveAgentsWithObject( + SimObjPhysics objectToMove, + Vector3 d, + bool snapToGrid = true + ) { List startAgentPositions = new List(); var agentMovePQ = new SimplePriorityQueue(); foreach (BaseFPSAgentController agent in agentManager.agents) { @@ -1286,22 +1473,38 @@ public bool moveAgentsWithObject(SimObjPhysics objectToMove, Vector3 d, bool sna Physics.autoSimulation = false; while (agentMovePQ.Count > 0 || !objectMoved) { if (agentMovePQ.Count == 0) { - success = moveObjectWithTeleport(objectToMove, objectToMove.transform.position + d, snapToGrid); + success = moveObjectWithTeleport( + objectToMove, + objectToMove.transform.position + d, + snapToGrid + ); PhysicsSceneManager.PhysicsSimulateTHOR(0.04f); break; } else { - PhysicsRemoteFPSAgentController nextAgent = (PhysicsRemoteFPSAgentController)agentMovePQ.First; + PhysicsRemoteFPSAgentController nextAgent = (PhysicsRemoteFPSAgentController) + agentMovePQ.First; float agentPriority = -agentMovePQ.GetPriority(nextAgent); if (!objectMoved && agentPriority < objectPriority) { // Debug.Log("Object"); - success = moveObjectWithTeleport(objectToMove, objectToMove.transform.position + d, snapToGrid); + success = moveObjectWithTeleport( + objectToMove, + objectToMove.transform.position + d, + snapToGrid + ); PhysicsSceneManager.PhysicsSimulateTHOR(0.04f); objectMoved = true; } else { // Debug.Log(nextAgent); agentMovePQ.Dequeue(); - success = nextAgent.moveInDirection(d, "", -1, false, false, agentsAndObjColliders); + success = nextAgent.moveInDirection( + d, + "", + -1, + false, + false, + agentsAndObjColliders + ); PhysicsSceneManager.PhysicsSimulateTHOR(0.04f); } } @@ -1325,9 +1528,13 @@ public void MoveAgentsAheadWithObject(ServerAction action) { actionFinished(false); return; } - SimObjPhysics objectToMove = physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId]; + SimObjPhysics objectToMove = physicsSceneManager.ObjectIdToSimObjPhysics[ + action.objectId + ]; action.moveMagnitude = action.moveMagnitude > 0 ? action.moveMagnitude : gridSize; - actionFinished(moveAgentsWithObject(objectToMove, transform.forward * action.moveMagnitude)); + actionFinished( + moveAgentsWithObject(objectToMove, transform.forward * action.moveMagnitude) + ); } public void MoveAgentsLeftWithObject(ServerAction action) { @@ -1336,9 +1543,13 @@ public void MoveAgentsLeftWithObject(ServerAction action) { actionFinished(false); return; } - SimObjPhysics objectToMove = physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId]; + SimObjPhysics objectToMove = physicsSceneManager.ObjectIdToSimObjPhysics[ + action.objectId + ]; action.moveMagnitude = action.moveMagnitude > 0 ? action.moveMagnitude : gridSize; - actionFinished(moveAgentsWithObject(objectToMove, -transform.right * action.moveMagnitude)); + actionFinished( + moveAgentsWithObject(objectToMove, -transform.right * action.moveMagnitude) + ); } public void MoveAgentsRightWithObject(ServerAction action) { @@ -1347,9 +1558,13 @@ public void MoveAgentsRightWithObject(ServerAction action) { actionFinished(false); return; } - SimObjPhysics objectToMove = physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId]; + SimObjPhysics objectToMove = physicsSceneManager.ObjectIdToSimObjPhysics[ + action.objectId + ]; action.moveMagnitude = action.moveMagnitude > 0 ? action.moveMagnitude : gridSize; - actionFinished(moveAgentsWithObject(objectToMove, transform.right * action.moveMagnitude)); + actionFinished( + moveAgentsWithObject(objectToMove, transform.right * action.moveMagnitude) + ); } public void MoveAgentsBackWithObject(ServerAction action) { @@ -1358,9 +1573,13 @@ public void MoveAgentsBackWithObject(ServerAction action) { actionFinished(false); return; } - SimObjPhysics objectToMove = physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId]; + SimObjPhysics objectToMove = physicsSceneManager.ObjectIdToSimObjPhysics[ + action.objectId + ]; action.moveMagnitude = action.moveMagnitude > 0 ? action.moveMagnitude : gridSize; - actionFinished(moveAgentsWithObject(objectToMove, -transform.forward * action.moveMagnitude)); + actionFinished( + moveAgentsWithObject(objectToMove, -transform.forward * action.moveMagnitude) + ); } public void TeleportObjectToFloor(ServerAction action) { @@ -1406,7 +1625,7 @@ public void TeleportObjectToFloor(ServerAction action) { ////////////// TELEPORT FULL ////////////// /////////////////////////////////////////// - // [ObsoleteAttribute(message: "This action is deprecated. Call TeleportFull(position, ...) instead.", error: false)] + // [ObsoleteAttribute(message: "This action is deprecated. Call TeleportFull(position, ...) instead.", error: false)] // public void TeleportFull( // float x, float y, float z, // float rotation, @@ -1423,9 +1642,14 @@ public void TeleportObjectToFloor(ServerAction action) { // ); // } - [ObsoleteAttribute(message: "This action is deprecated. Call TeleportFull(position, ...) instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call TeleportFull(position, ...) instead.", + error: false + )] public void TeleportFull( - float x, float y, float z, + float x, + float y, + float z, Vector3? rotation, float? horizon, bool? standing, @@ -1500,14 +1724,15 @@ public virtual void TeleportFull( // add arm value cases if (!forceAction) { if (isHandObjectColliding(ignoreAgent: true)) { - throw new InvalidOperationException("Cannot teleport due to hand object collision."); + throw new InvalidOperationException( + "Cannot teleport due to hand object collision." + ); } if (Arm != null && Arm.IsArmColliding()) { throw new InvalidOperationException( "Mid Level Arm is actively clipping with some geometry in the environment. TeleportFull fails in this position." ); - } - else if (SArm != null && SArm.IsArmColliding()) { + } else if (SArm != null && SArm.IsArmColliding()) { throw new InvalidOperationException( "Stretch Arm is actively clipping with some geometry in the environment. TeleportFull fails in this position." ); @@ -1538,7 +1763,7 @@ public virtual void TeleportFull( //////////////// TELEPORT ///////////////// /////////////////////////////////////////// - // [ObsoleteAttribute(message: "This action is deprecated. Call Teleport(position, ...) instead.", error: false)] + // [ObsoleteAttribute(message: "This action is deprecated. Call Teleport(position, ...) instead.", error: false)] // public void Teleport( // float x, float y, float z, // float? rotation = null, @@ -1555,9 +1780,14 @@ public virtual void TeleportFull( // ); // } - [ObsoleteAttribute(message: "This action is deprecated. Call Teleport(position, ...) instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call Teleport(position, ...) instead.", + error: false + )] public void Teleport( - float x, float y, float z, + float x, + float y, + float z, Vector3? rotation = null, float? horizon = null, bool? standing = null, @@ -1635,10 +1865,10 @@ public virtual void MoveLeft( bool forceAction = false, bool manualInteract = false, bool allowAgentsToIntersect = false, - float speed = 1, // TODO: Unused, remove when refactoring the controllers + float speed = 1, // TODO: Unused, remove when refactoring the controllers float? fixedDeltaTime = null, // TODO: Unused, remove when refactoring the controllers - bool returnToStart = true, // TODO: Unused, remove when refactoring the controllers - bool disableRendering = true // TODO: Unused, remove when refactoring the controllers + bool returnToStart = true, // TODO: Unused, remove when refactoring the controllers + bool disableRendering = true // TODO: Unused, remove when refactoring the controllers ) { if (!moveMagnitude.HasValue) { moveMagnitude = gridSize; @@ -1646,14 +1876,16 @@ public virtual void MoveLeft( throw new InvalidOperationException("moveMagnitude must be > 0"); } - actionFinished(moveInDirection( - direction: -transform.right * moveMagnitude.Value, - objectId: objectId, - maxDistanceToObject: maxAgentsDistance, - forceAction: forceAction, - manualInteract: manualInteract, - ignoreColliders: allowAgentsToIntersect ? allAgentColliders() : null - )); + actionFinished( + moveInDirection( + direction: -transform.right * moveMagnitude.Value, + objectId: objectId, + maxDistanceToObject: maxAgentsDistance, + forceAction: forceAction, + manualInteract: manualInteract, + ignoreColliders: allowAgentsToIntersect ? allAgentColliders() : null + ) + ); } public virtual void MoveRight( @@ -1664,7 +1896,6 @@ public virtual void MoveRight( bool manualInteract = false, bool allowAgentsToIntersect = false ) { - Debug.Log("MoveRight at physics fps? call "); if (!moveMagnitude.HasValue) { moveMagnitude = gridSize; @@ -1672,22 +1903,24 @@ public virtual void MoveRight( throw new InvalidOperationException("moveMagnitude must be > 0"); } - actionFinished(moveInDirection( - direction: transform.right * moveMagnitude.Value, - objectId: objectId, - maxDistanceToObject: maxAgentsDistance, - forceAction: forceAction, - manualInteract: manualInteract, - ignoreColliders: allowAgentsToIntersect ? allAgentColliders() : null - )); + actionFinished( + moveInDirection( + direction: transform.right * moveMagnitude.Value, + objectId: objectId, + maxDistanceToObject: maxAgentsDistance, + forceAction: forceAction, + manualInteract: manualInteract, + ignoreColliders: allowAgentsToIntersect ? allAgentColliders() : null + ) + ); } public virtual void MoveAhead( - float? moveMagnitude = null, - string objectId = "", - float maxAgentsDistance = -1f, - bool forceAction = false, - bool manualInteract = false, + float? moveMagnitude = null, + string objectId = "", + float maxAgentsDistance = -1f, + bool forceAction = false, + bool manualInteract = false, bool allowAgentsToIntersect = false ) { if (!moveMagnitude.HasValue) { @@ -1696,14 +1929,16 @@ public virtual void MoveAhead( throw new InvalidOperationException("moveMagnitude must be > 0"); } - actionFinished(moveInDirection( - direction: transform.forward * moveMagnitude.Value, - objectId: objectId, - maxDistanceToObject: maxAgentsDistance, - forceAction: forceAction, - manualInteract: manualInteract, - ignoreColliders: allowAgentsToIntersect ? allAgentColliders() : null - )); + actionFinished( + moveInDirection( + direction: transform.forward * moveMagnitude.Value, + objectId: objectId, + maxDistanceToObject: maxAgentsDistance, + forceAction: forceAction, + manualInteract: manualInteract, + ignoreColliders: allowAgentsToIntersect ? allAgentColliders() : null + ) + ); } public virtual void MoveBack( @@ -1713,10 +1948,10 @@ public virtual void MoveBack( bool forceAction = false, bool manualInteract = false, bool allowAgentsToIntersect = false, - float speed = 1, // TODO: Unused, remove when refactoring the controllers + float speed = 1, // TODO: Unused, remove when refactoring the controllers float? fixedDeltaTime = null, // TODO: Unused, remove when refactoring the controllers - bool returnToStart = true, // TODO: Unused, remove when refactoring the controllers - bool disableRendering = true // TODO: Unused, remove when refactoring the controllers + bool returnToStart = true, // TODO: Unused, remove when refactoring the controllers + bool disableRendering = true // TODO: Unused, remove when refactoring the controllers ) { if (!moveMagnitude.HasValue) { moveMagnitude = gridSize; @@ -1724,14 +1959,16 @@ public virtual void MoveBack( throw new InvalidOperationException("moveMagnitude must be > 0"); } - actionFinished(moveInDirection( - direction: -transform.forward * moveMagnitude.Value, - objectId: objectId, - maxDistanceToObject: maxAgentsDistance, - forceAction: forceAction, - manualInteract: manualInteract, - ignoreColliders: allowAgentsToIntersect ? allAgentColliders() : null - )); + actionFinished( + moveInDirection( + direction: -transform.forward * moveMagnitude.Value, + objectId: objectId, + maxDistanceToObject: maxAgentsDistance, + forceAction: forceAction, + manualInteract: manualInteract, + ignoreColliders: allowAgentsToIntersect ? allAgentColliders() : null + ) + ); } // a no op action used to return metadata via actionFinished call, but not actually doing anything to interact with the scene or manipulate the Agent @@ -1740,7 +1977,10 @@ public void NoOp() { } public void PushObject(ServerAction action) { - if (ItemInHand != null && action.objectId == ItemInHand.GetComponent().objectID) { + if ( + ItemInHand != null + && action.objectId == ItemInHand.GetComponent().objectID + ) { errorMessage = "Please use Throw for an item in the Agent's Hand"; Debug.Log(errorMessage); actionFinished(false); @@ -1757,7 +1997,10 @@ public void PushObject(ServerAction action) { } public void PullObject(ServerAction action) { - if (ItemInHand != null && action.objectId == ItemInHand.GetComponent().objectID) { + if ( + ItemInHand != null + && action.objectId == ItemInHand.GetComponent().objectID + ) { errorMessage = "Please use Throw for an item in the Agent's Hand"; Debug.Log(errorMessage); actionFinished(false); @@ -1775,7 +2018,10 @@ public void PullObject(ServerAction action) { // pass in a magnitude and an angle offset to push an object relative to agent forward public void DirectionalPush(ServerAction action) { - if (ItemInHand != null && action.objectId == ItemInHand.GetComponent().objectID) { + if ( + ItemInHand != null + && action.objectId == ItemInHand.GetComponent().objectID + ) { errorMessage = "Please use Throw for an item in the Agent's Hand"; Debug.Log(errorMessage); actionFinished(false); @@ -1797,9 +2043,16 @@ public void DirectionalPush(ServerAction action) { SimObjPhysics target = null; if (action.objectId == null) { - target = getInteractableSimObjectFromXY(x: action.x, y: action.y, forceAction: action.forceAction); + target = getInteractableSimObjectFromXY( + x: action.x, + y: action.y, + forceAction: action.forceAction + ); } else { - target = getInteractableSimObjectFromId(objectId: action.objectId, forceAction: action.forceAction); + target = getInteractableSimObjectFromId( + objectId: action.objectId, + forceAction: action.forceAction + ); } // SimObjPhysics[] simObjPhysicsArray = VisibleSimObjs(action); @@ -1831,8 +2084,15 @@ public void DirectionalPush(ServerAction action) { Vector3 agentForward = transform.forward; float pushAngleInRadians = action.pushAngle * Mathf.PI / -180; // using -180 so positive PushAngle values go clockwise - Vector3 direction = new Vector3((agentForward.x * Mathf.Cos(pushAngleInRadians) - agentForward.z * Mathf.Sin(pushAngleInRadians)), 0, - agentForward.x * Mathf.Sin(pushAngleInRadians) + agentForward.z * Mathf.Cos(pushAngleInRadians)); + Vector3 direction = new Vector3( + ( + agentForward.x * Mathf.Cos(pushAngleInRadians) + - agentForward.z * Mathf.Sin(pushAngleInRadians) + ), + 0, + agentForward.x * Mathf.Sin(pushAngleInRadians) + + agentForward.z * Mathf.Cos(pushAngleInRadians) + ); ServerAction pushAction = new ServerAction(); pushAction.x = direction.x; @@ -1855,26 +2115,39 @@ public void ApplyForceObject(ServerAction action) { SimObjPhysics target = null; if (action.objectId == null) { - target = getInteractableSimObjectFromXY(x: action.x, y: action.y, forceAction: action.forceAction); + target = getInteractableSimObjectFromXY( + x: action.x, + y: action.y, + forceAction: action.forceAction + ); } else { - target = getInteractableSimObjectFromId(objectId: action.objectId, forceAction: action.forceAction); + target = getInteractableSimObjectFromId( + objectId: action.objectId, + forceAction: action.forceAction + ); } bool canbepushed = false; - if (target.PrimaryProperty == SimObjPrimaryProperty.CanPickup || - target.PrimaryProperty == SimObjPrimaryProperty.Moveable) { + if ( + target.PrimaryProperty == SimObjPrimaryProperty.CanPickup + || target.PrimaryProperty == SimObjPrimaryProperty.Moveable + ) { canbepushed = true; } if (!canbepushed) { - errorMessage = "Target Sim Object cannot be moved. It's primary property must be Pickupable or Moveable"; + errorMessage = + "Target Sim Object cannot be moved. It's primary property must be Pickupable or Moveable"; actionFinished(false); return; } if (!action.forceAction && !IsInteractable(target)) { - errorMessage = "Target:" + target.objectID + "is not interactable and is probably occluded by something!"; + errorMessage = + "Target:" + + target.objectID + + "is not interactable and is probably occluded by something!"; actionFinished(false); return; } @@ -1918,7 +2191,11 @@ protected void sopApplyForce(ServerAction action, SimObjPhysics sop, float lengt // print("autosimulation off"); sop.ApplyForce(action); if (length >= 0.00001f) { - WhatDidITouch feedback = new WhatDidITouch() { didHandTouchSomething = true, objectId = sop.objectID, armsLength = length }; + WhatDidITouch feedback = new WhatDidITouch() { + didHandTouchSomething = true, + objectId = sop.objectID, + armsLength = length + }; #if UNITY_EDITOR print("didHandTouchSomething: " + feedback.didHandTouchSomething); print("object id: " + feedback.objectId); @@ -1926,13 +2203,11 @@ protected void sopApplyForce(ServerAction action, SimObjPhysics sop, float lengt #endif actionFinished(true, feedback); } - // why is this here? else { actionFinished(true); } } - // if physics is automatically being simulated, use coroutine rather than returning actionFinished immediately else { // print("autosimulation true"); @@ -1940,13 +2215,15 @@ protected void sopApplyForce(ServerAction action, SimObjPhysics sop, float lengt StartCoroutine(checkIfObjectHasStoppedMoving(sop: sop, length: length)); } } + // used to check if an specified sim object has come to rest // set useTimeout bool to use a faster time out //overload for arm length to be used with TouchThenApplyForce functions protected IEnumerator checkIfObjectHasStoppedMoving( SimObjPhysics sop, float length, - bool useTimeout = false) { + bool useTimeout = false + ) { // yield for the physics update to make sure this yield is consistent regardless of framerate yield return new WaitForFixedUpdate(); @@ -1966,7 +2243,9 @@ protected IEnumerator checkIfObjectHasStoppedMoving( break; } - float currentVelocity = Math.Abs(rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude); + float currentVelocity = Math.Abs( + rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude + ); float accel = (currentVelocity - sop.lastVelocity) / Time.fixedDeltaTime; // ok the accel is basically zero, so it has stopped moving @@ -1991,7 +2270,11 @@ protected IEnumerator checkIfObjectHasStoppedMoving( } // return to metadatawrapper.actionReturn if an object was touched during this interaction - WhatDidITouch feedback = new WhatDidITouch() { didHandTouchSomething = true, objectId = sop.objectID, armsLength = length }; + WhatDidITouch feedback = new WhatDidITouch() { + didHandTouchSomething = true, + objectId = sop.objectID, + armsLength = length + }; #if UNITY_EDITOR print("yield timed out"); @@ -2000,13 +2283,12 @@ protected IEnumerator checkIfObjectHasStoppedMoving( print("armslength: " + feedback.armsLength); #endif - // force objec to stop moving + // force objec to stop moving rb.velocity = Vector3.zero; rb.angularVelocity = Vector3.zero; rb.Sleep(); actionFinished(true, feedback); - } else { errorMessage = "null reference sim obj in checkIfObjectHasStoppedMoving call"; actionFinished(false); @@ -2021,7 +2303,8 @@ protected void sopApplyForce(ServerAction action, SimObjPhysics sop) { private IEnumerator checkIfAllObjectsHaveStoppedMoving( float length, double squaredAccelerationEpsilon = 1e-3, - bool useTimeout = false) { + bool useTimeout = false + ) { // yield for the physics update to make sure this yield is consistent regardless of framerate yield return new WaitForFixedUpdate(); @@ -2033,7 +2316,6 @@ private IEnumerator checkIfAllObjectsHaveStoppedMoving( } foreach (var sop in GameObject.FindObjectsOfType()) { - Rigidbody rb = sop.GetComponentInChildren(); bool stoppedMoving = false; @@ -2042,8 +2324,11 @@ private IEnumerator checkIfAllObjectsHaveStoppedMoving( break; } - float currentSqrVelocity = rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude; - float squaredAccel = (currentSqrVelocity - sop.lastVelocity) / (Time.fixedDeltaTime * Time.fixedDeltaTime); + float currentSqrVelocity = + rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude; + float squaredAccel = + (currentSqrVelocity - sop.lastVelocity) + / (Time.fixedDeltaTime * Time.fixedDeltaTime); // ok the accel is basically zero, so it has stopped moving if (Mathf.Abs(squaredAccel) <= squaredAccelerationEpsilon) { @@ -2073,7 +2358,11 @@ private IEnumerator checkIfAllObjectsHaveStoppedMoving( // return to metadatawrapper.actionReturn if an object was touched during this interaction if (length != 0.0f) { - WhatDidITouch feedback = new WhatDidITouch() { didHandTouchSomething = true, objectId = sop.objectID, armsLength = length }; + WhatDidITouch feedback = new WhatDidITouch() { + didHandTouchSomething = true, + objectId = sop.objectID, + armsLength = length + }; #if UNITY_EDITOR print("yield timed out"); @@ -2082,22 +2371,19 @@ private IEnumerator checkIfAllObjectsHaveStoppedMoving( print("armslength: " + feedback.armsLength); #endif - // force objec to stop moving + // force objec to stop moving rb.velocity = Vector3.zero; rb.angularVelocity = Vector3.zero; rb.Sleep(); actionFinished(true, feedback); } - // if passed in length is 0, don't return feedback cause not all actions need that else { DefaultAgentHand(); actionFinished(true, sop.transform.position); } - } - } // Sweeptest to see if the object Agent is holding will prohibit movement @@ -2109,7 +2395,6 @@ public bool CheckIfItemBlocksAgentStandOrCrouch() { result = true; return result; } - // otherwise we are holding an object and need to do a sweep using that object's rb else { Vector3 dir = new Vector3(); @@ -2122,7 +2407,11 @@ public bool CheckIfItemBlocksAgentStandOrCrouch() { Rigidbody rb = ItemInHand.GetComponent(); - RaycastHit[] sweepResults = rb.SweepTestAll(dir, standingLocalCameraPosition.y, QueryTriggerInteraction.Ignore); + RaycastHit[] sweepResults = rb.SweepTestAll( + dir, + standingLocalCameraPosition.y, + QueryTriggerInteraction.Ignore + ); if (sweepResults.Length > 0) { foreach (RaycastHit res in sweepResults) { // did the item in the hand touch the agent? if so, ignore it's fine @@ -2133,12 +2422,16 @@ public bool CheckIfItemBlocksAgentStandOrCrouch() { result = true; break; } else { - errorMessage = res.transform.name + " is blocking the Agent from moving " + dir + " with " + ItemInHand.name; + errorMessage = + res.transform.name + + " is blocking the Agent from moving " + + dir + + " with " + + ItemInHand.name; result = false; Debug.Log(errorMessage); return result; } - } } // if the array is empty, nothing was hit by the sweeptest so we are clear to move @@ -2151,7 +2444,12 @@ public bool CheckIfItemBlocksAgentStandOrCrouch() { } ///// AGENT HAND STUFF//// - protected IEnumerator moveHandToTowardsXYZWithForce(float x, float y, float z, float maxDistance) { + protected IEnumerator moveHandToTowardsXYZWithForce( + float x, + float y, + float z, + float maxDistance + ) { if (ItemInHand == null) { errorMessage = "Agent can only move hand if holding an item"; actionFinished(false); @@ -2200,7 +2498,11 @@ protected IEnumerator moveHandToTowardsXYZWithForce(float x, float y, float z, f if (i >= 5) { bool repeatedPosition = false; - for (int j = seenPositions.Count - 4; j >= Math.Max(seenPositions.Count - 8, 0); j--) { + for ( + int j = seenPositions.Count - 4; + j >= Math.Max(seenPositions.Count - 8, 0); + j-- + ) { float distance = Vector3.Distance(rb.transform.position, seenPositions[i]); float angle = Quaternion.Angle(rb.transform.rotation, seenRotations[i]); if (distance <= 0.001f && angle <= 3f) { @@ -2221,7 +2523,8 @@ protected IEnumerator moveHandToTowardsXYZWithForce(float x, float y, float z, f Vector3 perpDir = delta - forceDir; float perpNorm = perpDir.magnitude; if (perpNorm > 0.1f * maxDistance) { - newPosition = initialPosition + forceDir + (0.1f * maxDistance) * perpDir / perpNorm; + newPosition = + initialPosition + forceDir + (0.1f * maxDistance) * perpDir / perpNorm; rb.transform.position = newPosition; } @@ -2229,7 +2532,9 @@ protected IEnumerator moveHandToTowardsXYZWithForce(float x, float y, float z, f tmpForCamera.y = m_Camera.transform.position.y; hitMaxDistance = Vector3.Distance(initialPosition, newPosition) > maxDistance; - beyondVisibleDistance = Vector3.Distance(m_Camera.transform.position, tmpForCamera) > maxVisibleDistance; + beyondVisibleDistance = + Vector3.Distance(m_Camera.transform.position, tmpForCamera) + > maxVisibleDistance; leavingViewport = !objectIsWithinViewport(simObjInHand); // leavingViewport = !objectIsCurrentlyVisible(simObjInHand, 1000f); @@ -2252,7 +2557,9 @@ protected IEnumerator moveHandToTowardsXYZWithForce(float x, float y, float z, f Vector3 normalSum = new Vector3(0.0f, 0.0f, 0.0f); Vector3 aveCollisionsNormal = new Vector3(0.0f, 0.0f, 0.0f); int count = 0; - foreach (KeyValuePair pair in simObjInHand.contactPointsDictionary) { + foreach ( + KeyValuePair pair in simObjInHand.contactPointsDictionary + ) { foreach (ContactPoint cp in pair.Value) { normalSum += cp.normal; count += 1; @@ -2277,7 +2584,8 @@ protected IEnumerator moveHandToTowardsXYZWithForce(float x, float y, float z, f bool handObjectIsColliding = isHandObjectColliding(true); if (count != 0) { for (int j = 0; handObjectIsColliding && j < 5; j++) { - AgentHand.transform.position = AgentHand.transform.position + 0.01f * aveCollisionsNormal; + AgentHand.transform.position = + AgentHand.transform.position + 0.01f * aveCollisionsNormal; PhysicsSceneManager.PhysicsSimulateTHOR(0.1f); handObjectIsColliding = isHandObjectColliding(true); } @@ -2294,7 +2602,12 @@ protected IEnumerator moveHandToTowardsXYZWithForce(float x, float y, float z, f AgentHand.transform.position = initialPosition; rb.transform.rotation = initialRotation; errorMessage = "Hand object was colliding with: "; - foreach (KeyValuePair pair in simObjInHand.contactPointsDictionary) { + foreach ( + KeyValuePair< + Collider, + ContactPoint[] + > pair in simObjInHand.contactPointsDictionary + ) { SimObjPhysics sop = ancestorSimObjPhysics(pair.Key.gameObject); if (sop != null) { errorMessage += "" + sop.ObjectID + ", "; @@ -2304,8 +2617,10 @@ protected IEnumerator moveHandToTowardsXYZWithForce(float x, float y, float z, f } errorMessage += " object(s) after movement."; actionFinished(false); - } else if (Vector3.Distance(initialPosition, lastPosition) < 0.001f && - Quaternion.Angle(initialRotation, lastRotation) < 0.001f) { + } else if ( + Vector3.Distance(initialPosition, lastPosition) < 0.001f + && Quaternion.Angle(initialRotation, lastRotation) < 0.001f + ) { if (beyondVisibleDistance) { errorMessage = "Hand already at max distance."; } else if (leavingViewport) { @@ -2320,17 +2635,28 @@ protected IEnumerator moveHandToTowardsXYZWithForce(float x, float y, float z, f } public void OpenWithHand(ServerAction action) { - Vector3 direction = transform.forward * action.z + - transform.right * action.x + - transform.up * action.y; + Vector3 direction = + transform.forward * action.z + transform.right * action.x + transform.up * action.y; direction.Normalize(); if (ItemInHand != null) { ItemInHand.SetActive(false); } RaycastHit hit; - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "SimObjInvisible"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "SimObjInvisible" + ); bool raycastDidHit = Physics.Raycast( - AgentHand.transform.position, direction, out hit, 10f, layerMask); + AgentHand.transform.position, + direction, + out hit, + 10f, + layerMask + ); if (ItemInHand != null) { ItemInHand.SetActive(true); } @@ -2350,11 +2676,8 @@ public void OpenWithHand(ServerAction action) { } public void MoveHandForce(float x, float y, float z) { - Vector3 direction = transform.forward * z + - transform.right * x + - transform.up * y; - Vector3 target = AgentHand.transform.position + - direction; + Vector3 direction = transform.forward * z + transform.right * x + transform.up * y; + Vector3 target = AgentHand.transform.position + direction; if (ItemInHand == null) { Debug.Log("Agent can only move hand if holding an item"); actionFinished(false); @@ -2382,7 +2705,15 @@ public void TouchThenApplyForce(ServerAction action) { ray, out hit, action.handDistance, - LayerMask.GetMask("Default", "SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent"), + LayerMask.GetMask( + "Default", + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent" + ), QueryTriggerInteraction.Ignore ) ) { @@ -2390,7 +2721,11 @@ public void TouchThenApplyForce(ServerAction action) { // wait! First check if the point hit is withing visibility bounds (camera viewport, max distance etc) // this should basically only happen if the handDistance value is too big try { - assertPosInView(targetPosition: hit.point, inMaxVisibleDistance: true, inViewport: true); + assertPosInView( + targetPosition: hit.point, + inMaxVisibleDistance: true, + inViewport: true + ); } catch (InvalidOperationException e) { actionFinished( success: false, @@ -2408,14 +2743,20 @@ public void TouchThenApplyForce(ServerAction action) { SimObjPhysics target = hit.transform.GetComponent(); bool canbepushed = false; - if (target.PrimaryProperty == SimObjPrimaryProperty.CanPickup || - target.PrimaryProperty == SimObjPrimaryProperty.Moveable) { + if ( + target.PrimaryProperty == SimObjPrimaryProperty.CanPickup + || target.PrimaryProperty == SimObjPrimaryProperty.Moveable + ) { canbepushed = true; } if (!canbepushed) { // the sim object hit was not moveable or pickupable - WhatDidITouch feedback = new WhatDidITouch() { didHandTouchSomething = true, objectId = target.objectID, armsLength = hit.distance }; + WhatDidITouch feedback = new WhatDidITouch() { + didHandTouchSomething = true, + objectId = target.objectID, + armsLength = hit.distance + }; #if UNITY_EDITOR print("object touched was not moveable or pickupable"); print("didHandTouchSomething: " + feedback.didHandTouchSomething); @@ -2438,10 +2779,13 @@ public void TouchThenApplyForce(ServerAction action) { sopApplyForce(apply, target, hit.distance); } - // raycast hit something but it wasn't a sim object else { - WhatDidITouch feedback = new WhatDidITouch() { didHandTouchSomething = true, objectId = "not a sim object, a structure was touched", armsLength = hit.distance }; + WhatDidITouch feedback = new WhatDidITouch() { + didHandTouchSomething = true, + objectId = "not a sim object, a structure was touched", + armsLength = hit.distance + }; #if UNITY_EDITOR print("object touched was not a sim object at all"); print("didHandTouchSomething: " + feedback.didHandTouchSomething); @@ -2452,14 +2796,17 @@ public void TouchThenApplyForce(ServerAction action) { return; } } - // raycast didn't hit anything else { // get ray.origin, multiply handDistance with ray.direction, add to origin to get the final point // if the final point was out of range, return actionFinished false, otherwise return actionFinished true with feedback Vector3 testPosition = ((action.handDistance * ray.direction) + ray.origin); try { - assertPosInView(targetPosition: testPosition, inMaxVisibleDistance: true, inViewport: true); + assertPosInView( + targetPosition: testPosition, + inMaxVisibleDistance: true, + inViewport: true + ); } catch (InvalidOperationException e) { actionFinished( success: false, @@ -2474,7 +2821,11 @@ public void TouchThenApplyForce(ServerAction action) { } // the nothing hit was not out of range, but still nothing was hit - WhatDidITouch feedback = new WhatDidITouch() { didHandTouchSomething = false, objectId = "", armsLength = action.handDistance }; + WhatDidITouch feedback = new WhatDidITouch() { + didHandTouchSomething = false, + objectId = "", + armsLength = action.handDistance + }; #if UNITY_EDITOR print("raycast did not hit anything, it only hit empty space"); print("didHandTouchSomething: " + feedback.didHandTouchSomething); @@ -2483,14 +2834,13 @@ public void TouchThenApplyForce(ServerAction action) { #endif actionFinished(true, feedback); } - } // for use with TouchThenApplyForce feedback return public struct WhatDidITouch { - public bool didHandTouchSomething;// did the hand touch something or did it hit nothing? - public string objectId;// id of object touched, if it is a sim object - public float armsLength;// the amount the hand moved from it's starting position to hit the object touched + public bool didHandTouchSomething; // did the hand touch something or did it hit nothing? + public string objectId; // id of object touched, if it is a sim object + public float armsLength; // the amount the hand moved from it's starting position to hit the object touched } // checks if agent hand that is holding an object can move to a target location. Returns false if any obstructions @@ -2509,20 +2859,22 @@ public bool CheckIfAgentCanMoveHand(Vector3 targetPosition, bool mustBeVisible = tmp.y = targetPosition.y; if (Vector3.Distance(tmp, targetPosition) > maxVisibleDistance) { - errorMessage = "The target position is out of range- object cannot move outside of max visibility distance."; + errorMessage = + "The target position is out of range- object cannot move outside of max visibility distance."; result = false; return result; } // Note: Viewport normalizes to (0,0) bottom left, (1, 0) top right of screen - // now make sure the targetPosition is actually within the Camera Bounds + // now make sure the targetPosition is actually within the Camera Bounds Vector3 lastPosition = AgentHand.transform.position; AgentHand.transform.position = targetPosition; // now make sure that the targetPosition is within the Agent's x/y view, restricted by camera if (!objectIsWithinViewport(ItemInHand.GetComponent())) { AgentHand.transform.position = lastPosition; - errorMessage = "Target position is outside of the agent's viewport. The target position must be within the frustrum of the viewport."; + errorMessage = + "Target position is outside of the agent's viewport. The target position must be within the frustrum of the viewport."; result = false; return result; } @@ -2537,7 +2889,8 @@ public bool CheckIfAgentCanMoveHand(Vector3 targetPosition, bool mustBeVisible = lastPosition = AgentHand.transform.position; AgentHand.transform.position = targetPosition; if (!objectIsCurrentlyVisible(ItemInHand.GetComponent(), 1000f)) { - errorMessage = "The target position is not in the Area of the Agent's Viewport!"; + errorMessage = + "The target position is not in the Area of the Agent's Viewport!"; result = false; AgentHand.transform.position = lastPosition; return result; @@ -2545,35 +2898,35 @@ public bool CheckIfAgentCanMoveHand(Vector3 targetPosition, bool mustBeVisible = AgentHand.transform.position = lastPosition; } - // ok now actually check if the Agent Hand holding ItemInHand can move to the target position without // being obstructed by anything Rigidbody ItemRB = ItemInHand.GetComponent(); - RaycastHit[] sweepResults = ItemRB.SweepTestAll(targetPosition - AgentHand.transform.position, + RaycastHit[] sweepResults = ItemRB.SweepTestAll( + targetPosition - AgentHand.transform.position, Vector3.Distance(targetPosition, AgentHand.transform.position), - QueryTriggerInteraction.Ignore); + QueryTriggerInteraction.Ignore + ); // did we hit anything? if (sweepResults.Length > 0) { - foreach (RaycastHit hit in sweepResults) { // hit the player? it's cool, no problem if (hit.transform.tag == "Player") { result = true; break; } - // oh we hit something else? oh boy, that's blocking! else { - errorMessage = hit.transform.name + " is in Object In Hand's Path! Can't Move Hand holding " + ItemInHand.name; + errorMessage = + hit.transform.name + + " is in Object In Hand's Path! Can't Move Hand holding " + + ItemInHand.name; result = false; return result; } } - } - // didnt hit anything in sweep, we are good to go else { result = true; @@ -2610,20 +2963,29 @@ protected IEnumerator waitForNFramesAndReturn(int n, bool actionSuccess) { // x=.1, y=.1, z=0 will move the hand .1 in both the x and y coordinates. public void MoveHand(float x, float y, float z) { // get new direction relative to Agent forward facing direction (not the camera) - Vector3 newPos = AgentHand.transform.position + - transform.forward * z + - transform.right * x + - transform.up * y; + Vector3 newPos = + AgentHand.transform.position + + transform.forward * z + + transform.right * x + + transform.up * y; StartCoroutine(waitForNFramesAndReturn(1, moveHandToXYZ(newPos.x, newPos.y, newPos.z))); } - [ObsoleteAttribute(message: "This action is deprecated. Call MoveHeldObject(right, up, ahead) instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call MoveHeldObject(right, up, ahead) instead.", + error: false + )] public void MoveHandDelta(float x, float y, float z, bool forceVisible = false) { MoveHeldObject(right: x, up: y, ahead: z); } // moves hand constrained to x, y, z axes a given magnitude- x y z describe the magnitude in this case - public void MoveHeldObject(float right = 0, float up = 0, float ahead = 0, bool forceVisible = false) { + public void MoveHeldObject( + float right = 0, + float up = 0, + float ahead = 0, + bool forceVisible = false + ) { Vector3 newPos = AgentHand.transform.position; newPos += ( m_Camera.transform.forward * ahead @@ -2633,7 +2995,10 @@ public void MoveHeldObject(float right = 0, float up = 0, float ahead = 0, bool actionFinished(moveHandToXYZ(newPos.x, newPos.y, newPos.z, forceVisible)); } - [ObsoleteAttribute(message: "This action is deprecated. Call MoveHeldObjectAhead() instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call MoveHeldObjectAhead() instead.", + error: false + )] public void MoveHandAhead(float moveMagnitude, bool forceVisible = false) { MoveHeldObjectAhead(moveMagnitude: moveMagnitude, forceVisible: forceVisible); } @@ -2644,7 +3009,10 @@ public void MoveHeldObjectAhead(float moveMagnitude, bool forceVisible = false) actionFinished(moveHandToXYZ(newPos.x, newPos.y, newPos.z, forceVisible)); } - [ObsoleteAttribute(message: "This action is deprecated. Call MoveHeldObjectLeft() instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call MoveHeldObjectLeft() instead.", + error: false + )] public void MoveHandLeft(float moveMagnitude, bool forceVisible = false) { MoveHeldObjectLeft(moveMagnitude: moveMagnitude, forceVisible: forceVisible); } @@ -2655,7 +3023,10 @@ public void MoveHeldObjectLeft(float moveMagnitude, bool forceVisible = false) { actionFinished(moveHandToXYZ(newPos.x, newPos.y, newPos.z, forceVisible)); } - [ObsoleteAttribute(message: "This action is deprecated. Call MoveHeldObjectDown() instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call MoveHeldObjectDown() instead.", + error: false + )] public void MoveHandDown(float moveMagnitude, bool forceVisible = false) { MoveHeldObjectDown(moveMagnitude: moveMagnitude, forceVisible: forceVisible); } @@ -2666,7 +3037,10 @@ public void MoveHeldObjectDown(float moveMagnitude, bool forceVisible = false) { actionFinished(moveHandToXYZ(newPos.x, newPos.y, newPos.z, forceVisible)); } - [ObsoleteAttribute(message: "This action is deprecated. Call MoveHeldObjectUp() instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call MoveHeldObjectUp() instead.", + error: false + )] public void MoveHandUp(float moveMagnitude, bool forceVisible = false) { MoveHeldObjectUp(moveMagnitude: moveMagnitude, forceVisible: forceVisible); } @@ -2677,7 +3051,10 @@ public void MoveHeldObjectUp(float moveMagnitude, bool forceVisible = false) { actionFinished(moveHandToXYZ(newPos.x, newPos.y, newPos.z, forceVisible)); } - [ObsoleteAttribute(message: "This action is deprecated. Call MoveHeldObjectRight() instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call MoveHeldObjectRight() instead.", + error: false + )] public void MoveHandRight(float moveMagnitude, bool forceVisible = false) { MoveHeldObjectRight(moveMagnitude: moveMagnitude, forceVisible: forceVisible); } @@ -2688,7 +3065,10 @@ public void MoveHeldObjectRight(float moveMagnitude, bool forceVisible = false) actionFinished(moveHandToXYZ(newPos.x, newPos.y, newPos.z, forceVisible)); } - [ObsoleteAttribute(message: "This action is deprecated. Call MoveHeldObjectBack() instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call MoveHeldObjectBack() instead.", + error: false + )] public void MoveHandBack(float moveMagnitude, bool forceVisible = false) { MoveHeldObjectBack(moveMagnitude: moveMagnitude, forceVisible: forceVisible); } @@ -2701,10 +3081,15 @@ public void MoveHeldObjectBack(float moveMagnitude, bool forceVisible = false) { // uh this kinda does what MoveHandDelta does but in more steps, splitting direction and magnitude into // two separate params in case someone wants it that way - public void MoveHandMagnitude(float moveMagnitude, float x = 0.0f, float y = 0.0f, float z = 0.0f) { + public void MoveHandMagnitude( + float moveMagnitude, + float x = 0.0f, + float y = 0.0f, + float z = 0.0f + ) { Vector3 newPos = AgentHand.transform.position; - // get new direction relative to Agent's (camera's) forward facing + // get new direction relative to Agent's (camera's) forward facing if (x > 0) { newPos = newPos + (m_Camera.transform.right * moveMagnitude); } @@ -2746,14 +3131,23 @@ public bool CheckIfAgentCanRotateHand() { // make sure there is a box collider if (ItemInHand.GetComponent().BoundingBox.GetComponent()) { - Vector3 sizeOfBox = ItemInHand.GetComponent().BoundingBox.GetComponent().size; + Vector3 sizeOfBox = ItemInHand + .GetComponent() + .BoundingBox.GetComponent() + .size; float overlapRadius = Math.Max(Math.Max(sizeOfBox.x, sizeOfBox.y), sizeOfBox.z); // all colliders hit by overlapsphere Collider[] hitColliders = Physics.OverlapSphere( AgentHand.transform.position, overlapRadius, - LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"), + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ), QueryTriggerInteraction.Ignore ); @@ -2763,25 +3157,28 @@ public bool CheckIfAgentCanRotateHand() { // is this a sim object? if (col.GetComponentInParent()) { // is it not the item we are holding? then it's blocking - if (col.GetComponentInParent().transform != ItemInHand.transform) { - errorMessage = "Rotating the object results in it colliding with " + col.gameObject.name; + if ( + col.GetComponentInParent().transform + != ItemInHand.transform + ) { + errorMessage = + "Rotating the object results in it colliding with " + + col.gameObject.name; return false; } - // oh it is the item we are holding, it's fine else { result = true; } } - // ok it's not a sim obj and it's not the player, so it must be a structure or something else that would block else if (col.tag != "Player") { - errorMessage = "Rotating the object results in it colliding with an agent."; + errorMessage = + "Rotating the object results in it colliding with an agent."; return false; } } } - // nothing hit by sphere, so we are safe to rotate else { result = true; @@ -2793,7 +3190,10 @@ public bool CheckIfAgentCanRotateHand() { return result; } - [ObsoleteAttribute(message: "This action is deprecated. Call RotateHeldObject() instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call RotateHeldObject() instead.", + error: false + )] public void RotateHand(float x, float y, float z) { RotateHeldObject(rotation: new Vector3(x, y, z)); } @@ -2801,11 +3201,15 @@ public void RotateHand(float x, float y, float z) { // rotate the held object if there is an object in it public void RotateHeldObject(Vector3 rotation) { if (ItemInHand == null) { - throw new InvalidOperationException("Can't rotate held object since no object is being held."); + throw new InvalidOperationException( + "Can't rotate held object since no object is being held." + ); } if (!CheckIfAgentCanRotateHand()) { - throw new InvalidOperationException("Object is unable to rotate in its current state!"); + throw new InvalidOperationException( + "Object is unable to rotate in its current state!" + ); } AgentHand.transform.localRotation = Quaternion.Euler(rotation); @@ -2813,7 +3217,9 @@ public void RotateHeldObject(Vector3 rotation) { // if this is rotated too much, drop any contained object if held item is a receptacle if (Vector3.Angle(ItemInHand.transform.up, Vector3.up) > 95) { - ItemInHand.GetComponent().DropContainedObjects(reparentContainedObjects: true, forceKinematic: false); + ItemInHand + .GetComponent() + .DropContainedObjects(reparentContainedObjects: true, forceKinematic: false); } actionFinished(true); @@ -2822,7 +3228,9 @@ public void RotateHeldObject(Vector3 rotation) { // rotate the hand if there is an object in it public void RotateHeldObject(float pitch = 0, float yaw = 0, float roll = 0) { if (ItemInHand == null) { - throw new InvalidOperationException("Can't rotate held object since no object is being held."); + throw new InvalidOperationException( + "Can't rotate held object since no object is being held." + ); } Quaternion agentRot = transform.rotation; @@ -2831,9 +3239,7 @@ public void RotateHeldObject(float pitch = 0, float yaw = 0, float roll = 0) { transform.rotation = Quaternion.identity; // NOTE: -roll is used so that rotating an object rightward is positive - AgentHand.transform.Rotate( - new Vector3(pitch, yaw, -roll), Space.World - ); + AgentHand.transform.Rotate(new Vector3(pitch, yaw, -roll), Space.World); transform.rotation = agentRot; if (isHandObjectColliding(true)) { @@ -2852,32 +3258,70 @@ public void RotateHandRelative(float x = 0, float y = 0, float z = 0) { //utility function, spawn prefab at random position in receptacle //Object will fall into place with physics resolution - public void SpawnObjectInReceptacleRandomly(string objectId, string prefabName, string targetReceptacle, FlexibleRotation rotation) { + public void SpawnObjectInReceptacleRandomly( + string objectId, + string prefabName, + string targetReceptacle, + FlexibleRotation rotation + ) { SimObjPhysics target = getInteractableSimObjectFromId(targetReceptacle, true); - var spawnedObj = ProceduralTools.spawnObjectInReceptacleRandomly(this, ProceduralTools.getAssetMap(), prefabName, objectId, target, rotation); + var spawnedObj = ProceduralTools.spawnObjectInReceptacleRandomly( + this, + ProceduralTools.getAssetMap(), + prefabName, + objectId, + target, + rotation + ); bool result = false; //object succesfully spawned, wait for it to settle, then actionReturn success and the object's position if (spawnedObj != null) { result = true; - StartCoroutine(checkIfObjectHasStoppedMoving(sop: spawnedObj.GetComponent(), useTimeout: false)); + StartCoroutine( + checkIfObjectHasStoppedMoving( + sop: spawnedObj.GetComponent(), + useTimeout: false + ) + ); } else { - errorMessage = $"object ({prefabName}) could not find free space to spawn in ({targetReceptacle})"; + errorMessage = + $"object ({prefabName}) could not find free space to spawn in ({targetReceptacle})"; //if spawnedObj null, that means the random spawn failed because it couldn't find a free position actionFinished(result, errorMessage); } } //spawn prefab in a receptacle at target position. Object will fall into place with physics resolution - public void SpawnObjectInReceptacle(string objectId, string prefabName, string targetReceptacle, Vector3 position, FlexibleRotation rotation) { + public void SpawnObjectInReceptacle( + string objectId, + string prefabName, + string targetReceptacle, + Vector3 position, + FlexibleRotation rotation + ) { SimObjPhysics target = getInteractableSimObjectFromId(targetReceptacle, true); - var spawnedObj = ProceduralTools.spawnObjectInReceptacle(this, ProceduralTools.getAssetMap(), prefabName, objectId, target, position, rotation); + var spawnedObj = ProceduralTools.spawnObjectInReceptacle( + this, + ProceduralTools.getAssetMap(), + prefabName, + objectId, + target, + position, + rotation + ); bool result = false; //object succesfully spawned, wait for it to settle, then actionReturn success and the object's position if (spawnedObj != null) { result = true; - StartCoroutine(checkIfObjectHasStoppedMoving(sop: spawnedObj.GetComponent(), useTimeout: false)); + StartCoroutine( + checkIfObjectHasStoppedMoving( + sop: spawnedObj.GetComponent(), + useTimeout: false + ) + ); } else { - errorMessage = $"object ({prefabName}) could not find free space to spawn in ({targetReceptacle}) at position ({position})"; + errorMessage = + $"object ({prefabName}) could not find free space to spawn in ({targetReceptacle}) at position ({position})"; //if spawnedObj null, that means the random spawn failed because it couldn't find a free position actionFinished(result, errorMessage); } @@ -2887,9 +3331,14 @@ public void SpawnObjectInReceptacle(string objectId, string prefabName, string t public void SpawnObjectInScene(HouseObject ho) { CollisionDetectionMode collDet = CollisionDetectionMode.ContinuousSpeculative; Enum.TryParse(ho.collisionDetectionMode, true, out collDet); - var spawnedObj = ProceduralTools.spawnHouseObject(ProceduralTools.getAssetMap(), ho, collDet); + var spawnedObj = ProceduralTools.spawnHouseObject( + ProceduralTools.getAssetMap(), + ho, + collDet + ); actionFinished(true); } + //used to spawn in a new object at a given position, used with ProceduralTools.spawnObjectAtReceptacle //places an object on the surface directly below the `position` value, with slight offset public bool placeNewObjectAtPoint(SimObjPhysics t, Vector3 position) { @@ -2908,7 +3357,10 @@ public bool placeNewObjectAtPoint(SimObjPhysics t, Vector3 position) { Vector3 bottomPoint = b.ClosestPoint(targetNegY); b.enabled = false; - float distFromSopToBottomPoint = Vector3.Distance(bottomPoint, target.transform.position); + float distFromSopToBottomPoint = Vector3.Distance( + bottomPoint, + target.transform.position + ); //adding slight offset so it doesn't clip with the floor float offset = distFromSopToBottomPoint + 0.00001f; @@ -2931,9 +3383,11 @@ public void ScaleObject( float scaleOverSeconds = 1.0f, bool forceAction = false ) { - // if object is in the scene and visible, assign it to 'target' - SimObjPhysics target = getInteractableSimObjectFromId(objectId: objectId, forceAction: forceAction); + SimObjPhysics target = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: forceAction + ); // neither objectId nor coordinates found an object if (target == null) { @@ -2941,7 +3395,9 @@ public void ScaleObject( actionFinished(false); return; } else { - StartCoroutine(scaleObject(gameObject.transform.localScale * scale, target, scaleOverSeconds)); + StartCoroutine( + scaleObject(gameObject.transform.localScale * scale, target, scaleOverSeconds) + ); } } @@ -2957,7 +3413,9 @@ public void ScaleObject( y: y, forceAction: forceAction ); - StartCoroutine(scaleObject(gameObject.transform.localScale * scale, target, scaleOverSeconds)); + StartCoroutine( + scaleObject(gameObject.transform.localScale * scale, target, scaleOverSeconds) + ); } private IEnumerator scaleObject( @@ -3067,7 +3525,11 @@ public void GetSpawnCoordinatesAboveReceptacle(ServerAction action) { List filteredTargetPoints = new List(); foreach (Vector3 v in targetPoints) { try { - assertPosInView(targetPosition: v, inMaxVisibleDistance: true, inViewport: true); + assertPosInView( + targetPosition: v, + inMaxVisibleDistance: true, + inViewport: true + ); filteredTargetPoints.Add(v); } catch (Exception e) { continue; @@ -3087,7 +3549,10 @@ public void GetSpawnCoordinatesAboveReceptacle(ServerAction action) { // same as GetSpawnCoordinatesAboveReceptacle(Server Action) but takes a sim obj phys instead // returns a list of vector3 coordinates above a receptacle. These coordinates will make up a grid above the receptacle - public List getSpawnCoordinatesAboveReceptacle(SimObjPhysics t, bool fromReceptacleTop = true) { + public List getSpawnCoordinatesAboveReceptacle( + SimObjPhysics t, + bool fromReceptacleTop = true + ) { SimObjPhysics target = t; // ok now get spawn points from target List targetPoints = new List(); @@ -3095,49 +3560,69 @@ public List getSpawnCoordinatesAboveReceptacle(SimObjPhysics t, bool fr return targetPoints; } - - public void MakeReceptacleDirty(string objectId, float density, int seed = 0, Vector3? scale = null) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { - actionFinished(success: false, errorMessage: $"Object ID {objectId} appears to be invalid."); + public void MakeReceptacleDirty( + string objectId, + float density, + int seed = 0, + Vector3? scale = null + ) { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + actionFinished( + success: false, + errorMessage: $"Object ID {objectId} appears to be invalid." + ); } SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; if (!sop.IsReceptacle) { - actionFinished(success: false, errorMessage: $"Object ID {objectId} is not a Receptacle."); - + actionFinished( + success: false, + errorMessage: $"Object ID {objectId} is not a Receptacle." + ); } var dirtyDensityClamped = Mathf.Clamp(density, 0.0f, 1.0f); var dc = sop.GetComponentInChildren(); - var spawnCoordinates = getSpawnCoordinatesAboveReceptacle(sop, fromReceptacleTop: false); - // TODO adjust this value as it is to dense still as a percentage, probably base it on the scale and - // total receptacle area + var spawnCoordinates = getSpawnCoordinatesAboveReceptacle( + sop, + fromReceptacleTop: false + ); + // TODO adjust this value as it is to dense still as a percentage, probably base it on the scale and + // total receptacle area var coordinateCount = Mathf.RoundToInt(density * spawnCoordinates.Count); - - Debug.Log($"--- total coords {spawnCoordinates.Count}, selected count {coordinateCount} "); - var selectedCoords = spawnCoordinates.Shuffle_(new System.Random(seed)).Take(coordinateCount); - foreach (var coord in selectedCoords) { - dc.SpawnDecal(position: coord, scale: scale, randomRotationAxis: DecalRotationAxis.FORWARD); + Debug.Log( + $"--- total coords {spawnCoordinates.Count}, selected count {coordinateCount} " + ); + var selectedCoords = spawnCoordinates + .Shuffle_(new System.Random(seed)) + .Take(coordinateCount); + foreach (var coord in selectedCoords) { + dc.SpawnDecal( + position: coord, + scale: scale, + randomRotationAxis: DecalRotationAxis.FORWARD + ); } - actionFinished(success: true); + actionFinished(success: true); } - // instantiate a target circle, and then place it in a "SpawnOnlyOUtsideReceptacle" that is also within camera view // If fails, return actionFinished(false) and despawn target circle public void SpawnTargetCircle(ServerAction action) { if (action.objectVariation > 2 || action.objectVariation < 0) { - errorMessage = "Please use valid int for SpawnTargetCircleAction. Valid ints are: 0, 1, 2 for small, medium, large circles"; + errorMessage = + "Please use valid int for SpawnTargetCircleAction. Valid ints are: 0, 1, 2 for small, medium, large circles"; actionFinished(false); return; } // instantiate a target circle - GameObject targetCircle = Instantiate( - original: TargetCircles[action.objectVariation], - position: new Vector3(0, 100, 0), - rotation: Quaternion.identity - ) as GameObject; + GameObject targetCircle = + Instantiate( + original: TargetCircles[action.objectVariation], + position: new Vector3(0, 100, 0), + rotation: Quaternion.identity + ) as GameObject; targetCircle.transform.parent = GameObject.Find("Objects").transform; List targetReceptacles = new List(); InstantiatePrefabTest ipt = physicsSceneManager.GetComponent(); @@ -3146,9 +3631,15 @@ public void SpawnTargetCircle(ServerAction action) { if (!action.anywhere) { // check every sim object and see if it is within the viewport foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.Receptacle + ) + ) { /// one more check, make sure this receptacle - if (ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(sop.ObjType)) { + if ( + ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(sop.ObjType) + ) { // ok now check if the object is for real in the viewport if (objectIsWithinViewport(sop)) { targetReceptacles.Add(sop); @@ -3157,10 +3648,9 @@ public void SpawnTargetCircle(ServerAction action) { } } } - // spawn target circle in any valid "outside" receptacle in the scene even if not in veiw else { - // targetReceptacles.AddRange(physicsSceneManager.ReceptaclesInScene); + // targetReceptacles.AddRange(physicsSceneManager.ReceptaclesInScene); foreach (SimObjPhysics sop in physicsSceneManager.GatherAllReceptaclesInScene()) { if (ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(sop.ObjType)) { targetReceptacles.Add(sop); @@ -3168,7 +3658,6 @@ public void SpawnTargetCircle(ServerAction action) { } } - // if we passed in a objectId, see if it is in the list of targetReceptacles found so far if (action.objectId != null) { List filteredTargetReceptacleList = new List(); @@ -3202,18 +3691,27 @@ public void SpawnTargetCircle(ServerAction action) { rsps = sop.ReturnMySpawnPoints(); List editedRsps = new List(); - bool constraintsUsed = false;// only set rsps to editedRsps if constraints were passed in + bool constraintsUsed = false; // only set rsps to editedRsps if constraints were passed in // only do further constraint checks if defaults are overwritten if (!(action.minDistance == 0 && action.maxDistance == 0)) { foreach (ReceptacleSpawnPoint p in rsps) { // get rid of differences in y values for points - Vector3 normalizedPosition = new Vector3(transform.position.x, 0, transform.position.z); + Vector3 normalizedPosition = new Vector3( + transform.position.x, + 0, + transform.position.z + ); Vector3 normalizedPoint = new Vector3(p.Point.x, 0, p.Point.z); if (action.minDistance == 0 && action.maxDistance > 0) { // check distance from agent's transform to spawnpoint - if ((Vector3.Distance(normalizedPoint, normalizedPosition) <= action.maxDistance)) { + if ( + ( + Vector3.Distance(normalizedPoint, normalizedPosition) + <= action.maxDistance + ) + ) { editedRsps.Add(p); } @@ -3223,7 +3721,12 @@ public void SpawnTargetCircle(ServerAction action) { // min distance passed in, no max distance if (action.maxDistance == 0 && action.minDistance > 0) { // check distance from agent's transform to spawnpoint - if ((Vector3.Distance(normalizedPoint, normalizedPosition) >= action.minDistance)) { + if ( + ( + Vector3.Distance(normalizedPoint, normalizedPosition) + >= action.minDistance + ) + ) { editedRsps.Add(p); } @@ -3231,8 +3734,14 @@ public void SpawnTargetCircle(ServerAction action) { } else { // these are default so don't filter by distance // check distance from agent's transform to spawnpoint - if ((Vector3.Distance(normalizedPoint, normalizedPosition) >= action.minDistance - && Vector3.Distance(normalizedPoint, normalizedPosition) <= action.maxDistance)) { + if ( + ( + Vector3.Distance(normalizedPoint, normalizedPosition) + >= action.minDistance + && Vector3.Distance(normalizedPoint, normalizedPosition) + <= action.maxDistance + ) + ) { editedRsps.Add(p); } @@ -3249,7 +3758,17 @@ public void SpawnTargetCircle(ServerAction action) { // only place in viewport if (!action.anywhere) { - if (ipt.PlaceObjectReceptacleInViewport(this, rsps, targetCircle.GetComponent(), true, 500, 90, true)) { + if ( + ipt.PlaceObjectReceptacleInViewport( + this, + rsps, + targetCircle.GetComponent(), + true, + 500, + 90, + true + ) + ) { // make sure target circle is within viewport succesfulSpawn = true; break; @@ -3257,7 +3776,16 @@ public void SpawnTargetCircle(ServerAction action) { } // place anywhere else { - if (ipt.PlaceObjectReceptacle(rsps, targetCircle.GetComponent(), true, 500, 90, true)) { + if ( + ipt.PlaceObjectReceptacle( + rsps, + targetCircle.GetComponent(), + true, + 500, + 90, + true + ) + ) { // make sure target circle is within viewport succesfulSpawn = true; break; @@ -3267,7 +3795,10 @@ public void SpawnTargetCircle(ServerAction action) { if (succesfulSpawn) { // if image synthesis is active, make sure to update the renderers for image synthesis since now there are new objects with renderes in the scene - BaseFPSAgentController primaryAgent = GameObject.Find("PhysicsSceneManager").GetComponent().PrimaryAgent; + BaseFPSAgentController primaryAgent = GameObject + .Find("PhysicsSceneManager") + .GetComponent() + .PrimaryAgent; if (primaryAgent.imageSynthesis) { if (primaryAgent.imageSynthesis.enabled) { primaryAgent.imageSynthesis.OnSceneChange(); @@ -3277,7 +3808,7 @@ public void SpawnTargetCircle(ServerAction action) { SimObjPhysics targetSOP = targetCircle.GetComponent(); physicsSceneManager.Generate_ObjectID(targetSOP); physicsSceneManager.AddToObjectsInScene(targetSOP); - actionFinished(true, targetSOP.objectID);// return the objectID of circle spawned for easy reference + actionFinished(true, targetSOP.objectID); // return the objectID of circle spawned for easy reference } else { Destroy(targetCircle); errorMessage = "circle failed to spawn"; @@ -3291,11 +3822,16 @@ public void MakeObjectsOfTypeUnbreakable(string objectType) { actionFinished(false); } - SimObjPhysics[] simObjs = GameObject.FindObjectsOfType(typeof(SimObjPhysics)) as SimObjPhysics[]; + SimObjPhysics[] simObjs = + GameObject.FindObjectsOfType(typeof(SimObjPhysics)) as SimObjPhysics[]; if (simObjs != null) { foreach (SimObjPhysics sop in simObjs) { if (sop.Type.ToString() == objectType) { - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBreak)) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBreak + ) + ) { //look both in this object and children so things like Windows don't FREAK OUT sop.GetComponentInChildren().Unbreakable = true; } @@ -3317,8 +3853,6 @@ public void MakeObjectBreakable(string objectId) { actionFinishedEmit(true); } - - // set all objects objects of a given type to a specific state, if that object has that state // ie: All objects of type Bowl that have the state property breakable, set isBroken = true public void SetObjectStates(ServerAction action) { @@ -3329,24 +3863,34 @@ public void SetObjectStates(ServerAction action) { } // if both the objectType and stateChange members are null, params not set correctly - if (action.SetObjectStates.objectType == null && action.SetObjectStates.stateChange == null) { - errorMessage = "action.SetObjectStates has objectType and stateChange strings null. Please pass in valid strings."; + if ( + action.SetObjectStates.objectType == null + && action.SetObjectStates.stateChange == null + ) { + errorMessage = + "action.SetObjectStates has objectType and stateChange strings null. Please pass in valid strings."; actionFinished(false); return; } // if you pass in an ObjectType, you must also pass in which stateChange of that object you are trying to Set - if (action.SetObjectStates.objectType != null && action.SetObjectStates.stateChange == null) { - errorMessage = "action.SetObjectStates is missing stateChange string. If setting objects by objectType, Please specify both an objectType and a stateChange compatible with that objectType to set."; + if ( + action.SetObjectStates.objectType != null + && action.SetObjectStates.stateChange == null + ) { + errorMessage = + "action.SetObjectStates is missing stateChange string. If setting objects by objectType, Please specify both an objectType and a stateChange compatible with that objectType to set."; actionFinished(false); return; } // call a coroutine to return actionFinished for all objects that have animation time - if (action.SetObjectStates.stateChange == "toggleable" || action.SetObjectStates.stateChange == "openable") { + if ( + action.SetObjectStates.stateChange == "toggleable" + || action.SetObjectStates.stateChange == "openable" + ) { StartCoroutine(SetStateOfAnimatedObjects(action.SetObjectStates)); } - // these object change states instantly, so no need for coroutine // the function called will handle the actionFinished() return; else { @@ -3358,13 +3902,18 @@ public void SetObjectStates(ServerAction action) { // toggle them to the bool if applicable: isOpen, isToggled, isBroken etc. protected IEnumerator SetStateOfAnimatedObjects(SetObjectStates SetObjectStates) { List animating = new List(); - Dictionary animatingType = new Dictionary(); + Dictionary animatingType = + new Dictionary(); // in this case, we will try and set isToggled for all toggleable objects in the entire scene if (SetObjectStates.objectType == null) { foreach (SimObjPhysics sop in VisibleSimObjs(true)) { if (SetObjectStates.stateChange == "toggleable") { - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanToggleOnOff) && sop.GetComponent()) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanToggleOnOff + ) && sop.GetComponent() + ) { StartCoroutine(toggleObject(sop, SetObjectStates.isToggled)); animating.Add(sop); animatingType[sop] = "toggleable"; @@ -3386,14 +3935,19 @@ protected IEnumerator SetStateOfAnimatedObjects(SetObjectStates SetObjectStates) } } else { // in this case, we will only try and set states for objects of the specified objectType - SimObjType sot = (SimObjType)System.Enum.Parse(typeof(SimObjType), SetObjectStates.objectType); + SimObjType sot = (SimObjType) + System.Enum.Parse(typeof(SimObjType), SetObjectStates.objectType); // for every sim obj in scene, find objects of type specified first foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - // ok we found an object with type specified, now toggle it + // ok we found an object with type specified, now toggle it if (sop.ObjType == sot) { if (SetObjectStates.stateChange == "toggleable") { - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanToggleOnOff) && sop.GetComponent()) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanToggleOnOff + ) && sop.GetComponent() + ) { StartCoroutine(toggleObject(sop, SetObjectStates.isToggled)); animating.Add(sop); animatingType[sop] = "toggleable"; @@ -3406,7 +3960,8 @@ protected IEnumerator SetStateOfAnimatedObjects(SetObjectStates SetObjectStates) target: sop, openness: SetObjectStates.isOpen ? 1 : 0, forceAction: true, - markActionFinished: false); + markActionFinished: false + ); animating.Add(sop); animatingType[sop] = "openable"; } @@ -3420,9 +3975,15 @@ protected IEnumerator SetStateOfAnimatedObjects(SetObjectStates SetObjectStates) int numStillGoing = animating.Count; while (numStillGoing > 0) { foreach (SimObjPhysics sop in animating) { - if (animatingType.ContainsKey(sop) && - (animatingType[sop] == "toggleable" && sop.GetComponent().GetIsCurrentlyLerping() == false || animatingType[sop] == "openable") && - sop.GetComponent().GetIsCurrentlyLerping() == false + if ( + animatingType.ContainsKey(sop) + && ( + animatingType[sop] == "toggleable" + && sop.GetComponent().GetIsCurrentlyLerping() + == false + || animatingType[sop] == "openable" + ) + && sop.GetComponent().GetIsCurrentlyLerping() == false ) { numStillGoing--; } @@ -3443,21 +4004,30 @@ protected IEnumerator SetStateOfAnimatedObjects(SetObjectStates SetObjectStates) // for setting object states that don't have an animation time, which means they don't require coroutines yeah! protected void SetStateOfObjectsThatDontHaveAnimationTime(SetObjectStates SetObjectStates) { - // ok what state are we lookin at here switch (SetObjectStates.stateChange) { case "breakable": { foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBreak)) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBreak + ) + ) { // only break objects that are not already broken Break b = sop.GetComponent(); // only actually do stuff is the object is not broken and we are trying to break it if (!b.isBroken() && SetObjectStates.isBroken) { - // oh we have a specific object type? if (SetObjectStates.objectType != null) { - if (sop.Type == (SimObjType)System.Enum.Parse(typeof(SimObjType), SetObjectStates.objectType)) { + if ( + sop.Type + == (SimObjType) + System.Enum.Parse( + typeof(SimObjType), + SetObjectStates.objectType + ) + ) { b.BreakObject(null); } else { continue; @@ -3475,7 +4045,11 @@ protected void SetStateOfObjectsThatDontHaveAnimationTime(SetObjectStates SetObj case "canFillWithLiquid": { foreach (SimObjPhysics sop in VisibleSimObjs(true)) { // only proceed if the sop is fillable - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeFilled)) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBeFilled + ) + ) { Fill fil = sop.GetComponent(); // object is empty and trying to fill it @@ -3483,10 +4057,16 @@ protected void SetStateOfObjectsThatDontHaveAnimationTime(SetObjectStates SetObj // oh, we have a specific object type? if (SetObjectStates.objectType != null) { // we found an object of the type we want to set - if (sop.Type == (SimObjType)System.Enum.Parse(typeof(SimObjType), SetObjectStates.objectType)) { + if ( + sop.Type + == (SimObjType) + System.Enum.Parse( + typeof(SimObjType), + SetObjectStates.objectType + ) + ) { fil.FillObject("water"); } - // doesn't match objectType, continue to next object else { continue; @@ -3495,16 +4075,21 @@ protected void SetStateOfObjectsThatDontHaveAnimationTime(SetObjectStates SetObj fil.FillObject("water"); } } - // object is full of some liquid, and trying to empty it else if (fil.IsFilled() && !SetObjectStates.isFilledWithLiquid) { // oh, we have a specific object type? if (SetObjectStates.objectType != null) { // we found an object of the type we want to set - if (sop.Type == (SimObjType)System.Enum.Parse(typeof(SimObjType), SetObjectStates.objectType)) { + if ( + sop.Type + == (SimObjType) + System.Enum.Parse( + typeof(SimObjType), + SetObjectStates.objectType + ) + ) { fil.EmptyObject(); } - // doesn't match objectType, continue to next object else { continue; @@ -3522,7 +4107,11 @@ protected void SetStateOfObjectsThatDontHaveAnimationTime(SetObjectStates SetObj case "dirtyable": { foreach (SimObjPhysics sop in VisibleSimObjs(true)) { // only proceed if the sop is dirtyable - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeDirty)) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBeDirty + ) + ) { Dirty deedsDoneDirtCheap = sop.GetComponent(); // object is clean and we are trying to dirty it @@ -3530,10 +4119,16 @@ protected void SetStateOfObjectsThatDontHaveAnimationTime(SetObjectStates SetObj // oh, we have a specific object type? if (SetObjectStates.objectType != null) { // we found an object of the type we want to set - if (sop.Type == (SimObjType)System.Enum.Parse(typeof(SimObjType), SetObjectStates.objectType)) { + if ( + sop.Type + == (SimObjType) + System.Enum.Parse( + typeof(SimObjType), + SetObjectStates.objectType + ) + ) { deedsDoneDirtCheap.ToggleCleanOrDirty(); } - // doesn't match objectType, continue to next object else { continue; @@ -3542,16 +4137,21 @@ protected void SetStateOfObjectsThatDontHaveAnimationTime(SetObjectStates SetObj deedsDoneDirtCheap.ToggleCleanOrDirty(); } } - // object is dirty and we are trying to clean it else if (deedsDoneDirtCheap.IsDirty() && !SetObjectStates.isDirty) { // oh, we have a specific object type? if (SetObjectStates.objectType != null) { // we found an object of the type we want to set - if (sop.Type == (SimObjType)System.Enum.Parse(typeof(SimObjType), SetObjectStates.objectType)) { + if ( + sop.Type + == (SimObjType) + System.Enum.Parse( + typeof(SimObjType), + SetObjectStates.objectType + ) + ) { deedsDoneDirtCheap.ToggleCleanOrDirty(); } - // doesn't match objectType, continue to next object else { continue; @@ -3569,13 +4169,24 @@ protected void SetStateOfObjectsThatDontHaveAnimationTime(SetObjectStates SetObj // one way case "cookable": { foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeCooked)) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBeCooked + ) + ) { CookObject c = sop.GetComponent(); // only do stuff if object is not cooked and we are trying to cook it if (!c.IsCooked() && SetObjectStates.isCooked) { if (SetObjectStates.objectType != null) { - if (sop.Type == (SimObjType)System.Enum.Parse(typeof(SimObjType), SetObjectStates.objectType)) { + if ( + sop.Type + == (SimObjType) + System.Enum.Parse( + typeof(SimObjType), + SetObjectStates.objectType + ) + ) { c.Cook(); } else { continue; @@ -3593,13 +4204,24 @@ protected void SetStateOfObjectsThatDontHaveAnimationTime(SetObjectStates SetObj // one way case "sliceable": { foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeSliced)) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBeSliced + ) + ) { SliceObject s = sop.GetComponent(); // only do stuff if object is unsliced and we are trying to slice it if (!s.IsSliced() && SetObjectStates.isSliced) { if (SetObjectStates.objectType != null) { - if (sop.Type == (SimObjType)System.Enum.Parse(typeof(SimObjType), SetObjectStates.objectType)) { + if ( + sop.Type + == (SimObjType) + System.Enum.Parse( + typeof(SimObjType), + SetObjectStates.objectType + ) + ) { s.Slice(); } else { continue; @@ -3617,13 +4239,24 @@ protected void SetStateOfObjectsThatDontHaveAnimationTime(SetObjectStates SetObj // one way case "canBeUsedUp": { foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeUsedUp)) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBeUsedUp + ) + ) { UsedUp u = sop.GetComponent(); // only do stuff if object is not used up and we are trying to use it up if (!u.isUsedUp && SetObjectStates.isUsedUp) { if (SetObjectStates.objectType != null) { - if (sop.Type == (SimObjType)System.Enum.Parse(typeof(SimObjType), SetObjectStates.objectType)) { + if ( + sop.Type + == (SimObjType) + System.Enum.Parse( + typeof(SimObjType), + SetObjectStates.objectType + ) + ) { u.UseUp(); } else { continue; @@ -3642,8 +4275,14 @@ protected void SetStateOfObjectsThatDontHaveAnimationTime(SetObjectStates SetObj actionFinished(true); } - - public void PutObject(float x, float y, bool forceAction = false, bool placeStationary = true, int randomSeed = 0, bool putNearXY = false) { + public void PutObject( + float x, + float y, + bool forceAction = false, + bool placeStationary = true, + int randomSeed = 0, + bool putNearXY = false + ) { PlaceHeldObject( x: x, y: y, @@ -3651,22 +4290,37 @@ public void PutObject(float x, float y, bool forceAction = false, bool placeStat placeStationary: placeStationary, randomSeed: randomSeed, putNearXY: putNearXY, - maxDistance: maxVisibleDistance); + maxDistance: maxVisibleDistance + ); } - public void PutObject(string objectId, bool forceAction = false, bool placeStationary = true, int randomSeed = 0) { + public void PutObject( + string objectId, + bool forceAction = false, + bool placeStationary = true, + int randomSeed = 0 + ) { PlaceHeldObject( objectId: objectId, forceAction: forceAction, placeStationary: placeStationary, randomSeed: randomSeed, - maxDistance: maxVisibleDistance); + maxDistance: maxVisibleDistance + ); } - // if you are holding an object, place it on a valid Receptacle + // if you are holding an object, place it on a valid Receptacle // used for placing objects on receptacles without enclosed restrictions (drawers, cabinets, etc) - // only checks if the object can be placed on top of the target receptacle via the receptacle trigger box - public void PlaceHeldObject(float x, float y, float maxDistance, bool forceAction = false, bool placeStationary = true, int randomSeed = 0, bool putNearXY = false) { + // only checks if the object can be placed on top of the target receptacle via the receptacle trigger box + public void PlaceHeldObject( + float x, + float y, + float maxDistance, + bool forceAction = false, + bool placeStationary = true, + int randomSeed = 0, + bool putNearXY = false + ) { SimObjPhysics targetReceptacle = null; RaycastHit hit = new RaycastHit(); @@ -3690,22 +4344,30 @@ public void PlaceHeldObject(float x, float y, float maxDistance, bool forceActio ); } - // overload of PlaceHeldObject that takes a target receptacle by objectId instead of screenspace coordinate raycast - public void PlaceHeldObject(string objectId, float maxDistance, bool forceAction = false, bool placeStationary = true, int randomSeed = 0) { + public void PlaceHeldObject( + string objectId, + float maxDistance, + bool forceAction = false, + bool placeStationary = true, + int randomSeed = 0 + ) { // get the target receptacle based on the action object ID SimObjPhysics targetReceptacle = null; // if object is in the scene and visible, assign it to 'target' - targetReceptacle = getInteractableSimObjectFromId(objectId: objectId, forceAction: forceAction); + targetReceptacle = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: forceAction + ); placeHeldObject( targetReceptacle: targetReceptacle, forceAction: forceAction, placeStationary: placeStationary, randomSeed: randomSeed, - maxDistance: maxDistance); - + maxDistance: maxDistance + ); } private void placeHeldObject( @@ -3713,8 +4375,8 @@ private void placeHeldObject( bool forceAction, bool placeStationary, int randomSeed, - float maxDistance) { - + float maxDistance + ) { RaycastHit hit = new RaycastHit(); placeHeldObject( @@ -3724,7 +4386,8 @@ private void placeHeldObject( randomSeed: randomSeed, maxDistance: maxDistance, putNearXY: false, - hit: hit); + hit: hit + ); } private void placeHeldObject( @@ -3734,7 +4397,8 @@ private void placeHeldObject( int randomSeed, float maxDistance, bool putNearXY, - RaycastHit hit) { + RaycastHit hit + ) { // #if UNITY_EDITOR // var watch = System.Diagnostics.Stopwatch.StartNew(); // #endif @@ -3746,7 +4410,6 @@ private void placeHeldObject( return; } - if (targetReceptacle == null) { errorMessage = "No valid Receptacle found"; Debug.Log(errorMessage); @@ -3754,7 +4417,11 @@ private void placeHeldObject( return; } - if (!targetReceptacle.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { + if ( + !targetReceptacle.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.Receptacle + ) + ) { errorMessage = "This target object is NOT a receptacle!"; Debug.Log(errorMessage); actionFinished(false); @@ -3762,10 +4429,19 @@ private void placeHeldObject( } // if receptacle can open, check that it's open before placing. Can't place objects in something that is closed! - if (targetReceptacle.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanOpen)) { - if (ReceptacleRestrictions.MustBeOpenToPlaceObjectsIn.Contains(targetReceptacle.ObjType)) { + if ( + targetReceptacle.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanOpen + ) + ) { + if ( + ReceptacleRestrictions.MustBeOpenToPlaceObjectsIn.Contains( + targetReceptacle.ObjType + ) + ) { if (!targetReceptacle.GetComponent().isOpen) { - errorMessage = "Target openable Receptacle is CLOSED, can't place if target is not open!"; + errorMessage = + "Target openable Receptacle is CLOSED, can't place if target is not open!"; Debug.Log(errorMessage); actionFinished(false); return; @@ -3775,37 +4451,53 @@ private void placeHeldObject( // if this receptacle only receives specific objects, check that the ItemInHand is compatible and // check if the receptacle is currently full with another valid object or not - if (targetReceptacle.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.ObjectSpecificReceptacle)) { - ObjectSpecificReceptacle osr = targetReceptacle.GetComponent(); - if (osr.HasSpecificType(ItemInHand.GetComponent().ObjType) && !osr.isFull()) { + if ( + targetReceptacle.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.ObjectSpecificReceptacle + ) + ) { + ObjectSpecificReceptacle osr = + targetReceptacle.GetComponent(); + if ( + osr.HasSpecificType(ItemInHand.GetComponent().ObjType) + && !osr.isFull() + ) { // check spawn area specifically if it's a stove top we are trying to place something in because // they are close together and can overlap and are weird if (osr.GetComponent().Type == SimObjType.StoveBurner) { // PhysicsSceneManager psm = GameObject.Find("PhysicsSceneManager").GetComponent(); - if (physicsSceneManager.StoveTopCheckSpawnArea(ItemInHand.GetComponent(), osr.attachPoint.transform.position, - osr.attachPoint.transform.rotation, false) == false) { - errorMessage = "another object's collision is blocking held object from being placed"; + if ( + physicsSceneManager.StoveTopCheckSpawnArea( + ItemInHand.GetComponent(), + osr.attachPoint.transform.position, + osr.attachPoint.transform.rotation, + false + ) == false + ) { + errorMessage = + "another object's collision is blocking held object from being placed"; actionFinished(false); return; } - } ItemInHand.transform.position = osr.attachPoint.position; ItemInHand.transform.SetParent(osr.attachPoint.transform); ItemInHand.transform.localRotation = Quaternion.identity; ItemInHand.GetComponent().isKinematic = true; - ItemInHand.GetComponent().isInAgentHand = false;// remove in agent hand flag + ItemInHand.GetComponent().isInAgentHand = false; // remove in agent hand flag ItemInHand = null; DefaultAgentHand(); actionFinished(true); return; } else { - if (osr.attachPoint.transform.childCount > 0 || osr.isFull()) { errorMessage = targetReceptacle.name + " is full right now"; } else { - errorMessage = ItemInHand.name + " is not a valid Object Type to be placed in " + targetReceptacle.name; + errorMessage = + ItemInHand.name + + " is not a valid Object Type to be placed in " + + targetReceptacle.name; } actionFinished(false); @@ -3817,11 +4509,19 @@ private void placeHeldObject( if (!forceAction) { // check if the item we are holding can even be placed in the action.ObjectID target at all - foreach (KeyValuePair> res in ReceptacleRestrictions.PlacementRestrictions) { + foreach ( + KeyValuePair< + SimObjType, + List + > res in ReceptacleRestrictions.PlacementRestrictions + ) { // find the Object Type in the PlacementRestrictions dictionary if (res.Key == handSOP.ObjType) { if (!res.Value.Contains(targetReceptacle.ObjType)) { - errorMessage = ItemInHand.name + " cannot be placed in " + targetReceptacle.transform.name; + errorMessage = + ItemInHand.name + + " cannot be placed in " + + targetReceptacle.transform.name; Debug.Log(errorMessage); actionFinished(false); return; @@ -3844,23 +4544,33 @@ private void placeHeldObject( } // ok we are holding something, time to try and place it - InstantiatePrefabTest script = physicsSceneManager.GetComponent(); + InstantiatePrefabTest script = + physicsSceneManager.GetComponent(); // set degreeIncrement to 90 for placing held objects to check for vertical angles - List spawnPoints = targetReceptacle.ReturnMySpawnPoints(onlyPointsCloseToAgent ? this : null); + List spawnPoints = targetReceptacle.ReturnMySpawnPoints( + onlyPointsCloseToAgent ? this : null + ); if (randomSeed != 0 || putNearXY) { - List> distSpawnPoints = new List>(); + List> distSpawnPoints = + new List>(); foreach (ReceptacleSpawnPoint sp in spawnPoints) { // calculate distance from potential spawn point to the agent's current x/z coordinate. Compare using the spawn point's y value so // we compare distance as a flat plane parallel to the agent's x/z plane. This keeps things consistent regardless of agent camera // position if the agent is crouching or standing - Vector3 tmp = new Vector3(transform.position.x, sp.Point.y, transform.position.z); + Vector3 tmp = new Vector3( + transform.position.x, + sp.Point.y, + transform.position.z + ); if (Vector3.Distance(sp.Point, tmp) < maxDistance) { float dist = 0; if (putNearXY) { dist = Vector3.Distance(sp.Point, hit.point); } - distSpawnPoints.Add(new KeyValuePair(sp, dist)); + distSpawnPoints.Add( + new KeyValuePair(sp, dist) + ); } } @@ -3871,13 +4581,22 @@ private void placeHeldObject( distSpawnPoints.Shuffle_(randomSeed); } - spawnPoints = new List(); // populate a new spawnPoints list with sorted keys + spawnPoints = new List(); // populate a new spawnPoints list with sorted keys foreach (KeyValuePair pair in distSpawnPoints) { spawnPoints.Add(pair.Key); } } - if (script.PlaceObjectReceptacle(spawnPoints, ItemInHand.GetComponent(), placeStationary, -1, 90, placeUpright)) { + if ( + script.PlaceObjectReceptacle( + spawnPoints, + ItemInHand.GetComponent(), + placeStationary, + -1, + 90, + placeUpright + ) + ) { ItemInHand = null; DefaultAgentHand(); actionFinished(true); @@ -3893,7 +4612,6 @@ private void placeHeldObject( // #endif } - protected void pickupObject( SimObjPhysics target, bool forceAction, @@ -3906,16 +4624,21 @@ bool markActionFinished // found non-pickupable object if (target.PrimaryProperty != SimObjPrimaryProperty.CanPickup) { - - throw new InvalidOperationException(target.objectID + " must have the property CanPickup to be picked up."); + throw new InvalidOperationException( + target.objectID + " must have the property CanPickup to be picked up." + ); } // agent is holding something if (ItemInHand != null) { - throw new InvalidOperationException("Agent hand has something in it already! Can't pick up anything else"); + throw new InvalidOperationException( + "Agent hand has something in it already! Can't pick up anything else" + ); } if (!IsHandDefault) { - throw new InvalidOperationException("Must reset Hand to default position before attempting to Pick Up objects"); + throw new InvalidOperationException( + "Must reset Hand to default position before attempting to Pick Up objects" + ); } // save all initial values in case we need to reset on action fail @@ -3963,7 +4686,9 @@ bool markActionFinished target.transform.SetParent(savedParent); ItemInHand = null; target.DropContainedObjects(reparentContainedObjects: true, forceKinematic: false); - throw new InvalidOperationException("Picking up object would cause it to collide and clip into something!"); + throw new InvalidOperationException( + "Picking up object would cause it to collide and clip into something!" + ); } // we have successfully picked up something! @@ -3974,54 +4699,85 @@ bool markActionFinished } public void GetDoorHandle(string objectId) { - SimObjPhysics target = getInteractableSimObjectFromId(objectId: objectId, forceAction: true); - + SimObjPhysics target = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: true + ); + List doorHandlePositions = new List(); foreach (Transform child in target.transform.GetComponentsInChildren()) { - if(child.CompareTag("Handle")) { + if (child.CompareTag("Handle")) { doorHandlePositions.Add(child.transform.position); } } - #if UNITY_EDITOR - foreach(Vector3 v in doorHandlePositions) { +#if UNITY_EDITOR + foreach (Vector3 v in doorHandlePositions) { Debug.Log(v); } - #endif +#endif actionFinished(true, doorHandlePositions); } public void GetDoorHinge(string objectId) { - SimObjPhysics target = getInteractableSimObjectFromId(objectId: objectId, forceAction: true); + SimObjPhysics target = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: true + ); List hingePositions = new List(); foreach (Transform child in target.transform.GetComponentsInChildren()) { - if(child.CompareTag("Hinge")) { + if (child.CompareTag("Hinge")) { hingePositions.Add(child.transform.position); } } - #if UNITY_EDITOR - foreach(Vector3 v in hingePositions) { +#if UNITY_EDITOR + foreach (Vector3 v in hingePositions) { Debug.Log(v); } - #endif +#endif actionFinished(true, hingePositions); } - - public virtual void PickupObject(float x, float y, bool forceAction = false, bool manualInteract = false) { - SimObjPhysics target = getInteractableSimObjectFromXY(x: x, y: y, forceAction: forceAction); - pickupObject(target: target, forceAction: forceAction, manualInteract: manualInteract, markActionFinished: true); + public virtual void PickupObject( + float x, + float y, + bool forceAction = false, + bool manualInteract = false + ) { + SimObjPhysics target = getInteractableSimObjectFromXY( + x: x, + y: y, + forceAction: forceAction + ); + pickupObject( + target: target, + forceAction: forceAction, + manualInteract: manualInteract, + markActionFinished: true + ); } - public virtual void PickupObject(string objectId, bool forceAction = false, bool manualInteract = false) { - SimObjPhysics target = getInteractableSimObjectFromId(objectId: objectId, forceAction: forceAction); - pickupObject(target: target, forceAction: forceAction, manualInteract: manualInteract, markActionFinished: true); + public virtual void PickupObject( + string objectId, + bool forceAction = false, + bool manualInteract = false + ) { + SimObjPhysics target = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: forceAction + ); + pickupObject( + target: target, + forceAction: forceAction, + manualInteract: manualInteract, + markActionFinished: true + ); } // make sure not to pick up any sliced objects because those should remain uninteractable i they have been sliced @@ -4032,7 +4788,11 @@ public void PickupContainedObjects(SimObjPhysics target) { // turn off the colliders (so contained object doesn't block movement), leaving Trigger Colliders active (this is important to maintain visibility!) if (sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup) { // wait! check if this object is sliceable and is sliced, if so SKIP! - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeSliced)) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBeSliced + ) + ) { // if this object is sliced, don't pick it up because it is effectively disabled if (sop.GetComponent().IsSliced()) { target.RemoveFromContainedObjectReferences(sop); @@ -4049,16 +4809,13 @@ public void PickupContainedObjects(SimObjPhysics target) { // used to reference objects in the receptacle that is being picked up without having to search through all children target.AddToContainedObjectReferences(sop); - target.GetComponent().isInAgentHand = true;// agent hand flag - + target.GetComponent().isInAgentHand = true; // agent hand flag } } } } - - - // private IEnumerator checkDropHeldObjectAction(SimObjPhysics currentHandSimObj) + // private IEnumerator checkDropHeldObjectAction(SimObjPhysics currentHandSimObj) // { // yield return null; // wait for two frames to pass // yield return null; @@ -4068,18 +4825,18 @@ public void PickupContainedObjects(SimObjPhysics target) { // if (currentHandSimObj != null) // { // Rigidbody rb = currentHandSimObj.GetComponentInChildren(); - // while (Time.time - startTime < 2) + // while (Time.time - startTime < 2) // { // if(currentHandSimObj == null) // break; - // if (Math.Abs(rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude) < 0.00001) + // if (Math.Abs(rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude) < 0.00001) // { // // Debug.Log ("object is now at rest"); // break; - // } + // } - // else + // else // { // // Debug.Log ("object is still moving"); // yield return null; @@ -4102,7 +4859,10 @@ private IEnumerator checkDropHeldObjectActionFast(SimObjPhysics currentHandSimOb #if UNITY_EDITOR yield return null; #endif - if (Math.Abs(rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude) < 0.00001) { + if ( + Math.Abs(rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude) + < 0.00001 + ) { break; } } @@ -4123,8 +4883,8 @@ public void DropHeldObject(bool forceAction = false, bool autoSimulation = true) // dropping an object while it is inside the agent will cause it to shoot out weirdly if (!forceAction && isHandObjectColliding(false)) { throw new InvalidOperationException( - $"{ItemInHand.transform.name} can't be dropped. " + - "It must be clear of all other collision first, including the Agent." + $"{ItemInHand.transform.name} can't be dropped. " + + "It must be clear of all other collision first, including the Agent." ); } @@ -4134,7 +4894,7 @@ public void DropHeldObject(bool forceAction = false, bool autoSimulation = true) rb.useGravity = true; // change collision detection mode while falling so that obejcts don't phase through colliders. - // this is reset to discrete on SimObjPhysics.cs's update + // this is reset to discrete on SimObjPhysics.cs's update rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; GameObject topObject = GameObject.Find("Objects"); @@ -4143,16 +4903,25 @@ public void DropHeldObject(bool forceAction = false, bool autoSimulation = true) } else { ItemInHand.transform.parent = null; } - ItemInHand.GetComponent().DropContainedObjects(reparentContainedObjects: true, forceKinematic: false); + ItemInHand + .GetComponent() + .DropContainedObjects(reparentContainedObjects: true, forceKinematic: false); // if physics simulation has been paused by the PausePhysicsAutoSim() action, // don't do any coroutine checks if (!physicsSceneManager.physicsSimulationPaused) { // this is true by default if (autoSimulation) { - StartCoroutine(checkIfObjectHasStoppedMoving(sop: ItemInHand.GetComponent(), useTimeout: false)); + StartCoroutine( + checkIfObjectHasStoppedMoving( + sop: ItemInHand.GetComponent(), + useTimeout: false + ) + ); } else { - StartCoroutine(checkDropHeldObjectActionFast(ItemInHand.GetComponent())); + StartCoroutine( + checkDropHeldObjectActionFast(ItemInHand.GetComponent()) + ); } } else { DefaultAgentHand(); @@ -4162,14 +4931,21 @@ public void DropHeldObject(bool forceAction = false, bool autoSimulation = true) ItemInHand = null; } - [ObsoleteAttribute(message: "This action is deprecated. Call DropHeldObject instead.", error: false)] + [ObsoleteAttribute( + message: "This action is deprecated. Call DropHeldObject instead.", + error: false + )] public void DropHandObject(bool forceAction = false, bool autoSimulation = true) { DropHeldObject(forceAction: forceAction, autoSimulation: autoSimulation); } // by default will throw in the forward direction relative to the Agent's Camera // moveMagnitude, strength of throw, good values for an average throw are around 150-250 - public void ThrowObject(float moveMagnitude, bool forceAction = false, bool autoSimulation = true) { + public void ThrowObject( + float moveMagnitude, + bool forceAction = false, + bool autoSimulation = true + ) { if (ItemInHand == null) { throw new InvalidOperationException("Nothing in Hand to Throw!"); } @@ -4252,7 +5028,7 @@ public void CloseObject( bool stopAtNonStaticCol = false, float? physicsInterval = null, bool useGripper = false - ) { + ) { OpenObject( objectId: objectId, openness: 0, @@ -4262,25 +5038,32 @@ public void CloseObject( stopAtNonStaticCol: stopAtNonStaticCol, physicsInterval: physicsInterval, useGripper: useGripper - ); + ); } // syntactic sugar for open object with openness = 0. - public void CloseObject( - float x, - float y, - bool forceAction = false - ) { + public void CloseObject(float x, float y, bool forceAction = false) { OpenObject(x: x, y: y, forceAction: forceAction, openness: 0); } protected SimObjPhysics getOpenableOrCloseableObjectNearLocation( - bool open, float x, float y, float radius, bool forceAction + bool open, + float x, + float y, + float radius, + bool forceAction ) { y = 1.0f - y; RaycastHit hit; - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "SimObjInvisible"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "SimObjInvisible" + ); if (ItemInHand != null) { foreach (Collider c in ItemInHand.GetComponentsInChildren()) { c.enabled = false; @@ -4309,14 +5092,18 @@ protected SimObjPhysics getOpenableOrCloseableObjectNearLocation( if (raycastDidHit) { SimObjPhysics sop = ancestorSimObjPhysics(hit.transform.gameObject); - if (sop != null && sop.GetComponent() && ( - forceAction || objectIsCurrentlyVisible(sop, maxVisibleDistance) - )) { + if ( + sop != null + && sop.GetComponent() + && (forceAction || objectIsCurrentlyVisible(sop, maxVisibleDistance)) + ) { CanOpen_Object coo = sop.GetComponent(); if (open != coo.isOpen) { if (ItemInHand != null) { - foreach (Collider c in ItemInHand.GetComponentsInChildren()) { + foreach ( + Collider c in ItemInHand.GetComponentsInChildren() + ) { c.enabled = true; } } @@ -4340,7 +5127,14 @@ private void OpenOrCloseObjectAtLocation(bool open, ServerAction action) { float y = 1.0f - action.y; Ray ray = m_Camera.ViewportPointToRay(new Vector3(x, y, 0.0f)); RaycastHit hit; - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "SimObjInvisible"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "SimObjInvisible" + ); if (ItemInHand != null) { foreach (Collider c in ItemInHand.GetComponentsInChildren()) { c.enabled = false; @@ -4359,9 +5153,10 @@ private void OpenOrCloseObjectAtLocation(bool open, ServerAction action) { return; } SimObjPhysics so = ancestorSimObjPhysics(hit.transform.gameObject); - if (so != null && ( - action.forceAction || objectIsCurrentlyVisible(so, maxVisibleDistance) - )) { + if ( + so != null + && (action.forceAction || objectIsCurrentlyVisible(so, maxVisibleDistance)) + ) { if (open) { OpenObject(objectId: so.ObjectID, forceAction: true); } else { @@ -4380,7 +5175,11 @@ private void OpenOrCloseObjectAtLocation(bool open, ServerAction action) { public void OpenObjectAtLocation(ServerAction action) { if (action.z > 0) { SimObjPhysics sop = getOpenableOrCloseableObjectNearLocation( - true, action.x, action.y, action.z, false + true, + action.x, + action.y, + action.z, + false ); if (sop != null) { OpenObject(objectId: sop.ObjectID, forceAction: true); @@ -4398,7 +5197,6 @@ public void CloseObjectAtLocation(ServerAction action) { OpenOrCloseObjectAtLocation(false, action); } - // swap an object's materials out to the cooked version of the object public void CookObject(ServerAction action) { // specify target to pickup via objectId or coordinates @@ -4408,15 +5206,23 @@ public void CookObject(ServerAction action) { SimObjPhysics target = null; if (action.objectId == null) { - target = getInteractableSimObjectFromXY(x: action.x, y: action.y, forceAction: action.forceAction); + target = getInteractableSimObjectFromXY( + x: action.x, + y: action.y, + forceAction: action.forceAction + ); } else { - target = getInteractableSimObjectFromId(objectId: action.objectId, forceAction: action.forceAction); + target = getInteractableSimObjectFromId( + objectId: action.objectId, + forceAction: action.forceAction + ); } if (target) { if (!action.forceAction && !IsInteractable(target)) { actionFinished(false); - errorMessage = "object is visible but occluded by something: " + action.objectId; + errorMessage = + "object is visible but occluded by something: " + action.objectId; return; } @@ -4439,7 +5245,6 @@ public void CookObject(ServerAction action) { return; } } - // target not found in currently visible objects, report not found else { actionFinished(false); @@ -4507,7 +5312,9 @@ public void ToggleObjectOff(float x, float y, bool forceAction = false) { private void toggleObject(float x, float y, bool toggleOn, bool forceAction) { SimObjPhysics target = getInteractableSimObjectFromXY( - x: x, y: y, forceAction: forceAction + x: x, + y: y, + forceAction: forceAction ); toggleObject(target, toggleOn, forceAction); } @@ -4519,7 +5326,6 @@ private void toggleObject(string objectId, bool toggleOn, bool forceAction) { target = getInteractableSimObjectFromId(objectId: objectId, forceAction: forceAction); if (!target) { - // target not found in currently visible objects, report not found errorMessage = "object not found: " + objectId; actionFinished(false); @@ -4567,7 +5373,8 @@ private bool toggleObject(SimObjPhysics target, bool toggleOn, bool forceAction) CanToggleOnOff ctof = target.GetComponent(); if (!ctof.ReturnSelfControlled()) { - errorMessage = "target object is controlled by another sim object. target object cannot be turned on/off directly"; + errorMessage = + "target object is controlled by another sim object. target object cannot be turned on/off directly"; actionFinished(false); return false; } @@ -4593,20 +5400,23 @@ private bool toggleObject(SimObjPhysics target, bool toggleOn, bool forceAction) } // check if this object is broken, it should not be able to be turned on - if (toggleOn && target.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBreak)) { + if ( + toggleOn + && target.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBreak + ) + ) { // if this breakable object is broken, we can't turn it on if (target.IsBroken) { errorMessage = "Target is broken and cannot be Toggled On!"; actionFinished(false); return false; } - } // interact then wait StartCoroutine(ToggleAndWait(ctof)); return true; - } else { errorMessage = "object is not toggleable."; actionFinished(false); @@ -4623,8 +5433,14 @@ protected IEnumerator ToggleAndWait(CanToggleOnOff ctof) { bool success = false; - - yield return new WaitUntil(() => (ctof != null && ctof.GetIsCurrentlyLerping() == false && ctof.isOn == !ctofInitialState)); + yield return new WaitUntil( + () => + ( + ctof != null + && ctof.GetIsCurrentlyLerping() == false + && ctof.isOn == !ctofInitialState + ) + ); success = true; if (!success) { @@ -4644,7 +5460,10 @@ public void Contains(ServerAction action) { return; } - SimObjPhysics target = getInteractableSimObjectFromId(objectId: action.objectId, forceAction: action.forceAction); + SimObjPhysics target = getInteractableSimObjectFromId( + objectId: action.objectId, + forceAction: action.forceAction + ); if (target) { List ids = target.GetAllSimObjectsInReceptacleTriggersByObjectID(); @@ -4663,7 +5482,7 @@ public void Contains(ServerAction action) { } // override for SimpleSimObj? - // public override SimpleSimObj[] VisibleSimObjs() + // public override SimpleSimObj[] VisibleSimObjs() // { // return GetAllVisibleSimObjPhysics(m_Camera, maxVisibleDistance); // } @@ -4672,7 +5491,9 @@ public void Contains(ServerAction action) { ////// HIDING AND MASKING OBJECTS ////// //////////////////////////////////////// - private Dictionary maskedGameObjectDict = new Dictionary(); + private Dictionary maskedGameObjectDict = + new Dictionary(); + private void maskGameObject(GameObject go, Material mat) { if (go.name == "Objects" || go.name == "Structure") { return; @@ -4760,14 +5581,21 @@ public void HideAllObjectsExcept(ServerAction action) { UpdateDisplayGameObject(go, false); } if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { - UpdateDisplayGameObject(physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId].gameObject, true); + UpdateDisplayGameObject( + physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId].gameObject, + true + ); } actionFinished(true); } public void HideTranslucentObjects() { foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) { - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanSeeThrough)) { + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanSeeThrough + ) + ) { UpdateDisplayGameObject(sop.gameObject, false); } } @@ -4793,11 +5621,13 @@ public void HideTransparentStructureObjects() { bool transparent = true; foreach (Material m in r.materials) { if ( - !(m.IsKeywordEnabled("_ALPHATEST_ON") || - m.IsKeywordEnabled("_ALPHABLEND_ON") || - m.IsKeywordEnabled("_ALPHAPREMULTIPLY_ON") - ) || m.color.a == 1.0f - ) { + !( + m.IsKeywordEnabled("_ALPHATEST_ON") + || m.IsKeywordEnabled("_ALPHABLEND_ON") + || m.IsKeywordEnabled("_ALPHAPREMULTIPLY_ON") + ) + || m.color.a == 1.0f + ) { transparent = false; break; } @@ -4851,8 +5681,12 @@ public void GetAwayFromObject(ServerAction action) { int k = 0; while (isAgentCapsuleCollidingWith(sop.gameObject) && k < 20) { k++; - Vector3[] dirs = { - transform.forward, -transform.forward, transform.right, -transform.right + Vector3[] dirs = + { + transform.forward, + -transform.forward, + transform.right, + -transform.right }; dirs.Shuffle_(action.randomSeed); @@ -4872,7 +5706,6 @@ public void GetAwayFromObject(ServerAction action) { } } - public void DisableObjectCollisionWithAgent(ServerAction action) { if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId]; @@ -4894,7 +5727,10 @@ public void DisableObjectCollisionWithAgent(ServerAction action) { public void HideObject(string objectId, bool hideContained = true) { if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; - if (hideContained && !ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(sop.ObjType)) { + if ( + hideContained + && !ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(sop.ObjType) + ) { foreach (SimObjPhysics containedSop in sop.SimObjectsContainedByReceptacle) { UpdateDisplayGameObject(containedSop.gameObject, false); } @@ -4912,7 +5748,10 @@ public void HideObject(string objectId, bool hideContained = true) { public void UnhideObject(string objectId, bool unhideContained = true) { if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; - if (unhideContained && !ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(sop.ObjType)) { + if ( + unhideContained + && !ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(sop.ObjType) + ) { foreach (SimObjPhysics containedSop in sop.SimObjectsContainedByReceptacle) { UpdateDisplayGameObject(containedSop.gameObject, true); } @@ -4949,7 +5788,10 @@ protected void MaskSimObj(SimObjPhysics so, Material mat) { } } Dictionary dict = new Dictionary(); - foreach (MeshRenderer r in so.gameObject.GetComponentsInChildren() as MeshRenderer[]) { + foreach ( + MeshRenderer r in so.gameObject.GetComponentsInChildren() + as MeshRenderer[] + ) { if (!renderersToSkip.Contains(r)) { dict[r.GetInstanceID()] = r.materials; Material[] newMaterials = new Material[r.materials.Length]; @@ -4979,7 +5821,10 @@ protected void UnmaskSimObj(SimObjPhysics so) { } if (maskedObjects.ContainsKey(so.ObjectID)) { - foreach (MeshRenderer r in so.gameObject.GetComponentsInChildren() as MeshRenderer[]) { + foreach ( + MeshRenderer r in so.gameObject.GetComponentsInChildren() + as MeshRenderer[] + ) { if (r != null) { if (maskedObjects[so.ObjectID].ContainsKey(r.GetInstanceID())) { r.materials = maskedObjects[so.ObjectID][r.GetInstanceID()]; @@ -4992,7 +5837,12 @@ protected void UnmaskSimObj(SimObjPhysics so) { public void EmphasizeObject(ServerAction action) { #if UNITY_EDITOR - foreach (KeyValuePair entry in physicsSceneManager.ObjectIdToSimObjPhysics) { + foreach ( + KeyValuePair< + string, + SimObjPhysics + > entry in physicsSceneManager.ObjectIdToSimObjPhysics + ) { Debug.Log(entry.Key); Debug.Log(entry.Key == action.objectId); } @@ -5000,8 +5850,14 @@ public void EmphasizeObject(ServerAction action) { if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { HideAll(); - UpdateDisplayGameObject(physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId].gameObject, true); - MaskSimObj(physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId], Color.magenta); + UpdateDisplayGameObject( + physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId].gameObject, + true + ); + MaskSimObj( + physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId], + Color.magenta + ); actionFinished(true); } else { errorMessage = "No object with id: " + action.objectId; @@ -5019,7 +5875,10 @@ public void UnemphasizeAll() { public void MaskObject(ServerAction action) { if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { - MaskSimObj(physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId], Color.magenta); + MaskSimObj( + physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId], + Color.magenta + ); actionFinished(true); } else { errorMessage = "No such object with id: " + action.objectId; @@ -5055,7 +5914,8 @@ private bool AnythingAbovePositionIgnoreObject( Vector3 position, float distance, int layerMask, - GameObject toIgnore) { + GameObject toIgnore + ) { Vector3 up = new Vector3(0.0f, 1.0f, 0.0f); RaycastHit[] hits = Physics.RaycastAll(position, up, distance, layerMask); foreach (RaycastHit hit in hits) { @@ -5093,7 +5953,13 @@ public void FlatSurfacesOnGrid(ServerAction action) { toggleColliders(ItemInHand.GetComponentsInChildren()); } - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); for (int i = 0; i < yGridSize; i++) { for (int j = 0; j < xGridSize; j++) { float x = j * (1.0f / xGridSize) + (0.5f / xGridSize); @@ -5107,13 +5973,16 @@ public void FlatSurfacesOnGrid(ServerAction action) { } } foreach (RaycastHit hit in hits) { - if (NormalIsApproximatelyUp(hit.normal) && - !AnythingAbovePosition(hit.point, 0.1f)) { + if ( + NormalIsApproximatelyUp(hit.normal) + && !AnythingAbovePosition(hit.point, 0.1f) + ) { if (hit.distance == minHitDistance) { flatSurfacesOnGrid[0, i, j] = minHitDistance; } else { flatSurfacesOnGrid[1, i, j] = Math.Min( - flatSurfacesOnGrid[1, i, j], hit.distance + flatSurfacesOnGrid[1, i, j], + hit.distance ); } } @@ -5137,7 +6006,13 @@ public void GetMetadataOnGrid(ServerAction action) { toggleColliders(ItemInHand.GetComponentsInChildren()); } - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); for (int i = 0; i < yGridSize; i++) { for (int j = 0; j < xGridSize; j++) { float x = j * (1.0f / xGridSize) + (0.5f / xGridSize); @@ -5200,7 +6075,7 @@ virtual public void crouch() { ); } - virtual public void stand() { + public virtual void stand() { m_Camera.transform.localPosition = standingLocalCameraPosition; } @@ -5237,36 +6112,39 @@ public void RotateUniverseAroundAgent(ServerAction action) { actionFinished(true); } - public void ChangeFOV(float fieldOfView, string camera="") { - + public void ChangeFOV(float fieldOfView, string camera = "") { if (fieldOfView > 0 && fieldOfView < 180) { if (string.IsNullOrEmpty(camera)) { m_Camera.fieldOfView = fieldOfView; actionFinished(true); - } - else { - var cameraTuples = new List<(Camera camera, bool isThirdPartyCamera, int id)>(){(camera: m_Camera, isThirdPartyCamera: false, id: -1)}.Concat(this.agentManager.thirdPartyCameras.Select((c, i) => (camera: c, isThirdPartyCamera: true, id: i))); + } else { + var cameraTuples = new List<(Camera camera, bool isThirdPartyCamera, int id)>() + { + (camera: m_Camera, isThirdPartyCamera: false, id: -1) + }.Concat( + this.agentManager.thirdPartyCameras.Select( + (c, i) => (camera: c, isThirdPartyCamera: true, id: i) + ) + ); var matches = cameraTuples; if (camera != "*") { matches = cameraTuples.Where(t => t.camera.name == camera); } // Debug.Log($"Camera matches: {matches.Count()} {string.Join(", ", matches.Select(m => m.camera.name))}"); if (matches.Count() == 0) { - errorMessage = $"Camera '{camera}' is not present in the agent, make sure the agent was initialized correctly or camera was added via 'AddThirdPartyCamera'."; + errorMessage = + $"Camera '{camera}' is not present in the agent, make sure the agent was initialized correctly or camera was added via 'AddThirdPartyCamera'."; actionFinished(false); - } - else { + } else { foreach (var tuple in matches) { if (tuple.isThirdPartyCamera) { agentManager.UpdateThirdPartyCamera( tuple.id, fieldOfView: fieldOfView ); - } - else { + } else { tuple.camera.fieldOfView = fieldOfView; } - } actionFinished(true); } @@ -5276,7 +6154,6 @@ public void ChangeFOV(float fieldOfView, string camera="") { Debug.Log(errorMessage); actionFinished(false); } - } // in case you want to change the timescale @@ -5307,9 +6184,13 @@ public bool objectIsOnScreen(SimObjPhysics sop) { float ViewPointRangeLow = 0.0f; // first make sure the vis point is within the viewport at all - if (viewPoint.z > 0 && - viewPoint.x < ViewPointRangeHigh && viewPoint.x > ViewPointRangeLow && // within x bounds of viewport - viewPoint.y < ViewPointRangeHigh && viewPoint.y > ViewPointRangeLow // within y bounds of viewport + if ( + viewPoint.z > 0 + && viewPoint.x < ViewPointRangeHigh + && viewPoint.x > ViewPointRangeLow + && // within x bounds of viewport + viewPoint.y < ViewPointRangeHigh + && viewPoint.y > ViewPointRangeLow // within y bounds of viewport ) { // ok so it is within the viewport, not lets do a raycast to see if we can see the vis point updateAllAgentCollidersForVisibilityCheck(false); @@ -5322,7 +6203,14 @@ public bool objectIsOnScreen(SimObjPhysics sop) { point.position - m_Camera.transform.position, out hit, Mathf.Infinity, - LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent") + LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent" + ) ) ) { if (hit.transform != sop.transform) { @@ -5355,8 +6243,22 @@ public bool objectIsCurrentlyVisible(SimObjPhysics sop, float maxDistance) { // Debug.Log(Vector3.Distance(tmp, transform.position)); if (Vector3.Distance(tmp, transform.position) < maxDistance) { // if this particular point is in view... - if ((CheckIfVisibilityPointInViewport(sop, point, m_Camera, false).visible || - CheckIfVisibilityPointInViewport(sop, point, m_Camera, true).visible)) { + if ( + ( + CheckIfVisibilityPointInViewport( + sop, + point, + m_Camera, + false + ).visible + || CheckIfVisibilityPointInViewport( + sop, + point, + m_Camera, + true + ).visible + ) + ) { updateAllAgentCollidersForVisibilityCheck(true); return true; } @@ -5370,8 +6272,10 @@ public bool objectIsCurrentlyVisible(SimObjPhysics sop, float maxDistance) { } protected int xzManhattanDistance(Vector3 p0, Vector3 p1, float gridSize) { - return (Math.Abs(Convert.ToInt32((p0.x - p1.x) / gridSize)) + - Math.Abs(Convert.ToInt32((p0.z - p1.z) / gridSize))); + return ( + Math.Abs(Convert.ToInt32((p0.x - p1.x) / gridSize)) + + Math.Abs(Convert.ToInt32((p0.z - p1.z) / gridSize)) + ); } // hide and seek action. @@ -5510,7 +6414,12 @@ protected HashSet getAllItemsVisibleFromPositions(Vector3[] posit } else { crouch(); } - foreach (SimObjPhysics sop in GetAllVisibleSimObjPhysics(m_Camera, 1.0f + maxVisibleDistance)) { + foreach ( + SimObjPhysics sop in GetAllVisibleSimObjPhysics( + m_Camera, + 1.0f + maxVisibleDistance + ) + ) { allVisible.Add(sop); } } @@ -5536,37 +6445,43 @@ protected HashSet getAllItemsVisibleFromPositions(Vector3[] posit } //helper function to set transform or position for game objects - public void SetTransform(Transform transform, Vector3? position = null, Quaternion? rotation = null) { - if(!transform.GetComponent()) { - if(position != null) { - transform.position = (Vector3) position; - + public void SetTransform( + Transform transform, + Vector3? position = null, + Quaternion? rotation = null + ) { + if (!transform.GetComponent()) { + if (position != null) { + transform.position = (Vector3)position; } - if(rotation != null) { - transform.rotation = (Quaternion) rotation; + if (rotation != null) { + transform.rotation = (Quaternion)rotation; } } - //handle if this transform we are trying to manipulate is an articulation body and needs to be treated special else { Debug.Log("SetTransform with Articulation Body happening!"); ArticulationBody articulationBody = transform.GetComponent(); - if(position != null && rotation != null) { + if (position != null && rotation != null) { Debug.Log("Teleporting position and rotation"); - articulationBody.TeleportRoot((Vector3) position, (Quaternion) rotation); - } - - else if(position != null && rotation == null) { + articulationBody.TeleportRoot((Vector3)position, (Quaternion)rotation); + } else if (position != null && rotation == null) { Debug.Log("Teleporting position, default rotation"); - Debug.Log($"Passing to TeleportRoot(): position is {position}, but casting it is {(Vector3) position}"); - articulationBody.TeleportRoot((Vector3) position, articulationBody.transform.rotation); - } - - else if (position == null && rotation != null) { + Debug.Log( + $"Passing to TeleportRoot(): position is {position}, but casting it is {(Vector3)position}" + ); + articulationBody.TeleportRoot( + (Vector3)position, + articulationBody.transform.rotation + ); + } else if (position == null && rotation != null) { Debug.Log("Teleporting rotation, default position"); - articulationBody.TeleportRoot(articulationBody.transform.position, (Quaternion) rotation); + articulationBody.TeleportRoot( + articulationBody.transform.position, + (Quaternion)rotation + ); } } } @@ -5581,11 +6496,15 @@ public virtual List> getInteractablePoses( float[] horizons = null, bool[] standings = null, float? maxDistance = null, - int maxPoses = int.MaxValue // works like infinity + int maxPoses = int.MaxValue // works like infinity ) { - Debug.Log($"Position of agent at start of GetInteractablePoses: {this.transform.position}"); + Debug.Log( + $"Position of agent at start of GetInteractablePoses: {this.transform.position}" + ); if (360 % rotateStepDegrees != 0 && rotations != null) { - throw new InvalidOperationException($"360 % rotateStepDegrees (360 % {rotateStepDegrees} != 0) must be 0, unless 'rotations: float[]' is overwritten."); + throw new InvalidOperationException( + $"360 % rotateStepDegrees (360 % {rotateStepDegrees} != 0) must be 0, unless 'rotations: float[]' is overwritten." + ); } if (maxPoses <= 0) { @@ -5597,12 +6516,17 @@ public virtual List> getInteractablePoses( if (maxDistance == null) { maxDistanceFloat = maxVisibleDistance; } else if ((float)maxDistance <= 0) { - throw new ArgumentOutOfRangeException("maxDistance must be >= 0 meters from the object."); + throw new ArgumentOutOfRangeException( + "maxDistance must be >= 0 meters from the object." + ); } else { maxDistanceFloat = (float)maxDistance; } - SimObjPhysics theObject = getInteractableSimObjectFromId(objectId: objectId, forceAction: true); + SimObjPhysics theObject = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: true + ); // Populate default standings. Note that these are boolean because that's // the most natural integration with Teleport @@ -5641,13 +6565,24 @@ public virtual List> getInteractablePoses( // if rotateStepDegrees=90 and offset=10, then the paths would be [10, 100, 190, 280] rotations = new float[(int)Math.Round(360 / rotateStepDegrees)]; int i = 0; - for (float rotation = offset; rotation < 360 + offset; rotation += rotateStepDegrees) { + for ( + float rotation = offset; + rotation < 360 + offset; + rotation += rotateStepDegrees + ) { rotations[i++] = rotation; } } - if (horizons.Length == 0 || rotations.Length == 0 || positions.Length == 0 || standings.Length == 0) { - throw new InvalidOperationException("Every degree of freedom must have at least 1 valid value."); + if ( + horizons.Length == 0 + || rotations.Length == 0 + || positions.Length == 0 + || standings.Length == 0 + ) { + throw new InvalidOperationException( + "Every degree of freedom must have at least 1 valid value." + ); } // save current agent pose @@ -5668,12 +6603,18 @@ public virtual List> getInteractablePoses( objectBounds.Encapsulate(vp.position); } float fudgeFactor = objectBounds.extents.magnitude; - List filteredPositions = positions.Where( - p => (Vector3.Distance(a: p, b: theObject.transform.position) <= maxDistanceFloat + fudgeFactor + gridSize) - ).ToList(); + List filteredPositions = positions + .Where(p => + ( + Vector3.Distance(a: p, b: theObject.transform.position) + <= maxDistanceFloat + fudgeFactor + gridSize + ) + ) + .ToList(); // set each key to store a list - List> validAgentPoses = new List>(); + List> validAgentPoses = + new List>(); //commenting this out because I don't think its actually ever used??? //string[] keys = { "x", "y", "z", "rotation", "standing", "horizon" }; @@ -5693,28 +6634,35 @@ public virtual List> getInteractablePoses( foreach (float rotation in rotations) { Vector3 rotationVector = new Vector3(x: 0, y: rotation, z: 0); //Debug.Log($"initial rotation: {transform.rotation}"); - SetTransform(transform: transform, rotation: (Quaternion?) Quaternion.Euler(rotationVector)); + SetTransform( + transform: transform, + rotation: (Quaternion?)Quaternion.Euler(rotationVector) + ); //Debug.Log($"Rotation after SetTransform(): {transform.rotation}"); foreach (Vector3 position in filteredPositions) { Debug.Log("////////////////////"); Debug.Log($"position Before SetTransform: {transform.position}"); - Debug.Log($"Passing in position to SetTransform: Vector3 {position}, Vector3? {(Vector3?) position}"); - SetTransform(transform: transform, position: (Vector3?) position); + Debug.Log( + $"Passing in position to SetTransform: Vector3 {position}, Vector3? {(Vector3?)position}" + ); + SetTransform(transform: transform, position: (Vector3?)position); Debug.Log($"Position After SetTransform(): {transform.position}"); Debug.Log("////////////////////"); // Each of these values is directly compatible with TeleportFull // and should be used with .step(action='TeleportFull', **interactable_positions[0]) if (objectIsCurrentlyVisible(theObject, maxDistanceFloat)) { - validAgentPoses.Add(new Dictionary { - ["x"] = position.x, - ["y"] = position.y, - ["z"] = position.z, - ["rotation"] = rotation, - ["standing"] = standing, - ["horizon"] = horizon - }); + validAgentPoses.Add( + new Dictionary { + ["x"] = position.x, + ["y"] = position.y, + ["z"] = position.z, + ["rotation"] = rotation, + ["standing"] = standing, + ["horizon"] = horizon + } + ); if (validAgentPoses.Count >= maxPoses) { stopEarly = true; @@ -5723,7 +6671,12 @@ public virtual List> getInteractablePoses( #if UNITY_EDITOR // In the editor, draw lines indicating from where the object was visible. - Debug.DrawLine(position, position + transform.forward * (gridSize * 0.5f), Color.red, 20f); + Debug.DrawLine( + position, + position + transform.forward * (gridSize * 0.5f), + Color.red, + 20f + ); #endif } } @@ -5746,7 +6699,11 @@ public virtual List> getInteractablePoses( } else { crouch(); } - SetTransform(transform: transform, position: (Vector3?) oldPosition, rotation: (Quaternion?) oldRotation); + SetTransform( + transform: transform, + position: (Vector3?)oldPosition, + rotation: (Quaternion?)oldRotation + ); m_Camera.transform.localEulerAngles = oldHorizon; if (ItemInHand != null) { ItemInHand.gameObject.SetActive(true); @@ -5773,19 +6730,29 @@ public virtual void GetInteractablePoses( float[] horizons = null, bool[] standings = null, float? maxDistance = null, - int maxPoses = int.MaxValue // works like infinity + int maxPoses = int.MaxValue // works like infinity ) { getInteractablePoses( objectId: objectId, markActionFinished: true, - positions: positions, rotations: rotations, horizons: horizons, standings: standings, + positions: positions, + rotations: rotations, + horizons: horizons, + standings: standings, maxDistance: maxDistance, maxPoses: maxPoses ); } - [ObsoleteAttribute(message: "This action is deprecated. Call GetInteractablePoses instead.", error: false)] - public void PositionsFromWhichItemIsInteractable(string objectId, float horizon = 30, Vector3[] positions = null) { + [ObsoleteAttribute( + message: "This action is deprecated. Call GetInteractablePoses instead.", + error: false + )] + public void PositionsFromWhichItemIsInteractable( + string objectId, + float horizon = 30, + Vector3[] positions = null + ) { // set horizons using the horizon as an increment List horizons = new List(); for (float h = -maxUpwardLookAngle; h <= maxDownwardLookAngle; h += horizon) { @@ -5821,12 +6788,17 @@ public void PositionsFromWhichItemIsInteractable(string objectId, float horizon } // private helper for NumberOfPositionsFromWhichItemIsVisible - private int numVisiblePositions(string objectId, bool markActionFinished, Vector3[] positions = null, int maxPoses = int.MaxValue) { + private int numVisiblePositions( + string objectId, + bool markActionFinished, + Vector3[] positions = null, + int maxPoses = int.MaxValue + ) { List> interactablePoses = getInteractablePoses( objectId: objectId, positions: positions, - maxDistance: 1e5f, // super large number for maximum distance! - horizons: new float[] { m_Camera.transform.localEulerAngles.x }, // don't care about every horizon here, just horizon={current horizon} + maxDistance: 1e5f, // super large number for maximum distance! + horizons: new float[] { m_Camera.transform.localEulerAngles.x }, // don't care about every horizon here, just horizon={current horizon} markActionFinished: false, maxPoses: maxPoses ); @@ -5839,7 +6811,10 @@ private int numVisiblePositions(string objectId, bool markActionFinished, Vector } // Similar to GetInteractablePositions, but with horizon=0 and maxDistance like infinity - public void NumberOfPositionsFromWhichItemIsVisible(string objectId, Vector3[] positions = null) { + public void NumberOfPositionsFromWhichItemIsVisible( + string objectId, + Vector3[] positions = null + ) { numVisiblePositions(objectId: objectId, positions: positions, markActionFinished: true); } @@ -5869,8 +6844,20 @@ protected bool isHandObjectColliding(bool ignoreAgent = false, float expandBy = } protected bool isAgentCapsuleCollidingWith(GameObject otherGameObject) { - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); - foreach (Collider c in PhysicsExtensions.OverlapCapsule(GetComponent(), layerMask, QueryTriggerInteraction.Ignore)) { + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); + foreach ( + Collider c in PhysicsExtensions.OverlapCapsule( + GetComponent(), + layerMask, + QueryTriggerInteraction.Ignore + ) + ) { if (hasAncestor(c.transform.gameObject, otherGameObject)) { return true; } @@ -5927,7 +6914,7 @@ protected bool isAgentCapsuleCollidingWith(GameObject otherGameObject) { // // if (openableObject) == // Blah blah blah working on it... // return containedCol.gameObject; // } - // // collider shouldn't be + // // collider shouldn't be // else if (ancestorSimObjPhysics(containedCol.gameObject) != null && // ancestorSimObjPhysics(containedCol.gameObject).gameObject != openableObject && // ancestorSimObjPhysics(containedCol.gameObject).PrimaryProperty == SimObjPrimaryProperty.Static) { @@ -5984,12 +6971,7 @@ public void RandomlyMoveAgent(int randomSeed = 0) { randomSeed = UnityEngine.Random.Range(0, 1000000); #endif Vector3[] reachablePositions = getReachablePositions(); - var orientations = new float[]{ - 0, - 90, - 180, - 270 - }; + var orientations = new float[] { 0, 90, 180, 270 }; orientations.Shuffle_(randomSeed); reachablePositions.Shuffle_(randomSeed); @@ -6062,26 +7044,38 @@ public void GetReachablePositionsForObject(ServerAction action) { } sop.BoundingBox.GetComponent().enabled = true; - Dictionary> reachablePerRotation = new Dictionary>(); + Dictionary> reachablePerRotation = + new Dictionary>(); for (int k = 0; k < 4; k++) { reachablePerRotation[90 * k] = new List(); sop.transform.rotation = Quaternion.Euler(new Vector3(0f, k * 90f, 0f)); for (int i = 0; i <= (int)((xMax - xMin) / gridSize); i++) { for (int j = 0; j <= (int)((zMax - zMin) / gridSize); j++) { - Vector3 p = new Vector3(xMin + gridSize * i, startPos.y, zMin + j * gridSize); + Vector3 p = new Vector3( + xMin + gridSize * i, + startPos.y, + zMin + j * gridSize + ); sop.transform.position = p; - if (!UtilityFunctions.isObjectColliding( + if ( + !UtilityFunctions.isObjectColliding( sop.BoundingBox.gameObject, agentGameObjects, 0.0f, true - )) { + ) + ) { // #if UNITY_EDITOR // Debug.Log(p); // #endif #if UNITY_EDITOR - Debug.DrawLine(p, new Vector3(p.x, p.y + 0.3f, p.z) + sop.transform.forward * 0.3f, Color.red, 60f); + Debug.DrawLine( + p, + new Vector3(p.x, p.y + 0.3f, p.z) + sop.transform.forward * 0.3f, + Color.red, + 60f + ); #endif reachablePerRotation[90 * k].Add(p); } @@ -6128,7 +7122,13 @@ public void HideObscuringObjects(ServerAction action) { } int xGridSize = 100; int yGridSize = 100; - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); for (int i = 0; i < yGridSize; i++) { for (int j = 0; j < xGridSize; j++) { float x = j * (1.0f / xGridSize) + (0.5f / xGridSize); @@ -6138,8 +7138,13 @@ public void HideObscuringObjects(ServerAction action) { while (true) { if (Physics.Raycast(ray, out hit, 10f, layerMask)) { UpdateDisplayGameObject(hit.transform.gameObject, false); - SimObjPhysics hitObj = hit.transform.gameObject.GetComponentInChildren(); - if (hitObj != null && objType != "" && hitObj.ObjectID.Contains(objType)) { + SimObjPhysics hitObj = + hit.transform.gameObject.GetComponentInChildren(); + if ( + hitObj != null + && objType != "" + && hitObj.ObjectID.Contains(objType) + ) { ray.origin = hit.point + ray.direction / 100f; } else { break; @@ -6156,7 +7161,8 @@ public void HideObscuringObjects(ServerAction action) { // spawns object in agent's hand with the same orientation as the agent's hand public void CreateObject(ServerAction action) { if (ItemInHand != null) { - errorMessage = "Already have an object in hand, can't create a new one to put there."; + errorMessage = + "Already have an object in hand, can't create a new one to put there."; actionFinished(false); return; } @@ -6168,7 +7174,8 @@ public void CreateObject(ServerAction action) { } // spawn the object at the agent's hand position - InstantiatePrefabTest script = physicsSceneManager.GetComponent(); + InstantiatePrefabTest script = + physicsSceneManager.GetComponent(); SimObjPhysics so = script.SpawnObject( action.objectType, action.randomizeObjectAppearance, @@ -6188,10 +7195,7 @@ public void CreateObject(ServerAction action) { // update the Physics Scene Manager with this new object physicsSceneManager.AddToObjectsInScene(so); - PickupObject( - objectId: so.objectID, - forceAction: true - ); + PickupObject(objectId: so.objectID, forceAction: true); } public void CreateObjectAtLocation(ServerAction action) { @@ -6211,9 +7215,17 @@ public void CreateObjectAtLocation(ServerAction action) { } // spawn the object at the agent's hand position - InstantiatePrefabTest script = physicsSceneManager.GetComponent(); - SimObjPhysics so = script.SpawnObject(action.objectType, action.randomizeObjectAppearance, action.objectVariation, - targetPosition, targetRotation, false, action.forceAction); + InstantiatePrefabTest script = + physicsSceneManager.GetComponent(); + SimObjPhysics so = script.SpawnObject( + action.objectType, + action.randomizeObjectAppearance, + action.objectVariation, + targetPosition, + targetRotation, + false, + action.forceAction + ); if (so == null) { errorMessage = "Failed to create object, are you sure it can be spawned?"; @@ -6227,7 +7239,12 @@ public void CreateObjectAtLocation(ServerAction action) { actionFinished(true, so.ObjectID); } - protected SimObjPhysics createObjectAtLocation(string objectType, Vector3 targetPosition, Vector3 targetRotation, int objectVariation = 1) { + protected SimObjPhysics createObjectAtLocation( + string objectType, + Vector3 targetPosition, + Vector3 targetRotation, + int objectVariation = 1 + ) { if (!agentManager.SceneBounds.Contains(targetPosition)) { errorMessage = "Target position is out of bounds!"; return null; @@ -6239,9 +7256,16 @@ protected SimObjPhysics createObjectAtLocation(string objectType, Vector3 target } // spawn the object at the agent's hand position - InstantiatePrefabTest script = physicsSceneManager.GetComponent(); - SimObjPhysics so = script.SpawnObject(objectType, false, objectVariation, - targetPosition, targetRotation, false); + InstantiatePrefabTest script = + physicsSceneManager.GetComponent(); + SimObjPhysics so = script.SpawnObject( + objectType, + false, + objectVariation, + targetPosition, + targetRotation, + false + ); if (so == null) { errorMessage = "Failed to create object, are you sure it can be spawned?"; @@ -6254,9 +7278,9 @@ protected SimObjPhysics createObjectAtLocation(string objectType, Vector3 target return so; } - public void CreateObjectOnFloor(ServerAction action) { - InstantiatePrefabTest script = physicsSceneManager.GetComponent(); + InstantiatePrefabTest script = + physicsSceneManager.GetComponent(); Bounds b = script.BoundsOfObject(action.objectType, 1); if (b.min.x == float.PositiveInfinity) { errorMessage = "Could not get bounds for the object to be created on the floor"; @@ -6280,7 +7304,8 @@ protected bool randomlyPlaceObjectOnFloor(SimObjPhysics sop, Vector3[] candidate } } - List shuffledCurrentlyReachable = (List)candidatePositions.ToList().Shuffle_(); + List shuffledCurrentlyReachable = + (List)candidatePositions.ToList().Shuffle_(); float[] rotations = { 0f, 90f, 180f, 270f }; List shuffledRotations = (List)rotations.ToList().Shuffle_(); bool objectColliding = true; @@ -6305,14 +7330,21 @@ protected bool randomlyPlaceObjectOnFloor(SimObjPhysics sop, Vector3[] candidate return objectColliding; } - protected SimObjPhysics randomlyCreateAndPlaceObjectOnFloor(string objectType, int objectVariation, Vector3[] candidatePositions) { - InstantiatePrefabTest script = physicsSceneManager.GetComponent(); + protected SimObjPhysics randomlyCreateAndPlaceObjectOnFloor( + string objectType, + int objectVariation, + Vector3[] candidatePositions + ) { + InstantiatePrefabTest script = + physicsSceneManager.GetComponent(); Bounds b = script.BoundsOfObject(objectType, 1); if (b.min.x != float.PositiveInfinity) { errorMessage = "Could not get bounds of object with type " + objectType; } - Vector3[] shuffledCurrentlyReachable = candidatePositions.OrderBy(x => systemRandom.Next()).ToArray(); + Vector3[] shuffledCurrentlyReachable = candidatePositions + .OrderBy(x => systemRandom.Next()) + .ToArray(); float[] rotations = { 0f, 90f, 180f, 270f }; float[] shuffledRotations = rotations.OrderBy(x => systemRandom.Next()).ToArray(); SimObjPhysics objectCreated = null; @@ -6323,7 +7355,8 @@ protected SimObjPhysics randomlyCreateAndPlaceObjectOnFloor(string objectType, i objectType, new Vector3(position.x, y, position.z), new Vector3(0.0f, r, 0.0f), - objectVariation); + objectVariation + ); if (objectCreated) { break; } @@ -6336,12 +7369,22 @@ protected SimObjPhysics randomlyCreateAndPlaceObjectOnFloor(string objectType, i return objectCreated; } - protected SimObjPhysics randomlyCreateAndPlaceObjectOnFloor(string objectType, int objectVariation) { - return randomlyCreateAndPlaceObjectOnFloor(objectType, objectVariation, getReachablePositions()); + protected SimObjPhysics randomlyCreateAndPlaceObjectOnFloor( + string objectType, + int objectVariation + ) { + return randomlyCreateAndPlaceObjectOnFloor( + objectType, + objectVariation, + getReachablePositions() + ); } public void RandomlyCreateAndPlaceObjectOnFloor(string objectType, int objectVariation = 0) { - SimObjPhysics objectCreated = randomlyCreateAndPlaceObjectOnFloor(objectType, objectVariation); + SimObjPhysics objectCreated = randomlyCreateAndPlaceObjectOnFloor( + objectType, + objectVariation + ); if (!objectCreated) { errorMessage = "Failed to randomly create object. " + errorMessage; actionFinished(false); @@ -6414,7 +7457,10 @@ public void WorldToViewportPoint(Vector3 position) { actionFinished(true, new Vector3(point.x, 1.0f - point.y, point.z)); } - protected float approxPercentScreenObjectOccupies(SimObjPhysics sop, bool updateVisibilityColliders = true) { + protected float approxPercentScreenObjectOccupies( + SimObjPhysics sop, + bool updateVisibilityColliders = true + ) { float percent = 0.0f; if (sop.VisibilityPoints != null && sop.VisibilityPoints.Length > 0) { float minX = 1.0f; @@ -6484,7 +7530,13 @@ public void ApproxPercentScreenObjectFromPositions(ServerAction action) { transform.rotation = Quaternion.Euler(0f, rotation, 0f); float approxVisible = approxPercentScreenObjectOccupies(sop, false); if (approxVisible > 0.0f) { - float[] tuple = { position.x, position.y, position.z, transform.eulerAngles.y }; + float[] tuple = + { + position.x, + position.y, + position.z, + transform.eulerAngles.y + }; positionAndApproxAmountVisible.Add(tuple); } } @@ -6497,7 +7549,8 @@ public void ApproxPercentScreenObjectFromPositions(ServerAction action) { } public void GetVisibilityPointsOfObjects() { - Dictionary> objectIdToVisibilityPoints = new Dictionary>(); + Dictionary> objectIdToVisibilityPoints = + new Dictionary>(); foreach (SimObjPhysics sop in physicsSceneManager.ObjectIdToSimObjPhysics.Values) { objectIdToVisibilityPoints[sop.ObjectID] = new List(); if (sop.VisibilityPoints != null) { @@ -6521,18 +7574,30 @@ public void ObjectsVisibleFromPositions(ServerAction action) { Quaternion oldRotation = transform.rotation; float[] rotations = { 0f, 90f, 180f, 270f }; - Dictionary> objectIdToVisiblePositions = new Dictionary>(); + Dictionary> objectIdToVisiblePositions = + new Dictionary>(); foreach (Vector3 position in positions) { transform.position = position; foreach (float rotation in rotations) { transform.rotation = Quaternion.Euler(0f, rotation, 0f); - foreach (SimObjPhysics sop in GetAllVisibleSimObjPhysics(m_Camera, maxVisibleDistance)) { + foreach ( + SimObjPhysics sop in GetAllVisibleSimObjPhysics( + m_Camera, + maxVisibleDistance + ) + ) { if (!objectIdToVisiblePositions.ContainsKey(sop.ObjectID)) { objectIdToVisiblePositions[sop.ObjectID] = new List(); } List l = objectIdToVisiblePositions[sop.ObjectID]; - float[] tuple = { position.x, position.y, position.z, transform.eulerAngles.y }; + float[] tuple = + { + position.x, + position.y, + position.z, + transform.eulerAngles.y + }; l.Add(tuple); } } @@ -6546,7 +7611,8 @@ public void ObjectsVisibleFromPositions(ServerAction action) { public void StackBooks() { GameObject topLevelObject = GameObject.Find("HideAndSeek"); - SimObjPhysics[] hideSeekObjects = topLevelObject.GetComponentsInChildren(); + SimObjPhysics[] hideSeekObjects = + topLevelObject.GetComponentsInChildren(); HashSet seenBooks = new HashSet(); List> groups = new List>(); @@ -6555,12 +7621,16 @@ public void StackBooks() { if (sop.ObjectID.StartsWith("Book|")) { if (!seenBooks.Contains(sop.ObjectID)) { HashSet objectsNearBook = objectsInBox( - sop.transform.position.x, sop.transform.position.z); + sop.transform.position.x, + sop.transform.position.z + ); group.Add(sop); seenBooks.Add(sop.ObjectID); foreach (SimObjPhysics possibleBook in objectsNearBook) { - if (possibleBook.ObjectID.StartsWith("Book|") && - !seenBooks.Contains(possibleBook.ObjectID)) { + if ( + possibleBook.ObjectID.StartsWith("Book|") + && !seenBooks.Contains(possibleBook.ObjectID) + ) { group.Add(possibleBook); seenBooks.Add(possibleBook.ObjectID); } @@ -6581,7 +7651,9 @@ public void StackBooks() { topBook = so; topMesh = so.gameObject.transform.Find("mesh").gameObject; topColliders = so.gameObject.transform.Find("Colliders").gameObject; - topTrigColliders = so.gameObject.transform.Find("TriggerColliders").gameObject; + topTrigColliders = so + .gameObject.transform.Find("TriggerColliders") + .gameObject; topVisPoints = so.gameObject.transform.Find("VisibilityPoints").gameObject; } else { GameObject mesh = so.gameObject.transform.Find("mesh").gameObject; @@ -6594,14 +7666,18 @@ public void StackBooks() { } } - GameObject trigColliders = so.gameObject.transform.Find("TriggerColliders").gameObject; + GameObject trigColliders = so + .gameObject.transform.Find("TriggerColliders") + .gameObject; foreach (Transform t in trigColliders.GetComponentsInChildren()) { if (t != colliders.transform) { t.parent = topTrigColliders.transform; } } - GameObject visPoints = so.gameObject.transform.Find("VisibilityPoints").gameObject; + GameObject visPoints = so + .gameObject.transform.Find("VisibilityPoints") + .gameObject; foreach (Transform t in visPoints.GetComponentsInChildren()) { if (t != visPoints.transform) { t.parent = topVisPoints.transform; @@ -6680,9 +7756,9 @@ public void RandomizeHideSeekObjects(int randomSeed, float removeProb) { // @pOpen is the probability of opening an openable object. // @randOpenness specifies if the openness for each opened object should be random, between 0% : 100%, or always 100%. public void RandomlyOpenCloseObjects( - bool simplifyPhysics = false, - float pOpen = 0.5f, - bool randOpenness = true + bool simplifyPhysics = false, + float pOpen = 0.5f, + bool randOpenness = true ) { foreach (SimObjPhysics so in GameObject.FindObjectsOfType()) { if (so.GetComponent()) { @@ -6715,7 +7791,10 @@ public void GetApproximateVolume(string objectId) { } } if (!hasActiveRenderer) { - errorMessage = "Cannot get bounds for " + objectId + " as it has no attached (and active) renderers."; + errorMessage = + "Cannot get bounds for " + + objectId + + " as it has no attached (and active) renderers."; actionFinished(false); return; } @@ -6760,19 +7839,28 @@ public void GetVolumeOfAllObjects() { actionFinished(true); } - protected void changeObjectBlendMode(SimObjPhysics so, StandardShaderUtils.BlendMode bm, float alpha) { + protected void changeObjectBlendMode( + SimObjPhysics so, + StandardShaderUtils.BlendMode bm, + float alpha + ) { HashSet renderersToSkip = new HashSet(); foreach (SimObjPhysics childSo in so.GetComponentsInChildren()) { - if (!childSo.ObjectID.StartsWith("Drawer") && - !childSo.ObjectID.Split('|')[0].EndsWith("Door") && - so.ObjectID != childSo.ObjectID) { + if ( + !childSo.ObjectID.StartsWith("Drawer") + && !childSo.ObjectID.Split('|')[0].EndsWith("Door") + && so.ObjectID != childSo.ObjectID + ) { foreach (MeshRenderer mr in childSo.GetComponentsInChildren()) { renderersToSkip.Add(mr); } } } - foreach (MeshRenderer r in so.gameObject.GetComponentsInChildren() as MeshRenderer[]) { + foreach ( + MeshRenderer r in so.gameObject.GetComponentsInChildren() + as MeshRenderer[] + ) { if (!renderersToSkip.Contains(r)) { Material[] newMaterials = new Material[r.materials.Length]; for (int i = 0; i < newMaterials.Length; i++) { @@ -6855,14 +7943,24 @@ public void MaskWalkable() { walkableParent.transform.parent = topLevelObject.transform; } - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); foreach (Vector3 p in reachablePositions) { RaycastHit hit; bool somethingHit = false; float y = 0f; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { - Vector3 offset = new Vector3(i * 0.41f * gridSize, 0f, i * 0.41f * gridSize); + Vector3 offset = new Vector3( + i * 0.41f * gridSize, + 0f, + i * 0.41f * gridSize + ); if (Physics.Raycast(p + offset, -transform.up, out hit, 10f, layerMask)) { if (!somethingHit) { y = hit.point.y; @@ -6876,14 +7974,19 @@ public void MaskWalkable() { if (somethingHit) { y += 0.01f; y = Math.Max(y, 0.05f); - GameObject plane = Instantiate( - Resources.Load("BluePlane") as GameObject, - new Vector3(p.x, y, p.z), - Quaternion.identity - ) as GameObject; + GameObject plane = + Instantiate( + Resources.Load("BluePlane") as GameObject, + new Vector3(p.x, y, p.z), + Quaternion.identity + ) as GameObject; plane.name = "WalkablePlane"; plane.transform.parent = walkableParent.transform; - plane.transform.localScale = new Vector3(gridSize * 0.1f, 0.1f, gridSize * 0.1f); + plane.transform.localScale = new Vector3( + gridSize * 0.1f, + 0.1f, + gridSize * 0.1f + ); } } actionFinished(true); @@ -6928,7 +8031,9 @@ Vector3[] reachablePositions Material redMaterial = (Material)Resources.Load("RED", typeof(Material)); Material greenMaterial = (Material)Resources.Load("GREEN", typeof(Material)); - Collider[] fpsControllerColliders = GameObject.Find("FPSController").GetComponentsInChildren(); + Collider[] fpsControllerColliders = GameObject + .Find("FPSController") + .GetComponentsInChildren(); k = 0; foreach (SimObjPhysics so in newObjects) { if (!deleted[k]) { @@ -6948,7 +8053,9 @@ Vector3[] reachablePositions k++; } - HashSet visibleObjects = getAllItemsVisibleFromPositions(reachablePositions); + HashSet visibleObjects = getAllItemsVisibleFromPositions( + reachablePositions + ); foreach (SimObjPhysics so in newObjects) { if (so.gameObject.activeSelf && !visibleObjects.Contains(so)) { so.gameObject.SetActive(false); @@ -6972,62 +8079,87 @@ private void createCubeSurrounding(Bounds bounds) { float zLen = max.z - min.z; // Top - GameObject cube = Instantiate( - original: Resources.Load("BlueCube") as GameObject, - position: new Vector3(center.x, max.y + offset + size / 2, center.z), - rotation: Quaternion.identity - ) as GameObject; + GameObject cube = + Instantiate( + original: Resources.Load("BlueCube") as GameObject, + position: new Vector3(center.x, max.y + offset + size / 2, center.z), + rotation: Quaternion.identity + ) as GameObject; cube.transform.parent = GameObject.Find("Objects").transform; - cube.transform.localScale = new Vector3(xLen + 2 * (size + offset), size, zLen + 2 * (size + offset)); + cube.transform.localScale = new Vector3( + xLen + 2 * (size + offset), + size, + zLen + 2 * (size + offset) + ); // Bottom - cube = Instantiate( - original: Resources.Load("BlueCube") as GameObject, - position: new Vector3(center.x, min.y - offset - size / 2, center.z), - rotation: Quaternion.identity - ) as GameObject; + cube = + Instantiate( + original: Resources.Load("BlueCube") as GameObject, + position: new Vector3(center.x, min.y - offset - size / 2, center.z), + rotation: Quaternion.identity + ) as GameObject; cube.transform.parent = GameObject.Find("Objects").transform; - cube.transform.localScale = new Vector3(xLen + 2 * (size + offset), size, zLen + 2 * (size + offset)); + cube.transform.localScale = new Vector3( + xLen + 2 * (size + offset), + size, + zLen + 2 * (size + offset) + ); // z min - cube = Instantiate( - original: Resources.Load("BlueCube") as GameObject, - position: new Vector3(center.x, center.y, min.z - offset - size / 2), - rotation: Quaternion.identity - ) as GameObject; + cube = + Instantiate( + original: Resources.Load("BlueCube") as GameObject, + position: new Vector3(center.x, center.y, min.z - offset - size / 2), + rotation: Quaternion.identity + ) as GameObject; cube.transform.parent = GameObject.Find("Objects").transform; - cube.transform.localScale = new Vector3(xLen + 2 * (size + offset), yLen + 2 * offset, size); + cube.transform.localScale = new Vector3( + xLen + 2 * (size + offset), + yLen + 2 * offset, + size + ); // z max - cube = Instantiate( - original: Resources.Load("BlueCube") as GameObject, - position: new Vector3(center.x, center.y, max.z + offset + size / 2), - rotation: Quaternion.identity - ) as GameObject; + cube = + Instantiate( + original: Resources.Load("BlueCube") as GameObject, + position: new Vector3(center.x, center.y, max.z + offset + size / 2), + rotation: Quaternion.identity + ) as GameObject; cube.transform.parent = GameObject.Find("Objects").transform; - cube.transform.localScale = new Vector3(xLen + 2 * (size + offset), yLen + 2 * offset, size); + cube.transform.localScale = new Vector3( + xLen + 2 * (size + offset), + yLen + 2 * offset, + size + ); // x min - cube = Instantiate( - original: Resources.Load("BlueCube") as GameObject, - position: new Vector3(min.x - offset - size / 2, center.y, center.z), - rotation: Quaternion.identity - ) as GameObject; + cube = + Instantiate( + original: Resources.Load("BlueCube") as GameObject, + position: new Vector3(min.x - offset - size / 2, center.y, center.z), + rotation: Quaternion.identity + ) as GameObject; cube.transform.parent = GameObject.Find("Objects").transform; cube.transform.localScale = new Vector3(size, yLen + 2 * offset, zLen + 2 * offset); // x max - cube = Instantiate( - original: Resources.Load("BlueCube") as GameObject, - position: new Vector3(max.x + offset + size / 2, center.y, center.z), - rotation: Quaternion.identity - ) as GameObject; + cube = + Instantiate( + original: Resources.Load("BlueCube") as GameObject, + position: new Vector3(max.x + offset + size / 2, center.y, center.z), + rotation: Quaternion.identity + ) as GameObject; cube.transform.parent = GameObject.Find("Objects").transform; cube.transform.localScale = new Vector3(size, yLen + 2 * offset, zLen + 2 * offset); } private List RaycastWithRepeatHits( - Vector3 origin, Vector3 direction, float maxDistance, int layerMask + Vector3 origin, + Vector3 direction, + float maxDistance, + int layerMask ) { List hits = new List(); RaycastHit hit; @@ -7075,6 +8207,7 @@ public void SetAllObjectsToBlueUnlit() { setAllObjectsToMaterial((Material)Resources.Load("BLUE", typeof(Material))); actionFinished(true); } + public void SetAllObjectsToBlueStandard() { setAllObjectsToMaterial((Material)Resources.Load("BLUE_standard", typeof(Material))); actionFinished(true); @@ -7111,7 +8244,9 @@ public void ColorSurfaceColorObjectsByDistance(float z) { } } - foreach (SimObjPhysics sop in surfaceCoverObjects.GetComponentsInChildren()) { + foreach ( + SimObjPhysics sop in surfaceCoverObjects.GetComponentsInChildren() + ) { Material newMaterial; float minRed = 0.0f; float minGreen = 0.0f; @@ -7162,8 +8297,17 @@ public void CoverSurfacesWith(ServerAction action) { float yMax = b.max.y - 0.2f; float xRoomSize = b.max.x - b.min.x; float zRoomSize = b.max.z - b.min.z; - InstantiatePrefabTest script = physicsSceneManager.GetComponent(); - SimObjPhysics objForBounds = script.SpawnObject(prefab, false, objectVariation, new Vector3(0.0f, b.max.y + 10.0f, 0.0f), transform.eulerAngles, false, true); + InstantiatePrefabTest script = + physicsSceneManager.GetComponent(); + SimObjPhysics objForBounds = script.SpawnObject( + prefab, + false, + objectVariation, + new Vector3(0.0f, b.max.y + 10.0f, 0.0f), + transform.eulerAngles, + false, + true + ); Bounds objBounds = UtilityFunctions.CreateEmptyBounds(); foreach (Renderer r in objForBounds.GetComponentsInChildren()) { @@ -7210,7 +8354,13 @@ public void CoverSurfacesWith(ServerAction action) { var xsToTryArray = xsToTry.ToArray(); var zsToTryArray = zsToTry.ToArray(); - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); for (int i = 0; i < xsToTryArray.Length; i++) { float xPos = xsToTryArray[i]; float zPos = zsToTryArray[i]; @@ -7223,28 +8373,52 @@ public void CoverSurfacesWith(ServerAction action) { ); int k = -1; foreach (RaycastHit hit in hits) { - if (b.Contains(hit.point) && - hit.point.y < transform.position.y + 1.2f && - hit.point.y >= transform.position.y - 1.1f && - !AnythingAbovePositionIgnoreObject( + if ( + b.Contains(hit.point) + && hit.point.y < transform.position.y + 1.2f + && hit.point.y >= transform.position.y - 1.1f + && !AnythingAbovePositionIgnoreObject( hit.point + new Vector3(0f, -0.01f, 0f), 0.02f, layerMask, - hit.collider.transform.gameObject) + hit.collider.transform.gameObject + ) ) { - SimObjPhysics hitSimObj = hit.transform.gameObject.GetComponent(); + SimObjPhysics hitSimObj = + hit.transform.gameObject.GetComponent(); if (hitSimObj == null || hitSimObj.ObjectID.Split('|')[0] != prefab) { - Vector3 halfExtents = new Vector3(xExtent / 2.1f, yExtent / 2.1f, zExtent / 2.1f); + Vector3 halfExtents = new Vector3( + xExtent / 2.1f, + yExtent / 2.1f, + zExtent / 2.1f + ); Vector3 center = hit.point + objCenterRelPos + yOffset; - Collider[] colliders = Physics.OverlapBox(center, halfExtents, Quaternion.identity, layerMask); + Collider[] colliders = Physics.OverlapBox( + center, + halfExtents, + Quaternion.identity, + layerMask + ); if (colliders.Length == 0) { k++; - SimObjPhysics newObj = script.SpawnObject(prefab, false, objectVariation, center - objCenterRelPos, transform.eulerAngles, false, true); + SimObjPhysics newObj = script.SpawnObject( + prefab, + false, + objectVariation, + center - objCenterRelPos, + transform.eulerAngles, + false, + true + ); if (prefab == "Cup") { - foreach (Collider c in newObj.GetComponentsInChildren()) { + foreach ( + Collider c in newObj.GetComponentsInChildren() + ) { c.enabled = false; } - newObj.GetComponentInChildren().gameObject.AddComponent(); + newObj + .GetComponentInChildren() + .gameObject.AddComponent(); } newObjects.Add(newObj); } @@ -7261,7 +8435,6 @@ public void CoverSurfacesWith(ServerAction action) { StartCoroutine(CoverSurfacesWithHelper(100, newObjects, reachablePositions)); } - public void NumberOfPositionsObjectsOfTypeAreVisibleFrom( string objectType, Vector3[] positions @@ -7281,7 +8454,6 @@ Vector3[] positions } #endif - List objectsOfType = new List(); foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) { if (sop.Type.ToString().ToLower() == objectType.ToLower()) { @@ -7295,7 +8467,11 @@ Vector3[] positions sop.gameObject.SetActive(true); objectIdToPositionsVisibleFrom.Add( sop.ObjectID, - numVisiblePositions(objectId: sop.ObjectID, markActionFinished: false, positions: positions) + numVisiblePositions( + objectId: sop.ObjectID, + markActionFinished: false, + positions: positions + ) ); #if UNITY_EDITOR @@ -7317,7 +8493,9 @@ private IEnumerator SpamObjectsInRoomHelper(int n, List newObject yield return null; } - Collider[] fpsControllerColliders = GameObject.Find("FPSController").GetComponentsInChildren(); + Collider[] fpsControllerColliders = GameObject + .Find("FPSController") + .GetComponentsInChildren(); foreach (SimObjPhysics so in newObjects) { so.GetComponentInChildren().isKinematic = true; foreach (Collider c1 in so.GetComponentsInChildren()) { @@ -7330,17 +8508,11 @@ private IEnumerator SpamObjectsInRoomHelper(int n, List newObject actionFinished(true); } + public void SpamObjectsInRoom(int randomSeed = 0) { UnityEngine.Random.InitState(randomSeed); - string[] objectTypes = { - "Bread", - "Cup", - "Footstool", - "Knife", - "Plunger", - "Tomato", - }; + string[] objectTypes = { "Bread", "Cup", "Footstool", "Knife", "Plunger", "Tomato", }; int numObjectVariations = 3; Bounds b = UtilityFunctions.CreateEmptyBounds(); @@ -7358,7 +8530,8 @@ public void SpamObjectsInRoom(int randomSeed = 0) { ); float yMax = b.max.y - 0.2f; - InstantiatePrefabTest script = physicsSceneManager.GetComponent(); + InstantiatePrefabTest script = + physicsSceneManager.GetComponent(); List objsBounds = new List(); List objsCenterRelPos = new List(); @@ -7417,7 +8590,13 @@ public void SpamObjectsInRoom(int randomSeed = 0) { // var zsToTryArray = zsToTry.ToArray(); List newObjects = new List(); - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); // int attempts = 0; for (int i = 0; i < xsToTryArray.Length; i++) { if (newObjects.Count >= 100) { @@ -7440,7 +8619,11 @@ public void SpamObjectsInRoom(int randomSeed = 0) { Bounds ob = objsBounds[objectInd]; Vector3 randRotation = new Vector3(0.0f, 0.0f, 0.0f); if (UnityEngine.Random.value < 0.5f) { - randRotation = new Vector3(UnityEngine.Random.value * 360f, UnityEngine.Random.value * 360f, UnityEngine.Random.value * 360f); + randRotation = new Vector3( + UnityEngine.Random.value * 360f, + UnityEngine.Random.value * 360f, + UnityEngine.Random.value * 360f + ); } // Debug.Log(UnityEngine.Random.rotationUniform.ToEulerAngles()); @@ -7448,10 +8631,12 @@ public void SpamObjectsInRoom(int randomSeed = 0) { objectTypes[objectInd], false, objectVar, - hit.point + new Vector3(0f, ob.extents.y + 0.05f, 0f) - objsCenterRelPos[objectInd], + hit.point + + new Vector3(0f, ob.extents.y + 0.05f, 0f) + - objsCenterRelPos[objectInd], randRotation, // UnityEngine.Random.rotationUniform.ToEulerAngles(), - // transform.eulerAngles, + // transform.eulerAngles, false, false ); @@ -7460,10 +8645,17 @@ public void SpamObjectsInRoom(int randomSeed = 0) { objectTypes[objectInd], false, objectVar, - hit.point + new Vector3(0f, Math.Max(ob.extents.z, Math.Max(ob.extents.x, ob.extents.y)) + 0.05f, 0f) - objsCenterRelPos[objectInd], + hit.point + + new Vector3( + 0f, + Math.Max(ob.extents.z, Math.Max(ob.extents.x, ob.extents.y)) + + 0.05f, + 0f + ) + - objsCenterRelPos[objectInd], randRotation, // UnityEngine.Random.rotationUniform.ToEulerAngles(), - // transform.eulerAngles, + // transform.eulerAngles, false, false ); @@ -7475,7 +8667,9 @@ public void SpamObjectsInRoom(int randomSeed = 0) { foreach (Collider c in newObj.GetComponentsInChildren()) { c.enabled = false; } - newObj.GetComponentInChildren().gameObject.AddComponent(); + newObj + .GetComponentInChildren() + .gameObject.AddComponent(); } } } @@ -7502,33 +8696,46 @@ public void SliceObject(ServerAction action) { SimObjPhysics target = null; if (action.objectId == null) { - target = getInteractableSimObjectFromXY(x: action.x, y: action.y, forceAction: action.forceAction); + target = getInteractableSimObjectFromXY( + x: action.x, + y: action.y, + forceAction: action.forceAction + ); } else { - target = getInteractableSimObjectFromId(objectId: action.objectId, forceAction: action.forceAction); + target = getInteractableSimObjectFromId( + objectId: action.objectId, + forceAction: action.forceAction + ); } // we found it! if (target) { - if (ItemInHand != null) { if (target.transform == ItemInHand.transform) { - errorMessage = "target object cannot be sliced if it is in the agent's hand"; + errorMessage = + "target object cannot be sliced if it is in the agent's hand"; actionFinished(false); return; } } - if (target.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeSliced)) { + if ( + target + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBeSliced + ) + ) { target.GetComponent().Slice(); actionFinished(true); return; } else { - errorMessage = target.transform.name + " Does not have the CanBeSliced property!"; + errorMessage = + target.transform.name + " Does not have the CanBeSliced property!"; actionFinished(false); return; } } - // target not found in currently visible objects, report not found else { errorMessage = "object not found: " + action.objectId; @@ -7543,21 +8750,39 @@ public void BreakObject(ServerAction action) { SimObjPhysics target = null; if (action.objectId == null) { - target = getInteractableSimObjectFromXY(x: action.x, y: action.y, forceAction: action.forceAction); + target = getInteractableSimObjectFromXY( + x: action.x, + y: action.y, + forceAction: action.forceAction + ); } else { - target = getInteractableSimObjectFromId(objectId: action.objectId, forceAction: action.forceAction); + target = getInteractableSimObjectFromId( + objectId: action.objectId, + forceAction: action.forceAction + ); } // we found it! if (target) { - if (target.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBreak)) { + if ( + target + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBreak) + ) { SimObjPhysics targetsop = target.GetComponent(); // if the object is in the agent's hand, we need to reset the agent hand booleans and other cleanup as well if (targetsop.isInAgentHand) { // if the target is also a Receptacle, drop contained objects first - if (targetsop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { + if ( + targetsop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.Receptacle + ) + ) { // drop contained objects as well - targetsop.DropContainedObjects(reparentContainedObjects: true, forceKinematic: false); + targetsop.DropContainedObjects( + reparentContainedObjects: true, + forceKinematic: false + ); } targetsop.isInAgentHand = false; @@ -7575,7 +8800,6 @@ public void BreakObject(ServerAction action) { return; } } - // target not found in currently visible objects, report not found else { errorMessage = "object not found: " + action.objectId; @@ -7589,10 +8813,12 @@ public void SpawnDirt( bool forceAction = true, int randomSeed = 0, DirtSpawnPosition[] spawnPositions = null - ) { - - SimObjPhysics target = getInteractableSimObjectFromId(objectId: objectId, forceAction: forceAction); - + ) { + SimObjPhysics target = getInteractableSimObjectFromId( + objectId: objectId, + forceAction: forceAction + ); + if (target == null) { throw new ArgumentNullException(); } @@ -7608,7 +8834,7 @@ public void SpawnDirt( public void GetDirtCoordinateBounds(string objectId) { DirtCoordinateBounds toReturn = null; SimObjPhysics target = getInteractableSimObjectFromId(objectId: objectId, true); - + if (target == null) { throw new ArgumentNullException(); } @@ -7627,13 +8853,24 @@ public void DirtyObject(ServerAction action) { SimObjPhysics target = null; if (action.objectId == null) { - target = getInteractableSimObjectFromXY(x: action.x, y: action.y, forceAction: action.forceAction); + target = getInteractableSimObjectFromXY( + x: action.x, + y: action.y, + forceAction: action.forceAction + ); } else { - target = getInteractableSimObjectFromId(objectId: action.objectId, forceAction: action.forceAction); + target = getInteractableSimObjectFromId( + objectId: action.objectId, + forceAction: action.forceAction + ); } if (target) { - if (target.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeDirty)) { + if ( + target + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeDirty) + ) { Dirty dirt = target.GetComponent(); if (dirt.IsDirty() == false) { dirt.ToggleCleanOrDirty(); @@ -7662,13 +8899,24 @@ public void CleanObject(ServerAction action) { SimObjPhysics target = null; if (action.objectId == null) { - target = getInteractableSimObjectFromXY(x: action.x, y: action.y, forceAction: action.forceAction); + target = getInteractableSimObjectFromXY( + x: action.x, + y: action.y, + forceAction: action.forceAction + ); } else { - target = getInteractableSimObjectFromId(objectId: action.objectId, forceAction: action.forceAction); + target = getInteractableSimObjectFromId( + objectId: action.objectId, + forceAction: action.forceAction + ); } if (target) { - if (target.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeDirty)) { + if ( + target + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeDirty) + ) { Dirty dirt = target.GetComponent(); if (dirt.IsDirty()) { dirt.ToggleCleanOrDirty(); @@ -7698,9 +8946,16 @@ public void FillObjectWithLiquid(ServerAction action) { SimObjPhysics target = null; if (action.objectId == null) { - target = getInteractableSimObjectFromXY(x: action.x, y: action.y, forceAction: action.forceAction); + target = getInteractableSimObjectFromXY( + x: action.x, + y: action.y, + forceAction: action.forceAction + ); } else { - target = getInteractableSimObjectFromId(objectId: action.objectId, forceAction: action.forceAction); + target = getInteractableSimObjectFromId( + objectId: action.objectId, + forceAction: action.forceAction + ); } if (action.fillLiquid == null) { @@ -7714,8 +8969,14 @@ public void FillObjectWithLiquid(ServerAction action) { throw new ArgumentException("object not found: " + action.objectId); } - if (!target.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeFilled)) { - throw new ArgumentException(target.transform.name + " does not have CanBeFilled property!"); + if ( + !target + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeFilled) + ) { + throw new ArgumentException( + target.transform.name + " does not have CanBeFilled property!" + ); } Fill fil = target.GetComponent(); @@ -7740,13 +9001,26 @@ public void EmptyLiquidFromObject(ServerAction action) { SimObjPhysics target = null; if (action.objectId == null) { - target = getInteractableSimObjectFromXY(x: action.x, y: action.y, forceAction: action.forceAction); + target = getInteractableSimObjectFromXY( + x: action.x, + y: action.y, + forceAction: action.forceAction + ); } else { - target = getInteractableSimObjectFromId(objectId: action.objectId, forceAction: action.forceAction); + target = getInteractableSimObjectFromId( + objectId: action.objectId, + forceAction: action.forceAction + ); } if (target) { - if (target.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeFilled)) { + if ( + target + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBeFilled + ) + ) { Fill fil = target.GetComponent(); if (fil.IsFilled()) { @@ -7777,13 +9051,26 @@ public void UseUpObject(ServerAction action) { SimObjPhysics target = null; if (action.objectId == null) { - target = getInteractableSimObjectFromXY(x: action.x, y: action.y, forceAction: action.forceAction); + target = getInteractableSimObjectFromXY( + x: action.x, + y: action.y, + forceAction: action.forceAction + ); } else { - target = getInteractableSimObjectFromId(objectId: action.objectId, forceAction: action.forceAction); + target = getInteractableSimObjectFromId( + objectId: action.objectId, + forceAction: action.forceAction + ); } if (target) { - if (target.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeUsedUp)) { + if ( + target + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBeUsedUp + ) + ) { UsedUp u = target.GetComponent(); // make sure object is not already used up @@ -7812,22 +9099,25 @@ public void GetScenesInBuild() { int sceneCount = UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; string[] scenes = new string[sceneCount]; for (int i = 0; i < sceneCount; i++) { - scenes[i] = System.IO.Path.GetFileNameWithoutExtension(UnityEngine.SceneManagement.SceneUtility.GetScenePathByBuildIndex(i)); + scenes[i] = System.IO.Path.GetFileNameWithoutExtension( + UnityEngine.SceneManagement.SceneUtility.GetScenePathByBuildIndex(i) + ); } actionFinished(true, scenes); } protected bool objectIsOfIntoType(SimObjPhysics so) { - return so.ReceptacleTriggerBoxes != null && - so.ReceptacleTriggerBoxes.Length != 0 && - !so.ObjectID.Contains("Table") && // Don't include table tops, counter tops, etc. - !so.ObjectID.Contains("Counter") && - !so.ObjectID.Contains("Top") && - !so.ObjectID.Contains("Burner") && - !so.ObjectID.Contains("Chair") && - !so.ObjectID.Contains("Sofa") && - !so.ObjectID.Contains("Shelf") && - !so.ObjectID.Contains("Ottoman"); + return so.ReceptacleTriggerBoxes != null + && so.ReceptacleTriggerBoxes.Length != 0 + && !so.ObjectID.Contains("Table") + && // Don't include table tops, counter tops, etc. + !so.ObjectID.Contains("Counter") + && !so.ObjectID.Contains("Top") + && !so.ObjectID.Contains("Burner") + && !so.ObjectID.Contains("Chair") + && !so.ObjectID.Contains("Sofa") + && !so.ObjectID.Contains("Shelf") + && !so.ObjectID.Contains("Ottoman"); } public void ToggleColorIntoTypeReceptacleFloors() { @@ -7847,14 +9137,22 @@ public void ToggleColorIntoTypeReceptacleFloors() { newParent.transform.parent = topLevelObject.transform; } - int layerMask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); foreach (SimObjPhysics so in physicsSceneManager.ObjectIdToSimObjPhysics.Values) { if (objectIsOfIntoType(so)) { foreach (GameObject rtb in so.ReceptacleTriggerBoxes) { Quaternion oldRotation = rtb.transform.rotation; Vector3 euler = oldRotation.eulerAngles; - rtb.transform.rotation = Quaternion.Euler(new Vector3(euler.x, 0f, euler.z)); + rtb.transform.rotation = Quaternion.Euler( + new Vector3(euler.x, 0f, euler.z) + ); BoxCollider bc = rtb.GetComponent(); Bounds b = bc.bounds; rtb.transform.rotation = oldRotation; @@ -7863,26 +9161,48 @@ public void ToggleColorIntoTypeReceptacleFloors() { yOffsets.Add(b.extents.y - 0.01f); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { - Vector3 start = b.center + new Vector3(i * b.extents.x / 3f, b.extents.y - 0.001f, j * b.extents.z / 3f); - foreach (RaycastHit hit in Physics.RaycastAll(start, -transform.up, 10f, layerMask)) { - if (NormalIsApproximatelyUp(hit.normal) && - ancestorSimObjPhysics(hit.transform.gameObject) == so) { - yOffsets.Add((float)Math.Round(hit.distance - b.extents.y - 0.005f, 3)); + Vector3 start = + b.center + + new Vector3( + i * b.extents.x / 3f, + b.extents.y - 0.001f, + j * b.extents.z / 3f + ); + foreach ( + RaycastHit hit in Physics.RaycastAll( + start, + -transform.up, + 10f, + layerMask + ) + ) { + if ( + NormalIsApproximatelyUp(hit.normal) + && ancestorSimObjPhysics(hit.transform.gameObject) == so + ) { + yOffsets.Add( + (float) + Math.Round(hit.distance - b.extents.y - 0.005f, 3) + ); } } } } foreach (float yOffset in yOffsets) { - GameObject plane = Instantiate( - Resources.Load("BluePlane") as GameObject, - new Vector3(0f, 0f, 0f), - Quaternion.identity - ) as GameObject; + GameObject plane = + Instantiate( + Resources.Load("BluePlane") as GameObject, + new Vector3(0f, 0f, 0f), + Quaternion.identity + ) as GameObject; plane.transform.parent = newParent.transform; plane.transform.localScale = 0.1f * 2f * b.extents; - plane.transform.rotation = Quaternion.Euler(new Vector3(0f, euler.y, 0f)); // oldRotation; - plane.transform.position = bc.bounds.center + new Vector3(0f, -yOffset, 0f); + plane.transform.rotation = Quaternion.Euler( + new Vector3(0f, euler.y, 0f) + ); // oldRotation; + plane.transform.position = + bc.bounds.center + new Vector3(0f, -yOffset, 0f); } } } @@ -7890,4 +9210,4 @@ public void ToggleColorIntoTypeReceptacleFloors() { actionFinished(true); } } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/PhysicsSceneManager.cs b/unity/Assets/Scripts/PhysicsSceneManager.cs index 42daa61a76..5f90056326 100644 --- a/unity/Assets/Scripts/PhysicsSceneManager.cs +++ b/unity/Assets/Scripts/PhysicsSceneManager.cs @@ -1,36 +1,32 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; +using System.Linq; using UnityEngine; +using UnityEngine.SceneManagement; // using UnityEditor; // using System.Linq; using UnityStandardAssets.Characters.FirstPerson; -using System; -using System.Linq; using UnityStandardAssets.ImageEffects; -using UnityEngine.SceneManagement; [ExecuteInEditMode] - public class PhysicsSimulationParams { public bool autoSimulation = false; public float fixedDeltaTime = 0.02f; public float minSimulateTimeSeconds = 0; public bool syncTransformsAfterAction = false; + // public int maxActionPhysicsSteps = int.MaxValue; public override bool Equals(object p) { - - if (p is null) - { + if (p is null) { return false; } - if (object.ReferenceEquals(this, p)) - { + if (object.ReferenceEquals(this, p)) { return true; } - if (this.GetType() != p.GetType()) - { + if (this.GetType() != p.GetType()) { return false; } var otherPhysicsParams = p as PhysicsSimulationParams; @@ -49,7 +45,8 @@ public class PhysicsSceneManager : MonoBehaviour { // get references to the spawned Required objects after spawning them for the first time. public List SpawnedObjects = new List(); - public Dictionary ObjectIdToSimObjPhysics = new Dictionary(); + public Dictionary ObjectIdToSimObjPhysics = + new Dictionary(); public GameObject HideAndSeek; public GameObject[] ManipulatorTables; public GameObject[] ManipulatorReceptacles; @@ -86,33 +83,27 @@ public class PhysicsSceneManager : MonoBehaviour { public GameObject receptaclesDirtyDecalSurface; - public static PhysicsSimulationParams defaultPhysicsSimulationParams { - get; - private set; - } + public static PhysicsSimulationParams defaultPhysicsSimulationParams { get; private set; } protected PhysicsSimulationParams previousPhysicsSimulationParams; - public static PhysicsSimulationParams physicsSimulationParams { - get; - private set; - } + public static PhysicsSimulationParams physicsSimulationParams { get; private set; } public static float fixedDeltaTime { get { return physicsSimulationParams.fixedDeltaTime; } - private set { - return; - } + private set { return; } } - void Awake() { + void Awake() { SetDefaultSimulationParams(new PhysicsSimulationParams()); - } + } private void OnEnable() { // must do this here instead of Start() since OnEnable gets triggered prior to Start // when the component is enabled. - agentManager = GameObject.Find("PhysicsSceneManager").GetComponentInChildren(); + agentManager = GameObject + .Find("PhysicsSceneManager") + .GetComponentInChildren(); // clear this on start so that the CheckForDuplicates function doesn't check pre-existing lists SetupScene(); @@ -140,9 +131,12 @@ void Start() { GatherAllRBsInScene(); } - public static void SetDefaultSimulationParams(PhysicsSimulationParams defaultPhysicsSimulationParams) { - PhysicsSceneManager.defaultPhysicsSimulationParams = defaultPhysicsSimulationParams;// ?? new PhysicsSimulationParams(); - PhysicsSceneManager.physicsSimulationParams = PhysicsSceneManager.defaultPhysicsSimulationParams; + public static void SetDefaultSimulationParams( + PhysicsSimulationParams defaultPhysicsSimulationParams + ) { + PhysicsSceneManager.defaultPhysicsSimulationParams = defaultPhysicsSimulationParams; // ?? new PhysicsSimulationParams(); + PhysicsSceneManager.physicsSimulationParams = + PhysicsSceneManager.defaultPhysicsSimulationParams; } public static void SetPhysicsSimulationParams(PhysicsSimulationParams physicsSimulationParams) { @@ -155,21 +149,27 @@ public static void PhysicsSimulateTHOR(float deltaTime) { PhysicsSceneManager.PhysicsSimulateCallCount++; } - public static ActionFinished ExpandIEnumerator(IEnumerator enumerator, PhysicsSimulationParams physicsSimulationParams) { + public static ActionFinished ExpandIEnumerator( + IEnumerator enumerator, + PhysicsSimulationParams physicsSimulationParams + ) { ActionFinished actionFinished = null; while (enumerator.MoveNext()) { if (enumerator.Current == null) { continue; } - + // ActionFinished was found but enumerator keeps moving forward, throw error if (actionFinished != null) { // Premature ActionFinished, same as yield break, stops iterator evaluation break; } - if (enumerator.Current.GetType() == typeof(WaitForFixedUpdate) && !physicsSimulationParams.autoSimulation) { + if ( + enumerator.Current.GetType() == typeof(WaitForFixedUpdate) + && !physicsSimulationParams.autoSimulation + ) { // TODO: is this still used? if (physicsSimulationParams.fixedDeltaTime == 0f) { Physics.SyncTransforms(); @@ -185,36 +185,47 @@ public static ActionFinished ExpandIEnumerator(IEnumerator enumerator, PhysicsSi // Though C# compiler should handle it and MoveNext should recursively call MoveNext and set Current, but does not seem to work // so we manually expand iterators depth first else if (typeof(IEnumerator).IsAssignableFrom(enumerator.Current.GetType())) { - actionFinished = PhysicsSceneManager.ExpandIEnumerator(enumerator.Current as IEnumerator, physicsSimulationParams); + actionFinished = PhysicsSceneManager.ExpandIEnumerator( + enumerator.Current as IEnumerator, + physicsSimulationParams + ); } PhysicsSceneManager.IteratorExpandCount++; } return actionFinished; } - public static ActionFinished RunSimulatePhysicsForAction(IEnumerator enumerator, PhysicsSimulationParams physicsSimulationParams) { + public static ActionFinished RunSimulatePhysicsForAction( + IEnumerator enumerator, + PhysicsSimulationParams physicsSimulationParams + ) { var fixedDeltaTime = physicsSimulationParams.fixedDeltaTime; var previousAutoSimulate = Physics.autoSimulation; Physics.autoSimulation = physicsSimulationParams.autoSimulation; - + PhysicsSceneManager.PhysicsSimulateTimeSeconds = 0.0f; var startPhysicsSimulateCallTime = PhysicsSceneManager.PhysicsSimulateCallCount; PhysicsSceneManager.IteratorExpandCount = 0; // Recursive expansion of IEnumerator ActionFinished actionFinished = ExpandIEnumerator(enumerator, physicsSimulationParams); - + if (actionFinished == null) { throw new MissingActionFinishedException(); } - PhysicsSceneManager.LastPhysicsSimulateCallCount = PhysicsSceneManager.PhysicsSimulateCallCount - startPhysicsSimulateCallTime; - - if (!physicsSimulationParams.autoSimulation && physicsSimulationParams.minSimulateTimeSeconds > 0.0f) { + PhysicsSceneManager.LastPhysicsSimulateCallCount = + PhysicsSceneManager.PhysicsSimulateCallCount - startPhysicsSimulateCallTime; + + if ( + !physicsSimulationParams.autoSimulation + && physicsSimulationParams.minSimulateTimeSeconds > 0.0f + ) { // Because of floating point precision const float eps = 1e-5f; while ( - PhysicsSceneManager.PhysicsSimulateTimeSeconds <= (physicsSimulationParams.minSimulateTimeSeconds - eps) + PhysicsSceneManager.PhysicsSimulateTimeSeconds + <= (physicsSimulationParams.minSimulateTimeSeconds - eps) ) { PhysicsSceneManager.PhysicsSimulateTHOR(fixedDeltaTime); } @@ -228,7 +239,11 @@ public static ActionFinished RunSimulatePhysicsForAction(IEnumerator enumerator, return actionFinished; } - public static IEnumerator RunActionForCoroutine(ActionInvokable target, IEnumerator action, PhysicsSimulationParams physicsSimulationParams) { + public static IEnumerator RunActionForCoroutine( + ActionInvokable target, + IEnumerator action, + PhysicsSimulationParams physicsSimulationParams + ) { var fixedDeltaTime = physicsSimulationParams.fixedDeltaTime; var previousFixedDeltaTime = Time.fixedDeltaTime; Time.fixedDeltaTime = fixedDeltaTime; @@ -241,13 +256,12 @@ public static IEnumerator RunActionForCoroutine(ActionInvokable target, IEnumera if (!action.MoveNext()) { break; } - } - catch (Exception e) { - actionFinished = new ActionFinished() { + } catch (Exception e) { + actionFinished = new ActionFinished() { success = false, errorMessage = $"{e.GetType()}: {e.StackTrace}", errorCode = ServerActionErrorCode.UnhandledException - }; + }; // Calling InnerException throws exception so avoid that if we want to continue // actionFinished = new ActionFinished() { @@ -257,16 +271,16 @@ public static IEnumerator RunActionForCoroutine(ActionInvokable target, IEnumera // }; break; } - + if (action.Current != null && typeof(ActionFinished) == action.Current.GetType()) { actionFinished = (ActionFinished)(action.Current as ActionFinished); break; } yield return action.Current; } - + // For the coroutine path we can't throw an exception because there is no way to catch it - // as it's ran by unity's code + // as it's ran by unity's code // if (actionFinished == null) { // throw new MissingActionFinishedException(); // } @@ -279,23 +293,25 @@ public static IEnumerator RunActionForCoroutine(ActionInvokable target, IEnumera var actionFixedTime = Time.fixedTime - startFixedTimeSeconds; const float eps = 1e-5f; - - while (actionFixedTime <= (physicsSimulationParams.minSimulateTimeSeconds- eps)) { + + while (actionFixedTime <= (physicsSimulationParams.minSimulateTimeSeconds - eps)) { yield return new WaitForFixedUpdate(); actionFixedTime += fixedDeltaTime; } - + if (physicsSimulationParams.syncTransformsAfterAction) { Physics.SyncTransforms(); } target.Complete(actionFinished); - + Time.fixedDeltaTime = previousFixedDeltaTime; } // Returns previous parameters - public static PhysicsSimulationParams applyPhysicsSimulationParams(PhysicsSimulationParams physicsSimulationParams) { + public static PhysicsSimulationParams applyPhysicsSimulationParams( + PhysicsSimulationParams physicsSimulationParams + ) { return new PhysicsSimulationParams() { autoSimulation = Physics.autoSimulation, fixedDeltaTime = Time.fixedDeltaTime @@ -322,7 +338,9 @@ void LateUpdate() { if (rb.GetComponentInParent() && rb.transform.gameObject.activeSelf) { SimObjPhysics sop = rb.GetComponentInParent(); - float currentVelocity = Math.Abs(rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude); + float currentVelocity = Math.Abs( + rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude + ); float accel = (currentVelocity - sop.lastVelocity) / Time.fixedDeltaTime; if (Mathf.Abs(accel) <= 0.0001f) { @@ -342,7 +360,9 @@ void LateUpdate() { // this rigidbody is not a SimOBject, and might be a piece of a shattered sim object spawned in, or something if (rb.transform.gameObject.activeSelf) { // is the rigidbody at non zero velocity? then the scene is not at rest - if (Math.Abs(rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude) >= 0.01) { + if ( + Math.Abs(rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude) >= 0.01 + ) { isSceneAtRest = false; // make sure the rb's drag values are not at 0 exactly // if (rb.drag < 0.1f) @@ -405,15 +425,21 @@ public void ResetObjectIdToSimObjPhysics() { public void MakeAllObjectsMoveable() { foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) { // check if the sopType is something that can be hung - if (sop.Type == SimObjType.Towel || sop.Type == SimObjType.HandTowel || sop.Type == SimObjType.ToiletPaper) { + if ( + sop.Type == SimObjType.Towel + || sop.Type == SimObjType.HandTowel + || sop.Type == SimObjType.ToiletPaper + ) { // if this object is actively hung on its corresponding object specific receptacle... skip it so it doesn't fall on the floor if (sop.GetComponentInParent()) { continue; } } - if (sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup || - sop.PrimaryProperty == SimObjPrimaryProperty.Moveable) { + if ( + sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup + || sop.PrimaryProperty == SimObjPrimaryProperty.Moveable + ) { Rigidbody rb = sop.GetComponent(); rb.isKinematic = false; rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; @@ -435,7 +461,12 @@ public void GatherSimObjPhysInScene(bool generateObjectIds = true) { // debug in editor, make sure no two object share ids for some reason #if UNITY_EDITOR if (CheckForDuplicateObjectIDs(o)) { - Debug.Log("Yo there are duplicate ObjectIDs! Check" + o.ObjectID + "in scene " + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name); + Debug.Log( + "Yo there are duplicate ObjectIDs! Check" + + o.ObjectID + + "in scene " + + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + ); } else { AddToObjectsInScene(o); continue; @@ -463,7 +494,10 @@ public List GatherAllReceptaclesInScene() { // debug if some of these receptacles were not set up correctly foreach (GameObject go in sop.ReceptacleTriggerBoxes) { if (go == null) { - Debug.LogWarning(sop.gameObject + " has non-empty receptacle trigger boxes but contains a null value."); + Debug.LogWarning( + sop.gameObject + + " has non-empty receptacle trigger boxes but contains a null value." + ); continue; } Contains c = go.GetComponent(); @@ -471,7 +505,10 @@ public List GatherAllReceptaclesInScene() { // c.GetComponent().enabled = false; // c.GetComponent().enabled = true; if (c == null) { - Debug.LogWarning(sop.gameObject + " is missing a contains script on one of its receptacle boxes."); + Debug.LogWarning( + sop.gameObject + + " is missing a contains script on one of its receptacle boxes." + ); continue; } if (go.GetComponent().myParent == null) { @@ -482,7 +519,9 @@ public List GatherAllReceptaclesInScene() { } } - ReceptaclesInScene.Sort((r0, r1) => (r0.gameObject.GetInstanceID().CompareTo(r1.gameObject.GetInstanceID()))); + ReceptaclesInScene.Sort( + (r0, r1) => (r0.gameObject.GetInstanceID().CompareTo(r1.gameObject.GetInstanceID())) + ); return ReceptaclesInScene; } @@ -491,8 +530,12 @@ public void Generate_ObjectID(SimObjPhysics o) { if (ReceptacleRestrictions.UseParentObjectIDasPrefix.Contains(o.Type)) { SimObjPhysics parent = o.transform.parent.GetComponent(); if (parent == null) { - Debug.LogWarning("Object " + o + " requires a SimObjPhysics " + - "parent to create its object ID but none exists. Using 'None' instead."); + Debug.LogWarning( + "Object " + + o + + " requires a SimObjPhysics " + + "parent to create its object ID but none exists. Using 'None' instead." + ); o.ObjectID = "None|" + o.Type.ToString(); return; } @@ -514,11 +557,14 @@ public void Generate_ObjectID(SimObjPhysics o) { string yPos = (pos.y >= 0 ? "+" : "") + pos.y.ToString("00.00"); string zPos = (pos.z >= 0 ? "+" : "") + pos.z.ToString("00.00"); o.ObjectID = o.Type.ToString() + "|" + xPos + "|" + yPos + "|" + zPos; - } // used to create object id for an object created as result of a state change of another object ie: bread - >breadslice1, breadslice 2 etc - public void Generate_InheritedObjectID(SimObjPhysics sourceObject, SimObjPhysics createdObject, int count) { + public void Generate_InheritedObjectID( + SimObjPhysics sourceObject, + SimObjPhysics createdObject, + int count + ) { createdObject.ObjectID = sourceObject.ObjectID + "|" + createdObject.ObjType + "_" + count; AddToObjectsInScene(createdObject); } @@ -553,7 +599,11 @@ public void RemoveFromRequiredObjects(SimObjPhysics sop) { RequiredObjects.Remove(sop.gameObject); } - public bool SetObjectPoses(ObjectPose[] objectPoses, out string errorMessage, bool placeStationary) { + public bool SetObjectPoses( + ObjectPose[] objectPoses, + out string errorMessage, + bool placeStationary + ) { SetupScene(); errorMessage = ""; bool shouldFail = false; @@ -563,13 +613,14 @@ public bool SetObjectPoses(ObjectPose[] objectPoses, out string errorMessage, bo SimObjPhysics[] sceneObjects = FindObjectsOfType(); // this will contain all pickupable and moveable objects currently in the scene - Dictionary nameToObject = new Dictionary(); - Dictionary isStaticNameToObject = new Dictionary(); + Dictionary nameToObject = + new Dictionary(); + Dictionary isStaticNameToObject = + new Dictionary(); // get all sim objects in scene that are either pickupable or moveable and prepare them to be repositioned, cloned, or disabled foreach (SimObjPhysics sop in sceneObjects) { - - // note that any moveable or pickupable sim objects not explicitly passed in via objectPoses + // note that any moveable or pickupable sim objects not explicitly passed in via objectPoses // will be disabled since we SetActive(false) if (sop.IsPickupable || sop.IsMoveable) { sop.gameObject.SetActive(false); @@ -587,18 +638,26 @@ public bool SetObjectPoses(ObjectPose[] objectPoses, out string errorMessage, bo ObjectPose objectPose = objectPoses[ii]; if (!nameToObject.ContainsKey(objectPose.objectName)) { - errorMessage = "No Pickupable or Moveable object of name " + objectPose.objectName + " found in scene."; + errorMessage = + "No Pickupable or Moveable object of name " + + objectPose.objectName + + " found in scene."; Debug.Log(errorMessage); shouldFail = true; continue; } if (isStaticNameToObject.ContainsKey(objectPose.objectName)) { - errorMessage = objectPose.objectName + " is not a Moveable or Pickupable object. SetObjectPoses only works with Moveable and Pickupable sim objects."; + errorMessage = + objectPose.objectName + + " is not a Moveable or Pickupable object. SetObjectPoses only works with Moveable and Pickupable sim objects."; Debug.Log(errorMessage); shouldFail = true; continue; } - if (!nameToObject.ContainsKey(objectPose.objectName) && !isStaticNameToObject.ContainsKey(objectPose.objectName)) { + if ( + !nameToObject.ContainsKey(objectPose.objectName) + && !isStaticNameToObject.ContainsKey(objectPose.objectName) + ) { errorMessage = objectPose.objectName + " does not exist in scene."; shouldFail = true; continue; @@ -624,7 +683,8 @@ public bool SetObjectPoses(ObjectPose[] objectPoses, out string errorMessage, bo copy.gameObject.transform.parent = topObject.transform; if (placeStationary) { - copy.GetComponent().collisionDetectionMode = CollisionDetectionMode.Discrete; + copy.GetComponent().collisionDetectionMode = + CollisionDetectionMode.Discrete; copy.GetComponent().isKinematic = true; } else { copy.GetComponent().isKinematic = false; @@ -636,12 +696,17 @@ public bool SetObjectPoses(ObjectPose[] objectPoses, out string errorMessage, bo } public System.Collections.Generic.IEnumerator GetValidReceptaclesForSimObj( - SimObjPhysics simObj, List receptaclesInScene + SimObjPhysics simObj, + List receptaclesInScene ) { SimObjType goObjType = simObj.ObjType; - bool typeFoundInDictionary = ReceptacleRestrictions.PlacementRestrictions.ContainsKey(goObjType); + bool typeFoundInDictionary = ReceptacleRestrictions.PlacementRestrictions.ContainsKey( + goObjType + ); if (typeFoundInDictionary) { - List typesOfObjectsPrefabIsAllowedToSpawnIn = new List(ReceptacleRestrictions.PlacementRestrictions[goObjType]); + List typesOfObjectsPrefabIsAllowedToSpawnIn = new List( + ReceptacleRestrictions.PlacementRestrictions[goObjType] + ); // remove from list if receptacle isn't in this scene // compare to receptacles that exist in scene, get the ones that are the same @@ -667,7 +732,7 @@ public System.Collections.Generic.IEnumerator GetValidReceptacles // @maxPlacementAttempts - the max number of times an object will attempt to be placed in within a receptacle // @StaticPlacement - set to true if objects should be placed so they don't roll around after being repositioned // @numDuplicatesOfType - used to duplicate the first instance of an object type found in a scene - // @excludedReceptacles - + // @excludedReceptacles - public bool RandomSpawnRequiredSceneObjects( int seed, bool spawnOnlyOutside, @@ -717,9 +782,11 @@ bool allowMoveable if (SpawnedObjects.Count > 0) { HowManyCouldntSpawn = SpawnedObjects.Count; - Dictionary> typeToObjectList = new Dictionary>(); + Dictionary> typeToObjectList = + new Dictionary>(); - Dictionary requestedNumDuplicatesOfType = new Dictionary(); + Dictionary requestedNumDuplicatesOfType = + new Dictionary(); // List listOfExcludedReceptacles = new List(); HashSet originalObjects = new HashSet(SpawnedObjects); @@ -728,7 +795,8 @@ bool allowMoveable } foreach (ObjectTypeCount repeatCount in numDuplicatesOfType) { - SimObjType objType = (SimObjType)System.Enum.Parse(typeof(SimObjType), repeatCount.objectType); + SimObjType objType = (SimObjType) + System.Enum.Parse(typeof(SimObjType), repeatCount.objectType); requestedNumDuplicatesOfType[objType] = repeatCount.count; } @@ -743,8 +811,12 @@ bool allowMoveable } // Add this sim object to the list if the sim object's type matches the key in typeToObjectList - if (!requestedNumDuplicatesOfType.ContainsKey(sop.ObjType) || - (typeToObjectList[sop.ObjType].Count < requestedNumDuplicatesOfType[sop.ObjType]) + if ( + !requestedNumDuplicatesOfType.ContainsKey(sop.ObjType) + || ( + typeToObjectList[sop.ObjType].Count + < requestedNumDuplicatesOfType[sop.ObjType] + ) ) { typeToObjectList[sop.ObjType].Add(sop); } @@ -760,19 +832,23 @@ bool allowMoveable foreach (SimObjType sopType in typeToObjectList.Keys) { // we found a matching SimObjType and the requested count of duplicates is bigger than how many of that // object are currently in the scene - if (requestedNumDuplicatesOfType.ContainsKey(sopType) && - requestedNumDuplicatesOfType[sopType] > typeToObjectList[sopType].Count + if ( + requestedNumDuplicatesOfType.ContainsKey(sopType) + && requestedNumDuplicatesOfType[sopType] > typeToObjectList[sopType].Count ) { foreach (SimObjPhysics sop in typeToObjectList[sopType]) { gameObjsToPlaceInReceptacles.Add(sop.gameObject); } - int numExtra = requestedNumDuplicatesOfType[sopType] - typeToObjectList[sopType].Count; + int numExtra = + requestedNumDuplicatesOfType[sopType] - typeToObjectList[sopType].Count; // let's instantiate the duplicates now for (int j = 0; j < numExtra; j++) { // Add a copy of the item to try and match the requested number of duplicates - SimObjPhysics sop = typeToObjectList[sopType][UnityEngine.Random.Range(0, typeToObjectList[sopType].Count - 1)]; + SimObjPhysics sop = typeToObjectList[sopType][ + UnityEngine.Random.Range(0, typeToObjectList[sopType].Count - 1) + ]; SimObjPhysics copy = Instantiate(original: sop); copy.transform.parent = GameObject.Find("Objects").transform; copy.name += "_random_copy_" + j; @@ -794,15 +870,21 @@ bool allowMoveable gameObjsToPlaceInReceptacles.AddRange(unduplicatedSimObjects); gameObjsToPlaceInReceptacles.Shuffle_(rng); - Dictionary> objTypeToReceptacles = new Dictionary>(); + Dictionary> objTypeToReceptacles = + new Dictionary>(); foreach (SimObjPhysics receptacleSop in GatherAllReceptaclesInScene()) { SimObjType receptType = receptacleSop.ObjType; if ( - (receptacleObjectIds == null || receptacleObjectIds.Contains(receptacleSop.ObjectID)) + ( + receptacleObjectIds == null + || receptacleObjectIds.Contains(receptacleSop.ObjectID) + ) && !excludedReceptacleTypes.Contains(receptacleSop.Type) && ( (!spawnOnlyOutside) - || ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(receptacleSop.ObjType) + || ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains( + receptacleSop.ObjType + ) ) ) { if (!objTypeToReceptacles.ContainsKey(receptacleSop.ObjType)) { @@ -814,7 +896,8 @@ bool allowMoveable InstantiatePrefabTest spawner = gameObject.GetComponent(); foreach (GameObject gameObjToPlaceInReceptacle in gameObjsToPlaceInReceptacles) { - SimObjPhysics sopToPlaceInReceptacle = gameObjToPlaceInReceptacle.GetComponent(); + SimObjPhysics sopToPlaceInReceptacle = + gameObjToPlaceInReceptacle.GetComponent(); if (staticPlacement) { sopToPlaceInReceptacle.GetComponent().isKinematic = true; @@ -825,10 +908,7 @@ bool allowMoveable // } if ( - ( - objectIds != null - && !objectIds.Contains(sopToPlaceInReceptacle.ObjectID) - ) + (objectIds != null && !objectIds.Contains(sopToPlaceInReceptacle.ObjectID)) || excludedSimObjects.Contains(sopToPlaceInReceptacle) ) { HowManyCouldntSpawn--; @@ -836,10 +916,18 @@ bool allowMoveable } bool spawned = false; - foreach (SimObjPhysics receptacleSop in IterShuffleSimObjPhysicsDictList(objTypeToReceptacles, rng)) { + foreach ( + SimObjPhysics receptacleSop in IterShuffleSimObjPhysicsDictList( + objTypeToReceptacles, + rng + ) + ) { List targetReceptacleSpawnPoints; - if (receptacleSop.ContainedGameObjects().Count > 0 && receptacleSop.IsPickupable) { + if ( + receptacleSop.ContainedGameObjects().Count > 0 + && receptacleSop.IsPickupable + ) { //this pickupable object already has something in it, skip over it since we currently can't account for detecting bounds of a receptacle + any contained objects continue; } @@ -847,8 +935,13 @@ bool allowMoveable // check if the target Receptacle is an ObjectSpecificReceptacle // if so, if this game object is compatible with the ObjectSpecific restrictions, place it! // this is specifically for things like spawning a mug inside a coffee maker - if (receptacleSop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.ObjectSpecificReceptacle)) { - ObjectSpecificReceptacle osr = receptacleSop.GetComponent(); + if ( + receptacleSop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.ObjectSpecificReceptacle + ) + ) { + ObjectSpecificReceptacle osr = + receptacleSop.GetComponent(); if (osr.HasSpecificType(sopToPlaceInReceptacle.ObjType)) { // in the random spawn function, we need this additional check because there isn't a chance for @@ -858,22 +951,34 @@ bool allowMoveable break; } - // perform additional checks if this is a Stove Burner! - if (receptacleSop.GetComponent().Type == SimObjType.StoveBurner) { + // perform additional checks if this is a Stove Burner! + if ( + receptacleSop.GetComponent().Type + == SimObjType.StoveBurner + ) { if ( StoveTopCheckSpawnArea( sopToPlaceInReceptacle, osr.attachPoint.transform.position, osr.attachPoint.transform.rotation, - false) == true + false + ) == true ) { // print("moving object now"); - gameObjToPlaceInReceptacle.transform.position = osr.attachPoint.position; - gameObjToPlaceInReceptacle.transform.SetParent(osr.attachPoint.transform); - gameObjToPlaceInReceptacle.transform.localRotation = Quaternion.identity; - - gameObjToPlaceInReceptacle.GetComponent().collisionDetectionMode = CollisionDetectionMode.Discrete; - gameObjToPlaceInReceptacle.GetComponent().isKinematic = true; + gameObjToPlaceInReceptacle.transform.position = + osr.attachPoint.position; + gameObjToPlaceInReceptacle.transform.SetParent( + osr.attachPoint.transform + ); + gameObjToPlaceInReceptacle.transform.localRotation = + Quaternion.identity; + + gameObjToPlaceInReceptacle + .GetComponent() + .collisionDetectionMode = CollisionDetectionMode.Discrete; + gameObjToPlaceInReceptacle + .GetComponent() + .isKinematic = true; HowManyCouldntSpawn--; spawned = true; @@ -881,9 +986,13 @@ bool allowMoveable break; } } else { // for everything else (coffee maker, toilet paper holder, etc) just place it if there is nothing attached - gameObjToPlaceInReceptacle.transform.position = osr.attachPoint.position; - gameObjToPlaceInReceptacle.transform.SetParent(osr.attachPoint.transform); - gameObjToPlaceInReceptacle.transform.localRotation = Quaternion.identity; + gameObjToPlaceInReceptacle.transform.position = + osr.attachPoint.position; + gameObjToPlaceInReceptacle.transform.SetParent( + osr.attachPoint.transform + ); + gameObjToPlaceInReceptacle.transform.localRotation = + Quaternion.identity; Rigidbody rb = gameObjToPlaceInReceptacle.GetComponent(); rb.collisionDetectionMode = CollisionDetectionMode.Discrete; @@ -900,14 +1009,16 @@ bool allowMoveable // first shuffle the list so it's random targetReceptacleSpawnPoints.Shuffle_(rng); - if (spawner.PlaceObjectReceptacle( - targetReceptacleSpawnPoints, - sopToPlaceInReceptacle, - staticPlacement, - maxPlacementAttempts, - 90, - true - )) { + if ( + spawner.PlaceObjectReceptacle( + targetReceptacleSpawnPoints, + sopToPlaceInReceptacle, + staticPlacement, + maxPlacementAttempts, + 90, + true + ) + ) { HowManyCouldntSpawn--; spawned = true; break; @@ -924,7 +1035,6 @@ bool allowMoveable Destroy(gameObjToPlaceInReceptacle); } } - } } else { /// XXX: add exception in at some point @@ -945,22 +1055,39 @@ bool allowMoveable return true; } - // a variation of the CheckSpawnArea logic from InstantiatePrefabTest.cs, but filter out things specifically for stove tops // which are unique due to being placed close together, which can cause objects placed on them to overlap in super weird ways oh // my god it took like 2 days to figure this out it should have been so simple - public bool StoveTopCheckSpawnArea(SimObjPhysics simObj, Vector3 position, Quaternion rotation, bool spawningInHand) { + public bool StoveTopCheckSpawnArea( + SimObjPhysics simObj, + Vector3 position, + Quaternion rotation, + bool spawningInHand + ) { int layermask; // first do a check to see if the area is clear // if spawning in the agent's hand, ignore collisions with the Agent if (spawningInHand) { - layermask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + layermask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); } else { // oh we are spawning it somwhere in the environment, // we do need to make sure not to spawn inside the agent or the environment - layermask = LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0", "Agent"); + layermask = LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0", + "Agent" + ); } // make sure ALL colliders of the simobj are turned off for this check - can't just turn off the Colliders child object because of objects like @@ -995,9 +1122,13 @@ public bool StoveTopCheckSpawnArea(SimObjPhysics simObj, Vector3 position, Quate #endif // we need the center of the box collider in world space, we need the box collider size/2, we need the rotation to set the box at, layermask, querytrigger - Collider[] hitColliders = Physics.OverlapBox(bb.transform.TransformPoint(bbcol.center), - bbcol.size / 2.0f, simObj.transform.rotation, - layermask, QueryTriggerInteraction.Ignore); + Collider[] hitColliders = Physics.OverlapBox( + bb.transform.TransformPoint(bbcol.center), + bbcol.size / 2.0f, + simObj.transform.rotation, + layermask, + QueryTriggerInteraction.Ignore + ); // now check if any of the hit colliders were any object EXCEPT other stove top objects i guess bool result = true; @@ -1100,14 +1231,9 @@ System.Random rng } } - protected static IEnumerator toStandardCoroutineIEnumerator( - IEnumerator enumerator - ) { + protected static IEnumerator toStandardCoroutineIEnumerator(IEnumerator enumerator) { while (enumerator.MoveNext()) { - if ( - (!enumerator.Current.HasValue) - || (enumerator.Current <= 0f) - ) { + if ((!enumerator.Current.HasValue) || (enumerator.Current <= 0f)) { yield return null; } else { yield return new WaitForFixedUpdate(); @@ -1150,7 +1276,7 @@ public void PausePhysicsAutoSim() { physicsSimulationPaused = true; } - // manually advance the physics timestep + // manually advance the physics timestep public void AdvancePhysicsStep( float timeStep = 0.02f, float? simSeconds = null, @@ -1171,7 +1297,9 @@ public void AdvancePhysicsStep( foreach (Rigidbody rb in rbs) { if (rb.GetComponentInParent()) { SimObjPhysics sop = rb.GetComponentInParent(); - sop.lastVelocity = Math.Abs(rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude); + sop.lastVelocity = Math.Abs( + rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude + ); } } } @@ -1204,7 +1332,6 @@ void OnDrawGizmos() { Gizmos.matrix = oldGizmosMatrix; } - } #endif } diff --git a/unity/Assets/Scripts/PlacementManager.cs b/unity/Assets/Scripts/PlacementManager.cs index 66bf896a5f..b885249e50 100644 --- a/unity/Assets/Scripts/PlacementManager.cs +++ b/unity/Assets/Scripts/PlacementManager.cs @@ -1,9 +1,8 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; public class PlacementManager : MonoBehaviour { - public static PlacementManager Current { get { if (current == null) { @@ -42,9 +41,9 @@ ref Vector3 point Vector3 pointDirection = Vector3.zero; Vector3 agentCameraPos = agentCamera.transform.position; if ( - viewPoint.z > 0// in front of camera + viewPoint.z > 0 // in front of camera && viewPoint.x < SimUtil.ViewPointRangeHigh - && viewPoint.x > SimUtil.ViewPointRangeLow// within x bounds + && viewPoint.x > SimUtil.ViewPointRangeLow // within x bounds && viewPoint.y < SimUtil.ViewPointRangeHigh && viewPoint.y > SimUtil.ViewPointRangeLow ) { // within y bounds @@ -59,9 +58,7 @@ ref Vector3 point maxDistance * 2, SimUtil.RaycastVisibleLayerMask, QueryTriggerInteraction.Ignore - ) && ( - Vector3.Distance(pointHit.point, hit.position) < MaxRaycastCheckDistance - ) + ) && (Vector3.Distance(pointHit.point, hit.position) < MaxRaycastCheckDistance) ) { // if it's within reasonable distance of the original point, we'll know we're fine point = hit.position; diff --git a/unity/Assets/Scripts/PlaneGizmo.cs b/unity/Assets/Scripts/PlaneGizmo.cs index 7fd6d780e7..f48e95c9c4 100644 --- a/unity/Assets/Scripts/PlaneGizmo.cs +++ b/unity/Assets/Scripts/PlaneGizmo.cs @@ -4,9 +4,7 @@ public class PlaneGizmo : MonoBehaviour { // Start is called before the first frame update - void Start() { - - } + void Start() { } void OnDrawGizmos() { // Gizmos.color = Color.yellow; @@ -20,7 +18,6 @@ void OnDrawGizmos() { var p2 = rot * new Vector3(size, 0.0f, size); var p3 = rot * new Vector3(size, 0.0f, -size); - Gizmos.DrawLine(transform.TransformPoint(p0), transform.TransformPoint(p1)); Gizmos.DrawLine(transform.TransformPoint(p1), transform.TransformPoint(p2)); Gizmos.DrawLine(transform.TransformPoint(p2), transform.TransformPoint(p3)); @@ -28,7 +25,5 @@ void OnDrawGizmos() { } // Update is called once per frame - void Update() { - - } + void Update() { } } diff --git a/unity/Assets/Scripts/PlayerControllers.cs b/unity/Assets/Scripts/PlayerControllers.cs index cab28e2042..a5b88da038 100644 --- a/unity/Assets/Scripts/PlayerControllers.cs +++ b/unity/Assets/Scripts/PlayerControllers.cs @@ -1,6 +1,7 @@ +using System; using System.Collections; using System.Collections.Generic; -using System; + // using PlayerControllers; // using UnityStandardAssets.Characters.FirstPerson; @@ -14,13 +15,16 @@ public enum ControlMode { } class PlayerControllers { - public static Dictionary controlModeToComponent = new Dictionary{ - {ControlMode.DEBUG_TEXT_INPUT, typeof(DebugDiscreteAgentController)}, - {ControlMode.FPS, typeof(DebugFPSAgentController)}, - {ControlMode.DISCRETE_POINT_CLICK, typeof(DiscretePointClickAgentController)}, - {ControlMode.DISCRETE_HIDE_N_SEEK, typeof(DiscreteHidenSeekgentController)}, - {ControlMode.MINIMAL_FPS, typeof(MinimalFPSController)} + public static Dictionary controlModeToComponent = new Dictionary< + ControlMode, + Type + > + { + { ControlMode.DEBUG_TEXT_INPUT, typeof(DebugDiscreteAgentController) }, + { ControlMode.FPS, typeof(DebugFPSAgentController) }, + { ControlMode.DISCRETE_POINT_CLICK, typeof(DiscretePointClickAgentController) }, + { ControlMode.DISCRETE_HIDE_N_SEEK, typeof(DiscreteHidenSeekgentController) }, + { ControlMode.MINIMAL_FPS, typeof(MinimalFPSController) } }; } - -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/PrefabNameRevert.cs b/unity/Assets/Scripts/PrefabNameRevert.cs index 8e8be6c1dc..0f704b0429 100644 --- a/unity/Assets/Scripts/PrefabNameRevert.cs +++ b/unity/Assets/Scripts/PrefabNameRevert.cs @@ -29,6 +29,7 @@ public static void RemoveNameModification(UnityEngine.Object aObj) { } PrefabUtility.SetPropertyModifications(aObj, mods.ToArray()); } + public static void RevertAllNames(Object[] aObjects) { var items = new List(); foreach (var item in aObjects) { @@ -44,6 +45,5 @@ public static void RevertAllNames(Object[] aObjects) { RemoveNameModification(item); } } - } -#endif \ No newline at end of file +#endif diff --git a/unity/Assets/Scripts/ProceduralAssetDatabase.cs b/unity/Assets/Scripts/ProceduralAssetDatabase.cs index 5a1437ed84..2d9d84bf83 100644 --- a/unity/Assets/Scripts/ProceduralAssetDatabase.cs +++ b/unity/Assets/Scripts/ProceduralAssetDatabase.cs @@ -1,19 +1,25 @@ -using UnityEngine; +using System; using System.Collections.Generic; using System.Linq; using Priority_Queue; -using System; +using UnityEngine; namespace Thor.Procedural { public class ProceduralAssetDatabase : MonoBehaviour { public static ProceduralAssetDatabase Instance { get; private set; } - [SerializeField] public List materials; + [SerializeField] + public List materials; + // TODO: move to not use this list - [SerializeField] public List prefabs; - [SerializeField] public int totalMats; + [SerializeField] + public List prefabs; - [SerializeField] public ProceduralLRUCacheAssetMap assetMap; + [SerializeField] + public int totalMats; + + [SerializeField] + public ProceduralLRUCacheAssetMap assetMap; public bool dontDestroyOnLoad = true; @@ -24,11 +30,12 @@ public void Awake() { } Instance = this; - this.assetMap = new ProceduralLRUCacheAssetMap(prefabs.GroupBy(p => p.name).ToDictionary(p => p.Key, p => p.First())); + this.assetMap = new ProceduralLRUCacheAssetMap( + prefabs.GroupBy(p => p.name).ToDictionary(p => p.Key, p => p.First()) + ); if (dontDestroyOnLoad) { DontDestroyOnLoad(gameObject); - } - else { + } else { // Reset it back to enable caching for next time object is created dontDestroyOnLoad = true; } @@ -62,23 +69,22 @@ public IEnumerable GetPrefabs() { } } - public class ProceduralLRUCacheAssetMap : AssetMap { - - public SimplePriorityQueue proceduralAssetQueue { - get; private set; - } - public int priorityMinValue { - get; private set; - } - public int priorityMaxValue { - get; private set; - } + public SimplePriorityQueue proceduralAssetQueue { get; private set; } + public int priorityMinValue { get; private set; } + public int priorityMaxValue { get; private set; } private int originalPriorityMinValue; private int originalPriorityMaxValue; - public ProceduralLRUCacheAssetMap(int priorityMinValue = 0, int priorityMaxValue = 1) : this(new Dictionary(), priorityMinValue, priorityMaxValue) { - } - public ProceduralLRUCacheAssetMap(Dictionary assetMap, int rankingMinValue = 0, int rankingMaxValue = 1) : base(assetMap) { + + public ProceduralLRUCacheAssetMap(int priorityMinValue = 0, int priorityMaxValue = 1) + : this(new Dictionary(), priorityMinValue, priorityMaxValue) { } + + public ProceduralLRUCacheAssetMap( + Dictionary assetMap, + int rankingMinValue = 0, + int rankingMaxValue = 1 + ) + : base(assetMap) { this.priorityMinValue = this.originalPriorityMinValue = rankingMinValue; this.priorityMaxValue = this.originalPriorityMaxValue = rankingMaxValue; proceduralAssetQueue = new SimplePriorityQueue(); @@ -104,24 +110,28 @@ public void touch(IEnumerable ids) { this.advanceExpiration(); this.use(ids); } + public void touch(string id) { this.advanceExpiration(); this.use(id); } public AsyncOperation removeLRU(int limit, bool deleteWithHighestPriority = true) { -// Debug.Log($"Running removeLRU with {limit}, {deleteWithHighestPriority}"); + // Debug.Log($"Running removeLRU with {limit}, {deleteWithHighestPriority}"); if (proceduralAssetQueue.Count == 0) { -// Debug.Log($"Queue empty, returning"); + // Debug.Log($"Queue empty, returning"); return null; } -// Debug.Log($"Queue not empty"); + // Debug.Log($"Queue not empty"); var current = proceduralAssetQueue.First; var toDequeuePrio = proceduralAssetQueue.GetPriority(current); int dequeueCount = 0; // Do not delete items with the highest priority if !deleteWithHighestPriority - while (proceduralAssetQueue.Count > limit && (deleteWithHighestPriority || toDequeuePrio < this.priorityMaxValue)) { + while ( + proceduralAssetQueue.Count > limit + && (deleteWithHighestPriority || toDequeuePrio < this.priorityMaxValue) + ) { var removed = proceduralAssetQueue.Dequeue(); if (this.getAsset(removed) is GameObject go) { go.transform.parent = null; @@ -131,7 +141,7 @@ public AsyncOperation removeLRU(int limit, bool deleteWithHighestPriority = true } else { this.assetMap.Remove(removed); } -// Debug.Log($"Removing {removed}"); + // Debug.Log($"Removing {removed}"); dequeueCount++; if (proceduralAssetQueue.Count == 0) { break; @@ -139,27 +149,27 @@ public AsyncOperation removeLRU(int limit, bool deleteWithHighestPriority = true current = proceduralAssetQueue.First; toDequeuePrio = proceduralAssetQueue.GetPriority(current); } -// Debug.Log($"Remaining in queue {proceduralAssetQueue.Count}"); + // Debug.Log($"Remaining in queue {proceduralAssetQueue.Count}"); AsyncOperation asyncOp = null; - if (dequeueCount > 0) { + if (dequeueCount > 0) { // WARNING: Async operation, should be ok for deleting assets if using the same creation-deletion hook // cache should be all driven within one system, currently python driven - - asyncOp = Resources.UnloadUnusedAssets(); - asyncOp.completed += (op) => { - Debug.Log("Asyncop callback called calling GC"); - GC.Collect(); - }; - - // #if !UNITY_EDITOR && !UNITY_WEBGL - float timeout = 2.0f; - float startTime = Time.realtimeSinceStartup; - while (!asyncOp.isDone && Time.realtimeSinceStartup - startTime < timeout) { - // waiting - continue; - } - GC.Collect(); - // #endif + + asyncOp = Resources.UnloadUnusedAssets(); + asyncOp.completed += (op) => { + Debug.Log("Asyncop callback called calling GC"); + GC.Collect(); + }; + + // #if !UNITY_EDITOR && !UNITY_WEBGL + float timeout = 2.0f; + float startTime = Time.realtimeSinceStartup; + while (!asyncOp.isDone && Time.realtimeSinceStartup - startTime < timeout) { + // waiting + continue; + } + GC.Collect(); + // #endif } return asyncOp; } @@ -180,21 +190,22 @@ protected void use(string name) { } // Amortized O(n) - protected void advanceExpiration() { - if (this.priorityMaxValue+1 != int.MaxValue) { + protected void advanceExpiration() { + if (this.priorityMaxValue + 1 != int.MaxValue) { this.priorityMinValue++; this.priorityMaxValue++; - } - else { - foreach (var item in proceduralAssetQueue) { + } else { + foreach (var item in proceduralAssetQueue) { var currentPriority = proceduralAssetQueue.GetPriority(item); var distance = currentPriority - this.priorityMinValue; - proceduralAssetQueue.UpdatePriority(item, this.originalPriorityMinValue + distance); + proceduralAssetQueue.UpdatePriority( + item, + this.originalPriorityMinValue + distance + ); } this.priorityMinValue = this.originalPriorityMinValue; this.priorityMaxValue = this.originalPriorityMaxValue; } - } // O(n) every time @@ -207,4 +218,4 @@ protected void advanceExpiration() { // } // } } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/ProceduralAssetEditor.cs b/unity/Assets/Scripts/ProceduralAssetEditor.cs index 56b0f5a440..b59d826750 100644 --- a/unity/Assets/Scripts/ProceduralAssetEditor.cs +++ b/unity/Assets/Scripts/ProceduralAssetEditor.cs @@ -1,29 +1,27 @@ +using System; using System.Collections; +using System.Collections.Concurrent; using System.Collections.Generic; -using UnityEngine; +using System.Data.Common; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using EasyButtons; +using Newtonsoft.Json.Linq; +using Thor.Procedural; +using Thor.Procedural.Data; +using Thor.Utils; using UnityEditor; +using UnityEngine; using UnityEngine.SceneManagement; -using Newtonsoft.Json.Linq; +using diagnostics = System.Diagnostics; #if UNITY_EDITOR using EasyButtons.Editor; using UnityEditor.SceneManagement; #endif -using EasyButtons; -using System; -using Thor.Procedural; -using Thor.Procedural.Data; -using System.Linq; -using System.IO; -using Thor.Utils; - -using diagnostics = System.Diagnostics; -using System.Text; -using System.Threading.Tasks; -using System.Collections.Concurrent; -using System.Data.Common; namespace Thor.Procedural { - [System.Serializable] public class AssetEditorPaths { public string serializeBasePath; @@ -31,20 +29,18 @@ public class AssetEditorPaths { public string texturesRelativePath; public string prefabsRelativePath; public string modelsRelativePath; - public string collidersInModelsPath; + public string collidersInModelsPath; public string repoRootObjaverseDir; } [System.Serializable] public class ObjaversePipelinseSettings { public string pythonExecutablePath; - public string vidaRepo; + public string vidaRepo; public int timeoutSeconds; - } public class ProceduralAssetEditor : MonoBehaviour { - public AssetEditorPaths paths = new AssetEditorPaths() { serializeBasePath = "Assets/Resources/ai2thor-objaverse/NoveltyTHOR_Assets", materialsRelativePath = "Materials/objaverse", @@ -52,11 +48,10 @@ public class ProceduralAssetEditor : MonoBehaviour { prefabsRelativePath = "Prefabs", repoRootObjaverseDir = "objaverse", modelsRelativePath = "Models/objaverse", - collidersInModelsPath = "Colliders", - + collidersInModelsPath = "Colliders", }; - public ObjaversePipelinseSettings objaversePipelineConfig = new ObjaversePipelinseSettings{ + public ObjaversePipelinseSettings objaversePipelineConfig = new ObjaversePipelinseSettings { pythonExecutablePath = "/Users/alvaroh/anaconda3/envs/vida/bin/python", vidaRepo = "/Users/alvaroh/ai2/vida", timeoutSeconds = 800 @@ -69,26 +64,30 @@ public class ProceduralAssetEditor : MonoBehaviour { public string objectId; - #if UNITY_EDITOR private string copyTexture(string original, string destinationDir) { var outName = $"{destinationDir}/{Path.GetFileName(original)}"; if (!File.Exists(outName)) { File.Copy(original, outName); - } - else { - Debug.LogWarning($"Failed to save texture {outName}, as it already extists. To overwite delete them first and load object again."); + } else { + Debug.LogWarning( + $"Failed to save texture {outName}, as it already extists. To overwite delete them first and load object again." + ); } return outName; - } + } private string getAssetRelativePath(string absPath) { - return string.Join("/", absPath.Split('/').SkipWhile(x=> x != "Assets")); + return string.Join("/", absPath.Split('/').SkipWhile(x => x != "Assets")); } private Texture2D loadTexture(string textureAbsPath) { - return (Texture2D)AssetDatabase.LoadAssetAtPath(getAssetRelativePath(textureAbsPath),typeof(Texture2D));//Resources.Load(newAlbedo); - } + return (Texture2D) + AssetDatabase.LoadAssetAtPath( + getAssetRelativePath(textureAbsPath), + typeof(Texture2D) + ); //Resources.Load(newAlbedo); + } // private Texture2D copyAndLoadTexture(string original, string destinationDir) { // var outName = $"{destinationDir}/{Path.GetFileName(original)}"; @@ -96,31 +95,38 @@ private Texture2D loadTexture(string textureAbsPath) { // var relativeName = string.Join("/", outName.Split('/').SkipWhile(x=> x != "Assets")); // return (Texture2D)AssetDatabase.LoadAssetAtPath(relativeName,typeof(Texture2D));//Resources.Load(newAlbedo); - - // } + + // } private void SaveTextures(GameObject go, bool savePrefab) { var assetId = go.GetComponentInChildren().assetID; - var matOutPath = $"{paths.serializeBasePath}/{paths.materialsRelativePath}/{assetId}.mat"; + var matOutPath = + $"{paths.serializeBasePath}/{paths.materialsRelativePath}/{assetId}.mat"; if (File.Exists(matOutPath)) { - Debug.LogWarning($"Failed to save material {matOutPath}, as it already extists. To overwite delete it first and load object again."); + Debug.LogWarning( + $"Failed to save material {matOutPath}, as it already extists. To overwite delete it first and load object again." + ); - var savedMat = (Material)AssetDatabase.LoadAssetAtPath(getAssetRelativePath(matOutPath),typeof(Material)); + var savedMat = (Material) + AssetDatabase.LoadAssetAtPath( + getAssetRelativePath(matOutPath), + typeof(Material) + ); go.GetComponentInChildren().sharedMaterial = savedMat; - } - else { + } else { UnityEditor.AssetDatabase.CreateAsset( - go.GetComponentInChildren().sharedMaterial, matOutPath + go.GetComponentInChildren().sharedMaterial, + matOutPath ); } - var runtimeP = go.GetComponent(); var dir = string.Join("/", paths.serializeBasePath.Split('/').Skip(1)); - var outTextureBasePath = $"{Application.dataPath}/{dir}/{paths.texturesRelativePath}/{assetId}"; + var outTextureBasePath = + $"{Application.dataPath}/{dir}/{paths.texturesRelativePath}/{assetId}"; if (!Directory.Exists(outTextureBasePath)) { Directory.CreateDirectory(outTextureBasePath); @@ -129,10 +135,13 @@ private void SaveTextures(GameObject go, bool savePrefab) { Debug.Log($"---- SaveTextures {outTextureBasePath}"); var newAlbedo = copyTexture(runtimeP.albedoTexturePath, outTextureBasePath); - var newMetallicSmoothness = copyTexture(runtimeP.metallicSmoothnessTexturePath, outTextureBasePath); + var newMetallicSmoothness = copyTexture( + runtimeP.metallicSmoothnessTexturePath, + outTextureBasePath + ); var newNormal = copyTexture(runtimeP.normalTexturePath, outTextureBasePath); var newEmission = copyTexture(runtimeP.emissionTexturePath, outTextureBasePath); - + var mr = go.GetComponentInChildren(); var sharedMaterial = mr.sharedMaterial; @@ -141,14 +150,15 @@ private void SaveTextures(GameObject go, bool savePrefab) { // newAlbedo = newAlbedo.Substring(0,newAlbedo.LastIndexOf('.')); AssetDatabase.Refresh(); - var normalImporter = AssetImporter.GetAtPath(getAssetRelativePath(newNormal)) as TextureImporter; + var normalImporter = + AssetImporter.GetAtPath(getAssetRelativePath(newNormal)) as TextureImporter; normalImporter.textureType = TextureImporterType.NormalMap; - - sharedMaterial.SetTexture("_MainTex", loadTexture(newAlbedo));//Resources.Load(newAlbedo)); + + sharedMaterial.SetTexture("_MainTex", loadTexture(newAlbedo)); //Resources.Load(newAlbedo)); sharedMaterial.SetTexture("_MetallicGlossMap", loadTexture(newMetallicSmoothness)); - sharedMaterial.SetTexture("_BumpMap", loadTexture(newNormal)); - sharedMaterial.SetTexture("_EmissionMap", loadTexture(newEmission)); + sharedMaterial.SetTexture("_BumpMap", loadTexture(newNormal)); + sharedMaterial.SetTexture("_EmissionMap", loadTexture(newEmission)); sharedMaterial.SetColor("_EmissionColor", Color.white); @@ -156,7 +166,7 @@ private void SaveTextures(GameObject go, bool savePrefab) { SerializeMesh.SaveMeshesAsObjAndReplaceReferences( go, - assetId, + assetId, $"{Application.dataPath}/{dir}/{paths.modelsRelativePath}/{assetId}", $"{Application.dataPath}/{dir}/{paths.modelsRelativePath}/{assetId}/{paths.collidersInModelsPath}" ); @@ -185,25 +195,31 @@ private void SaveTextures(GameObject go, bool savePrefab) { // mf.sharedMesh = mesh; - + if (savePrefab) { - PrefabUtility.SaveAsPrefabAssetAndConnect(go, $"{paths.serializeBasePath}/{paths.prefabsRelativePath}/{assetId}.prefab", InteractionMode.UserAction); + PrefabUtility.SaveAsPrefabAssetAndConnect( + go, + $"{paths.serializeBasePath}/{paths.prefabsRelativePath}/{assetId}.prefab", + InteractionMode.UserAction + ); } } - - // NOT WORKIGN drag prefab manually private void SavePrefab(GameObject go) { - // var dir = string.Join("/", SerializeMesh.serializeBasePath.Split('/').Skip(1)); var path = $"{paths.serializeBasePath}/{paths.prefabsRelativePath}/{go.name}.prefab"; Debug.Log($"---- Savingprefabs {path}"); // PrefabUtility.SaveAsPrefabAsset(go, path); bool prefabSuccess; - PrefabUtility.SaveAsPrefabAssetAndConnect(go, path, InteractionMode.UserAction, out prefabSuccess); - Debug.Log($"---- prefab save {prefabSuccess}"); - } + PrefabUtility.SaveAsPrefabAssetAndConnect( + go, + path, + InteractionMode.UserAction, + out prefabSuccess + ); + Debug.Log($"---- prefab save {prefabSuccess}"); + } private GameObject importAsset(string objectPath, bool addAnotationComponent = false) { var jsonStr = System.IO.File.ReadAllText(objectPath); @@ -213,7 +229,7 @@ private GameObject importAsset(string objectPath, bool addAnotationComponent = f var procAsset = obj.ToObject(); // var prefabParentTransform = transform.Find("ProceduralAssets"); - + // if (prefabParentTransform == null) { // Debug.Log($"ProceduralAssets container does not exist {prefabParentTransform == null}"); // var prefabParent = new GameObject("ProceduralAssets"); @@ -222,26 +238,26 @@ private GameObject importAsset(string objectPath, bool addAnotationComponent = f // } var result = ProceduralTools.CreateAsset( - procAsset.vertices, - procAsset.normals, - procAsset.name, - procAsset.triangles, - procAsset.uvs, - procAsset.albedoTexturePath , - procAsset.metallicSmoothnessTexturePath , - procAsset.normalTexturePath , - procAsset.emissionTexturePath, - procAsset.colliders , - procAsset.physicalProperties, - procAsset.visibilityPoints , - procAsset.annotations , - procAsset.receptacleCandidate , - procAsset.yRotOffset , - serializable: true, - returnObject: true, - parent: transform, - addAnotationComponent: addAnotationComponent - ); + procAsset.vertices, + procAsset.normals, + procAsset.name, + procAsset.triangles, + procAsset.uvs, + procAsset.albedoTexturePath, + procAsset.metallicSmoothnessTexturePath, + procAsset.normalTexturePath, + procAsset.emissionTexturePath, + procAsset.colliders, + procAsset.physicalProperties, + procAsset.visibilityPoints, + procAsset.annotations, + procAsset.receptacleCandidate, + procAsset.yRotOffset, + serializable: true, + returnObject: true, + parent: transform, + addAnotationComponent: addAnotationComponent + ); var go = result["gameObject"] as GameObject; // var intermediate = result["intermediateGameObject"] as GameObject; @@ -250,22 +266,20 @@ private GameObject importAsset(string objectPath, bool addAnotationComponent = f if (go.transform.parent != null && !go.transform.parent.gameObject.activeSelf) { go.transform.parent.gameObject.SetActive(true); } - if (savePrefabsOnLoad) { SaveTextures(go, savePrefab); - } - else { + } else { var runtimeP = go.GetComponent(); if (runtimeP != null) { runtimeP.RealoadTextures(); } - } return go; } private List coroutines = new List(); + // TODO: put in ifdef block [Button(Expanded = true)] public void LoadObject() { @@ -273,7 +287,7 @@ public void LoadObject() { if (!file.EndsWith(".json")) { file += ".json"; } - + var pathSplit = Application.dataPath.Split('/'); var repoRoot = pathSplit.Reverse().Skip(2).Reverse().ToList(); @@ -290,61 +304,61 @@ public void LoadObject() { cancellAll = false; Debug.Log("Starting objaverse pipeline background process..."); coroutines.Add( - StartCoroutine(runAssetPipelineAsync(objectId, objaverseRoot, () => { - if (!cancellAll) { importAsset(objectPath, addAnotationComponent: true); } - })) + StartCoroutine( + runAssetPipelineAsync( + objectId, + objaverseRoot, + () => { + if (!cancellAll) { + importAsset(objectPath, addAnotationComponent: true); + } + } + ) + ) ); - } - else { + } else { importAsset(objectPath, forceCreateAnnotationComponent); } - - - - // if (savePrefab) { // if (!saveTextures) { - // SaveTextures(go); + // SaveTextures(go); // } // SavePrefab(go); - + // } } [Button(Expanded = true)] - public void CancelAll() { + public void CancelAll() { EditorUtility.ClearProgressBar(); cancellAll = true; - + foreach (var ap in this.processingIds.Values) { - Debug.Log($"Cancelled conversion process for '{ap.id}'"); - ap.process.Kill(); - ap.process.CancelOutputRead(); - ap.process.CancelErrorRead(); - + Debug.Log($"Cancelled conversion process for '{ap.id}'"); + ap.process.Kill(); + ap.process.CancelOutputRead(); + ap.process.CancelErrorRead(); } - + foreach (var coroutine in coroutines) { StopCoroutine(coroutine); } - + processingIds.Clear(); coroutines.Clear(); } - // [UnityEditor.MenuItem("Procedural/Fix Prefabs")] - [Button(Expanded = false)] + [Button(Expanded = false)] public void FixPrefabs() { - var procAssets = GameObject.FindObjectsOfType(typeof(SimObjPhysics)) as SimObjPhysics[]; + var procAssets = GameObject.FindObjectsOfType(typeof(SimObjPhysics)) as SimObjPhysics[]; //var gos = procAssets.GroupBy(so => so.assetID).Select(k => (IdentifierCase: k.Key, go: k.First().gameObject)).Where(p => p.go.GetComponentInChildren() != null); - //var dict = new Dictionary (id: k.assetID, go: k.gameObject));//.Where(p => p.id == "1807cfeea89c4a57997cbe5fce569b53");//.Where(p => p.go.GetComponentInChildren() != null); + //var dict = new Dictionary (id: k.assetID, go: k.gameObject)); //.Where(p => p.id == "1807cfeea89c4a57997cbe5fce569b53");//.Where(p => p.go.GetComponentInChildren() != null); Debug.Log($"running for {gos.Count()}"); - Debug.Log($"running for {string.Join(",", gos.Select(g => g.id).Distinct())}"); // var loadedObjs = gos.Select(m => m.id).Distinct().ToDictionary(id => id, assetId => { @@ -387,19 +401,18 @@ public void FixPrefabs() { foreach (var (assetId, go) in gos) { - var dir =string.Join("/", paths.serializeBasePath.Split('/').Skip(1)); - if (PrefabUtility.IsPartOfPrefabInstance(go)) { - + var dir = string.Join("/", paths.serializeBasePath.Split('/').Skip(1)); + if (PrefabUtility.IsPartOfPrefabInstance(go)) { SerializeMesh.SaveMeshesAsObjAndReplaceReferences( go, assetId, $"{Application.dataPath}/{dir}/{paths.modelsRelativePath}/{assetId}", $"{Application.dataPath}/{dir}/{paths.modelsRelativePath}/{assetId}/{paths.collidersInModelsPath}", overwrite: true - //,sourceGo: loadedObjs[assetId] + //,sourceGo: loadedObjs[assetId] ); var meshGo = go.transform.Find("mesh"); - // if (meshGo != null) + // if (meshGo != null) // { // var negRot = -meshGo.transform.localEulerAngles; // meshGo.transform.localEulerAngles = negRot; @@ -408,21 +421,21 @@ public void FixPrefabs() { if (go.GetComponentInChildren() != null) { DestroyImmediate(go.GetComponentInChildren()); } - + PrefabUtility.ApplyPrefabInstance(go, InteractionMode.UserAction); - Selection.activeGameObject=go; - } + Selection.activeGameObject = go; + } } // foreach (var go in loadedObjs.Values) { // DestroyImmediate(go); // } - } + } + + [MenuItem("Procedural/Revert Prefabs")] + public void RevertPrefabs() { + var simObjs = GameObject.FindObjectsOfType(typeof(SimObjPhysics)) as SimObjPhysics[]; - [MenuItem("Procedural/Revert Prefabs")] - public void RevertPrefabs() { - var simObjs = GameObject.FindObjectsOfType(typeof(SimObjPhysics)) as SimObjPhysics[]; - foreach (var so in simObjs) { if (PrefabUtility.IsPartOfPrefabInstance(so.gameObject)) { Debug.Log($"Reverting {so.gameObject}"); @@ -430,11 +443,10 @@ public void RevertPrefabs() { PrefabUtility.RevertPrefabInstance(so.gameObject, InteractionMode.UserAction); } } - } - + } [Button(Expanded = true)] - public void SaveObjectPrefabAndTextures() { + public void SaveObjectPrefabAndTextures() { var transformRoot = GameObject.Find(objectId); var transform = gameObject.transform.root.FirstChildOrDefault(g => g.name == objectId); @@ -444,32 +456,30 @@ public void SaveObjectPrefabAndTextures() { // Debug.Log($"Root: {gameObject.transform.root.name}"); if (transform != null) { SaveTextures(transform.gameObject, savePrefab); - } - else { + } else { Debug.LogError($"Invalid object {objectId} not present in scene."); } } [Button(Expanded = true)] - public void SaveAllPrefabsAndTextures() { - var procAssets = GameObject.FindObjectsOfType(typeof(RuntimePrefab)) as RuntimePrefab[]; + public void SaveAllPrefabsAndTextures() { + var procAssets = GameObject.FindObjectsOfType(typeof(RuntimePrefab)) as RuntimePrefab[]; // var procAssets = gameObject.transform.root.GetComponentsInChildren(); foreach (var asset in procAssets) { if (asset != null) { SaveTextures(asset.gameObject, savePrefab); - } - else { + } else { Debug.LogError($"Invalid object in scene."); } } } - [UnityEditor.MenuItem("Procedural/Reload Procedural Asset Textures _s")] + [UnityEditor.MenuItem("Procedural/Reload Procedural Asset Textures _s")] public static void ReloadTextures() { - var procAssets = GameObject.FindObjectsOfType(typeof(RuntimePrefab)) as RuntimePrefab[]; - foreach (var asset in procAssets) { + var procAssets = GameObject.FindObjectsOfType(typeof(RuntimePrefab)) as RuntimePrefab[]; + foreach (var asset in procAssets) { asset.RealoadTextures(); - } + } } class AsyncProcess { @@ -480,41 +490,47 @@ class AsyncProcess { public GameObject goResultß; } - private ConcurrentDictionary processingIds = new ConcurrentDictionary(); + private ConcurrentDictionary processingIds = + new ConcurrentDictionary(); private bool cancellAll = false; - private IEnumerator waitForProcess(diagnostics.Process p, string id, int sleepSeconds, int debugIntervalSeconds, int timeoutSeconds) { - + private IEnumerator waitForProcess( + diagnostics.Process p, + string id, + int sleepSeconds, + int debugIntervalSeconds, + int timeoutSeconds + ) { var secs = 0; var start = Time.realtimeSinceStartup; var prevCount = processingIds.Count; var updateProgressBar = false; Debug.Log("Running objaverse conversion pipeline..."); while (!p.HasExited) { - - // var currentCount = processingIds.Count; // p.StandardOutput.ReadAsync() yield return new WaitForSeconds(sleepSeconds); - // yield return true; var currentCount = processingIds.Count; - + var deltaSeconds = Time.realtimeSinceStartup - start; int roundedSeconds = (int)Mathf.Round(deltaSeconds); if (roundedSeconds % debugIntervalSeconds == 0) { Debug.Log($"Ran pipeline for ({roundedSeconds}) for '{id}'."); - + // Debug.Log($"Output: {p.StandardOutput.ReadToEnd()}"); // Debug.Log($"Error Out: {p.StandardError.ReadToEnd()}"); } - if (currentCount < prevCount) { // prevCount = currentCount; - EditorUtility.DisplayProgressBar("Objaverse import", $"Still running glb conversion pipeline for {id}...", 0.1f); + EditorUtility.DisplayProgressBar( + "Objaverse import", + $"Still running glb conversion pipeline for {id}...", + 0.1f + ); // prevCount = currentCount; } // if (updateProgressBar && currentCount < prevCount) { @@ -524,7 +540,9 @@ private IEnumerator waitForProcess(diagnostics.Process p, string id, int sleepSe if (deltaSeconds >= timeoutSeconds) { - Debug.Log($"Timeout reached, possible issue with object '{id}', or increase components 'objaversePipelineConfig.timeoutSeconds'."); + Debug.Log( + $"Timeout reached, possible issue with object '{id}', or increase components 'objaversePipelineConfig.timeoutSeconds'." + ); p.Kill(); break; } @@ -532,37 +550,43 @@ private IEnumerator waitForProcess(diagnostics.Process p, string id, int sleepSe } private diagnostics.Process runPythonCommand(string id, string saveDir) { - diagnostics.Process p = new diagnostics.Process (); - var pythonFilename = $"{objaversePipelineConfig.vidaRepo}/data_generation/objaverse/object_consolidater_blender_direct.py"; - Debug.Log($"Running conversion script: `{objaversePipelineConfig.pythonExecutablePath} {pythonFilename} {objectId} {saveDir}`"); - p.StartInfo = new diagnostics.ProcessStartInfo(objaversePipelineConfig.pythonExecutablePath, $"{pythonFilename} {objectId} {saveDir}") - { + diagnostics.Process p = new diagnostics.Process(); + var pythonFilename = + $"{objaversePipelineConfig.vidaRepo}/data_generation/objaverse/object_consolidater_blender_direct.py"; + Debug.Log( + $"Running conversion script: `{objaversePipelineConfig.pythonExecutablePath} {pythonFilename} {objectId} {saveDir}`" + ); + p.StartInfo = new diagnostics.ProcessStartInfo( + objaversePipelineConfig.pythonExecutablePath, + $"{pythonFilename} {objectId} {saveDir}" + ) { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true }; Console.InputEncoding = Encoding.UTF8; - + p.OutputDataReceived += (sender, args) => Debug.Log(args.Data); p.ErrorDataReceived += (sender, args) => Debug.LogError(args.Data); // processes.Enqueue(p); - processingIds.GetOrAdd(id, new AsyncProcess() { - id = id, - process = p, - progress = 0.0f - - }); + processingIds.GetOrAdd( + id, + new AsyncProcess() { + id = id, + process = p, + progress = 0.0f + } + ); p.Start(); - + // cant mix async and non async output read - p.BeginOutputReadLine(); - p.BeginErrorReadLine(); + p.BeginOutputReadLine(); + p.BeginErrorReadLine(); return p; - } // private float getPipelineAverageProgress() { @@ -570,16 +594,26 @@ private diagnostics.Process runPythonCommand(string id, string saveDir) { // } private IEnumerator runAssetPipelineAsync(string id, string saveDir, Action callback = null) { - // processingIds.TryUpdate(id) - EditorUtility.DisplayProgressBar("Objaverse import", $"'{id}' Running import pipeline...", 0.0f); + EditorUtility.DisplayProgressBar( + "Objaverse import", + $"'{id}' Running import pipeline...", + 0.0f + ); var p = runPythonCommand(id, saveDir); - EditorUtility.DisplayProgressBar("Objaverse import", $"'{id}' Running glb conversion...", 0.1f); + EditorUtility.DisplayProgressBar( + "Objaverse import", + $"'{id}' Running glb conversion...", + 0.1f + ); yield return waitForProcess(p, id, 1, 5, objaversePipelineConfig.timeoutSeconds); - EditorUtility.DisplayProgressBar("Objaverse import", $"'{id}' Finished glb conversion.", 0.8f); - + EditorUtility.DisplayProgressBar( + "Objaverse import", + $"'{id}' Finished glb conversion.", + 0.8f + ); // var outputStr = p.StandardOutput.ReadToEnd(); // var errorStr = p.StandardError.ReadToEnd(); @@ -591,12 +625,16 @@ private IEnumerator runAssetPipelineAsync(string id, string saveDir, Action call // foreach (var line in split) { // Debug.Log (line); // } - + p.WaitForExit(); - + Debug.Log($"Exit: {p.ExitCode}"); Debug.Log("Running callback..."); - EditorUtility.DisplayProgressBar("Objaverse import", $"'{id}' Importing to Unity", 0.9f); + EditorUtility.DisplayProgressBar( + "Objaverse import", + $"'{id}' Importing to Unity", + 0.9f + ); callback?.Invoke(); EditorUtility.DisplayProgressBar("Objaverse import", $"'{id}' Finished!", 1f); @@ -604,7 +642,6 @@ private IEnumerator runAssetPipelineAsync(string id, string saveDir, Action call if (processingIds.IsEmpty) { EditorUtility.ClearProgressBar(); } - } // [Button(Expanded = true)] @@ -615,16 +652,15 @@ private IEnumerator runAssetPipelineAsync(string id, string saveDir, Action call // var errorStr = p.StandardError.ReadToEnd(); // Debug.Log(outputStr); // Debug.Log(errorStr); - - + + // p.WaitForExit(); - + // Debug.Log($"Exit: {p.ExitCode}"); - + // } - -#endif +#endif } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/ProceduralData.cs b/unity/Assets/Scripts/ProceduralData.cs index 18f1aa05bb..8aa95b16b3 100644 --- a/unity/Assets/Scripts/ProceduralData.cs +++ b/unity/Assets/Scripts/ProceduralData.cs @@ -1,20 +1,18 @@ +using System; using System.Collections.Generic; -using UnityEngine; +using System.IO; using System.Linq; -using UnityStandardAssets.Characters.FirstPerson; -using System; - using System.Runtime.Serialization.Formatters.Binary; - using System.IO; -using MessagePack.Resolvers; -using MessagePack.Formatters; +using System.Runtime.Serialization.Formatters.Binary; using MessagePack; +using MessagePack.Formatters; +using MessagePack.Resolvers; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; - +using UnityEngine; +using UnityStandardAssets.Characters.FirstPerson; namespace Thor.Procedural.Data { - [Serializable] [MessagePackObject(keyAsPropertyName: true)] public class AssetMetadata { @@ -44,14 +42,15 @@ public class LightParameters { public string type { get; set; } public Vector3 position { get; set; } public Vector3 localPosition { get; set; } - public string[] cullingMaskOff { get; set;} + public string[] cullingMaskOff { get; set; } public FlexibleRotation rotation; public float intensity { get; set; } public float indirectMultiplier { get; set; } public float range { get; set; } - public float spotAngle { get; set; } //only used for spot lights, [1-179] valid range + public float spotAngle { get; set; } //only used for spot lights, [1-179] valid range public SerializableColor rgb { get; set; } public ShadowParameters shadow = null; + /* linked objects are one of two cases: this is a scene light and it is controlled by some light switch sim object, and is linked to that light switch @@ -61,7 +60,7 @@ this is a light that is a child of some sim object (ie: lamp) and it is controll public string linkedSimObj { get; set; } //explicit reference to what Sim Object controls if this light is enabled/disabled when using ToggleOnOff public bool enabled { get; set; } public string parentSimObjId { get; set; } //explicit reference to the objectID of a parent Sim Object this Light is a child of - public string parentSimObjName { get; set;} //explicit reference to the game object name of the parent Sim Object this Light is a child of + public string parentSimObjName { get; set; } //explicit reference to the game object name of the parent Sim Object this Light is a child of } [Serializable] @@ -89,7 +88,12 @@ public Color toUnityColor() { } public static SerializableColor fromUnityColor(Color color) { - return new SerializableColor() {r = color.r, g = color.g, b = color.b, a = color.a}; + return new SerializableColor() { + r = color.r, + g = color.g, + b = color.b, + a = color.a + }; } } @@ -129,7 +133,7 @@ public class ProceduralParameters { public float minWallColliderThickness { get; set; } public float receptacleHeight { get; set; } public string skyboxId { get; set; } - public SerializableColor skyboxColor { get; set; } + public SerializableColor skyboxColor { get; set; } public string datetime { get; set; } public List lights { get; set; } @@ -197,6 +201,7 @@ public class RoomHierarchy { }; public string layer { get; set; } + // public float y { get; set; } public List floorPolygon { get; set; } public List ceilings { get; set; } @@ -236,7 +241,7 @@ public Vector3 size() { public class BoundingBoxWithOffset { public Vector3 min { get; set; } public Vector3 max { get; set; } - public Vector3 offset {get; set; } + public Vector3 offset { get; set; } } [Serializable] @@ -360,7 +365,7 @@ public class HouseObject { public float? openness { get; set; } = null; public bool? isOn { get; set; } = null; public bool? isDirty { get; set; } = null; - + public bool unlit; public MaterialProperties material; @@ -388,10 +393,9 @@ public class ProceduralHouse { public HouseMetadata metadata { get; set; } } - [Serializable] + [Serializable] [MessagePackObject(keyAsPropertyName: true)] public class NavMeshConfig { - public int id; public float agentRadius; public int? tileSize; @@ -400,7 +404,6 @@ public class NavMeshConfig { public float? agentClimb; public float? voxelSize; public bool? overrideVoxelSize; - } [Serializable] @@ -424,7 +427,7 @@ public class AgentPose { [Serializable] [MessagePackObject(keyAsPropertyName: true)] public class MaterialProperties { - // TODO: move material id, color (as albedo) and tiling divisors + // TODO: move material id, color (as albedo) and tiling divisors public string name { get; set; } public SerializableColor color { get; set; } public string shader { get; set; } = "Standard"; @@ -434,7 +437,7 @@ public class MaterialProperties { public float? metallic; public float? smoothness; } - + public interface WallRectangularHole { string id { get; set; } string assetId { get; set; } @@ -494,12 +497,11 @@ public class ProceduralAsset { } public static class ExtensionMethods { - public static T DeepClone(this T obj) - { + public static T DeepClone(this T obj) { // Don't serialize a null object, simply return the default for that object if (ReferenceEquals(obj, null)) { return default; - } + } // initialize inner objects individually // for example in default constructor some list property initialized with some values, @@ -520,24 +522,28 @@ public static T DeepClone(this T obj) return jObj.ToObject(); } - public static TValue GetValueOrDefault(this Dictionary dictionary, TKey key, TValue defaultValue = default(TValue)) - { + public static TValue GetValueOrDefault( + this Dictionary dictionary, + TKey key, + TValue defaultValue = default(TValue) + ) { TValue value; return dictionary.TryGetValue(key, out value) ? value : defaultValue; } - public static int AddCount(this Dictionary dictionary, TKey key, int count = 1) - { + public static int AddCount( + this Dictionary dictionary, + TKey key, + int count = 1 + ) { int value; dictionary.TryGetValue(key, out value); if (dictionary.ContainsKey(key)) { dictionary[key] = dictionary[key] + count; - } - else { + } else { dictionary[key] = count; } return dictionary[key]; } } - } diff --git a/unity/Assets/Scripts/ProceduralEditor.cs b/unity/Assets/Scripts/ProceduralEditor.cs index 61f72a8118..b8ad21840b 100644 --- a/unity/Assets/Scripts/ProceduralEditor.cs +++ b/unity/Assets/Scripts/ProceduralEditor.cs @@ -43,4 +43,4 @@ // } // return assets; // } -// } \ No newline at end of file +// } diff --git a/unity/Assets/Scripts/ProceduralRoomEditor.cs b/unity/Assets/Scripts/ProceduralRoomEditor.cs index 8cf9c4fcaf..f30d4734ed 100644 --- a/unity/Assets/Scripts/ProceduralRoomEditor.cs +++ b/unity/Assets/Scripts/ProceduralRoomEditor.cs @@ -1,25 +1,26 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; -using UnityEngine; +using System.IO; +using System.Linq; +using EasyButtons; +using Newtonsoft.Json.Linq; +using Thor.Procedural; +using Thor.Procedural.Data; +using Thor.Utils; using UnityEditor; +using UnityEngine; using UnityEngine.SceneManagement; -using Newtonsoft.Json.Linq; #if UNITY_EDITOR using EasyButtons.Editor; using UnityEditor.SceneManagement; #endif -using EasyButtons; -using System; -using Thor.Procedural; -using Thor.Procedural.Data; -using System.Linq; -using System.IO; -using Thor.Utils; [ExecuteInEditMode] public class ProceduralRoomEditor : MonoBehaviour { private List<(Vector3, Color)> spheres = new List<(Vector3, Color)>(); public ProceduralHouse loadedHouse; + protected class NamedSimObj { public string assetId; public string id; @@ -30,7 +31,7 @@ protected class NamedSimObj { public string LoadBasePath = "/Resources/rooms/"; public string layoutJSONFilename; - #if UNITY_EDITOR +#if UNITY_EDITOR private ProceduralHouse readHouseFromJson(string fileName) { var path = BuildLayoutPath(fileName); @@ -41,7 +42,6 @@ private ProceduralHouse readHouseFromJson(string fileName) { JObject obj = JObject.Parse(jsonStr); return obj.ToObject(); - } private List assignObjectIds() { @@ -53,17 +53,26 @@ private List assignObjectIds() { var namedObjects = simobjs .Where(s => s.transform.parent.GetComponentInParent() == null) .GroupBy(s => s.Type) - .SelectMany(objsOfType => objsOfType.Select((simObj, index) => new NamedSimObj { - assetId = !string.IsNullOrEmpty(simObj.assetID) ? simObj.assetID : PrefabNameRevert.GetPrefabAssetName(simObj.gameObject), - simObj = simObj, - id = $"{Enum.GetName(typeof(SimObjType), simObj.ObjType)}_{index}" - })).ToList(); + .SelectMany(objsOfType => + objsOfType.Select( + (simObj, index) => + new NamedSimObj { + assetId = !string.IsNullOrEmpty(simObj.assetID) + ? simObj.assetID + : PrefabNameRevert.GetPrefabAssetName(simObj.gameObject), + simObj = simObj, + id = $"{Enum.GetName(typeof(SimObjType), simObj.ObjType)}_{index}" + } + ) + ) + .ToList(); foreach (var namedObj in namedObjects) { - Debug.Log($" Renaming obj: {namedObj.simObj.gameObject.name} to {namedObj.id}, assetId: {namedObj.assetId}"); + Debug.Log( + $" Renaming obj: {namedObj.simObj.gameObject.name} to {namedObj.id}, assetId: {namedObj.assetId}" + ); namedObj.simObj.assetID = namedObj.assetId; namedObj.simObj.objectID = namedObj.id; namedObj.simObj.gameObject.name = namedObj.id; - } return namedObjects; // foreach (var namedObj in this.namedSimObjects) { @@ -83,34 +92,46 @@ public void LoadLayout() { this.loadedHouse, ProceduralTools.GetMaterials() ); - } - private List getPolygonFromWallPoints(Vector3 p0, Vector3 p1, float height) { - return new List() { - p0, - p1, - p1 + Vector3.up * height, - p0 + Vector3.up * height - }; - + return new List() { p0, p1, p1 + Vector3.up * height, p0 + Vector3.up * height }; } - // private List getPolygonFromWallObject(GameObject wall, bool reverse = false, bool debug = false) { - private List getPolygonFromWallObject(GameObject wall, bool reverse = false, bool debug = false) { + private List getPolygonFromWallObject( + GameObject wall, + bool reverse = false, + bool debug = false + ) { var box = wall.GetComponent(); var offset = box.size / 2.0f; offset.z = 0.0f; - if (debug) { - - Debug.Log(" wall " + $"name: '{wall.gameObject.name}' " + wall.GetComponentInParent().gameObject.name + " box " + box.center + " offset " + offset + " size: " + box.size + " p0 " + wall.transform.TransformPoint(box.center - offset).ToString("F8") + " p1 " + wall.transform.TransformPoint(box.center + new Vector3(offset.x, -offset.y, 0.0f)).ToString("F8") + $"local p0: {(box.center + new Vector3(offset.x, -offset.y, 0.0f)).ToString("F8")} p1: {(box.center + new Vector3(offset.x, -offset.y, 0.0f)).ToString("F8")}"); + Debug.Log( + " wall " + + $"name: '{wall.gameObject.name}' " + + wall.GetComponentInParent().gameObject.name + + " box " + + box.center + + " offset " + + offset + + " size: " + + box.size + + " p0 " + + wall.transform.TransformPoint(box.center - offset).ToString("F8") + + " p1 " + + wall.transform.TransformPoint( + box.center + new Vector3(offset.x, -offset.y, 0.0f) + ) + .ToString("F8") + + $"local p0: {(box.center + new Vector3(offset.x, -offset.y, 0.0f)).ToString("F8")} p1: {(box.center + new Vector3(offset.x, -offset.y, 0.0f)).ToString("F8")}" + ); } - var r = new List() { - wall.transform.TransformPoint(box.center - offset) , + var r = new List() + { + wall.transform.TransformPoint(box.center - offset), wall.transform.TransformPoint(box.center + new Vector3(offset.x, -offset.y, 0.0f)), wall.transform.TransformPoint(box.center + new Vector3(offset.x, offset.y, 0.0f)), wall.transform.TransformPoint(box.center + new Vector3(-offset.x, offset.y, 0.0f)), @@ -119,12 +140,7 @@ private List getPolygonFromWallObject(GameObject wall, bool reverse = f if (!reverse) { return r; } else { - return new List() { - r[1], - r[0], - r[3], - r[2] - }; + return new List() { r[1], r[0], r[3], r[2] }; } } @@ -135,511 +151,722 @@ public class ConnectionAndWalls { public List wallIdsToDelete; } - private IEnumerable serializeConnections(IEnumerable connections, SimObjType filterType, string prefix, Dictionary wallMap, Dictionary connectionMap = null) { + private IEnumerable serializeConnections( + IEnumerable connections, + SimObjType filterType, + string prefix, + Dictionary wallMap, + Dictionary connectionMap = null + ) { var flippedForward = filterType == SimObjType.Window; - var connectionsWithWalls = connections.Where(s => s.Type == filterType).Select((d, i) => { - var id = d.gameObject.name; - - // Debug.Log($"----- {prefix} " + d.gameObject.name); - var box = d.BoundingBox.GetComponent(); - box.enabled = true; - var boxOffset = box.size / 2.0f; - var poly = getPolygonFromWallObject(d.BoundingBox, flippedForward, true); - - Debug.Log($"----- i: {i}, {prefix} {d.gameObject.name} p0 {poly[0]} p1 {poly[1]}"); - var polyRev = getPolygonFromWallObject(d.BoundingBox, !flippedForward); - ConnectionProperties connectionProps = d.GetComponentInChildren(); - var materialId = ""; - - - // Doesnt work for some reason - // var colliders = Physics.OverlapBox(d.transform.TransformPoint(box.center), boxOffset * 4, - // Quaternion.identity, - // LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"), - // QueryTriggerInteraction.UseGlobal); - var colliders = GameObject.Find( - $"/{ProceduralTools.DefaultRootStructureObjectName}/{ProceduralTools.DefaultRootWallsObjectName}" - ).transform.GetComponentsInChildren(); - - var wallColliders = colliders; //.Where(s => s.GetComponent()?.Type == SimObjType.Wall); //&& s.GetType().IsAssignableFrom(typeof(BoxCollider))).Select(c => c as BoxCollider); - - var p0 = poly[0]; - var p1 = poly[1]; - - wallColliders = wallColliders.Where(s => s.GetComponent()?.Type == SimObjType.Wall).ToArray(); - Debug.Log("After filter " + wallColliders.Length); - - var p0UpWorld = d.transform.TransformPoint(poly[2] - poly[1]).normalized; - - // var p0World = d.transform.worldToLocalMatrix.MultiplyPoint( p0); - // var p1World = d.transform.worldToLocalMatrix.MultiplyPoint(p1); - - var p0World = p0; - var p1World = p1; - - spheres.Add((p0World, Color.cyan)); - spheres.Add((p1World, Color.green)); - Debug.Log("diff " + (p1 - p0) + " p0: " + p0 + " p1: " + p1 + " p0World: " + p0World + " p1World: " + p1World); - // Gizmos.color = Color.yellow; - // Debug.Dr - // Gizmos.DrawSphere(p0World, 0.2f); - // Gizmos.DrawSphere(p1World, 0.2f); - - var normal = Vector3.Cross((p1World - p0World).normalized, p0UpWorld); - - var colliderDistances = wallColliders.Select(collider => { - var offset = collider.size / 2.0f; - - // Debug.Log("Getting collider: " + collider.gameObject.name + " in dic " + wallMap.ContainsKey(collider.gameObject.name)); - var wallM = wallMap[collider.gameObject.name]; - - - - var localP0 = collider.center - offset; - // var localP0OnConnection = - - var localP1 = collider.center + new Vector3(offset.x, 0, 0) - new Vector3(0, offset.y, 0); - // var topP0 = collider.transform.TransformPoint(collider.center + new Vector3(0, offset.y, 0)); - // var cP0 = collider.transform.TransformPoint(localP0); - // var cP1 = collider.transform.TransformPoint(localP1); - - var topP0 = wallM.polygon[3]; - var cP0 = wallM.polygon[0]; - var cP1 = wallM.polygon[1]; - - var upVec = (topP0 - cP0).normalized; - - - return new { - collider = collider, - p0SqrDistance = (p1World - cP0).sqrMagnitude, - p1SqrDistance = (p0World - cP1).sqrMagnitude, - p0 = cP0, - p1 = cP1, - height = collider.size.y, - normal = Vector3.Cross((cP1 - cP0).normalized, upVec) - }; - }); - - // && Vector3.Dot(next.normal, normal) > 0 - - Debug.Log("Colliders returned " + colliders.Count() + " collider distances " + colliderDistances.Count()); - var dir = (p1World - p0World); - var dirNormalized = dir.normalized; - var eps = 0.1f; - var tEps = 1e-12; - - - var tEpsStrict = 1e-5; - var dirEps = 1e-5; - var normalEps = -1e-4; - - bool wallPointOnConnectionLine(Vector3 wallP0, Vector3 wallP1, Vector3 direction, Vector3 wallNormal, string name) { - var p0Ref = new Vector3(p0World.x, wallP0.y, p0World.z); - var p1Ref = new Vector3(p1World.x, wallP1.y, p1World.z); - - var len = (p1Ref - p0Ref).magnitude; - var connP0ToWallP1 = wallP1 - p0Ref; - // var p0toP1 = direction; - var connP1ToWallP0 = wallP0 - p1Ref; - // var p1toP0 = -p0toP1; - - // var sign = Vector3.Dot(wallNormal, d.transform.forward) >= normalEps ? 1.0f : -1.0f; - // direction *= sign; - - // var proy0 = Vector3.Dot(connP0ToWallP1, direction) * direction; - var t0 = new Vector3(connP0ToWallP1.x / direction.x, connP0ToWallP1.y / direction.y, connP0ToWallP1.z / direction.z); - // var proy1 = Vector3.Dot(connP1ToWallP0, -direction) * -direction; - var t1 = new Vector3(connP1ToWallP0.x / -direction.x, connP1ToWallP0.y / -direction.y, connP1ToWallP0.z / -direction.z); - // var onLine0 = Math.Abs(t0.x - t0.z) < eps || Math.Abs(t0.z) < eps || Math.Abs(t0.x) < eps; - // var onLine1 = Math.Abs(t1.x - t1.z) < eps || Math.Abs(t1.z) < eps || Math.Abs(t1.x) < eps; - - var connP0toWallP0 = (wallP0 - p0Ref).normalized; - var connP1toWallP1 = (wallP1 - p1Ref).normalized; + var connectionsWithWalls = connections + .Where(s => s.Type == filterType) + .Select( + (d, i) => { + var id = d.gameObject.name; + + // Debug.Log($"----- {prefix} " + d.gameObject.name); + var box = d.BoundingBox.GetComponent(); + box.enabled = true; + var boxOffset = box.size / 2.0f; + var poly = getPolygonFromWallObject(d.BoundingBox, flippedForward, true); + + Debug.Log( + $"----- i: {i}, {prefix} {d.gameObject.name} p0 {poly[0]} p1 {poly[1]}" + ); + var polyRev = getPolygonFromWallObject(d.BoundingBox, !flippedForward); + ConnectionProperties connectionProps = + d.GetComponentInChildren(); + var materialId = ""; + + // Doesnt work for some reason + // var colliders = Physics.OverlapBox(d.transform.TransformPoint(box.center), boxOffset * 4, + // Quaternion.identity, + // LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"), + // QueryTriggerInteraction.UseGlobal); + var colliders = GameObject + .Find( + $"/{ProceduralTools.DefaultRootStructureObjectName}/{ProceduralTools.DefaultRootWallsObjectName}" + ) + .transform.GetComponentsInChildren(); + + var wallColliders = colliders; //.Where(s => s.GetComponent()?.Type == SimObjType.Wall); //&& s.GetType().IsAssignableFrom(typeof(BoxCollider))).Select(c => c as BoxCollider); + + var p0 = poly[0]; + var p1 = poly[1]; + + wallColliders = wallColliders + .Where(s => s.GetComponent()?.Type == SimObjType.Wall) + .ToArray(); + Debug.Log("After filter " + wallColliders.Length); + + var p0UpWorld = d.transform.TransformPoint(poly[2] - poly[1]).normalized; + + // var p0World = d.transform.worldToLocalMatrix.MultiplyPoint( p0); + // var p1World = d.transform.worldToLocalMatrix.MultiplyPoint(p1); + + var p0World = p0; + var p1World = p1; + + spheres.Add((p0World, Color.cyan)); + spheres.Add((p1World, Color.green)); + Debug.Log( + "diff " + + (p1 - p0) + + " p0: " + + p0 + + " p1: " + + p1 + + " p0World: " + + p0World + + " p1World: " + + p1World + ); + // Gizmos.color = Color.yellow; + // Debug.Dr + // Gizmos.DrawSphere(p0World, 0.2f); + // Gizmos.DrawSphere(p1World, 0.2f); + + var normal = Vector3.Cross((p1World - p0World).normalized, p0UpWorld); + + var colliderDistances = wallColliders.Select(collider => { + var offset = collider.size / 2.0f; + + // Debug.Log("Getting collider: " + collider.gameObject.name + " in dic " + wallMap.ContainsKey(collider.gameObject.name)); + var wallM = wallMap[collider.gameObject.name]; + + var localP0 = collider.center - offset; + // var localP0OnConnection = + + var localP1 = + collider.center + + new Vector3(offset.x, 0, 0) + - new Vector3(0, offset.y, 0); + // var topP0 = collider.transform.TransformPoint(collider.center + new Vector3(0, offset.y, 0)); + // var cP0 = collider.transform.TransformPoint(localP0); + // var cP1 = collider.transform.TransformPoint(localP1); + + var topP0 = wallM.polygon[3]; + var cP0 = wallM.polygon[0]; + var cP1 = wallM.polygon[1]; + + var upVec = (topP0 - cP0).normalized; + + return new { + collider = collider, + p0SqrDistance = (p1World - cP0).sqrMagnitude, + p1SqrDistance = (p0World - cP1).sqrMagnitude, + p0 = cP0, + p1 = cP1, + height = collider.size.y, + normal = Vector3.Cross((cP1 - cP0).normalized, upVec) + }; + }); - var dot0 = Vector3.Dot(connP0toWallP0, direction.normalized); - var dot1 = Vector3.Dot(connP1toWallP1, -direction.normalized); + // && Vector3.Dot(next.normal, normal) > 0 + + Debug.Log( + "Colliders returned " + + colliders.Count() + + " collider distances " + + colliderDistances.Count() + ); + var dir = (p1World - p0World); + var dirNormalized = dir.normalized; + var eps = 0.1f; + var tEps = 1e-12; + + var tEpsStrict = 1e-5; + var dirEps = 1e-5; + var normalEps = -1e-4; + + bool wallPointOnConnectionLine( + Vector3 wallP0, + Vector3 wallP1, + Vector3 direction, + Vector3 wallNormal, + string name + ) { + var p0Ref = new Vector3(p0World.x, wallP0.y, p0World.z); + var p1Ref = new Vector3(p1World.x, wallP1.y, p1World.z); + + var len = (p1Ref - p0Ref).magnitude; + var connP0ToWallP1 = wallP1 - p0Ref; + // var p0toP1 = direction; + var connP1ToWallP0 = wallP0 - p1Ref; + // var p1toP0 = -p0toP1; + + // var sign = Vector3.Dot(wallNormal, d.transform.forward) >= normalEps ? 1.0f : -1.0f; + // direction *= sign; + + // var proy0 = Vector3.Dot(connP0ToWallP1, direction) * direction; + var t0 = new Vector3( + connP0ToWallP1.x / direction.x, + connP0ToWallP1.y / direction.y, + connP0ToWallP1.z / direction.z + ); + // var proy1 = Vector3.Dot(connP1ToWallP0, -direction) * -direction; + var t1 = new Vector3( + connP1ToWallP0.x / -direction.x, + connP1ToWallP0.y / -direction.y, + connP1ToWallP0.z / -direction.z + ); + // var onLine0 = Math.Abs(t0.x - t0.z) < eps || Math.Abs(t0.z) < eps || Math.Abs(t0.x) < eps; + // var onLine1 = Math.Abs(t1.x - t1.z) < eps || Math.Abs(t1.z) < eps || Math.Abs(t1.x) < eps; + + var connP0toWallP0 = (wallP0 - p0Ref).normalized; + var connP1toWallP1 = (wallP1 - p1Ref).normalized; + + var dot0 = Vector3.Dot(connP0toWallP0, direction.normalized); + var dot1 = Vector3.Dot(connP1toWallP1, -direction.normalized); + + var onLine0 = Math.Abs(dot0) >= 1.0f - eps; + var onLine1 = Math.Abs(dot1) >= 1.0f - eps; + + if ( + name == "wall_3_1" + || name == "wall_3_2" && d.gameObject.name == "Window_3" + ) { + Debug.Log( + $" ^^^^^^^^^^ DIRECTION p0 {p0World.x},{p0World.y},{p0World.z} p1 {p1World.x},{p1World.y},{p1World.z} dir {dir.x},{dir.y},{dir.z}" + ); + Debug.Log( + $"************* wall {name}, wallp0 ({wallP0.x}, {wallP0.y}, {wallP0.z}), wallp1 ({wallP1.x}, {wallP1.y}, {wallP1.z}), connP0 {p0Ref}, connP1 {p1Ref}, connP0ToWallP1 {connP0ToWallP1}, connP1ToWallP0 {connP1ToWallP0} dir {direction} connP1ToWallP0 {connP1ToWallP0} connP0ToWallP1 {connP0ToWallP1} t0.x {t0.x}, t0.y {t0.y}, t0.z {t0.z} t1.x {t1.x}, t1.y {t1.y}, t1.z {t1.z} onLine0 {onLine0}, onLine1 {onLine1} dot0 {dot0} dot1 {dot1} num0.z {connP0ToWallP1.z} num1.z {connP1ToWallP0.z} dir.z {direction.z}" + ); + } + + return ( + onLine0 + && ( + ( + Math.Abs(direction.x) > dirEps + && t0.x <= (1.0f + tEpsStrict) + && t0.x >= (0.0f - tEpsStrict) + ) + || ( + ( + Math.Abs(direction.z) > dirEps + && t0.z <= (1.0f + tEpsStrict) + && t0.z >= (0.0f - tEpsStrict) + ) + ) + ) + ) + || ( + onLine1 + && ( + ( + Math.Abs(direction.x) > dirEps + && t1.x <= (1.0f + tEpsStrict) + && t1.x >= (0.0f - tEpsStrict) + ) + || ( + ( + Math.Abs(direction.z) > dirEps + && t1.z <= (1.0f + tEpsStrict) + && t1.z >= (0.0f - tEpsStrict) + ) + ) + ) + ); + } - var onLine0 = Math.Abs(dot0) >= 1.0f - eps; - var onLine1 = Math.Abs(dot1) >= 1.0f - eps; + // bool pointOnWallLine(Vector3 p, Vector3 direction, Vector3 origin, string name) { + // var num = (p - origin); + // var proyLength = Vector3.Dot(num, direction); + // num = direction * proyLength; + + + // var t = new Vector3(num.x / direction.x, num.y / direction.y, num.z / direction.z); + // var onLine = Math.Abs(t.x - t.z) < eps; + + // if (name == "wall1_7" || name == "wall1_6" || name == "wall1_5" && d.gameObject.name == "Window_1") { + // Debug.Log($"************* wall {name}, p {p}, orig {origin}, diff {(p - origin)} dir {direction} PROJ {proyLength} num {num} t.x {t.x}, t.y {t.y}, t.z {t.z} onLine {onLine}" ); + // } + // return onLine && t.x <= (1.0f+tEps) && t.x >= (0.0f-tEps); + // } + + bool pointOnWallLine( + Vector3 p, + Vector3 direction, + Vector3 origin, + string name, + string side = "" + ) { + var originRef = new Vector3(origin.x, p.y, origin.z); + var originToP = (p - originRef); + + var dot0 = Vector3.Dot(originToP.normalized, direction.normalized); + + var t = new Vector3( + originToP.x / direction.x, + originToP.y / direction.y, + originToP.z / direction.z + ); + // var proyLength = Vector3.Dot(num, direction); + + var onLine = Math.Abs(dot0) >= 1.0f - eps; + + // if (name == "wall1_7" || name == "wall1_6" || name == "wall1_5" && d.gameObject.name == "Window_1") { + // if (name == "wall_2_8" && d.gameObject.name == "Window_Hung_48x44") { + if ( + name == "wall_2_6" + || name == "wall_2_7" + || name == "wall_2_8" && d.gameObject.name == "Window_5" + ) { + Debug.Log( + $"!!!!!!!!!!!!!!! Window_Hung_48x44 wall {name} - {side} walls, p {p}, orig {originRef}, dir {direction} dot0 {dot0} originToP {originToP} t.x {t.x}, t.y {t.y}, t.z {t.z} onLine {onLine} t.x <= (1.0f+tEps) {t.x <= (1.0f + tEps)} t.x >= (0.0f-tEps) {t.x >= (0.0f - tEps)} (Math.Abs(direction.x) > dirEps && t.x <= (1.0f+tEps) && t.x >= (0.0f-tEps)) {(Math.Abs(direction.x) > dirEps && t.x <= (1.0f + tEps) && t.x >= (0.0f - tEps))} ((Math.Abs(direction.z) > dirEps && t.z <= (1.0f+tEps) && t.z >= (0.0f-tEps))) {((Math.Abs(direction.z) > dirEps && t.z <= (1.0f + tEps) && t.z >= (0.0f - tEps)))} " + ); + } + + return onLine + && ( + ( + Math.Abs(direction.x) > dirEps + && t.x <= (1.0f + tEps) + && t.x >= (0.0f - tEps) + ) + || ( + ( + Math.Abs(direction.z) > dirEps + && t.z <= (1.0f + tEps) + && t.z >= (0.0f - tEps) + ) + ) + ); + } - if (name == "wall_3_1" || name == "wall_3_2" && d.gameObject.name == "Window_3") { - Debug.Log($" ^^^^^^^^^^ DIRECTION p0 {p0World.x},{p0World.y},{p0World.z} p1 {p1World.x},{p1World.y},{p1World.z} dir {dir.x},{dir.y},{dir.z}"); - Debug.Log($"************* wall {name}, wallp0 ({wallP0.x}, {wallP0.y}, {wallP0.z}), wallp1 ({wallP1.x}, {wallP1.y}, {wallP1.z}), connP0 {p0Ref}, connP1 {p1Ref}, connP0ToWallP1 {connP0ToWallP1}, connP1ToWallP0 {connP1ToWallP0} dir {direction} connP1ToWallP0 {connP1ToWallP0} connP0ToWallP1 {connP0ToWallP1} t0.x {t0.x}, t0.y {t0.y}, t0.z {t0.z} t1.x {t1.x}, t1.y {t1.y}, t1.z {t1.z} onLine0 {onLine0}, onLine1 {onLine1} dot0 {dot0} dot1 {dot1} num0.z {connP0ToWallP1.z} num1.z {connP1ToWallP0.z} dir.z {direction.z}"); - } + var connectionNormal = flippedForward + ? -d.transform.forward + : d.transform.forward; + // if (filterType == SimObjType.Window) { + // connectionNormal = -connectionNormal; + // } + + // Func pointOnWallLine = (Vector3 p, Vector3 direction, Vector3 origin, string name, bool ignoreSign) => { + + // }; + + var wallRight = colliderDistances.Aggregate( + new { + collider = box, + p0SqrDistance = float.MaxValue, + p1SqrDistance = float.MaxValue, + p0 = new Vector3(), + p1 = new Vector3(), + height = 0.0f, + normal = new Vector3() + }, + (min, next) => + min.p0SqrDistance > next.p0SqrDistance + && Vector3.Dot(next.collider.transform.forward, connectionNormal) + >= normalEps + && !pointOnWallLine( + next.p0, + dir, + p0World, + next.collider.gameObject.name, + "right" + ) + ? next + : min + ); + + // && Vector3.Dot(next.normal, normal) > 0 + var wallLeft = colliderDistances.Aggregate( + new { + collider = box, + p0SqrDistance = float.MaxValue, + p1SqrDistance = float.MaxValue, + p0 = new Vector3(), + p1 = new Vector3(), + height = 0.0f, + normal = new Vector3() + }, + (min, next) => { + var name = next.collider.gameObject.name; + // if (name == "wall1_7" || name == "wall1_6" || name == "wall1_5" && d.gameObject.name == "Window_1") { + if (name == "wall_2_8" && d.gameObject.name == "Window_Hung_48x44") { + Debug.Log( + $"########## -- connection {d.gameObject.name} wall Left {name} p1SqrDistance {next.p1SqrDistance}, normal {Vector3.Dot(next.collider.transform.forward, connectionNormal)} !onLine {!pointOnWallLine(next.p1, -dirNormalized, p1World, next.collider.gameObject.name)}" + ); + } + + return + min.p1SqrDistance > next.p1SqrDistance + && Vector3.Dot(next.collider.transform.forward, connectionNormal) + >= normalEps + // && wallPointOnConnectionLine(next.p0, next.p1, -dirNormalized) + && !pointOnWallLine( + next.p1, + -dir, + p1World, + next.collider.gameObject.name, + "left" + ) + ? next + : min; + } + ); + + Debug.Log($"^^^^^^^^^^^^ Wall left p0: {wallLeft.p0} p1: {wallLeft.p1}"); + + var backWallClosestLeft = colliderDistances.Aggregate( + new { + collider = box, + p0SqrDistance = float.MaxValue, + p1SqrDistance = float.MaxValue, + p0 = new Vector3(), + p1 = new Vector3(), + height = 0.0f, + normal = new Vector3() + }, + (min, next) => + min.p0SqrDistance > next.p0SqrDistance + && Vector3.Dot(next.collider.transform.forward, -connectionNormal) + >= normalEps + && !pointOnWallLine( + next.p0, + -dirNormalized, + p1World, + next.collider.gameObject.name, + "backLeft" + ) + ? next + : min + ); + + var backWallClosestRight = colliderDistances.Aggregate( + new { + collider = box, + p0SqrDistance = float.MaxValue, + p1SqrDistance = float.MaxValue, + p0 = new Vector3(), + p1 = new Vector3(), + height = 0.0f, + normal = new Vector3() + }, + (min, next) => + min.p1SqrDistance > next.p1SqrDistance + && Vector3.Dot(next.collider.transform.forward, -connectionNormal) + >= normalEps + && !pointOnWallLine( + next.p1, + dirNormalized, + p0World, + next.collider.gameObject.name, + "backRight" + ) + ? next + : min + ); + + var toDelete = colliderDistances.Where(next => + ( + Vector3.Dot(next.collider.transform.forward, connectionNormal) + >= normalEps + && pointOnWallLine( + next.p0, + dir, + p0World, + next.collider.gameObject.name, + "right" + ) + ) + || ( + Vector3.Dot(next.collider.transform.forward, connectionNormal) + >= normalEps + && pointOnWallLine( + next.p1, + -dir, + p1World, + next.collider.gameObject.name, + "left" + ) + ) + || ( + Vector3.Dot(next.collider.transform.forward, -connectionNormal) + >= normalEps + && pointOnWallLine( + next.p0, + -dirNormalized, + p1World, + next.collider.gameObject.name, + "backLeft" + ) + ) + || ( + Vector3.Dot(next.collider.transform.forward, -connectionNormal) + >= normalEps + && pointOnWallLine( + next.p1, + dirNormalized, + p0World, + next.collider.gameObject.name, + "backRight" + ) + ) + // next => wallPointOnConnectionLine(next.p0, next.p1, dir, next.collider.transform.forward, next.collider.gameObject.name) + ); + + Debug.Log( + $"&&&&&&&&&& TODELETE {d.gameObject.name} " + + string.Join(", ", toDelete.Select(w => w.collider.gameObject.name)) + ); + + //Debug.Log("Walls0 " + wall0.collider.name + " wall 1 " +wall1.collider.gameObject.name); + // var debug = colliderDistances.ToList()[0]; + // // var debug = colliderDistances.ElementAt(0); + // Debug.Log(" p0 CDist " + debug.p0SqrDistance + " p1 CDist " + debug.p1SqrDistance + " name " + debug.collider.GetComponentInParent().ObjectID); + Debug.Log( + "walls_right " + + wallRight.collider.gameObject.name + + " dist " + + wallRight.p0SqrDistance + + " wall_left " + + wallLeft.collider.gameObject.name + + " dist " + + wallLeft.p1SqrDistance + + " backwallLeft " + + backWallClosestLeft.collider.gameObject.name + + " backwallRight " + + backWallClosestRight.collider.name + ); + + spheres.Add((wallLeft.p1, Color.red)); + spheres.Add((wallRight.p0, Color.blue)); + // var m_HitDetect = Physics.BoxCast(box.bounds.center, boxOffset * 4, transform.forward, out m_Hit, transform.rotation, m_MaxDistance); + // if (m_HitDetect) + // { + // //Output the name of the Collider your Box hit + // Debug.Log("Hit : " + m_Hit.collider.name); + // } + // var wall = new PolygonWall { + // id = $"wall_{id}_front", + // roomId = connectionProps?.OpenFromRoomId, + // polygon = poly, + // // TODO get material somehow + // // material = connectionProps?.openFromWallMaterial?.name + // material = wallRight.collider.GetComponent().sharedMaterial.name + + // // materialTilingXDivisor = box.size.x / material.mainTextureScale.x, + // // materialTilingYDivisor = box.size.y / material.mainTextureScale.y}; + // }; + // var wallRev = new PolygonWall { + // id = $"wall_{id}_back", + // roomId = connectionProps?.OpenToRoomId, + // polygon = polyRev, + // // TODO get material somehow + // // material = connectionProps?.openToWallMaterial?.name + + // material = backWallClosestLeft.collider.GetComponent().sharedMaterial.name + + // // materialTilingXDivisor = box.size.x / material.mainTextureScale.x, + // // materialTilingYDivisor = box.size.y / material.mainTextureScale.y}; + // }; + + var wall = createNewWall( + $"wall_{id}_front", + connectionProps, + wallLeft.p1, + wallRight.p0, + wallLeft.height, + wallLeft.collider.GetComponent().sharedMaterial + ); + + var material = backWallClosestRight + .collider.GetComponent() + .sharedMaterial; + var lenn = (wall.polygon[1] - wall.polygon[0]).magnitude; + // var height = + var wallRev = new PolygonWall { + id = $"wall_{id}_back", + roomId = connectionProps?.OpenToRoomId, + polygon = new List() + { + wall.polygon[1], + wall.polygon[0], + wall.polygon[3], + wall.polygon[2] + }, + // polygon = getPolygonFromWallPoints(p0, p1, backWallClosestRight.height), + // TODO get material somehow + // material = connectionProps?.openFromWallMaterial?.name + material = new MaterialProperties() { + name = material.name, + tilingDivisorX = lenn / material.mainTextureScale.x, + tilingDivisorY = + backWallClosestRight.height / material.mainTextureScale.y + }, + }; - return - (onLine0 && ((Math.Abs(direction.x) > dirEps && t0.x <= (1.0f + tEpsStrict) && t0.x >= (0.0f - tEpsStrict)) || ((Math.Abs(direction.z) > dirEps && t0.z <= (1.0f + tEpsStrict) && t0.z >= (0.0f - tEpsStrict))))) - || - (onLine1 && ((Math.Abs(direction.x) > dirEps && t1.x <= (1.0f + tEpsStrict) && t1.x >= (0.0f - tEpsStrict)) || ((Math.Abs(direction.z) > dirEps && t1.z <= (1.0f + tEpsStrict) && t1.z >= (0.0f - tEpsStrict))))); - } + // var wallRev = createNewWall( + // $"wall_{id}_back", + // connectionProps, + // backWallClosestLeft.p0, + // backWallClosestRight.p1, + + // backWallClosestRight.height, + // backWallClosestRight.collider.GetComponent().sharedMaterial + // ); + + Debug.Log( + $"^^^^^^^^^^^^ Created wall p0: {wall.polygon[0].ToString("F8")} p1: {wall.polygon[1].ToString("F8")}" + ); + + WallRectangularHole connection = null; + + var p0WallLevel = new Vector3(p0World.x, wallLeft.p1.y, p0World.z); + var p0ToConnection = p0WallLevel - wallLeft.p1; + var xLen = Vector3.Dot(p0ToConnection, p0ToConnection.normalized); + + Debug.Log($"............. Door {xLen} p0To {p0ToConnection} "); + + var assetId = !string.IsNullOrEmpty(d.assetID) + ? d.assetID + : PrefabNameRevert.GetPrefabAssetName(d.gameObject); + + // assetId = assetId == null ? d.assetID : assetId; + + if (filterType == SimObjType.Doorway) { + connection = new Thor.Procedural.Data.Door { + id = id, + + room0 = connectionProps?.OpenFromRoomId, + room1 = connectionProps?.OpenToRoomId, + wall0 = wall.id, + wall1 = wallRev.id, + holePolygon = new List() + { + new Vector3(xLen, 0.0f, box.size.z / 2.0f), + new Vector3(xLen + box.size.x, box.size.y, box.size.z / 2.0f) + }, + // boundingBox = new Thor.Procedural.Data.BoundingBox { min = new Vector3(xLen, 0.0f, box.size.z / 2.0f), max = new Vector3(xLen + box.size.x, box.size.y, box.size.z / 2.0f) }, + type = Enum.GetName( + typeof(ConnectionType), + (connectionProps?.Type).GetValueOrDefault() + ), + + openable = d.SecondaryProperties.Contains( + SimObjSecondaryProperty.CanOpen + ), + openness = (connectionProps?.IsOpen).GetValueOrDefault() ? 1.0f : 0.0f, + assetId = assetId + }; + } else if (filterType == SimObjType.Window) { + var yMin = p0World.y - wallLeft.p1.y; + connection = new Thor.Procedural.Data.Window { + id = id, + + room0 = connectionProps?.OpenFromRoomId, + room1 = connectionProps?.OpenToRoomId, + wall0 = wall.id, + wall1 = wallRev.id, + holePolygon = new List() + { + new Vector3(xLen, yMin, box.size.z / 2.0f), // Min + new Vector3(xLen + box.size.x, yMin + box.size.y, box.size.z / 2.0f) // Max + }, + + // boundingBox = new Thor.Procedural.Data.BoundingBox { min = box.center - boxOffset, max = box.center + boxOffset }, + type = Enum.GetName( + typeof(ConnectionType), + (connectionProps?.Type).GetValueOrDefault() + ), + openable = d.SecondaryProperties.Contains( + SimObjSecondaryProperty.CanOpen + ), + + openness = (connectionProps?.IsOpen).GetValueOrDefault() ? 1.0f : 0.0f, + assetId = assetId + }; + } - // bool pointOnWallLine(Vector3 p, Vector3 direction, Vector3 origin, string name) { - // var num = (p - origin); - // var proyLength = Vector3.Dot(num, direction); - // num = direction * proyLength; + // var connection = new Thor.Procedural.Data.Door { + // id = id, - // var t = new Vector3(num.x / direction.x, num.y / direction.y, num.z / direction.z); - // var onLine = Math.Abs(t.x - t.z) < eps; + // room0 = connectionProps?.OpenFromRoomId, + // room1 = connectionProps?.OpenToRoomId, + // wall0 = wall.id, + // wall1 = wallRev.id, + // boundingBox = new Thor.Procedural.Data.BoundingBox { min = box.center - boxOffset, max = box.center + boxOffset }, + // type = "???", + // openable = d.SecondaryProperties.Contains(SimObjSecondaryProperty.CanOpen), + // // TODO + // open = false, + // assetId = PrefabNameRevert.GetPrefabAssetName(d.gameObject) - // if (name == "wall1_7" || name == "wall1_6" || name == "wall1_5" && d.gameObject.name == "Window_1") { - // Debug.Log($"************* wall {name}, p {p}, orig {origin}, diff {(p - origin)} dir {direction} PROJ {proyLength} num {num} t.x {t.x}, t.y {t.y}, t.z {t.z} onLine {onLine}" ); - // } - // return onLine && t.x <= (1.0f+tEps) && t.x >= (0.0f-tEps); - // } + // }; + box.enabled = false; - bool pointOnWallLine(Vector3 p, Vector3 direction, Vector3 origin, string name, string side = "") { + var wallsToCreate = new List<(PolygonWall wall, string afterWallId)>() + { + (wall, wallLeft.collider.name), + (wallRev, backWallClosestLeft.collider.name) + }; - var originRef = new Vector3(origin.x, p.y, origin.z); - var originToP = (p - originRef); + // if ( wallLeft.p1SqrDistance > minimumWallSqrDistanceCreateEpsilon ) { + // wallsToCreate.Add( + // createNewWall( + // $"wall_{id}_left_front", connectionProps, wallLeft.p1, p0World, wallLeft.height, wallLeft.collider.GetComponent().sharedMaterial) + // ); + // } - var dot0 = Vector3.Dot(originToP.normalized, direction.normalized); + // if ( (backWallClosestLeft.p0 - p0World).magnitude > minimumWallSqrDistanceCreateEpsilon ) { - var t = new Vector3(originToP.x / direction.x, originToP.y / direction.y, originToP.z / direction.z); - // var proyLength = Vector3.Dot(num, direction); + // wallsToCreate.Add( + // createNewWall($"wall_{id}_right_back", connectionProps, backWallClosestLeft.p0, p0World, backWallClosestLeft.height, backWallClosestLeft.collider.GetComponent().sharedMaterial) + // ); + // } - var onLine = Math.Abs(dot0) >= 1.0f - eps; + // if ( wallRight.p0SqrDistance > minimumWallSqrDistanceCreateEpsilon ) { + // wallsToCreate.Add( + // createNewWall($"wall_{id}_right_front", connectionProps, wallRight.p0, p1World, wallRight.height, wallRight.collider.GetComponent().sharedMaterial) + // ); + // } - // if (name == "wall1_7" || name == "wall1_6" || name == "wall1_5" && d.gameObject.name == "Window_1") { - // if (name == "wall_2_8" && d.gameObject.name == "Window_Hung_48x44") { - if (name == "wall_2_6" || name == "wall_2_7" || name == "wall_2_8" && d.gameObject.name == "Window_5") { + // if ( (backWallClosestRight.p1 - p1World).magnitude > minimumWallSqrDistanceCreateEpsilon ) { - Debug.Log($"!!!!!!!!!!!!!!! Window_Hung_48x44 wall {name} - {side} walls, p {p}, orig {originRef}, dir {direction} dot0 {dot0} originToP {originToP} t.x {t.x}, t.y {t.y}, t.z {t.z} onLine {onLine} t.x <= (1.0f+tEps) {t.x <= (1.0f + tEps)} t.x >= (0.0f-tEps) {t.x >= (0.0f - tEps)} (Math.Abs(direction.x) > dirEps && t.x <= (1.0f+tEps) && t.x >= (0.0f-tEps)) {(Math.Abs(direction.x) > dirEps && t.x <= (1.0f + tEps) && t.x >= (0.0f - tEps))} ((Math.Abs(direction.z) > dirEps && t.z <= (1.0f+tEps) && t.z >= (0.0f-tEps))) {((Math.Abs(direction.z) > dirEps && t.z <= (1.0f + tEps) && t.z >= (0.0f - tEps)))} "); - } + // // Debug.Log(" Wall closest right dist " + ) + // wallsToCreate.Add( + // createNewWall($"wall_{id}_right_back", connectionProps, backWallClosestRight.p1, p1World, backWallClosestLeft.height, backWallClosestLeft.collider.GetComponent().sharedMaterial) + // ); + // } - return onLine && ((Math.Abs(direction.x) > dirEps && t.x <= (1.0f + tEps) && t.x >= (0.0f - tEps)) || ((Math.Abs(direction.z) > dirEps && t.z <= (1.0f + tEps) && t.z >= (0.0f - tEps)))); + // wallsToCreate.Add((wall, wallLeft.collider.name)); - } + // if (filterType != SimObjType.Window) { - var connectionNormal = flippedForward ? -d.transform.forward : d.transform.forward; - // if (filterType == SimObjType.Window) { - // connectionNormal = -connectionNormal; - // } + // wallsToCreate.Add((wallRev, backWallClosestLeft.collider.name)); - // Func pointOnWallLine = (Vector3 p, Vector3 direction, Vector3 origin, string name, bool ignoreSign) => { - - // }; - - var wallRight = colliderDistances.Aggregate(new { - collider = box, - p0SqrDistance = float.MaxValue, - p1SqrDistance = float.MaxValue, - p0 = new Vector3(), - p1 = new Vector3(), - height = 0.0f, - normal = new Vector3() - }, - (min, next) => - min.p0SqrDistance > next.p0SqrDistance - && Vector3.Dot(next.collider.transform.forward, connectionNormal) >= normalEps - && !pointOnWallLine(next.p0, dir, p0World, next.collider.gameObject.name, "right") ? next : min - ); + // wallsToCreate = wallsToCreate.(new List<(PolygonWall wall, string afterWallId)>() {(wallRev, backWallClosestLeft.collider.name)}); + // } - // && Vector3.Dot(next.normal, normal) > 0 - var wallLeft = colliderDistances.Aggregate(new { - collider = box, - p0SqrDistance = float.MaxValue, - p1SqrDistance = float.MaxValue, - p0 = new Vector3(), - p1 = new Vector3(), - height = 0.0f, - normal = new Vector3() - }, - (min, next) => { - var name = next.collider.gameObject.name; - // if (name == "wall1_7" || name == "wall1_6" || name == "wall1_5" && d.gameObject.name == "Window_1") { - if (name == "wall_2_8" && d.gameObject.name == "Window_Hung_48x44") { - Debug.Log($"########## -- connection {d.gameObject.name} wall Left {name} p1SqrDistance {next.p1SqrDistance}, normal {Vector3.Dot(next.collider.transform.forward, connectionNormal)} !onLine {!pointOnWallLine(next.p1, -dirNormalized, p1World, next.collider.gameObject.name)}"); - } + Debug.Log( + "^^^^^^^^^^^^^^^^ SUPPOSED TO ADD PIECE OF SHIT " + + string.Join(", ", wallsToCreate.Select(x => x.afterWallId)) + ); - return - min.p1SqrDistance > next.p1SqrDistance - && Vector3.Dot(next.collider.transform.forward, connectionNormal) >= normalEps - // && wallPointOnConnectionLine(next.p0, next.p1, -dirNormalized) - && !pointOnWallLine(next.p1, -dir, p1World, next.collider.gameObject.name, "left") - ? next : min; + var anchoredSet = new HashSet() + { + wallLeft.collider.name, + wallRight.collider.name, + backWallClosestLeft.collider.name, + backWallClosestRight.collider.name + }; + toDelete = toDelete.Where(o => !anchoredSet.Contains(o.collider.name)); + Debug.Log( + $"~~~~~~~~~~ Walls to delete {string.Join(", ", toDelete.Select(o => o.collider.name))}" + ); + + return new ConnectionAndWalls() { + connection = connection, + walls = wallsToCreate, + wallIdsToDelete = toDelete.Select(o => o.collider.name).ToList() + }; } ); - - Debug.Log($"^^^^^^^^^^^^ Wall left p0: {wallLeft.p0} p1: {wallLeft.p1}"); - - - var backWallClosestLeft = colliderDistances.Aggregate(new { - collider = box, - p0SqrDistance = float.MaxValue, - p1SqrDistance = float.MaxValue, - p0 = new Vector3(), - p1 = new Vector3(), - height = 0.0f, - normal = new Vector3() - }, - (min, next) => - min.p0SqrDistance > next.p0SqrDistance - && Vector3.Dot(next.collider.transform.forward, -connectionNormal) >= normalEps - && !pointOnWallLine(next.p0, -dirNormalized, p1World, next.collider.gameObject.name, "backLeft") - ? next : min - ); - - - var backWallClosestRight = colliderDistances.Aggregate(new { - collider = box, - p0SqrDistance = float.MaxValue, - p1SqrDistance = float.MaxValue, - p0 = new Vector3(), - p1 = new Vector3(), - height = 0.0f, - normal = new Vector3() - }, - (min, next) => - min.p1SqrDistance > next.p1SqrDistance && - Vector3.Dot(next.collider.transform.forward, -connectionNormal) >= normalEps - && !pointOnWallLine(next.p1, dirNormalized, p0World, next.collider.gameObject.name, "backRight") - ? next : min - ); - - - var toDelete = colliderDistances.Where( - next => - ( - Vector3.Dot(next.collider.transform.forward, connectionNormal) >= normalEps - && pointOnWallLine(next.p0, dir, p0World, next.collider.gameObject.name, "right") - ) - || - ( - Vector3.Dot(next.collider.transform.forward, connectionNormal) >= normalEps - && pointOnWallLine(next.p1, -dir, p1World, next.collider.gameObject.name, "left") - ) - || - ( - Vector3.Dot(next.collider.transform.forward, -connectionNormal) >= normalEps - && pointOnWallLine(next.p0, -dirNormalized, p1World, next.collider.gameObject.name, "backLeft") - ) - || - ( - Vector3.Dot(next.collider.transform.forward, -connectionNormal) >= normalEps - && pointOnWallLine(next.p1, dirNormalized, p0World, next.collider.gameObject.name, "backRight") - ) - // next => wallPointOnConnectionLine(next.p0, next.p1, dir, next.collider.transform.forward, next.collider.gameObject.name) - ); - - - Debug.Log($"&&&&&&&&&& TODELETE {d.gameObject.name} " + string.Join(", ", toDelete.Select(w => w.collider.gameObject.name))); - - //Debug.Log("Walls0 " + wall0.collider.name + " wall 1 " +wall1.collider.gameObject.name); - // var debug = colliderDistances.ToList()[0]; - // // var debug = colliderDistances.ElementAt(0); - // Debug.Log(" p0 CDist " + debug.p0SqrDistance + " p1 CDist " + debug.p1SqrDistance + " name " + debug.collider.GetComponentInParent().ObjectID); - Debug.Log("walls_right " + wallRight.collider.gameObject.name + " dist " + wallRight.p0SqrDistance + " wall_left " + wallLeft.collider.gameObject.name + " dist " + wallLeft.p1SqrDistance + - " backwallLeft " + backWallClosestLeft.collider.gameObject.name + " backwallRight " + backWallClosestRight.collider.name); - - - spheres.Add((wallLeft.p1, Color.red)); - spheres.Add((wallRight.p0, Color.blue)); - // var m_HitDetect = Physics.BoxCast(box.bounds.center, boxOffset * 4, transform.forward, out m_Hit, transform.rotation, m_MaxDistance); - // if (m_HitDetect) - // { - // //Output the name of the Collider your Box hit - // Debug.Log("Hit : " + m_Hit.collider.name); - // } - // var wall = new PolygonWall { - // id = $"wall_{id}_front", - // roomId = connectionProps?.OpenFromRoomId, - // polygon = poly, - // // TODO get material somehow - // // material = connectionProps?.openFromWallMaterial?.name - // material = wallRight.collider.GetComponent().sharedMaterial.name - - // // materialTilingXDivisor = box.size.x / material.mainTextureScale.x, - // // materialTilingYDivisor = box.size.y / material.mainTextureScale.y}; - // }; - // var wallRev = new PolygonWall { - // id = $"wall_{id}_back", - // roomId = connectionProps?.OpenToRoomId, - // polygon = polyRev, - // // TODO get material somehow - // // material = connectionProps?.openToWallMaterial?.name - - // material = backWallClosestLeft.collider.GetComponent().sharedMaterial.name - - // // materialTilingXDivisor = box.size.x / material.mainTextureScale.x, - // // materialTilingYDivisor = box.size.y / material.mainTextureScale.y}; - // }; - - var wall = createNewWall( - $"wall_{id}_front", - connectionProps, - wallLeft.p1, - wallRight.p0, - wallLeft.height, - wallLeft.collider.GetComponent().sharedMaterial - ); - - var material = backWallClosestRight.collider.GetComponent().sharedMaterial; - var lenn = (wall.polygon[1] - wall.polygon[0]).magnitude; - // var height = - var wallRev = new PolygonWall { - id = $"wall_{id}_back", - roomId = connectionProps?.OpenToRoomId, - polygon = new List() { wall.polygon[1], wall.polygon[0], wall.polygon[3], wall.polygon[2] }, - // polygon = getPolygonFromWallPoints(p0, p1, backWallClosestRight.height), - // TODO get material somehow - // material = connectionProps?.openFromWallMaterial?.name - material = new MaterialProperties() { - name = material.name, - tilingDivisorX = lenn / material.mainTextureScale.x, - tilingDivisorY = backWallClosestRight.height / material.mainTextureScale.y - }, - }; - - // var wallRev = createNewWall( - // $"wall_{id}_back", - // connectionProps, - // backWallClosestLeft.p0, - // backWallClosestRight.p1, - - // backWallClosestRight.height, - // backWallClosestRight.collider.GetComponent().sharedMaterial - // ); - - Debug.Log($"^^^^^^^^^^^^ Created wall p0: {wall.polygon[0].ToString("F8")} p1: {wall.polygon[1].ToString("F8")}"); - - WallRectangularHole connection = null; - - var p0WallLevel = new Vector3(p0World.x, wallLeft.p1.y, p0World.z); - var p0ToConnection = p0WallLevel - wallLeft.p1; - var xLen = Vector3.Dot(p0ToConnection, p0ToConnection.normalized); - - Debug.Log($"............. Door {xLen} p0To {p0ToConnection} "); - - - var assetId = !string.IsNullOrEmpty(d.assetID) ? d.assetID : PrefabNameRevert.GetPrefabAssetName(d.gameObject); - - // assetId = assetId == null ? d.assetID : assetId; - - if (filterType == SimObjType.Doorway) { - - - - connection = new Thor.Procedural.Data.Door { - - id = id, - - room0 = connectionProps?.OpenFromRoomId, - room1 = connectionProps?.OpenToRoomId, - wall0 = wall.id, - wall1 = wallRev.id, - holePolygon = new List() { new Vector3(xLen, 0.0f, box.size.z / 2.0f), new Vector3(xLen + box.size.x, box.size.y, box.size.z / 2.0f) }, - // boundingBox = new Thor.Procedural.Data.BoundingBox { min = new Vector3(xLen, 0.0f, box.size.z / 2.0f), max = new Vector3(xLen + box.size.x, box.size.y, box.size.z / 2.0f) }, - type = Enum.GetName(typeof(ConnectionType), (connectionProps?.Type).GetValueOrDefault()), - - openable = d.SecondaryProperties.Contains(SimObjSecondaryProperty.CanOpen), - openness = (connectionProps?.IsOpen).GetValueOrDefault() ? 1.0f : 0.0f, - assetId = assetId - - }; - } else if (filterType == SimObjType.Window) { - var yMin = p0World.y - wallLeft.p1.y; - connection = new Thor.Procedural.Data.Window { - - id = id, - - room0 = connectionProps?.OpenFromRoomId, - room1 = connectionProps?.OpenToRoomId, - wall0 = wall.id, - wall1 = wallRev.id, - holePolygon = new List() { - new Vector3(xLen, yMin, box.size.z / 2.0f), // Min - new Vector3(xLen + box.size.x, yMin + box.size.y, box.size.z / 2.0f) // Max - }, - - // boundingBox = new Thor.Procedural.Data.BoundingBox { min = box.center - boxOffset, max = box.center + boxOffset }, - type = Enum.GetName(typeof(ConnectionType), (connectionProps?.Type).GetValueOrDefault()), - openable = d.SecondaryProperties.Contains(SimObjSecondaryProperty.CanOpen), - - openness = (connectionProps?.IsOpen).GetValueOrDefault() ? 1.0f : 0.0f, - assetId = assetId - - }; - } - - // var connection = new Thor.Procedural.Data.Door { - - // id = id, - - // room0 = connectionProps?.OpenFromRoomId, - // room1 = connectionProps?.OpenToRoomId, - // wall0 = wall.id, - // wall1 = wallRev.id, - // boundingBox = new Thor.Procedural.Data.BoundingBox { min = box.center - boxOffset, max = box.center + boxOffset }, - // type = "???", - // openable = d.SecondaryProperties.Contains(SimObjSecondaryProperty.CanOpen), - // // TODO - // open = false, - // assetId = PrefabNameRevert.GetPrefabAssetName(d.gameObject) - - // }; - box.enabled = false; - - - var wallsToCreate = new List<(PolygonWall wall, string afterWallId)>() { (wall, wallLeft.collider.name), (wallRev, backWallClosestLeft.collider.name) }; - - // if ( wallLeft.p1SqrDistance > minimumWallSqrDistanceCreateEpsilon ) { - // wallsToCreate.Add( - // createNewWall( - // $"wall_{id}_left_front", connectionProps, wallLeft.p1, p0World, wallLeft.height, wallLeft.collider.GetComponent().sharedMaterial) - // ); - // } - - // if ( (backWallClosestLeft.p0 - p0World).magnitude > minimumWallSqrDistanceCreateEpsilon ) { - - // wallsToCreate.Add( - // createNewWall($"wall_{id}_right_back", connectionProps, backWallClosestLeft.p0, p0World, backWallClosestLeft.height, backWallClosestLeft.collider.GetComponent().sharedMaterial) - // ); - // } - - // if ( wallRight.p0SqrDistance > minimumWallSqrDistanceCreateEpsilon ) { - // wallsToCreate.Add( - // createNewWall($"wall_{id}_right_front", connectionProps, wallRight.p0, p1World, wallRight.height, wallRight.collider.GetComponent().sharedMaterial) - // ); - // } - - // if ( (backWallClosestRight.p1 - p1World).magnitude > minimumWallSqrDistanceCreateEpsilon ) { - - // // Debug.Log(" Wall closest right dist " + ) - // wallsToCreate.Add( - // createNewWall($"wall_{id}_right_back", connectionProps, backWallClosestRight.p1, p1World, backWallClosestLeft.height, backWallClosestLeft.collider.GetComponent().sharedMaterial) - // ); - // } - - // wallsToCreate.Add((wall, wallLeft.collider.name)); - - // if (filterType != SimObjType.Window) { - - // wallsToCreate.Add((wallRev, backWallClosestLeft.collider.name)); - - // wallsToCreate = wallsToCreate.(new List<(PolygonWall wall, string afterWallId)>() {(wallRev, backWallClosestLeft.collider.name)}); - // } - - Debug.Log("^^^^^^^^^^^^^^^^ SUPPOSED TO ADD PIECE OF SHIT " + string.Join(", ", wallsToCreate.Select(x => x.afterWallId))); - - - - var anchoredSet = new HashSet() { - wallLeft.collider.name, - wallRight.collider.name, - backWallClosestLeft.collider.name, - backWallClosestRight.collider.name - }; - toDelete = toDelete.Where(o => !anchoredSet.Contains(o.collider.name)); - Debug.Log($"~~~~~~~~~~ Walls to delete {string.Join(", ", toDelete.Select(o => o.collider.name))}"); - - return new ConnectionAndWalls() { - connection = connection, - walls = wallsToCreate, - wallIdsToDelete = toDelete.Select(o => o.collider.name).ToList() - }; - }); return connectionsWithWalls; } @@ -698,14 +925,20 @@ bool pointOnWallLine(Vector3 p, Vector3 direction, Vector3 origin, string name, // } void OnDrawGizmosSelected() { - foreach (var (c, color) in spheres) { Gizmos.color = color; Gizmos.DrawSphere(c, 0.2f); } } - private PolygonWall createNewWall(string id, ConnectionProperties connectionProps, Vector3 p0, Vector3 p1, float height, Material material) { + private PolygonWall createNewWall( + string id, + ConnectionProperties connectionProps, + Vector3 p0, + Vector3 p1, + float height, + Material material + ) { var len = (p1 - p0).magnitude; return new PolygonWall { id = id, @@ -713,78 +946,93 @@ private PolygonWall createNewWall(string id, ConnectionProperties connectionProp polygon = getPolygonFromWallPoints(p0, p1, height), // TODO get material somehow // material = connectionProps?.openFromWallMaterial?.name - material = new MaterialProperties() { + material = new MaterialProperties() { name = material.name, tilingDivisorX = len / material.mainTextureScale.x, tilingDivisorY = height / material.mainTextureScale.y } }; - } private ProceduralHouse regenerateWallsData(ProceduralHouse house) { - // if (this.loadedHouse == null) { // this.loadedHouse = readHouseFromJson(this.layoutJSONFilename); // } // var house = readHouseFromJson(this.layoutJSONFilename); var root = GameObject.Find(ProceduralTools.DefaultRootWallsObjectName); - var wallsGOs = root.GetComponentsInChildren().Where(s => s.Type == SimObjType.Wall); + var wallsGOs = root.GetComponentsInChildren() + .Where(s => s.Type == SimObjType.Wall); // var wallsDict = this.loadedHouse.walls.ToDictionary(w => w.id, w => w); var minimumWallSqrDistanceCreateEpsilon = 0.03f; - var wallsJson = wallsGOs.Select((w, i) => { - var material = w.GetComponent().sharedMaterial; - var poly = getPolygonFromWallObject(w.gameObject); - var box = w.GetComponent(); - - return new PolygonWall { - id = w.gameObject.name, - roomId = w.GetComponentInChildren().RoomId, - polygon = poly, - material = new MaterialProperties() { - name = material.name, - tilingDivisorX = box.size.x / material.mainTextureScale.x, - tilingDivisorY = box.size.y / material.mainTextureScale.y + var wallsJson = wallsGOs + .Select( + (w, i) => { + var material = w.GetComponent().sharedMaterial; + var poly = getPolygonFromWallObject(w.gameObject); + var box = w.GetComponent(); + + return new PolygonWall { + id = w.gameObject.name, + roomId = w.GetComponentInChildren().RoomId, + polygon = poly, + material = new MaterialProperties() { + name = material.name, + tilingDivisorX = box.size.x / material.mainTextureScale.x, + tilingDivisorY = box.size.y / material.mainTextureScale.y + } + }; } - }; - } - ).ToList(); - var simObjs = GameObject.Find(ProceduralTools.DefaultObjectsRootName).GetComponentsInChildren(); - - var wallsDict = new Dictionary(house.walls.ToDictionary(w => w.id, w => w)); + ) + .ToList(); + var simObjs = GameObject + .Find(ProceduralTools.DefaultObjectsRootName) + .GetComponentsInChildren(); + + var wallsDict = new Dictionary( + house.walls.ToDictionary(w => w.id, w => w) + ); - var connectionsDict = new Dictionary(house.doors.Select(d => d as WallRectangularHole).Concat(house.windows).ToDictionary(w => w.id, w => w)); + var connectionsDict = new Dictionary( + house + .doors.Select(d => d as WallRectangularHole) + .Concat(house.windows) + .ToDictionary(w => w.id, w => w) + ); // var wallsDict = new List(this.loadedHouse.walls).ToDictionary(w => w.id, w => w); // foreach (var m in wallsDict) { // Debug.Log("Dict: " + m.Key); // } - var doorWalls = serializeConnections(simObjs, SimObjType.Doorway, "door", wallsDict).ToList(); + var doorWalls = serializeConnections(simObjs, SimObjType.Doorway, "door", wallsDict) + .ToList(); //doorWalls = doorWalls.Take(1).ToList(); // var doorWalls = new List(); - var windowWalls = serializeConnections(simObjs, SimObjType.Window, "window", wallsDict).ToList(); + var windowWalls = serializeConnections(simObjs, SimObjType.Window, "window", wallsDict) + .ToList(); - Debug.Log("+++++++++++++++ Windows " + string.Join(", ", windowWalls.SelectMany(x => x.walls).Select(w => w.wall.id))); + Debug.Log( + "+++++++++++++++ Windows " + + string.Join(", ", windowWalls.SelectMany(x => x.walls).Select(w => w.wall.id)) + ); var allNewConnections = doorWalls.Concat(windowWalls); Debug.Log($"Walls: {string.Join(", ", wallsJson.Select(w => w.id))}"); - var wallWithInsertLocation = allNewConnections.SelectMany(s => s.walls).Select(wallIdPair => { - - // Debug.Log($"All Walls: {string.Join(", ", wallsJson.Select(w => w.id))}"); - // Debug.Log("Wall " + wallIdPair.wall.id + " search after: '" + wallIdPair.afterWallId + "' find: " + wallsJson.FirstOrDefault( w => string.Equals(w.id, wallIdPair.afterWallId,StringComparison.InvariantCultureIgnoreCase ) )+ " ." + $" find '{string.Join(", ", wallsJson.Where(w => string.Equals(w.id, "wall0_17")))}'"); - return ( - wall: wallIdPair.wall, - index: - wallsJson.Select( - (w, i) => (wall: w, index: i) - ).First(w => string.Equals(w.wall.id, wallIdPair.afterWallId)).index - ); - } - - ); + var wallWithInsertLocation = allNewConnections + .SelectMany(s => s.walls) + .Select(wallIdPair => { + // Debug.Log($"All Walls: {string.Join(", ", wallsJson.Select(w => w.id))}"); + // Debug.Log("Wall " + wallIdPair.wall.id + " search after: '" + wallIdPair.afterWallId + "' find: " + wallsJson.FirstOrDefault( w => string.Equals(w.id, wallIdPair.afterWallId,StringComparison.InvariantCultureIgnoreCase ) )+ " ." + $" find '{string.Join(", ", wallsJson.Where(w => string.Equals(w.id, "wall0_17")))}'"); + return ( + wall: wallIdPair.wall, + index: wallsJson + .Select((w, i) => (wall: w, index: i)) + .First(w => string.Equals(w.wall.id, wallIdPair.afterWallId)) + .index + ); + }); var toDeleteSet = new HashSet(allNewConnections.SelectMany(w => w.wallIdsToDelete)); //wallsJson = wallsJson.Where(w => !toDeleteSet.Contains(w.id)).ToList(); foreach (var pair in wallWithInsertLocation) { @@ -798,7 +1046,9 @@ private ProceduralHouse regenerateWallsData(ProceduralHouse house) { var windows = windowWalls.Select(d => d.connection as Thor.Procedural.Data.Window); Debug.Log($"TO DELETE: {string.Join(", ", toDeleteSet)}"); // house.walls = wallsJson.Where(w => !toDeleteSet.Contains(w.id)).ToList(); - Debug.Log($"################# WALLS Before DELETE {string.Join(",", house.walls.Select(c => c.id))}"); + Debug.Log( + $"################# WALLS Before DELETE {string.Join(",", house.walls.Select(c => c.id))}" + ); // house.doors = doors.ToList(); // house.windows = windows.ToList(); return new ProceduralHouse { @@ -827,10 +1077,10 @@ public void AssigObjectIds() { } [Button] - public void ReloadScene() { + public void ReloadScene() { var scene = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene(); - UnityEditor.SceneManagement.EditorSceneManager.OpenScene(scene.path); + UnityEditor.SceneManagement.EditorSceneManager.OpenScene(scene.path); } [Button(Expanded = true)] @@ -842,7 +1092,9 @@ public void SerializeSceneFromGameObjects(string outFilename) { // if (this.loadedHouse != null) { if (String.IsNullOrWhiteSpace(this.layoutJSONFilename)) { - Debug.LogError("No base layout filename provided, need this to get procedural params. Add a 'layoutJSONFilename'"); + Debug.LogError( + "No base layout filename provided, need this to get procedural params. Add a 'layoutJSONFilename'" + ); return; } @@ -852,8 +1104,9 @@ public void SerializeSceneFromGameObjects(string outFilename) { var house = regenerateWallsData(this.readHouseFromJson(this.layoutJSONFilename)); var outPath = BuildLayoutPath(outFilename); - Debug.Log($"Serializing to: '{outFilename}', using procedural params and elements not in scene from: '{this.layoutJSONFilename}'"); - + Debug.Log( + $"Serializing to: '{outFilename}', using procedural params and elements not in scene from: '{this.layoutJSONFilename}'" + ); // var house = jsonObj.ToObject(); @@ -865,58 +1118,67 @@ public void SerializeSceneFromGameObjects(string outFilename) { // RegenerateWallsData(); var assetDb = ProceduralTools.getAssetMap(); - var skipObjects = new HashSet() { - SimObjType.Doorway, - SimObjType.Window - }; + var skipObjects = new HashSet() { SimObjType.Doorway, SimObjType.Window }; house.objects = simObjects - .Where(obj => !skipObjects.Contains(obj.simObj.Type)) - .Select(obj => { - Vector3 axis; - float degrees; - obj.simObj.transform.rotation.ToAngleAxis(out degrees, out axis); + .Where(obj => !skipObjects.Contains(obj.simObj.Type)) + .Select(obj => { + Vector3 axis; + float degrees; + obj.simObj.transform.rotation.ToAngleAxis(out degrees, out axis); - // PrefabUtility.UnpackPrefabInstance(obj.simObj.gameObject, PrefabUnpackMode.Completely, InteractionMode.UserAction); + // PrefabUtility.UnpackPrefabInstance(obj.simObj.gameObject, PrefabUnpackMode.Completely, InteractionMode.UserAction); - var bb = obj.simObj.AxisAlignedBoundingBox; + var bb = obj.simObj.AxisAlignedBoundingBox; - // PrefabUtility.Pack + // PrefabUtility.Pack - // PrefabUtility.UnpackPrefabInstance(obj.simObj.gameObject, PrefabUnpackMode.Completely, InteractionMode.UserAction); + // PrefabUtility.UnpackPrefabInstance(obj.simObj.gameObject, PrefabUnpackMode.Completely, InteractionMode.UserAction); - RaycastHit hit; - var didHit = Physics.Raycast( - obj.simObj.transform.position, - -Vector3.up, - out hit, - Mathf.Infinity, - LayerMask.GetMask("NonInteractive") - ); - string room = ""; - if (didHit) { - room = hit.collider.transform.GetComponentInParent()?.ObjectID; - } - Debug.Log("Processing " + obj.assetId + " ..."); - if (!assetDb.ContainsKey(obj.assetId)) { - Debug.LogError($"Asset '{obj.assetId}' not in AssetLibrary, so it won't be able to be loaded as part of a procedural scene. Save the asset and rebuild asset library."); - } + RaycastHit hit; + var didHit = Physics.Raycast( + obj.simObj.transform.position, + -Vector3.up, + out hit, + Mathf.Infinity, + LayerMask.GetMask("NonInteractive") + ); + string room = ""; + if (didHit) { + room = hit.collider.transform.GetComponentInParent()?.ObjectID; + } + Debug.Log("Processing " + obj.assetId + " ..."); + if (!assetDb.ContainsKey(obj.assetId)) { + Debug.LogError( + $"Asset '{obj.assetId}' not in AssetLibrary, so it won't be able to be loaded as part of a procedural scene. Save the asset and rebuild asset library." + ); + } // var box = obj.simObj.BoundingBox.GetComponent(); // box.enabled = true; var serializedObj = new HouseObject() { - id = obj.id, - position = bb.center, - rotation = new FlexibleRotation() { axis = axis, degrees = degrees }, - kinematic = (obj.simObj.GetComponentInChildren()?.isKinematic).GetValueOrDefault(), - boundingBox = new BoundingBox() { min = bb.center - (bb.size / 2.0f), max = bb.center + (bb.size / 2.0f) }, - room = room, - types = new List() { new Taxonomy() { name = Enum.GetName(typeof(SimObjType), obj.simObj.ObjType) } }, - assetId = obj.assetId - }; + id = obj.id, + position = bb.center, + rotation = new FlexibleRotation() { axis = axis, degrees = degrees }, + kinematic = ( + obj.simObj.GetComponentInChildren()?.isKinematic + ).GetValueOrDefault(), + boundingBox = new BoundingBox() { + min = bb.center - (bb.size / 2.0f), + max = bb.center + (bb.size / 2.0f) + }, + room = room, + types = new List() + { + new Taxonomy() + { + name = Enum.GetName(typeof(SimObjType), obj.simObj.ObjType) + } + }, + assetId = obj.assetId + }; // box.enabled = false; return serializedObj; - } - ).ToList(); - + }) + .ToList(); GameObject floorRoot; floorRoot = GameObject.Find(house.id); @@ -924,29 +1186,35 @@ public void SerializeSceneFromGameObjects(string outFilename) { floorRoot = GameObject.Find(ProceduralTools.DefaultHouseRootObjectName); } - var roomIdToProps = floorRoot.GetComponentsInChildren() + var roomIdToProps = floorRoot + .GetComponentsInChildren() .ToDictionary( rp => rp.GetComponentInParent().ObjectID, - rp => new { - roomProps = rp, - simOb = rp.GetComponentInParent() - }); - - house.rooms = house.rooms.Select(r => { - r.roomType = roomIdToProps[r.id].roomProps.RoomType; - // TODO add more room annotations here - return r; - }).ToList(); + rp => new { roomProps = rp, simOb = rp.GetComponentInParent() } + ); - var sceneLights = GameObject.Find(ProceduralTools.DefaultLightingRootName).GetComponentsInChildren().Concat( - GameObject.Find(ProceduralTools.DefaultObjectsRootName).GetComponentsInChildren() - ); + house.rooms = house + .rooms.Select(r => { + r.roomType = roomIdToProps[r.id].roomProps.RoomType; + // TODO add more room annotations here + return r; + }) + .ToList(); + + var sceneLights = GameObject + .Find(ProceduralTools.DefaultLightingRootName) + .GetComponentsInChildren() + .Concat( + GameObject + .Find(ProceduralTools.DefaultObjectsRootName) + .GetComponentsInChildren() + ); Debug.Log("Scene light count " + sceneLights.Count()); var gatheredLights = new List(); - house.proceduralParameters.lights = sceneLights.Select( - l => { + house.proceduralParameters.lights = sceneLights + .Select(l => { RaycastHit hit; var didHit = Physics.Raycast( l.transform.position, @@ -977,7 +1245,10 @@ public void SerializeSceneFromGameObjects(string outFilename) { normalBias = l.shadowNormalBias, bias = l.shadowBias, nearPlane = l.shadowNearPlane, - resolution = Enum.GetName(typeof(UnityEngine.Rendering.LightShadowResolution), l.shadowResolution) + resolution = Enum.GetName( + typeof(UnityEngine.Rendering.LightShadowResolution), + l.shadowResolution + ) }; } return new LightParameters() { @@ -989,43 +1260,58 @@ public void SerializeSceneFromGameObjects(string outFilename) { intensity = l.intensity, indirectMultiplier = l.bounceIntensity, range = l.range, - rgb = new SerializableColor() { r = l.color.r, g = l.color.g, b = l.color.b, a = l.color.a }, + rgb = new SerializableColor() { + r = l.color.r, + g = l.color.g, + b = l.color.b, + a = l.color.a + }, shadow = sp, linkedSimObj = objectLink }; - } - ).ToList(); - var probes = GameObject.Find(ProceduralTools.DefaultLightingRootName).GetComponentsInChildren().Concat( - GameObject.Find(ProceduralTools.DefaultObjectsRootName).GetComponentsInChildren() - ); - house.proceduralParameters.reflections = probes.Select( probeComp => { - return new ProbeParameters() { - background = SerializableColor.fromUnityColor(probeComp.backgroundColor), - intensity = probeComp.intensity, - boxSize = probeComp.size, - shadowDistance = probeComp.shadowDistance, - boxOffset = probeComp.center, - id = probeComp.gameObject.name, - position = probeComp.transform.position - }; - }).ToList(); + }) + .ToList(); + var probes = GameObject + .Find(ProceduralTools.DefaultLightingRootName) + .GetComponentsInChildren() + .Concat( + GameObject + .Find(ProceduralTools.DefaultObjectsRootName) + .GetComponentsInChildren() + ); + house.proceduralParameters.reflections = probes + .Select(probeComp => { + return new ProbeParameters() { + background = SerializableColor.fromUnityColor(probeComp.backgroundColor), + intensity = probeComp.intensity, + boxSize = probeComp.size, + shadowDistance = probeComp.shadowDistance, + boxOffset = probeComp.center, + id = probeComp.gameObject.name, + position = probeComp.transform.position + }; + }) + .ToList(); foreach (var probe in house.proceduralParameters.reflections) { - var go = new GameObject(probe.id); - go.transform.position = probe.position; - - var probeComp = go.AddComponent(); - probeComp.backgroundColor = (probe.background?.toUnityColor()).GetValueOrDefault(); - probeComp.center = probe.boxOffset; - probeComp.intensity = probe.intensity; - probeComp.mode = UnityEngine.Rendering.ReflectionProbeMode.Realtime; - probeComp.size = probe.boxSize; - probeComp.shadowDistance = probe.shadowDistance; - } - - + var go = new GameObject(probe.id); + go.transform.position = probe.position; + + var probeComp = go.AddComponent(); + probeComp.backgroundColor = (probe.background?.toUnityColor()).GetValueOrDefault(); + probeComp.center = probe.boxOffset; + probeComp.intensity = probe.intensity; + probeComp.mode = UnityEngine.Rendering.ReflectionProbeMode.Realtime; + probeComp.size = probe.boxSize; + probeComp.shadowDistance = probe.shadowDistance; + } - house.proceduralParameters.ceilingMaterial = new MaterialProperties() { name = GameObject.Find(ProceduralTools.DefaultCeilingRootObjectName).GetComponentInChildren().sharedMaterial.name }; + house.proceduralParameters.ceilingMaterial = new MaterialProperties() { + name = GameObject + .Find(ProceduralTools.DefaultCeilingRootObjectName) + .GetComponentInChildren() + .sharedMaterial.name + }; house.proceduralParameters.skyboxId = RenderSettings.skybox.name; Debug.Log("Lights " + house.proceduralParameters.lights.Count); @@ -1033,15 +1319,14 @@ public void SerializeSceneFromGameObjects(string outFilename) { var jsonResolver = new ShouldSerializeContractResolver(); var outJson = JObject.FromObject( house, - new Newtonsoft.Json.JsonSerializer() { - ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, - ContractResolver = jsonResolver - }); + new Newtonsoft.Json.JsonSerializer() { + ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, + ContractResolver = jsonResolver + } + ); Debug.Log($"output json: {outJson.ToString()}"); System.IO.File.WriteAllText(outPath, outJson.ToString()); - - } private string BuildLayoutPath(string layoutFilename) { @@ -1058,7 +1343,7 @@ public static void BuildAssetDB() { var proceduralADB = GameObject.FindObjectOfType(); // proceduralADB.prefabs = new AssetMap(ProceduralTools.FindPrefabsInAssets().GroupBy(m => m.name).ToDictionary(m => m.Key, m => m.First())); // proceduralADB.materials = new AssetMap(ProceduralTools.FindAssetsByType().GroupBy(m => m.name).ToDictionary(m => m.Key, m => m.First())); - + proceduralADB.prefabs = ProceduralTools.FindPrefabsInAssets(); // proceduralADB.assetMap.Clear(); // proceduralADB.addAssets(prefabs); @@ -1085,27 +1370,29 @@ public static void ReduceAssetDb() { EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene()); } - public static void filterADBFromHousesAssets(ProceduralAssetDatabase assetDb, IEnumerable houses) { + public static void filterADBFromHousesAssets( + ProceduralAssetDatabase assetDb, + IEnumerable houses + ) { var mats = new HashSet(houses.SelectMany(h => getAllMaterials(h))); - var assets = new HashSet(houses.SelectMany(h => getAssetIds(h))); + var assets = new HashSet(houses.SelectMany(h => getAssetIds(h))); assetDb.prefabs = assetDb.prefabs.Where(p => assets.Contains(p.name)).ToList(); assetDb.materials = assetDb.materials.Where(p => mats.Contains(p.name)).ToList(); } public static IEnumerable getAllMaterials(ProceduralHouse house) { - return house.rooms.SelectMany( - r => r.ceilings - .Select(c => c.material.name) - .Concat(new List() { r.floorMaterial.name }) - .Concat(house.walls.Select(w => w.material.name)) - ).Concat( - new List() { house.proceduralParameters.ceilingMaterial.name } - ); - + return house + .rooms.SelectMany(r => + r.ceilings.Select(c => c.material.name) + .Concat(new List() { r.floorMaterial.name }) + .Concat(house.walls.Select(w => w.material.name)) + ) + .Concat(new List() { house.proceduralParameters.ceilingMaterial.name }); } public static IEnumerable getAssetIds(ProceduralHouse house) { - return house.objects.Select(o => o.assetId) + return house + .objects.Select(o => o.assetId) .Concat(house.windows.Select(w => w.assetId)) .Concat(house.doors.Select(d => d.assetId)); } @@ -1119,8 +1406,8 @@ public static ProceduralHouse readHouseFromJsonStatic(string fileName) { JObject obj = JObject.Parse(jsonStr); return obj.ToObject(); - } + public static string BuildLayoutPathStatic(string layoutFilename) { layoutFilename = layoutFilename.Trim(); string LoadBasePath = "/Resources/rooms/"; @@ -1130,7 +1417,5 @@ public static string BuildLayoutPathStatic(string layoutFilename) { var path = Application.dataPath + LoadBasePath + layoutFilename; return path; } - #endif +#endif } - - diff --git a/unity/Assets/Scripts/ProceduralTemplates.cs b/unity/Assets/Scripts/ProceduralTemplates.cs index 499229cb1c..48c584a9e1 100644 --- a/unity/Assets/Scripts/ProceduralTemplates.cs +++ b/unity/Assets/Scripts/ProceduralTemplates.cs @@ -1,23 +1,21 @@ +using System; using System.Collections.Generic; -using UnityEngine; using System.Linq; -using UnityStandardAssets.Characters.FirstPerson; -using System; -using MessagePack.Resolvers; -using MessagePack.Formatters; using MessagePack; +using MessagePack.Formatters; +using MessagePack.Resolvers; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using Thor.Procedural.Data; - +using UnityEngine; +using UnityStandardAssets.Characters.FirstPerson; #if UNITY_EDITOR using UnityEditor.SceneManagement; using UnityEditor; #endif namespace Thor.Procedural { - [Serializable] public class HouseTemplate { public string id; @@ -41,22 +39,36 @@ public class RoomTemplate { } public static class Templates { - public static ProceduralHouse createHouseFromTemplate( HouseTemplate houseTemplate, int outsideBoundaryId = 0 - ) { var layout = houseTemplate.layout; var objects = houseTemplate.objectsLayouts; - - Func toIntArray = (string l) => l.Split('\n').Select(x => x.Split(' ').Select(i => { - int res; - var isInt = int.TryParse(i, out res); - return (res, isInt); - }).Where(m => m.isInt).Select(m => m.res).ToArray()).Where(a => a.Length > 0).ToArray(); - Func toStringArray = (string l) => l.Split('\n').Select(x => x.Split(' ').Where(x => !string.IsNullOrEmpty(x)).Select(i => i).ToArray()).Where(a => a.Length > 0).ToArray(); - + + Func toIntArray = (string l) => + l.Split('\n') + .Select(x => + x.Split(' ') + .Select(i => { + int res; + var isInt = int.TryParse(i, out res); + return (res, isInt); + }) + .Where(m => m.isInt) + .Select(m => m.res) + .ToArray() + ) + .Where(a => a.Length > 0) + .ToArray(); + Func toStringArray = (string l) => + l.Split('\n') + .Select(x => + x.Split(' ').Where(x => !string.IsNullOrEmpty(x)).Select(i => i).ToArray() + ) + .Where(a => a.Length > 0) + .ToArray(); + var layoutIntArray = toIntArray(layout); var rows = layoutIntArray.Length; @@ -65,106 +77,176 @@ public static ProceduralHouse createHouseFromTemplate( var layoutStringArray = toStringArray(layout); var objectArray = objects.Select(toStringArray).ToArray(); - IEnumerable> holePairs = new List>(); + IEnumerable> holePairs = + new List>(); if (houseTemplate.doors != null) { - holePairs = holePairs.Concat(houseTemplate.doors.Select(d => new KeyValuePair(d.Key, d.Value as WallRectangularHole))); + holePairs = holePairs.Concat( + houseTemplate.doors.Select(d => new KeyValuePair( + d.Key, + d.Value as WallRectangularHole + )) + ); } if (houseTemplate.windows != null) { - holePairs = holePairs.Concat(houseTemplate.windows.Select(d => new KeyValuePair(d.Key, d.Value as WallRectangularHole))); + holePairs = holePairs.Concat( + houseTemplate.windows.Select(d => new KeyValuePair( + d.Key, + d.Value as WallRectangularHole + )) + ); } - - var holeTemplates = holePairs.ToDictionary(e => e.Key, e => e.Value);; + + var holeTemplates = holePairs.ToDictionary(e => e.Key, e => e.Value); + ; var doorIds = new HashSet(holeTemplates.Keys.Distinct()); - Func manhattanNeighbors = (int row, int column) => new (int row, int column)[]{ - (row - 1, column), - (row, column - 1), - (row + 1, column), - (row, column + 1) - }; - + Func manhattanNeighbors = (int row, int column) => + new (int row, int column)[] + { + (row - 1, column), + (row, column - 1), + (row + 1, column), + (row, column + 1) + }; + if (layoutIntArray.Select(r => r.Length).Distinct().Count() > 1) { throw new ArgumentException("Invalid layout all rows must be the same size"); } - var doorDict = new Dictionary<(string id, int layer, (int row, int column) index), HashSet<(int row, int column)>>(); - + var doorDict = + new Dictionary< + (string id, int layer, (int row, int column) index), + HashSet<(int row, int column)> + >(); + var objectCoordinates = objectArray .SelectMany( - (objectLayer, layer) => objectLayer - .SelectMany((objectRow, row) => - objectRow.Select( - (id, column) => { - // ignore no door ones - var isHole = holeTemplates.Keys.Contains(id); - if (isHole) { - - var neighborIndices = new List<(int row, int column)>() { (row, column) }.Concat(manhattanNeighbors(row, column)); - var holeContinuation = isHole ? - neighborIndices.Where(n => ProceduralTools.withinArrayBoundary(n, rows, columns) && objectArray[layer][n.row][n.column] == id) - : new List<(int, int)>(); - - var nf = new List>(){ - ((int row, int col) c) => (c.row - 1, c.col), - ((int row, int col) c) => (c.row, c.col - 1) - }; - - var neighborFunctions = neighborIndices.Take(2).Select((index, i) => (index, i)).Where( - v => { - return ProceduralTools.withinArrayBoundary(v.index, rows, columns) && - objectArray[layer][v.index.row][v.index.column] == id; // id of door continues in neighbor - // && layoutStringArray[v.index.row][v.index.col] != layoutStringArray[row][column] // room crossing - } - ).Select(tup => nf[tup.i]); - - var twoHeaded = false; - if (neighborFunctions.Count() > 1) { - var cornerLeftTopNeighbor = (row: row - 1, column: column - 1); - if (ProceduralTools.withinArrayBoundary(cornerLeftTopNeighbor, rows, columns) && objectArray[layer][cornerLeftTopNeighbor.row][cornerLeftTopNeighbor.column] == id) { - neighborFunctions = new List>(){ - ((int row, int col) c) => (c.row - 1, c.col - 1) - }; - } - else { - twoHeaded = true; - } - } - - var doorStarts = neighborFunctions.Select( f => + (objectLayer, layer) => + objectLayer.SelectMany( + (objectRow, row) => + objectRow.Select( + (id, column) => { + // ignore no door ones + var isHole = holeTemplates.Keys.Contains(id); + if (isHole) { + var neighborIndices = new List<(int row, int column)>() { - var minIndex = (row, column); - var prevMinIndex = minIndex; - while (ProceduralTools.withinArrayBoundary(minIndex, rows, columns) && objectArray[layer][minIndex.row][minIndex.column] == id) { - prevMinIndex = minIndex; - minIndex = f(minIndex); + (row, column) + }.Concat(manhattanNeighbors(row, column)); + var holeContinuation = isHole + ? neighborIndices.Where(n => + ProceduralTools.withinArrayBoundary( + n, + rows, + columns + ) + && objectArray[layer][n.row][n.column] == id + ) + : new List<(int, int)>(); + + var nf = new List>() + { + ((int row, int col) c) => (c.row - 1, c.col), + ((int row, int col) c) => (c.row, c.col - 1) + }; + + var neighborFunctions = neighborIndices + .Take(2) + .Select((index, i) => (index, i)) + .Where(v => { + return ProceduralTools.withinArrayBoundary( + v.index, + rows, + columns + ) + && objectArray[layer][v.index.row][ + v.index.column + ] == id; // id of door continues in neighbor + // && layoutStringArray[v.index.row][v.index.col] != layoutStringArray[row][column] // room crossing + }) + .Select(tup => nf[tup.i]); + + var twoHeaded = false; + if (neighborFunctions.Count() > 1) { + var cornerLeftTopNeighbor = ( + row: row - 1, + column: column - 1 + ); + if ( + ProceduralTools.withinArrayBoundary( + cornerLeftTopNeighbor, + rows, + columns + ) + && objectArray[layer][ + cornerLeftTopNeighbor.row + ][cornerLeftTopNeighbor.column] == id + ) { + neighborFunctions = new List< + Func<(int, int), (int, int)> + >() + { + ((int row, int col) c) => + (c.row - 1, c.col - 1) + }; + } else { + twoHeaded = true; } - return prevMinIndex; } - ).ToList(); - - foreach (var doorStartIndex in doorStarts) { - (string, int, (int, int)) key = (id, layer, doorStartIndex); - if (doorDict.ContainsKey(key)) { - var connected = holeContinuation; - if (!twoHeaded) { - var k = holeContinuation.SelectMany(c => doorDict[(id, layer, c)]); - connected = connected.Concat(k); + + var doorStarts = neighborFunctions + .Select(f => { + var minIndex = (row, column); + var prevMinIndex = minIndex; + while ( + ProceduralTools.withinArrayBoundary( + minIndex, + rows, + columns + ) + && objectArray[layer][minIndex.row][ + minIndex.column + ] == id + ) { + prevMinIndex = minIndex; + minIndex = f(minIndex); + } + return prevMinIndex; + }) + .ToList(); + + foreach (var doorStartIndex in doorStarts) { + (string, int, (int, int)) key = ( + id, + layer, + doorStartIndex + ); + if (doorDict.ContainsKey(key)) { + var connected = holeContinuation; + if (!twoHeaded) { + var k = holeContinuation.SelectMany(c => + doorDict[(id, layer, c)] + ); + connected = connected.Concat(k); + } + doorDict[key] = new HashSet<(int, int)>( + doorDict[key].Union(connected) + ); + } else { + doorDict[key] = new HashSet<(int, int)>( + holeContinuation + ); + } } - doorDict[key] = new HashSet<(int, int)>(doorDict[key].Union(connected)); - - } - else { - doorDict[key] = new HashSet<(int, int)>(holeContinuation); } + return (id, layer, (row, column), isHole); } - } - return (id, layer, (row, column), isHole); - } - ) + ) + ) ) - ).ToList(); - + .ToList(); + var interiorBoundary = findWalls(layoutIntArray); var boundaryGroups = consolidateWalls(interiorBoundary); // TODO: do global scaling on everything after room creation @@ -174,255 +256,349 @@ public static ProceduralHouse createHouseFromTemplate( var roomToWallsXZ = getXZRoomToWallDict(floatingPointBoundaryGroups, roomIds); var defaultRoomTemplate = getDefaultRoomTemplate(); - var wallCoordinatesToId = new Dictionary<((double, double), (double, double)), string>(); - var roomsWithWalls = roomIds.Where(id => id != outsideBoundaryId).Select(intId => { + var wallCoordinatesToId = + new Dictionary<((double, double), (double, double)), string>(); + var roomsWithWalls = roomIds + .Where(id => id != outsideBoundaryId) + .Select(intId => { var id = intId.ToString(); RoomTemplate template; var inDict = houseTemplate.rooms.TryGetValue(id, out template); template = inDict ? template : defaultRoomTemplate; var room = template.floorTemplate.DeepClone(); - + room.id = roomIntToId(intId, template.floorTemplate); var wallHeight = template.wallHeight; var walls2D = roomToWallsXZ[intId]; - room.floorPolygon = walls2D.Select(p => new Vector3((float)p.Item1.row, template.floorYPosition, (float)p.Item1.column)).ToList(); + room.floorPolygon = walls2D + .Select(p => new Vector3( + (float)p.Item1.row, + template.floorYPosition, + (float)p.Item1.column + )) + .ToList(); MaterialProperties ceilingMat = new MaterialProperties(); - if (room.ceilings == null || room.ceilings.Count < 1 || room.ceilings[0].material == null) { + if ( + room.ceilings == null + || room.ceilings.Count < 1 + || room.ceilings[0].material == null + ) { ceilingMat = houseTemplate.proceduralParameters.ceilingMaterial; - } - else { + } else { ceilingMat = room.ceilings[0].material; } - room.ceilings = (room.ceilings != null && room.ceilings.Count > 0) ? room.ceilings : new List() {new Ceiling()}; - + room.ceilings = + (room.ceilings != null && room.ceilings.Count > 0) + ? room.ceilings + : new List() { new Ceiling() }; + room.ceilings[0].material = ceilingMat; - room.ceilings[0].polygon = room.floorPolygon.Select(p => new Vector3(p.x, p.y + wallHeight, p.z)).ToList(); - - var walls = walls2D.Select((w, i) => { - var wallCopy = template.wallTemplate.DeepClone(); - wallCopy.id = wallToId(i, room.id, template.wallTemplate.id); - wallCopy.polygon = new List() { - new Vector3((float)w.Item1.row, template.floorYPosition, (float)w.Item1.column), - new Vector3((float)w.Item2.row, template.floorYPosition, (float)w.Item2.column), - new Vector3((float)w.Item2.row, template.floorYPosition + wallHeight, (float)w.Item2.column), - new Vector3((float)w.Item1.row, template.floorYPosition + wallHeight, (float)w.Item1.column) - }; - wallCopy.roomId = room.id; - wallCoordinatesToId[w] = wallCopy.id; - return wallCopy; - }).ToList(); + room.ceilings[0].polygon = room + .floorPolygon.Select(p => new Vector3(p.x, p.y + wallHeight, p.z)) + .ToList(); + + var walls = walls2D + .Select( + (w, i) => { + var wallCopy = template.wallTemplate.DeepClone(); + wallCopy.id = wallToId(i, room.id, template.wallTemplate.id); + wallCopy.polygon = new List() + { + new Vector3( + (float)w.Item1.row, + template.floorYPosition, + (float)w.Item1.column + ), + new Vector3( + (float)w.Item2.row, + template.floorYPosition, + (float)w.Item2.column + ), + new Vector3( + (float)w.Item2.row, + template.floorYPosition + wallHeight, + (float)w.Item2.column + ), + new Vector3( + (float)w.Item1.row, + template.floorYPosition + wallHeight, + (float)w.Item1.column + ) + }; + wallCopy.roomId = room.id; + wallCoordinatesToId[w] = wallCopy.id; + return wallCopy; + } + ) + .ToList(); return (room, walls); - } - - ).ToList(); + }) + .ToList(); var doorIdCounter = new Dictionary(); var assetMap = ProceduralTools.getAssetMap(); - doorDict = doorDict.GroupBy(d => d.Value, new CustomHashSetEqualityComparer<(int, int)>()).ToDictionary(p => p.First().Key, p => p.Key);// .SelectMany(d => d.Select(x => x)).ToDictionary(p => p.Key, p => p.Value); + doorDict = doorDict + .GroupBy(d => d.Value, new CustomHashSetEqualityComparer<(int, int)>()) + .ToDictionary(p => p.First().Key, p => p.Key); // .SelectMany(d => d.Select(x => x)).ToDictionary(p => p.Key, p => p.Value); var objectIdCounter = new Dictionary(); // TODO -1 be a padding value as the distance between the first room and the zero padding at the // begining of the array in x, z var distToZeros = new Vector3(1.0f, 0.0f, 1.0f); - var holes = doorDict.SelectMany((d, i) => { - var holeTemplateId = d.Key.id; - var holeStart = d.Key.index; // d.Value.Min(); - var holeEnd = d.Value.Max(); - WallRectangularHole hole; - var inDict = holeTemplates.TryGetValue(holeTemplateId, out hole); - - var isDoor = hole is Data.Door; - var isWindow = hole is Data.Window; - if (inDict) { - if (isDoor) { - hole = (hole as Data.Door).DeepClone(); - } - else if (isWindow) { - hole = (hole as Data.Window).DeepClone(); - } - } - else { - hole = getDefaultHoleTemplate(); - } - - if (hole == null) { - return new List(){}; - } - - var index = doorIdCounter.AddCount(holeTemplateId) - 1; - - var room0Id = layoutIntArray[holeStart.row][holeStart.column]; - var room1Id = layoutIntArray[holeEnd.row][holeEnd.column]; - - int room0ArrayValue; - var isInt = int.TryParse(hole.room0, out room0ArrayValue); - - if (!string.IsNullOrEmpty(hole.room0) && isInt && room0ArrayValue == room1Id) { - var tmp = room0Id; - room0Id = room1Id; - room1Id = tmp; - - var holeTmp =holeStart; - holeStart = holeEnd; - holeEnd = holeTmp; - } - - var doorDir = (row: holeEnd.row - holeStart.row, column: holeEnd.column - holeStart.column); - - if (doorDir.row > 1 || doorDir.column > 1) { - throw new ArgumentException(" invalid door thickness with id " + d.Key); - } - - var indexOffset = new Dictionary<(int, int), (int row, int column)>() { - {(0, -1), (-1, -1)}, - {(-1, 0), (-1, 0)}, - {(0, 1), (-1, 0)}, - {(1, 0), (0, -1)} - }; - - hole.room0 = roomIntToId(room0Id, houseTemplate.rooms.GetValueOrDefault(room0Id.ToString(), defaultRoomTemplate).floorTemplate); - hole.room1 = roomIntToId(room1Id, houseTemplate.rooms.GetValueOrDefault(room1Id.ToString(), defaultRoomTemplate).floorTemplate); - - var room0Walls2D = roomToWallsXZ[room0Id]; - var room1Walls2D = roomToWallsXZ[room1Id]; - - var holeAdjustOffset = indexOffset[doorDir]; - - var holeStartCoords = (row: holeStart.row + holeAdjustOffset.row, column: holeStart.column + holeAdjustOffset.column); - - var wall0 = room0Walls2D.Find( x => { - - - var xDiff = Math.Abs(holeStartCoords.row - x.Item1.row); - var zDiff = Math.Abs(holeStartCoords.column - x.Item1.column); - - var xDiff1 = Math.Abs(holeStartCoords.row - x.Item2.row); - var zDiff1 = Math.Abs(holeStartCoords.column - x.Item2.column); + var holes = doorDict + .SelectMany( + (d, i) => { + var holeTemplateId = d.Key.id; + var holeStart = d.Key.index; // d.Value.Min(); + var holeEnd = d.Value.Max(); + WallRectangularHole hole; + var inDict = holeTemplates.TryGetValue(holeTemplateId, out hole); + + var isDoor = hole is Data.Door; + var isWindow = hole is Data.Window; + if (inDict) { + if (isDoor) { + hole = (hole as Data.Door).DeepClone(); + } else if (isWindow) { + hole = (hole as Data.Window).DeepClone(); + } + } else { + hole = getDefaultHoleTemplate(); + } + if (hole == null) { + return new List() { }; + } - var start = new Vector2((float)x.Item1.column, (float)x.Item1.row); - var end = new Vector2((float)x.Item2.column, (float)x.Item2.row); - var wallDir = (end - start).normalized; + var index = doorIdCounter.AddCount(holeTemplateId) - 1; - var doorDirVec = new Vector2((float)doorDir.column, (float)doorDir.row).normalized; - var dot = Vector2.Dot(wallDir, doorDirVec); - // TODO add eps - return ((xDiff == 0.0 && xDiff1 == 0.0) || (zDiff == 0.0 && zDiff1 == 0.0)) && Math.Abs(dot) < 1e-4; - }); + var room0Id = layoutIntArray[holeStart.row][holeStart.column]; + var room1Id = layoutIntArray[holeEnd.row][holeEnd.column]; - + int room0ArrayValue; + var isInt = int.TryParse(hole.room0, out room0ArrayValue); - var wall1 = room1Walls2D.Find( x => { - var xDiff = Math.Abs(holeStartCoords.row - x.Item1.row); - var zDiff = Math.Abs(holeStartCoords.column - x.Item1.column); + if ( + !string.IsNullOrEmpty(hole.room0) + && isInt + && room0ArrayValue == room1Id + ) { + var tmp = room0Id; + room0Id = room1Id; + room1Id = tmp; - var xDiff1 = Math.Abs(holeStartCoords.row - x.Item2.row); - var zDiff1 = Math.Abs(holeStartCoords.column - x.Item2.column); + var holeTmp = holeStart; + holeStart = holeEnd; + holeEnd = holeTmp; + } - var start = new Vector2((float)x.Item1.column, (float)x.Item1.row); - var end = new Vector2((float)x.Item2.column, (float)x.Item2.row); - var wallDir = (end - start).normalized; + var doorDir = ( + row: holeEnd.row - holeStart.row, + column: holeEnd.column - holeStart.column + ); - var doorDirVec = new Vector2((float)doorDir.column, (float)doorDir.row).normalized; - var dot = Vector2.Dot(wallDir, doorDirVec); - // TODO add eps - return ((xDiff == 0.0 && xDiff1 == 0.0) || (zDiff == 0.0 && zDiff1 == 0.0)) && Math.Abs(dot) < 1e-4; - }); - - hole.wall0 = wallCoordinatesToId[wall0]; - hole.wall1 = wallCoordinatesToId[wall1]; - // TODO asset offset - hole.id = holeTemplateIdToHouseId(holeTemplateId, index, hole.id); - Debug.Log("---- Hole being created " + hole.id); - - if ( string.IsNullOrEmpty(hole.assetId) || !assetMap.ContainsKey(hole.assetId)) { - return new List(){}; - } + if (doorDir.row > 1 || doorDir.column > 1) { + throw new ArgumentException(" invalid door thickness with id " + d.Key); + } - var holeOffset = ProceduralTools.getHoleAssetBoundingBox(hole.assetId); + var indexOffset = new Dictionary<(int, int), (int row, int column)>() + { + { (0, -1), (-1, -1) }, + { (-1, 0), (-1, 0) }, + { (0, 1), (-1, 0) }, + { (1, 0), (0, -1) } + }; + + hole.room0 = roomIntToId( + room0Id, + houseTemplate + .rooms.GetValueOrDefault(room0Id.ToString(), defaultRoomTemplate) + .floorTemplate + ); + hole.room1 = roomIntToId( + room1Id, + houseTemplate + .rooms.GetValueOrDefault(room1Id.ToString(), defaultRoomTemplate) + .floorTemplate + ); + + var room0Walls2D = roomToWallsXZ[room0Id]; + var room1Walls2D = roomToWallsXZ[room1Id]; + + var holeAdjustOffset = indexOffset[doorDir]; + + var holeStartCoords = ( + row: holeStart.row + holeAdjustOffset.row, + column: holeStart.column + holeAdjustOffset.column + ); + + var wall0 = room0Walls2D.Find(x => { + var xDiff = Math.Abs(holeStartCoords.row - x.Item1.row); + var zDiff = Math.Abs(holeStartCoords.column - x.Item1.column); + + var xDiff1 = Math.Abs(holeStartCoords.row - x.Item2.row); + var zDiff1 = Math.Abs(holeStartCoords.column - x.Item2.column); + + var start = new Vector2((float)x.Item1.column, (float)x.Item1.row); + var end = new Vector2((float)x.Item2.column, (float)x.Item2.row); + var wallDir = (end - start).normalized; + + var doorDirVec = new Vector2( + (float)doorDir.column, + (float)doorDir.row + ).normalized; + var dot = Vector2.Dot(wallDir, doorDirVec); + // TODO add eps + return ( + (xDiff == 0.0 && xDiff1 == 0.0) + || (zDiff == 0.0 && zDiff1 == 0.0) + ) + && Math.Abs(dot) < 1e-4; + }); + + var wall1 = room1Walls2D.Find(x => { + var xDiff = Math.Abs(holeStartCoords.row - x.Item1.row); + var zDiff = Math.Abs(holeStartCoords.column - x.Item1.column); + + var xDiff1 = Math.Abs(holeStartCoords.row - x.Item2.row); + var zDiff1 = Math.Abs(holeStartCoords.column - x.Item2.column); + + var start = new Vector2((float)x.Item1.column, (float)x.Item1.row); + var end = new Vector2((float)x.Item2.column, (float)x.Item2.row); + var wallDir = (end - start).normalized; + + var doorDirVec = new Vector2( + (float)doorDir.column, + (float)doorDir.row + ).normalized; + var dot = Vector2.Dot(wallDir, doorDirVec); + // TODO add eps + return ( + (xDiff == 0.0 && xDiff1 == 0.0) + || (zDiff == 0.0 && zDiff1 == 0.0) + ) + && Math.Abs(dot) < 1e-4; + }); + + hole.wall0 = wallCoordinatesToId[wall0]; + hole.wall1 = wallCoordinatesToId[wall1]; + // TODO asset offset + hole.id = holeTemplateIdToHouseId(holeTemplateId, index, hole.id); + Debug.Log("---- Hole being created " + hole.id); + + if ( + string.IsNullOrEmpty(hole.assetId) + || !assetMap.ContainsKey(hole.assetId) + ) { + return new List() { }; + } - Debug.Log("---- Hole offset null? " + (hole == null)); + var holeOffset = ProceduralTools.getHoleAssetBoundingBox(hole.assetId); - if (holeOffset == null) { - return new List(){}; - } + Debug.Log("---- Hole offset null? " + (hole == null)); - var floorTemplate = houseTemplate.rooms[room0Id.ToString()]; + if (holeOffset == null) { + return new List() { }; + } - // TODO -1 be a padding value as the distance between the first room and the zero padding at the - // begining of the array in x, z - var minVector = new Vector3((float)(holeStartCoords.column - distToZeros.x), (float)floorTemplate.floorYPosition, 0.0f); - var maxVector = minVector + holeOffset.max; - hole.holePolygon = new List { - minVector, - maxVector - }; - var right = ( - new Vector3((float)wall0.Item2.column, 0.0f, (float)wall0.Item2.row) - - new Vector3((float)wall0.Item1.column, 0.0f, (float)wall0.Item1.row) - ).normalized; - - var forward = Vector3.Cross(right, Vector3.up); - Matrix4x4 wallSpace = new Matrix4x4(); - wallSpace.SetColumn(0, right); - wallSpace.SetColumn(1, Vector3.up); - wallSpace.SetColumn(2, forward); - - hole.assetPosition = wallSpace * (minVector + holeOffset.offset + (holeOffset.max / 2.0f)); - Debug.Log("---- Hole def being created " + hole.id); - return new List(){isDoor ? hole as Data.Door : isWindow ? hole as Data.Window : hole}; - }).ToList(); + var floorTemplate = houseTemplate.rooms[room0Id.ToString()]; + + // TODO -1 be a padding value as the distance between the first room and the zero padding at the + // begining of the array in x, z + var minVector = new Vector3( + (float)(holeStartCoords.column - distToZeros.x), + (float)floorTemplate.floorYPosition, + 0.0f + ); + var maxVector = minVector + holeOffset.max; + hole.holePolygon = new List { minVector, maxVector }; + var right = ( + new Vector3((float)wall0.Item2.column, 0.0f, (float)wall0.Item2.row) + - new Vector3((float)wall0.Item1.column, 0.0f, (float)wall0.Item1.row) + ).normalized; + + var forward = Vector3.Cross(right, Vector3.up); + Matrix4x4 wallSpace = new Matrix4x4(); + wallSpace.SetColumn(0, right); + wallSpace.SetColumn(1, Vector3.up); + wallSpace.SetColumn(2, forward); + + hole.assetPosition = + wallSpace * (minVector + holeOffset.offset + (holeOffset.max / 2.0f)); + Debug.Log("---- Hole def being created " + hole.id); + return new List() + { + isDoor + ? hole as Data.Door + : isWindow + ? hole as Data.Window + : hole + }; + } + ) + .ToList(); objectIdCounter = new Dictionary(); - var strRoomIds = new HashSet(roomIds.Select(x => x.ToString())); - var houseObjects = objectCoordinates.Where(item => !doorIds.Contains(item.id) && !strRoomIds.Contains(item.id)).SelectMany(item => { - var coord = item.Item3; - var result = new List(); - - var template = houseTemplate.objects.GetValueOrDefault(item.id, null); + var strRoomIds = new HashSet(roomIds.Select(x => x.ToString())); + var houseObjects = objectCoordinates + .Where(item => !doorIds.Contains(item.id) && !strRoomIds.Contains(item.id)) + .SelectMany(item => { + var coord = item.Item3; + var result = new List(); + var template = houseTemplate.objects.GetValueOrDefault(item.id, null); - - if (template != null) { - var obj = template.DeepClone(); + if (template != null) { + var obj = template.DeepClone(); - var count = objectIdCounter.AddCount(item.id); - obj.id = objectToId(item.id, count - 1, obj.id); - var roomId = layoutIntArray[coord.row][coord.column]; - var floorTemplate = houseTemplate.rooms[roomId.ToString()]; - obj.room = roomIntToId(roomId, floorTemplate.floorTemplate); - - if ( string.IsNullOrEmpty(obj.assetId) || !assetMap.ContainsKey(obj.assetId)) { - return result; - } + var count = objectIdCounter.AddCount(item.id); + obj.id = objectToId(item.id, count - 1, obj.id); + var roomId = layoutIntArray[coord.row][coord.column]; + var floorTemplate = houseTemplate.rooms[roomId.ToString()]; + obj.room = roomIntToId(roomId, floorTemplate.floorTemplate); - var asset = assetMap.getAsset(obj.assetId); - var simObj = asset.GetComponent(); - var bb = simObj.AxisAlignedBoundingBox; - - var centerOffset = bb.center + bb.size / 2.0f; + if (string.IsNullOrEmpty(obj.assetId) || !assetMap.ContainsKey(obj.assetId)) { + return result; + } - // TODO use bounding box to center - obj.position = new Vector3((float)coord.row - distToZeros.x + obj.position.x, floorTemplate.floorYPosition + obj.position.y, (float)coord.column - distToZeros.z + obj.position.z) + centerOffset;// - new Vector3(centerOffset.x, -centerOffset.y, centerOffset.z); - obj.rotation = obj.rotation == null ? new FlexibleRotation() { axis = new Vector3(0.0f, 1.0f, 0.0f), degrees = 0} : obj.rotation; - if (asset != null) { - result.Add(obj); + var asset = assetMap.getAsset(obj.assetId); + var simObj = asset.GetComponent(); + var bb = simObj.AxisAlignedBoundingBox; + + var centerOffset = bb.center + bb.size / 2.0f; + + // TODO use bounding box to center + obj.position = + new Vector3( + (float)coord.row - distToZeros.x + obj.position.x, + floorTemplate.floorYPosition + obj.position.y, + (float)coord.column - distToZeros.z + obj.position.z + ) + centerOffset; // - new Vector3(centerOffset.x, -centerOffset.y, centerOffset.z); + obj.rotation = + obj.rotation == null + ? new FlexibleRotation() { + axis = new Vector3(0.0f, 1.0f, 0.0f), + degrees = 0 + } + : obj.rotation; + if (asset != null) { + result.Add(obj); + } } - } - return result; - }); + return result; + }); HouseMetadata metadata = new HouseMetadata { schema = ProceduralTools.CURRENT_HOUSE_SCHEMA }; return new ProceduralHouse() { - metadata = new HouseMetadata() { schema=houseTemplate.metadata.schema }, + metadata = new HouseMetadata() { schema = houseTemplate.metadata.schema }, proceduralParameters = houseTemplate.proceduralParameters.DeepClone(), id = !string.IsNullOrEmpty(houseTemplate.id) ? houseTemplate.id : houseId(), rooms = roomsWithWalls.Select(p => p.room).ToList(), @@ -431,15 +607,14 @@ public static ProceduralHouse createHouseFromTemplate( windows = holes.Where(d => d is Data.Window).Select(d => d as Data.Window).ToList(), objects = houseObjects.ToList() }; - } - public static RoomTemplate getDefaultRoomTemplate() { + public static RoomTemplate getDefaultRoomTemplate() { return new RoomTemplate() { wallTemplate = new PolygonWall() { - polygon = new List() { new Vector3(0.0f, 3.0f, 0.0f)} + polygon = new List() { new Vector3(0.0f, 3.0f, 0.0f) } }, - floorTemplate = new RoomHierarchy() {} + floorTemplate = new RoomHierarchy() { } }; } @@ -447,18 +622,22 @@ public static WallRectangularHole getDefaultHoleTemplate() { return new Data.Door(); } - public static Dictionary<(int, int), List<((int row, int col), (int row, int col))>> findWalls(int[][] floorplan) { - var walls = new DefaultDictionary<(int, int), List<((int row, int col), (int row, int col))>>(); - for(var row = 0; row < floorplan.Length - 1; row++) { - for(var col = 0; col < floorplan[row].Length - 1; col++) { + public static Dictionary< + (int, int), + List<((int row, int col), (int row, int col))> + > findWalls(int[][] floorplan) { + var walls = + new DefaultDictionary<(int, int), List<((int row, int col), (int row, int col))>>(); + for (var row = 0; row < floorplan.Length - 1; row++) { + for (var col = 0; col < floorplan[row].Length - 1; col++) { var a = floorplan[row][col]; var b = floorplan[row][col + 1]; if (a != b) { - walls[(Math.Min(a, b), Math.Max(a,b))].Add(((row-1, col), (row, col))); + walls[(Math.Min(a, b), Math.Max(a, b))].Add(((row - 1, col), (row, col))); } - b = floorplan[row+1][col]; + b = floorplan[row + 1][col]; if (a != b) { - walls[(Math.Min(a, b), Math.Max(a,b))].Add(((row, col-1), (row, col))); + walls[(Math.Min(a, b), Math.Max(a, b))].Add(((row, col - 1), (row, col))); } } } @@ -466,9 +645,14 @@ public static WallRectangularHole getDefaultHoleTemplate() { return walls; } - - public static Dictionary<(int, int), HashSet<((int row, int col), (int row, int col))>> consolidateWalls(Dictionary<(int, int), List<((int row, int col), (int row, int col))>> walls) { - var output = new Dictionary<(int, int), HashSet<((int row, int col), (int row, int col))>>(); + public static Dictionary< + (int, int), + HashSet<((int row, int col), (int row, int col))> + > consolidateWalls( + Dictionary<(int, int), List<((int row, int col), (int row, int col))>> walls + ) { + var output = + new Dictionary<(int, int), HashSet<((int row, int col), (int row, int col))>>(); foreach (var item in walls) { var wallGroupId = item.Key; var wallPairs = item.Value; @@ -494,11 +678,22 @@ public static WallRectangularHole getDefaultHoleTemplate() { var w2_1 = w1_2; foreach (var w2_2 in wallMap[w2_1]) { if ( - (w1_1.Item1 == w1_2.Item1 && w1_2.Item1 == w2_1.Item1 && w2_1.Item1 == w2_2.Item1)|| - (w1_1.Item2 == w1_2.Item2 && w1_2.Item2 == w2_1.Item2 && w2_1.Item2 == w2_2.Item2) - ){ + ( + w1_1.Item1 == w1_2.Item1 + && w1_2.Item1 == w2_1.Item1 + && w2_1.Item1 == w2_2.Item1 + ) + || ( + w1_1.Item2 == w1_2.Item2 + && w1_2.Item2 == w2_1.Item2 + && w2_1.Item2 == w2_2.Item2 + ) + ) { wallMap[w2_1].Remove(w2_2); - if (wallMap.ContainsKey(w2_1) && (wallMap[w2_1] == null || wallMap[w2_1].Count == 0)) { + if ( + wallMap.ContainsKey(w2_1) + && (wallMap[w2_1] == null || wallMap[w2_1].Count == 0) + ) { wallMap.Remove(w2_1); } wallMap[w1_1].Remove(w2_1); @@ -507,7 +702,6 @@ public static WallRectangularHole getDefaultHoleTemplate() { breakLoop = true; break; } - } if (breakLoop) { break; @@ -516,11 +710,8 @@ public static WallRectangularHole getDefaultHoleTemplate() { if (breakLoop) { break; } - } - } - } output[wallGroupId] = new HashSet<((int row, int col), (int row, int col))>(); foreach (var w1 in wallMap.Keys) { @@ -528,46 +719,66 @@ public static WallRectangularHole getDefaultHoleTemplate() { output[wallGroupId].Add((w1, w2)); } } - } - + return output; } - public static Dictionary<(int, int), HashSet<((double row, double col), (double row, double col))>> scaleBoundaryGroups( - Dictionary<(int, int), HashSet<((int row, int col), (int row, int col))>> boundaryGroups, - float scale, + public static Dictionary< + (int, int), + HashSet<((double row, double col), (double row, double col))> + > scaleBoundaryGroups( + Dictionary< + (int, int), + HashSet<((int row, int col), (int row, int col))> + > boundaryGroups, + float scale, int precision ) { - return boundaryGroups.ToDictionary(bg => - bg.Key, bg => new HashSet<((double, double),(double, double))>(bg.Value.Select(pair => - ( - (Math.Round(pair.Item1.row * scale, precision), Math.Round(pair.Item1.col * scale, precision)), - (Math.Round(pair.Item2.row * scale, precision), Math.Round(pair.Item2.col * scale, precision)) - ))) + return boundaryGroups.ToDictionary( + bg => bg.Key, + bg => new HashSet<((double, double), (double, double))>( + bg.Value.Select(pair => + ( + ( + Math.Round(pair.Item1.row * scale, precision), + Math.Round(pair.Item1.col * scale, precision) + ), + ( + Math.Round(pair.Item2.row * scale, precision), + Math.Round(pair.Item2.col * scale, precision) + ) + ) + ) + ) ); } - - private static List<((double row, double col), (double row, double col))> getWallLoop(List<((double row, double col), (double row, double col))> walls) { - var remainingWalls = new HashSet<((double row, double col), (double row, double col))>(walls); - var output = new List<((double row, double col), (double row, double col))>() { walls[0] }; + + private static List<((double row, double col), (double row, double col))> getWallLoop( + List<((double row, double col), (double row, double col))> walls + ) { + var remainingWalls = new HashSet<((double row, double col), (double row, double col))>( + walls + ); + var output = new List<((double row, double col), (double row, double col))>() + { + walls[0] + }; remainingWalls.Remove(walls[0]); while (remainingWalls.Count > 0) { var didBreak = false; foreach (var wall in remainingWalls) { - if (output.Last().Item2 == wall.Item1) { output.Add(wall); remainingWalls.Remove(wall); didBreak = true; break; - } - else if (output.Last().Item2 == wall.Item2) { + } else if (output.Last().Item2 == wall.Item2) { output.Add((wall.Item2, wall.Item1)); remainingWalls.Remove(wall); didBreak = true; break; - } + } } if (!didBreak) { throw new ArgumentException($"No connecting wall for {output.Last()}!"); @@ -576,8 +787,18 @@ int precision return output; } - public static Dictionary> getXZRoomToWallDict(Dictionary<(int, int), HashSet<((double row, double col), (double row, double col))>> boundaryGroups, IEnumerable roomIds) { - var output = new Dictionary>(); + public static Dictionary< + int, + List<((double row, double column), (double row, double column))> + > getXZRoomToWallDict( + Dictionary< + (int, int), + HashSet<((double row, double col), (double row, double col))> + > boundaryGroups, + IEnumerable roomIds + ) { + var output = + new Dictionary>(); foreach (var roomId in roomIds) { var roomWals = new List<((double row, double col), (double row, double col))>(); foreach (var k in boundaryGroups.Keys.Where(k => TupleContains(k, roomId))) { @@ -585,13 +806,15 @@ int precision } var wallLoop = getWallLoop(roomWals); var edgeSum = 0.0; - foreach ( ((double x0, double z0), (double x1, double z1)) in wallLoop) { + foreach (((double x0, double z0), (double x1, double z1)) in wallLoop) { var dist = x0 * z1 - x1 * z0; edgeSum += dist; } if (edgeSum > 0) { - - wallLoop = wallLoop.Reverse<((double row, double col), (double row, double col))>().Select(p => (p.Item2, p.Item1)).ToList(); + wallLoop = wallLoop + .Reverse<((double row, double col), (double row, double col))>() + .Select(p => (p.Item2, p.Item1)) + .ToList(); } output[roomId] = wallLoop; } @@ -606,8 +829,11 @@ public static string houseId() { return "house"; } - public static string holeTemplateIdToHouseId(string holeTemplateId, int count = 0, string idPrefix = "") { - + public static string holeTemplateIdToHouseId( + string holeTemplateId, + int count = 0, + string idPrefix = "" + ) { var name = string.IsNullOrEmpty(idPrefix) ? holeTemplateId : idPrefix; return count == 0 ? $"{name}" : $"{name}_{count}"; // return $"{wallId}{holeId}{index}"; @@ -617,21 +843,18 @@ public static string wallToId(int wallIndexInRoom, string roomId, string wallIdP return $"{roomId}_{wallIdPrefix}{wallIndexInRoom}"; } - public static string objectToId(string objectId, int count = 0, string idPrefix = "") { + public static string objectToId(string objectId, int count = 0, string idPrefix = "") { var name = string.IsNullOrEmpty(idPrefix) ? objectId : idPrefix; return count == 0 ? $"{name}" : $"{name}_{count}"; // return count == 0 && string.IsNullOrEmpty(idPrefix) ? $"{objectId}" : $"{objectId}_{idPrefix}{count}"; } - public class DefaultDictionary : Dictionary where TValue : new() - { - public new TValue this[TKey key] - { - get - { + public class DefaultDictionary : Dictionary + where TValue : new() { + public new TValue this[TKey key] { + get { TValue val; - if (!TryGetValue(key, out val)) - { + if (!TryGetValue(key, out val)) { val = new TValue(); Add(key, val); } @@ -641,26 +864,21 @@ public static string objectToId(string objectId, int count = 0, string idPrefix } } - public class CustomHashSetEqualityComparer : IEqualityComparer> - { - public bool Equals(HashSet x, HashSet y) - { - if (ReferenceEquals(x, null)) + public class CustomHashSetEqualityComparer : IEqualityComparer> { + public bool Equals(HashSet x, HashSet y) { + if (ReferenceEquals(x, null)) { return false; + } return x.SetEquals(y); } - public int GetHashCode(HashSet set) - { + public int GetHashCode(HashSet set) { int hashCode = 0; - if (set != null) - { - foreach (T t in set) - { - hashCode = hashCode ^ - (set.Comparer.GetHashCode(t) & 0x7FFFFFFF); + if (set != null) { + foreach (T t in set) { + hashCode = hashCode ^ (set.Comparer.GetHashCode(t) & 0x7FFFFFFF); } } return hashCode; @@ -670,6 +888,5 @@ public int GetHashCode(HashSet set) private static bool TupleContains((int, int) t, int id) { return t.Item1 == id || t.Item2 == id; } - } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/ProceduralTools.cs b/unity/Assets/Scripts/ProceduralTools.cs index 7c1d937c0c..dfd541f496 100644 --- a/unity/Assets/Scripts/ProceduralTools.cs +++ b/unity/Assets/Scripts/ProceduralTools.cs @@ -1,20 +1,18 @@ -using System.Collections.Generic; -using UnityEngine; -using System.Linq; -using UnityStandardAssets.Characters.FirstPerson; using System; +using System.Collections.Generic; using System.IO; -using MessagePack.Resolvers; -using MessagePack.Formatters; +using System.Linq; using MessagePack; +using MessagePack.Formatters; +using MessagePack.Resolvers; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using Thor.Procedural.Data; -using UnityEngine.AI; using Thor.Utils; - - +using UnityEngine; +using UnityEngine.AI; +using UnityStandardAssets.Characters.FirstPerson; #if UNITY_EDITOR using UnityEditor.SceneManagement; using UnityEditor; @@ -25,6 +23,7 @@ namespace Thor.Procedural { [Serializable] public class AssetMap { protected Dictionary assetMap; + public AssetMap(Dictionary assetMap) { this.assetMap = assetMap; } @@ -41,7 +40,6 @@ public virtual int Count() { return assetMap.Count; } - public virtual IEnumerable Keys() { return assetMap.Keys; } @@ -59,17 +57,16 @@ public virtual void Clear() { // creation attributes like the material database [ExecuteInEditMode] public class RoomCreatorFactory { - public RoomCreatorFactory(AssetMap materials, AssetMap prefabs) { + public RoomCreatorFactory(AssetMap materials, AssetMap prefabs) { } - } public static GameObject CreateProceduralRoomFromArray() { - return null; } } public static class ProceduralTools { public const string CURRENT_HOUSE_SCHEMA = "1.0.0"; + public class Rectangle { public Vector3 center; public float width; @@ -85,11 +82,16 @@ private static IEnumerable GenerateTriangleVisibilityPoints( float interval = 1 / 3.0f ) { // Create Vector2 array from Vector3s, since y-axis is redundant - Vector2[] tPoints = new Vector2[] { new Vector2(p0.x, p0.z), new Vector2(p1.x, p1.z), new Vector2(p2.x, p2.z) }; + Vector2[] tPoints = new Vector2[] + { + new Vector2(p0.x, p0.z), + new Vector2(p1.x, p1.z), + new Vector2(p2.x, p2.z) + }; Vector2 vPointLocalOrigin; List trianglevPoints2D = new List(); - // Find triangle's largest angle, which we will either use as the local vPoint origin if it's exactly 90 degrees, or to find it + // Find triangle's largest angle, which we will either use as the local vPoint origin if it's exactly 90 degrees, or to find it Vector2 widestAngledPoint = tPoints[0]; float longestSideSquare = (tPoints[2] - tPoints[1]).sqrMagnitude; float largestAngle = Vector2.Angle(tPoints[0] - tPoints[2], tPoints[1] - tPoints[0]); @@ -112,7 +114,8 @@ private static IEnumerable GenerateTriangleVisibilityPoints( vPointLocalOrigin = widestAngledPoint; if (Vector2.Equals(widestAngledPoint, tPoints[0])) { - rightTriangle1 = new Vector2[] { tPoints[2], tPoints[0], tPoints[1] }; ; + rightTriangle1 = new Vector2[] { tPoints[2], tPoints[0], tPoints[1] }; + ; } else if (Vector2.Equals(widestAngledPoint, tPoints[1])) { rightTriangle1 = new Vector2[] { tPoints[0], tPoints[1], tPoints[2] }; } else if (Vector2.Equals(widestAngledPoint, tPoints[2])) { @@ -121,7 +124,6 @@ private static IEnumerable GenerateTriangleVisibilityPoints( trianglevPoints2D = FindVPointsOnTriangle(rightTriangle1, false); } - // If triangle is not right-angled, find v-point origin with trigonometry else { Vector2[] rightTriangle2 = new Vector2[3]; @@ -147,7 +149,9 @@ private static IEnumerable GenerateTriangleVisibilityPoints( List FindVPointLocalOrigin(Vector2 a, Vector2 b, Vector2 c) { List rightTriangleVPoints = new List(); - float sideLength = (a - c).magnitude * Mathf.Sin(Mathf.Deg2Rad * (90 - Vector2.Angle(a - c, b - c))); + float sideLength = + (a - c).magnitude + * Mathf.Sin(Mathf.Deg2Rad * (90 - Vector2.Angle(a - c, b - c))); vPointLocalOrigin = c + sideLength * (b - c).normalized; Vector2[] rightTriangle1 = new Vector2[] { a, vPointLocalOrigin, c }; Vector2[] rightTriangle2 = new Vector2[] { b, vPointLocalOrigin, a }; @@ -170,10 +174,23 @@ List FindVPointsOnTriangle(Vector2[] rightTriangle, bool triangle2) { for (int i = startingX; i * interval < xMax; i++) { for (int j = 0; j * interval < yMax; j++) { currentPoint = rightTriangle[1] + i * xIncrement + j * yIncrement; - if (i == 0 || j == 0 || 360 - 1e-3 <= - Vector2.Angle(rightTriangle[0] - currentPoint, rightTriangle[1] - currentPoint) + - Vector2.Angle(rightTriangle[1] - currentPoint, rightTriangle[2] - currentPoint) + - Vector2.Angle(rightTriangle[2] - currentPoint, rightTriangle[0] - currentPoint)) { + if ( + i == 0 + || j == 0 + || 360 - 1e-3 + <= Vector2.Angle( + rightTriangle[0] - currentPoint, + rightTriangle[1] - currentPoint + ) + + Vector2.Angle( + rightTriangle[1] - currentPoint, + rightTriangle[2] - currentPoint + ) + + Vector2.Angle( + rightTriangle[2] - currentPoint, + rightTriangle[0] - currentPoint + ) + ) { rightTriangleVPoints.Add(currentPoint); } } @@ -183,8 +200,11 @@ List FindVPointsOnTriangle(Vector2[] rightTriangle, bool triangle2) { } } - private static Mesh GenerateFloorMesh(IEnumerable floorPolygon, float yOffset = 0.0f, bool clockWise = false) { - + private static Mesh GenerateFloorMesh( + IEnumerable floorPolygon, + float yOffset = 0.0f, + bool clockWise = false + ) { // Get indices for creating triangles var m_points = floorPolygon.Select(p => new Vector2(p.x, p.z)).ToArray(); @@ -246,19 +266,22 @@ int[] TriangulateVertices() { } if (Snip(u, v, w, nv, V)) { - int a, b, c, s, t; + int a, + b, + c, + s, + t; a = V[u]; b = V[v]; c = V[w]; - if (!clockWise) { + if (!clockWise) { indices.Add(a); indices.Add(b); indices.Add(c); - } - else { - indices.Add(c); - indices.Add(b); + } else { + indices.Add(c); + indices.Add(b); indices.Add(a); } for (s = v, t = v + 1; t < nv; s++, t++) { @@ -309,15 +332,34 @@ bool Snip(int u, int v, int w, int n, int[] V) { } bool InsideTriangle(Vector2 A, Vector2 B, Vector2 C, Vector2 P) { - float ax, ay, bx, by, cx, cy, apx, apy, bpx, bpy, cpx, cpy; - float cCROSSap, bCROSScp, aCROSSbp; - - ax = C.x - B.x; ay = C.y - B.y; - bx = A.x - C.x; by = A.y - C.y; - cx = B.x - A.x; cy = B.y - A.y; - apx = P.x - A.x; apy = P.y - A.y; - bpx = P.x - B.x; bpy = P.y - B.y; - cpx = P.x - C.x; cpy = P.y - C.y; + float ax, + ay, + bx, + by, + cx, + cy, + apx, + apy, + bpx, + bpy, + cpx, + cpy; + float cCROSSap, + bCROSScp, + aCROSSbp; + + ax = C.x - B.x; + ay = C.y - B.y; + bx = A.x - C.x; + by = A.y - C.y; + cx = B.x - A.x; + cy = B.y - A.y; + apx = P.x - A.x; + apy = P.y - A.y; + bpx = P.x - B.x; + bpy = P.y - B.y; + cpx = P.x - C.x; + cpy = P.y - C.y; aCROSSbp = ax * bpy - ay * bpx; cCROSSap = cx * apy - cy * apx; @@ -339,7 +381,11 @@ Vector2[] GenerateUVs() { } // TODO triangulation code here - public static UnityEngine.Mesh GetPolygonMesh(RoomHierarchy room, float yOffset = 0.0f, bool generateBackFaces = false) { + public static UnityEngine.Mesh GetPolygonMesh( + RoomHierarchy room, + float yOffset = 0.0f, + bool generateBackFaces = false + ) { return new Mesh(); } @@ -375,31 +421,34 @@ public static GameObject CreateVisibilityPointsOnPlane( // var holeMinWorld = wallTransform.MultiplyPoint(hole.boundingBox.min); var boundingBox = getHoleBoundingBox(hole); - var holeMaxWorld = transform.TransformPoint(boundingBox.max) - (right + top) / 2.0f;// - transform.TransformPoint((right + top) / 2.0f); - var holeMinWorld = transform.TransformPoint(boundingBox.min - Vector3.forward * 0.1f) - (right + top) / 2.0f;// - transform.TransformPoint((right + top) / 2.0f); + var holeMaxWorld = transform.TransformPoint(boundingBox.max) - (right + top) / 2.0f; // - transform.TransformPoint((right + top) / 2.0f); + var holeMinWorld = + transform.TransformPoint(boundingBox.min - Vector3.forward * 0.1f) + - (right + top) / 2.0f; // - transform.TransformPoint((right + top) / 2.0f); - var dims = holeMaxWorld - holeMinWorld + transform.TransformVector(Vector3.forward) * 0.2f; + var dims = + holeMaxWorld - holeMinWorld + transform.TransformVector(Vector3.forward) * 0.2f; var originalDims = dims; - var center = holeMinWorld + (dims/ 2.0f);// transform.TransformVector((hole.boundingBox.max + Vector3.forward * 0.2f) - (hole.boundingBox.min - Vector3.forward * 0.1f)); + var center = holeMinWorld + (dims / 2.0f); // transform.TransformVector((hole.boundingBox.max + Vector3.forward * 0.2f) - (hole.boundingBox.min - Vector3.forward * 0.1f)); // Bounds.Contains does not work properly with negative sizes dims.z = Math.Sign(dims.z) == 1 ? dims.z : -dims.z; dims.x = Math.Sign(dims.x) == 1 ? dims.x : -dims.x; - + bounds = new Bounds(center, dims); // Debug Visualize /* var corners = new List> { - new List(){ + new List(){ Vector3.zero, new Vector3(dims.x, 0, 0) }, - new List(){ + new List(){ Vector3.zero, new Vector3(0, dims.y, 0) }, - new List(){ + new List(){ Vector3.zero, new Vector3(0, 0, dims.z) } @@ -423,11 +472,19 @@ public static GameObject CreateVisibilityPointsOnPlane( } } } - */ + */ } - for (Vector3 rightDelta = Vector3.zero; (width * width) - rightDelta.sqrMagnitude > (step * step); rightDelta += stepVecRight) { - for (Vector3 topDelta = Vector3.zero; (height * height) - topDelta.sqrMagnitude > (step * step); topDelta += stepVecTop) { + for ( + Vector3 rightDelta = Vector3.zero; + (width * width) - rightDelta.sqrMagnitude > (step * step); + rightDelta += stepVecRight + ) { + for ( + Vector3 topDelta = Vector3.zero; + (height * height) - topDelta.sqrMagnitude > (step * step); + topDelta += stepVecTop + ) { var pos = start + rightDelta + topDelta; if (hole != null && bounds.Contains(pos)) { @@ -438,13 +495,14 @@ public static GameObject CreateVisibilityPointsOnPlane( vp.transform.position = pos; vp.transform.parent = visibilityPoints.transform; count++; - } } return visibilityPoints; } - public static GameObject CreateVisibilityPointsGameObject(IEnumerable visibilityPoints) { + public static GameObject CreateVisibilityPointsGameObject( + IEnumerable visibilityPoints + ) { var visibilityPointsGO = new GameObject("VisibilityPoints"); var count = 0; foreach (var point in visibilityPoints) { @@ -456,18 +514,31 @@ public static GameObject CreateVisibilityPointsGameObject(IEnumerable v return visibilityPointsGO; } - public static GameObject createWalls(IEnumerable walls, AssetMap materialDb, ProceduralParameters proceduralParameters, string gameObjectId = "Structure") { + public static GameObject createWalls( + IEnumerable walls, + AssetMap materialDb, + ProceduralParameters proceduralParameters, + string gameObjectId = "Structure" + ) { var structure = new GameObject(gameObjectId); var wallsPerRoom = walls.GroupBy(w => w.roomId).Select(m => m.ToList()).ToList(); - var zip3 = wallsPerRoom.Select( walls => walls.Zip( - walls.Skip(1).Concat(new Wall[] { walls.FirstOrDefault() }), - (w0, w1) => (w0, w1) - ).Zip( - new Wall[] { walls.LastOrDefault() }.Concat(walls.Take(walls.Count() - 1)), - (wallPair, w2) => (wallPair.w0, w2, wallPair.w1) - )).ToList(); + var zip3 = wallsPerRoom + .Select(walls => + walls + .Zip( + walls.Skip(1).Concat(new Wall[] { walls.FirstOrDefault() }), + (w0, w1) => (w0, w1) + ) + .Zip( + new Wall[] { walls.LastOrDefault() }.Concat( + walls.Take(walls.Count() - 1) + ), + (wallPair, w2) => (wallPair.w0, w2, wallPair.w1) + ) + ) + .ToList(); // zip3 = zip3.Reverse().ToArray(); @@ -479,15 +550,15 @@ public static GameObject createWalls(IEnumerable walls, AssetMap index, materialDb, w0, - w1, + w1, w2, squareTiling: proceduralParameters.squareTiling, minimumBoxColliderThickness: proceduralParameters.minWallColliderThickness, layer: ( String.IsNullOrEmpty(w0.layer) - ? LayerMask.NameToLayer("SimObjVisible") - : LayerMask.NameToLayer(w0.layer) - ), + ? LayerMask.NameToLayer("SimObjVisible") + : LayerMask.NameToLayer(w0.layer) + ), backFaces: false // TODO param from json ); @@ -504,15 +575,21 @@ private static float getWallDegreesRotation(Wall wall) { var p0p1_norm = p0p1.normalized; - var theta = -Mathf.Sign(p0p1_norm.z) * Mathf.Acos(Vector3.Dot(p0p1_norm, Vector3.right)); + var theta = + -Mathf.Sign(p0p1_norm.z) * Mathf.Acos(Vector3.Dot(p0p1_norm, Vector3.right)); return theta * 180.0f / Mathf.PI; } - private static float TriangleArea(List vertices, int index0, int index1, int index2) { + private static float TriangleArea( + List vertices, + int index0, + int index1, + int index2 + ) { Vector3 a = vertices[index0]; Vector3 b = vertices[index1]; Vector3 c = vertices[index2]; - Vector3 cross = Vector3.Cross(a-b, a-c); + Vector3 cross = Vector3.Cross(a - b, a - c); float area = cross.magnitude * 0.5f; return area; } @@ -546,7 +623,10 @@ public static GameObject createAndJoinWall( var generateBackFaces = backFaces; const float zeroThicknessEpsilon = 1e-4f; - var colliderThickness = toCreate.thickness < zeroThicknessEpsilon ? minimumBoxColliderThickness : toCreate.thickness; + var colliderThickness = + toCreate.thickness < zeroThicknessEpsilon + ? minimumBoxColliderThickness + : toCreate.thickness; var p0p1 = toCreate.p1 - toCreate.p0; @@ -556,32 +636,43 @@ public static GameObject createAndJoinWall( var normal = Vector3.Cross(p0p1_norm, Vector3.up); - var center = toCreate.p0 + p0p1 * 0.5f + Vector3.up * toCreate.height * 0.5f + normal * toCreate.thickness * 0.5f; + var center = + toCreate.p0 + + p0p1 * 0.5f + + Vector3.up * toCreate.height * 0.5f + + normal * toCreate.thickness * 0.5f; var width = p0p1.magnitude; Vector3 p0; Vector3 p1; - var theta = -Mathf.Sign(p0p1_norm.z) * Mathf.Acos(Vector3.Dot(p0p1_norm, Vector3.right)); + var theta = + -Mathf.Sign(p0p1_norm.z) * Mathf.Acos(Vector3.Dot(p0p1_norm, Vector3.right)); if (globalVertexPositions) { - p0 = toCreate.p0; p1 = toCreate.p1; boxCenter = center; } else { - p0 = -(width / 2.0f) * Vector3.right - new Vector3(0.0f, toCreate.height / 2.0f, toCreate.thickness / 2.0f); - p1 = (width / 2.0f) * Vector3.right - new Vector3(0.0f, toCreate.height / 2.0f, toCreate.thickness / 2.0f); + p0 = + -(width / 2.0f) * Vector3.right + - new Vector3(0.0f, toCreate.height / 2.0f, toCreate.thickness / 2.0f); + p1 = + (width / 2.0f) * Vector3.right + - new Vector3(0.0f, toCreate.height / 2.0f, toCreate.thickness / 2.0f); normal = Vector3.forward; p0p1_norm = Vector3.right; - + wallGO.transform.position = center; - wallGO.transform.rotation = Quaternion.AngleAxis(theta * 180.0f / Mathf.PI, Vector3.up); + wallGO.transform.rotation = Quaternion.AngleAxis( + theta * 180.0f / Mathf.PI, + Vector3.up + ); } - var colliderOffset = Vector3.zero;//toCreate.thickness < zeroThicknessEpsilon ? normal * colliderThickness : Vector3.zero; + var colliderOffset = Vector3.zero; //toCreate.thickness < zeroThicknessEpsilon ? normal * colliderThickness : Vector3.zero; boxCenter += colliderOffset; @@ -598,98 +689,109 @@ public static GameObject createAndJoinWall( IEnumerable colliderBoundingBoxes = new List(); if (toCreate.hole != null) { - if (toCreate.hole.holePolygon != null && toCreate.hole.holePolygon.Count != 2) { - Debug.LogWarning($"Invalid `holePolygon` on object of id '{toCreate.hole.id}', only supported rectangle holes, 4 points in polygon. Using `boundingBox` instead."); + Debug.LogWarning( + $"Invalid `holePolygon` on object of id '{toCreate.hole.id}', only supported rectangle holes, 4 points in polygon. Using `boundingBox` instead." + ); if (toCreate.hole.holePolygon.Count < 2) { - throw new ArgumentException("$Invalid `holePolygon` on object of id '{toCreate.hole.id}', only supported rectangle holes, 4 points in polygon, polygon has {toCreate.hole.holePolygon.Count}."); + throw new ArgumentException( + "$Invalid `holePolygon` on object of id '{toCreate.hole.id}', only supported rectangle holes, 4 points in polygon, polygon has {toCreate.hole.holePolygon.Count}." + ); } } var holeBB = getHoleBoundingBox(toCreate.hole); var dims = holeBB.max - holeBB.min; - var offset = new Vector2( - holeBB.min.x, holeBB.min.y - ); + var offset = new Vector2(holeBB.min.x, holeBB.min.y); if (toCreate.hole.wall1 == toCreate.id) { - offset = new Vector2( - width - holeBB.max.x, holeBB.min.y - ); + offset = new Vector2(width - holeBB.max.x, holeBB.min.y); } - colliderBoundingBoxes = new List() { - new BoundingBox() {min = p0, max = p0 - + p0p1_norm * offset.x - + Vector3.up * (toCreate.height)}, - new BoundingBox() { - min = p0 - + p0p1_norm * offset.x - + Vector3.up * (offset.y + dims.y), - max = p0 - + p0p1_norm * (offset.x + dims.x) - + Vector3.up * (toCreate.height)}, - new BoundingBox() { - min = p0 - + p0p1_norm * (offset.x + dims.x), - max = p1 + Vector3.up * (toCreate.height)}, - new BoundingBox() { - min = p0 - + p0p1_norm * offset.x, - max = p0 - + p0p1_norm * (offset.x + dims.x) - + Vector3.up * (offset.y) + colliderBoundingBoxes = new List() + { + new BoundingBox() + { + min = p0, + max = p0 + p0p1_norm * offset.x + Vector3.up * (toCreate.height) + }, + new BoundingBox() + { + min = p0 + p0p1_norm * offset.x + Vector3.up * (offset.y + dims.y), + max = p0 + p0p1_norm * (offset.x + dims.x) + Vector3.up * (toCreate.height) + }, + new BoundingBox() + { + min = p0 + p0p1_norm * (offset.x + dims.x), + max = p1 + Vector3.up * (toCreate.height) + }, + new BoundingBox() + { + min = p0 + p0p1_norm * offset.x, + max = p0 + p0p1_norm * (offset.x + dims.x) + Vector3.up * (offset.y) } }; - const float areaEps =0.0001f; - colliderBoundingBoxes = colliderBoundingBoxes.Where(bb => Math.Abs(GetBBXYArea(bb)) > areaEps).ToList(); - - - vertices = new List() { - p0, - p0 + new Vector3(0.0f, toCreate.height, 0.0f), - p0 + p0p1_norm * offset.x - + Vector3.up * offset.y, - p0 - + p0p1_norm * offset.x - + Vector3.up * (offset.y + dims.y), - - p1 + new Vector3(0.0f, toCreate.height, 0.0f), - - p0 - + p0p1_norm * (offset.x + dims.x) - + Vector3.up * (offset.y + dims.y), - - p1, - - p0 - + p0p1_norm * (offset.x + dims.x) - + Vector3.up * offset.y - - }; - - - triangles = new List() { - 0, 1, 2, 1, 3, 2, 1, 4, 3, 3, 4, 5, 4, 6, 5, 5, 6, 7, 7, 6, 0, 0, 2, 7 + const float areaEps = 0.0001f; + colliderBoundingBoxes = colliderBoundingBoxes + .Where(bb => Math.Abs(GetBBXYArea(bb)) > areaEps) + .ToList(); + + vertices = new List() + { + p0, + p0 + new Vector3(0.0f, toCreate.height, 0.0f), + p0 + p0p1_norm * offset.x + Vector3.up * offset.y, + p0 + p0p1_norm * offset.x + Vector3.up * (offset.y + dims.y), + p1 + new Vector3(0.0f, toCreate.height, 0.0f), + p0 + p0p1_norm * (offset.x + dims.x) + Vector3.up * (offset.y + dims.y), + p1, + p0 + p0p1_norm * (offset.x + dims.x) + Vector3.up * offset.y }; + triangles = new List() + { + 0, + 1, + 2, + 1, + 3, + 2, + 1, + 4, + 3, + 3, + 4, + 5, + 4, + 6, + 5, + 5, + 6, + 7, + 7, + 6, + 0, + 0, + 2, + 7 + }; - // This would be for a left hand local axis space, so front being counter-clockwise of topdown polygon from inside the polygon + // This would be for a left hand local axis space, so front being counter-clockwise of topdown polygon from inside the polygon // triangles = new List() { // 7, 2, 0, 0, 6, 7, 7, 6, 5, 5, 6, 4, 5, 4, 3, 3, 4, 1, 2, 3, 1, 2, 1, 0 // }; - + var toRemove = new List(); // const float areaEps = 1e-4f; - for (int i = 0; i < triangles.Count/3; i++) { - var i0 = triangles[i*3]; - var i1 = triangles[ i*3 + 1]; - var i2 = triangles[ i*3 + 2]; + for (int i = 0; i < triangles.Count / 3; i++) { + var i0 = triangles[i * 3]; + var i1 = triangles[i * 3 + 1]; + var i2 = triangles[i * 3 + 2]; var area = TriangleArea(vertices, i0, i1, i2); - + if (area <= areaEps) { - toRemove.AddRange(new List() { i*3, i*3 + 1, i*3 + 2 }); + toRemove.AddRange(new List() { i * 3, i * 3 + 1, i * 3 + 2 }); } } var toRemoveSet = new HashSet(toRemove); @@ -698,16 +800,15 @@ public static GameObject createAndJoinWall( if (generateBackFaces) { triangles.AddRange(triangles.AsEnumerable().Reverse().ToList()); } - } else { + vertices = new List() + { + p0, + p0 + new Vector3(0.0f, toCreate.height, 0.0f), + p1 + new Vector3(0.0f, toCreate.height, 0.0f), + p1 + }; - vertices = new List() { - p0, - p0 + new Vector3(0.0f, toCreate.height, 0.0f), - p1 + new Vector3(0.0f, toCreate.height, 0.0f), - p1 - }; - triangles = new List() { 1, 2, 0, 2, 3, 0 }; // Counter clockwise wall definition left hand rule @@ -720,9 +821,12 @@ public static GameObject createAndJoinWall( normals = Enumerable.Repeat(-normal, vertices.Count).ToList(); // normals = Enumerable.Repeat(normal, vertices.Count).ToList();//.Concat(Enumerable.Repeat(-normal, vertices.Count)).ToList(); - uv = vertices.Select(v => - new Vector2(Vector3.Dot(p0p1_norm, v - p0) / width, v.y / toCreate.height)) - .ToList(); + uv = vertices + .Select(v => new Vector2( + Vector3.Dot(p0p1_norm, v - p0) / width, + v.y / toCreate.height + )) + .ToList(); mesh.vertices = vertices.ToArray(); mesh.uv = uv.ToArray(); @@ -734,18 +838,15 @@ public static GameObject createAndJoinWall( if (toCreate.hole != null) { // var meshCollider = wallGO.AddComponent(); // meshCollider.sharedMesh = mesh; - + var holeColliders = new GameObject($"Colliders"); - - holeColliders.transform.parent = wallGO.transform; holeColliders.transform.localPosition = Vector3.zero; holeColliders.transform.localRotation = Quaternion.identity; var i = 0; foreach (var boundingBox in colliderBoundingBoxes) { - var colliderObj = new GameObject($"Collider_{i}"); colliderObj.transform.parent = holeColliders.transform; colliderObj.transform.localPosition = Vector3.zero; @@ -755,11 +856,8 @@ public static GameObject createAndJoinWall( var boxCollider = colliderObj.AddComponent(); boxCollider.center = boundingBox.center(); boxCollider.size = boundingBox.size() + Vector3.forward * colliderThickness; - } - - } - else { + } else { var boxC = wallGO.AddComponent(); boxC.center = boxCenter; boxC.size = boxSize; @@ -769,7 +867,7 @@ public static GameObject createAndJoinWall( //var mats = ProceduralTools.FindAssetsByType().ToDictionary(m => m.name, m => m); // var mats = ProceduralTools.FindAssetsByType().GroupBy(m => m.name).ToDictionary(m => m.Key, m => m.First()); - + var visibilityPointsGO = CreateVisibilityPointsOnPlane( toCreate.p0, toCreate.p1 - toCreate.p0, @@ -788,19 +886,29 @@ public static GameObject createAndJoinWall( var dimensions = new Vector2(p0p1.magnitude, toCreate.height); var prev_p0p1 = previous.p1 - previous.p0; - var prevOffset = getWallMaterialOffset(previous.id).GetValueOrDefault(Vector2.zero); - var offsetX = (prev_p0p1.magnitude / previous.material.tilingDivisorX.GetValueOrDefault(1.0f)) - Mathf.Floor(prev_p0p1.magnitude / previous.material.tilingDivisorX.GetValueOrDefault(1.0f)) + prevOffset.x; - - var shaderName = toCreate.material == null || string.IsNullOrEmpty(toCreate.material.shader) ? "Standard" : toCreate.material.shader; - // TODO Offset Y would require to get joining walls from above and below - var mat = toCreate.material == null || string.IsNullOrEmpty(toCreate.material.name) ? new Material(Shader.Find(shaderName)) : materialDb.getAsset(toCreate.material.name); + var offsetX = + (prev_p0p1.magnitude / previous.material.tilingDivisorX.GetValueOrDefault(1.0f)) + - Mathf.Floor( + prev_p0p1.magnitude / previous.material.tilingDivisorX.GetValueOrDefault(1.0f) + ) + + prevOffset.x; + + var shaderName = + toCreate.material == null || string.IsNullOrEmpty(toCreate.material.shader) + ? "Standard" + : toCreate.material.shader; + // TODO Offset Y would require to get joining walls from above and below + var mat = + toCreate.material == null || string.IsNullOrEmpty(toCreate.material.name) + ? new Material(Shader.Find(shaderName)) + : materialDb.getAsset(toCreate.material.name); meshRenderer.material = generatePolygonMaterial( - mat, - dimensions, - toCreate.material, - offsetX, - 0.0f, + mat, + dimensions, + toCreate.material, + offsetX, + 0.0f, squareTiling: squareTiling ); @@ -811,7 +919,11 @@ public static GameObject createAndJoinWall( return wallGO; } - public static GameObject createFloorCollider(GameObject floorGameObject, Rectangle rectangle, float thickness) { + public static GameObject createFloorCollider( + GameObject floorGameObject, + Rectangle rectangle, + float thickness + ) { var colliders = new GameObject("Colliders"); var collider = new GameObject("Col"); @@ -820,7 +932,11 @@ public static GameObject createFloorCollider(GameObject floorGameObject, Rectang collider.tag = "SimObjPhysics"; var box = collider.AddComponent(); - var size = new Vector3(rectangle.width + rectangle.marginWidth * 2.0f, thickness, rectangle.depth + rectangle.marginDepth * 2.0f); + var size = new Vector3( + rectangle.width + rectangle.marginWidth * 2.0f, + thickness, + rectangle.depth + rectangle.marginDepth * 2.0f + ); var center = rectangle.center - new Vector3(0, thickness / 2.0f, 0); box.size = size; @@ -851,8 +967,11 @@ public static GameObject createFloorCollider(GameObject floorGameObject, Rectang } public static GameObject createFloorReceptacle( - GameObject floorGameObject, Rectangle rectangle, float height, string namePostfix = "" - ) { + GameObject floorGameObject, + Rectangle rectangle, + float height, + string namePostfix = "" + ) { var receptacleTriggerBox = new GameObject($"ReceptacleTriggerBox{namePostfix}"); // SimObjInvisible receptacleTriggerBox.layer = 9; @@ -907,11 +1026,12 @@ Vector3 boxSize var PotentialColliders = wallGameObject.GetComponentsInChildren(false); List actuallyMyColliders = new List(); foreach (Collider c in PotentialColliders) { - if(c.enabled) - actuallyMyColliders.Add(c); + if (c.enabled) { + actuallyMyColliders.Add(c); + } } - simObjPhysics.MyColliders = actuallyMyColliders.ToArray(); + simObjPhysics.MyColliders = actuallyMyColliders.ToArray(); simObjPhysics.transform.parent = wallGameObject.transform; @@ -920,12 +1040,12 @@ Vector3 boxSize } public static SimObjPhysics setRoomSimObjectPhysics( - GameObject floorGameObject, - string simObjId, - GameObject visibilityPoints, - GameObject receptacleTriggerBox, - Collider collider - ) { + GameObject floorGameObject, + string simObjId, + GameObject visibilityPoints, + GameObject receptacleTriggerBox, + Collider collider + ) { return setRoomSimObjectPhysics( floorGameObject, simObjId, @@ -947,7 +1067,10 @@ public static WallProperties setFloorProperties(GameObject gameObject, Wall wall return wallProps; } - public static ConnectionProperties setConnectionProperties(GameObject gameObject, WallRectangularHole hole) { + public static ConnectionProperties setConnectionProperties( + GameObject gameObject, + WallRectangularHole hole + ) { var holeProps = gameObject.AddComponent(); holeProps.OpenFromRoomId = hole.room0; holeProps.OpenToRoomId = hole.room1; @@ -977,13 +1100,17 @@ public static SimObjPhysics setRoomSimObjectPhysics( simObjPhysics.VisibilityPoints = visibilityPoints.GetComponentsInChildren(); visibilityPoints.transform.parent = floorGameObject.transform; - simObjPhysics.ReceptacleTriggerBoxes = receptacleTriggerBoxes ?? Array.Empty(); + simObjPhysics.ReceptacleTriggerBoxes = + receptacleTriggerBoxes ?? Array.Empty(); simObjPhysics.MyColliders = colliders ?? Array.Empty(); simObjPhysics.transform.parent = floorGameObject.transform; if (receptacleTriggerBoxes != null) { - secondaryProperties = new SimObjSecondaryProperty[] { SimObjSecondaryProperty.Receptacle }; + secondaryProperties = new SimObjSecondaryProperty[] + { + SimObjSecondaryProperty.Receptacle + }; foreach (var receptacleTriggerBox in receptacleTriggerBoxes) { receptacleTriggerBox.AddComponent(); } @@ -992,8 +1119,14 @@ public static SimObjPhysics setRoomSimObjectPhysics( return simObjPhysics; } - public static GameObject createSimObjPhysicsGameObject(string name = "Floor", Vector3? position = null, string tag = "SimObjPhysics", int layer = 8, bool withRigidBody = true) { + public static GameObject createSimObjPhysicsGameObject( + string name = "Floor", + Vector3? position = null, + string tag = "SimObjPhysics", + int layer = 8, + bool withRigidBody = true + ) { var floorGameObject = new GameObject(name); floorGameObject.transform.position = position.GetValueOrDefault(); @@ -1023,12 +1156,23 @@ private static void setUpFloorMesh(GameObject floorGameObject, Mesh mesh, Materi private static BoundingBox getRoomRectangle(IEnumerable polygonPoints) { var minY = polygonPoints.Count() > 0 ? polygonPoints.Min(p => p.y) : 0.0f; - var minPoint = new Vector3(polygonPoints.Count() > 0 ? polygonPoints.Min(c => c.x) : 0.0f, minY, polygonPoints.Count() > 0 ? polygonPoints.Min(c => c.z) : 0.0f); - var maxPoint = new Vector3(polygonPoints.Count() > 0 ? polygonPoints.Max(c => c.x) :0.0f, minY, polygonPoints.Count() > 0 ? polygonPoints.Max(c => c.z):0.0f); + var minPoint = new Vector3( + polygonPoints.Count() > 0 ? polygonPoints.Min(c => c.x) : 0.0f, + minY, + polygonPoints.Count() > 0 ? polygonPoints.Min(c => c.z) : 0.0f + ); + var maxPoint = new Vector3( + polygonPoints.Count() > 0 ? polygonPoints.Max(c => c.x) : 0.0f, + minY, + polygonPoints.Count() > 0 ? polygonPoints.Max(c => c.z) : 0.0f + ); return new BoundingBox() { min = minPoint, max = maxPoint }; } - private static Wall polygonWallToSimpleWall(PolygonWall wall, Dictionary holes) { + private static Wall polygonWallToSimpleWall( + PolygonWall wall, + Dictionary holes + ) { //wall.polygon. var polygons = wall.polygon.OrderBy(p => p.y); var maxY = wall.polygon.Max(p => p.y); @@ -1050,7 +1194,7 @@ private static Wall polygonWallToSimpleWall(PolygonWall wall, Dictionary polygon) { - // TODO: include rotation in json for floor and ceiling to compute the real scale not axis aligned scale + // TODO: include rotation in json for floor and ceiling to compute the real scale not axis aligned scale if (polygon.Count() > 1) { var maxX = polygon.Max(p => p.x); @@ -1058,9 +1202,8 @@ private static Vector2 getAxisAlignedWidthDepth(IEnumerable polygon) { var minX = polygon.Min(p => p.x); var minZ = polygon.Min(p => p.z); - - var width = maxX - minX; + var width = maxX - minX; var depth = maxZ - minZ; return new Vector2(width, depth); } @@ -1072,27 +1215,41 @@ private static Vector2 getAxisAlignedWidthDepth(IEnumerable polygon) { if (wallGO == null) { return null; } - var renderer = wallGO.GetComponent(); - if (renderer == null) { - return null; - } + var renderer = wallGO.GetComponent(); + if (renderer == null) { + return null; + } return renderer.material.mainTextureOffset; } private static BoundingBox getHoleBoundingBox(WallRectangularHole hole) { if (hole.holePolygon == null || hole.holePolygon.Count < 2) { - throw new ArgumentException($"Invalid `holePolygon` for object id: '{hole.id}'. Minimum 2 vertices indicating first min and second max of hole bounding box."); + throw new ArgumentException( + $"Invalid `holePolygon` for object id: '{hole.id}'. Minimum 2 vertices indicating first min and second max of hole bounding box." + ); } - return new BoundingBox() { - min = hole.holePolygon[0], - max = hole.holePolygon[1] - }; + return new BoundingBox() { min = hole.holePolygon[0], max = hole.holePolygon[1] }; } - private static Material generatePolygonMaterial(Material sharedMaterial, Vector2 dimensions, MaterialProperties materialProperties = null, float offsetX = 0.0f, float offsetY = 0.0f, bool squareTiling = false) { + private static Material generatePolygonMaterial( + Material sharedMaterial, + Vector2 dimensions, + MaterialProperties materialProperties = null, + float offsetX = 0.0f, + float offsetY = 0.0f, + bool squareTiling = false + ) { // optimization do not copy when not needed // Almost never happens because material continuity requires tilings offsets for every following wall - if (materialProperties == null && materialProperties.color == null && !materialProperties.tilingDivisorX.HasValue && !materialProperties.tilingDivisorY.HasValue && offsetX == 0.0f && offsetY == 0.0f && !materialProperties.unlit) { + if ( + materialProperties == null + && materialProperties.color == null + && !materialProperties.tilingDivisorX.HasValue + && !materialProperties.tilingDivisorY.HasValue + && offsetX == 0.0f + && offsetY == 0.0f + && !materialProperties.unlit + ) { return sharedMaterial; } @@ -1112,18 +1269,24 @@ private static Material generatePolygonMaterial(Material sharedMaterial, Vector2 materialCopy.mainTextureScale = new Vector2(tilingX, tilingY); materialCopy.mainTextureOffset = new Vector2(offsetX, offsetY); - + if (materialProperties.unlit) { var shader = Shader.Find("Unlit/Color"); materialCopy.shader = shader; } if (materialProperties.metallic != null) { - materialCopy.SetFloat("_Metallic", materialProperties.metallic.GetValueOrDefault(0.0f)); + materialCopy.SetFloat( + "_Metallic", + materialProperties.metallic.GetValueOrDefault(0.0f) + ); } if (materialProperties.metallic != null) { - materialCopy.SetFloat("_Glossiness", materialProperties.smoothness.GetValueOrDefault(0.0f)); + materialCopy.SetFloat( + "_Glossiness", + materialProperties.smoothness.GetValueOrDefault(0.0f) + ); } return materialCopy; @@ -1139,7 +1302,8 @@ private static Material generatePolygonMaterial(Material sharedMaterial, Vector2 public static string DefaultLightingRootName => "ProceduralLighting"; public static string DefaultObjectsRootName => "Objects"; - public static void SetLayer(GameObject go, int layer) where T : Component { + public static void SetLayer(GameObject go, int layer) + where T : Component { if (go.GetComponent() != null) { go.layer = layer; } @@ -1151,26 +1315,32 @@ public static void SetLayer(GameObject go, int layer) where T : Component { public static (int, int, int) parseHouseVersion(string version) { if (string.IsNullOrEmpty(version)) { return (0, 0, 0); - } - else { + } else { var versionSplit = version.Split('.'); - #if UNITY_EDITOR +#if UNITY_EDITOR Debug.Log($"HouseVersion: {string.Join(", ", versionSplit)}"); - #endif - var versionResult = new int[] {0, 0, 0 }.Select((x, i) => { - if (versionSplit.Length > i) { - int outVersion; - bool canParse = int.TryParse(versionSplit[i], out outVersion); - return canParse? outVersion : x; - } - return x; - }).ToArray(); +#endif + var versionResult = new int[] { 0, 0, 0 } + .Select( + (x, i) => { + if (versionSplit.Length > i) { + int outVersion; + bool canParse = int.TryParse(versionSplit[i], out outVersion); + return canParse ? outVersion : x; + } + return x; + } + ) + .ToArray(); return (versionResult[0], versionResult[1], versionResult[2]); } } public static int compareVersion((int, int, int) v0, (int, int, int) v1) { - var diffs = new int[] {v0.Item1, v0.Item2, v0.Item3}.Zip(new int[] {v1.Item1, v1.Item2, v1.Item3}, (e0, e1) => e0 - e1); + var diffs = new int[] { v0.Item1, v0.Item2, v0.Item3 }.Zip( + new int[] { v1.Item1, v1.Item2, v1.Item3 }, + (e0, e1) => e0 - e1 + ); foreach (var diff in diffs) { if (diff != 0) { return diff; @@ -1179,42 +1349,44 @@ public static int compareVersion((int, int, int) v0, (int, int, int) v1) { return 0; } - private static bool validateHouseObjects(AssetMap assetDb, IEnumerable hos, List missingIds) { + private static bool validateHouseObjects( + AssetMap assetDb, + IEnumerable hos, + List missingIds + ) { if (hos == null) { return true; - } - else { + } else { var result = true; foreach (var ho in hos) { - var inDb = assetDb.ContainsKey(ho.assetId); if (!inDb) { missingIds.Add(ho.assetId); } - result = inDb && validateHouseObjects(assetDb, ho.children, missingIds); + result = inDb && validateHouseObjects(assetDb, ho.children, missingIds); } - + return result; } } public static GameObject CreateHouse( - ProceduralHouse house, - AssetMap materialDb, - Vector3? position = null - ) { + ProceduralHouse house, + AssetMap materialDb, + Vector3? position = null + ) { // raise exception if metadata contains schema if (house.metadata == null || house.metadata.schema == null) { throw new ArgumentException( - $"House metadata schema not specified! Should be under house['metadata']['schema']." + - $" The current schema for this THOR version is '{CURRENT_HOUSE_SCHEMA}'" + $"House metadata schema not specified! Should be under house['metadata']['schema']." + + $" The current schema for this THOR version is '{CURRENT_HOUSE_SCHEMA}'" ); } var missingIds = new List(); - if (!validateHouseObjects(getAssetMap(), house.objects, missingIds )) { + if (!validateHouseObjects(getAssetMap(), house.objects, missingIds)) { throw new ArgumentException( - $"Object ids '{string.Join(", ", missingIds)}' not present in asset database." + - $" If it is a procedural asset make sure you call 'CreateAsset' before 'CreateHouse'" + $"Object ids '{string.Join(", ", missingIds)}' not present in asset database." + + $" If it is a procedural asset make sure you call 'CreateAsset' before 'CreateHouse'" ); } @@ -1223,32 +1395,44 @@ public static GameObject CreateHouse( var versionCompare = compareVersion(schema, latestSchema); if (versionCompare != 0) { - var message = versionCompare < 0 ? - $"Incompatible house schema version '{schema}', please upgrade to latest '{latestSchema}' using the 'procthor' package's 'scripts/upgrade_house.py'." : - $"Invalid house version: '{schema}'. Supported version: '{latestSchema}'"; + var message = + versionCompare < 0 + ? $"Incompatible house schema version '{schema}', please upgrade to latest '{latestSchema}' using the 'procthor' package's 'scripts/upgrade_house.py'." + : $"Invalid house version: '{schema}'. Supported version: '{latestSchema}'"; throw new ArgumentException(message, "house.version"); } - string simObjId = !String.IsNullOrEmpty(house.id) ? house.id : ProceduralTools.DefaultHouseRootObjectName; + string simObjId = !String.IsNullOrEmpty(house.id) + ? house.id + : ProceduralTools.DefaultHouseRootObjectName; float receptacleHeight = house.proceduralParameters.receptacleHeight; float floorColliderThickness = house.proceduralParameters.floorColliderThickness; string ceilingMaterialId = house.proceduralParameters.ceilingMaterial.name; - var windowsAndDoors = house.doors.Select(d => d as WallRectangularHole).Concat(house.windows); - + var windowsAndDoors = house + .doors.Select(d => d as WallRectangularHole) + .Concat(house.windows); + var holes = windowsAndDoors - .SelectMany(hole => new List<(string, WallRectangularHole)> { (hole.wall0, hole), (hole.wall1, hole) }) + .SelectMany(hole => new List<(string, WallRectangularHole)> + { + (hole.wall0, hole), + (hole.wall1, hole) + }) .Where(pair => !String.IsNullOrEmpty(pair.Item1)) .ToDictionary(pair => pair.Item1, pair => pair.Item2); - var roomMap = house.rooms.ToDictionary(r => r.id, r => r.floorPolygon.Select((p, i) => (p, i))); + var roomMap = house.rooms.ToDictionary( + r => r.id, + r => r.floorPolygon.Select((p, i) => (p, i)) + ); var walls = house.walls.Select(w => polygonWallToSimpleWall(w, holes)); var wallPoints = walls.SelectMany(w => new List() { w.p0, w.p1 }); - var wallsMinY = wallPoints.Count() > 0? wallPoints.Min(p => p.y) : 0.0f; - var wallsMaxY = wallPoints.Count() > 0? wallPoints.Max(p => p.y) : 0.0f; - var wallsMaxHeight = walls.Count() > 0? walls.Max(w => w.height) : 0.0f; + var wallsMinY = wallPoints.Count() > 0 ? wallPoints.Min(p => p.y) : 0.0f; + var wallsMaxY = wallPoints.Count() > 0 ? wallPoints.Max(p => p.y) : 0.0f; + var wallsMaxHeight = walls.Count() > 0 ? walls.Max(w => w.height) : 0.0f; var floorGameObject = createSimObjPhysicsGameObject( simObjId, @@ -1264,11 +1448,23 @@ public static GameObject CreateHouse( var visibilityPointInterval = 1 / 3.0f; // floorVisPoints is equal to, for the range of numbers equal to triangle-count... - var floorVisibilityPoints = Enumerable.Range(0, mesh.triangles.Length / 3) - // Ex: "For triangle "0", skip "0" * 3 indices in "mesh.triangle" array to get the correct 3 elements, and use those to select the respective indices from the mesh - .Select(triangleIndex => mesh.triangles.Skip(triangleIndex * 3).Take(3).Select(vertexIndex => mesh.vertices[vertexIndex])) - // With the selected 3 vertices, select all of the relevant vPoints, using the visibilityPointInvterval as an increment for their spacing - .SelectMany(vertices => GenerateTriangleVisibilityPoints(vertices.ElementAt(0), vertices.ElementAt(1), vertices.ElementAt(2), visibilityPointInterval)); + var floorVisibilityPoints = Enumerable + .Range(0, mesh.triangles.Length / 3) + // Ex: "For triangle "0", skip "0" * 3 indices in "mesh.triangle" array to get the correct 3 elements, and use those to select the respective indices from the mesh + .Select(triangleIndex => + mesh.triangles.Skip(triangleIndex * 3) + .Take(3) + .Select(vertexIndex => mesh.vertices[vertexIndex]) + ) + // With the selected 3 vertices, select all of the relevant vPoints, using the visibilityPointInvterval as an increment for their spacing + .SelectMany(vertices => + GenerateTriangleVisibilityPoints( + vertices.ElementAt(0), + vertices.ElementAt(1), + vertices.ElementAt(2), + visibilityPointInterval + ) + ); var visibilityPointsGO = CreateVisibilityPointsGameObject(floorVisibilityPoints); @@ -1279,8 +1475,8 @@ public static GameObject CreateHouse( meshRenderer.material = generatePolygonMaterial( sharedMaterial: materialDb.getAsset(room.floorMaterial.name), materialProperties: room.floorMaterial, - dimensions: dimensions, - squareTiling: house.proceduralParameters.squareTiling + dimensions: dimensions, + squareTiling: house.proceduralParameters.squareTiling ); //set up mesh collider to allow raycasts against only the floor inside the room @@ -1300,7 +1496,7 @@ public static GameObject CreateHouse( ProceduralTools.setRoomSimObjectPhysics(subFloorGO, room.id, visibilityPointsGO); ProceduralTools.setRoomProperties(subFloorGO, room); - Collider[] RoomMeshCollider = new Collider[] {meshCollider}; + Collider[] RoomMeshCollider = new Collider[] { meshCollider }; subFloorGO.GetComponent().MyColliders = RoomMeshCollider; } @@ -1319,14 +1515,33 @@ public static GameObject CreateHouse( visibilityPoints.transform.parent = floorGameObject.transform; - var receptacleTriggerBox = ProceduralTools.createFloorReceptacle(floorGameObject, rectangle, receptacleHeight); - var collider = ProceduralTools.createFloorCollider(floorGameObject, rectangle, floorColliderThickness); + var receptacleTriggerBox = ProceduralTools.createFloorReceptacle( + floorGameObject, + rectangle, + receptacleHeight + ); + var collider = ProceduralTools.createFloorCollider( + floorGameObject, + rectangle, + floorColliderThickness + ); - ProceduralTools.setRoomSimObjectPhysics(floorGameObject, simObjId, visibilityPoints, receptacleTriggerBox, collider.GetComponentInChildren()); + ProceduralTools.setRoomSimObjectPhysics( + floorGameObject, + simObjId, + visibilityPoints, + receptacleTriggerBox, + collider.GetComponentInChildren() + ); var structureGO = new GameObject(DefaultRootStructureObjectName); - var wallsGO = ProceduralTools.createWalls(walls, materialDb, house.proceduralParameters, DefaultRootWallsObjectName); + var wallsGO = ProceduralTools.createWalls( + walls, + materialDb, + house.proceduralParameters, + DefaultRootWallsObjectName + ); floorGameObject.transform.parent = structureGO.transform; wallsGO.transform.parent = structureGO.transform; @@ -1340,17 +1555,30 @@ public static GameObject CreateHouse( // var ceilingMesh = ProceduralTools.GetRectangleFloorMesh(new List { roomCluster }, 0.0f, house.proceduralParameters.ceilingBackFaces); // var k = house.rooms.SelectMany(r => r.floorPolygon.Select(p => new Vector3(p.x, p.y + wallsMaxY + wallsMaxHeight, p.z)).ToList()).ToList(); - var ceilingMeshes = house.rooms.Select(r => ProceduralTools.GenerateFloorMesh(r.floorPolygon, yOffset: 0.0f, clockWise: true)).ToArray(); + var ceilingMeshes = house + .rooms.Select(r => + ProceduralTools.GenerateFloorMesh( + r.floorPolygon, + yOffset: 0.0f, + clockWise: true + ) + ) + .ToArray(); for (int i = 0; i < house.rooms.Count(); i++) { var ceilingMesh = ceilingMeshes[i]; var room = house.rooms[i]; var floorName = house.rooms[i].id; - var ceilingGameObject = createSimObjPhysicsGameObject($"{DefaultCeilingRootObjectName}_{floorName}", new Vector3(0, wallsMaxY + wallsMaxHeight, 0), "Structure", 0); + var ceilingGameObject = createSimObjPhysicsGameObject( + $"{DefaultCeilingRootObjectName}_{floorName}", + new Vector3(0, wallsMaxY + wallsMaxHeight, 0), + "Structure", + 0 + ); StructureObject so = ceilingGameObject.AddComponent(); - so.WhatIsMyStructureObjectTag = StructureObjectTag.Ceiling; + so.WhatIsMyStructureObjectTag = StructureObjectTag.Ceiling; ceilingGameObject.GetComponent().mesh = ceilingMesh; var ceilingMeshRenderer = ceilingGameObject.GetComponent(); @@ -1372,36 +1600,38 @@ public static GameObject CreateHouse( 0.0f, squareTiling: house.proceduralParameters.squareTiling ); - ceilingMeshRenderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.TwoSided; + ceilingMeshRenderer.shadowCastingMode = UnityEngine + .Rendering + .ShadowCastingMode + .TwoSided; tagObjectNavmesh(ceilingGameObject, "Not Walkable"); ceilingGameObject.transform.parent = ceilingParent.transform; - } ceilingParent.transform.parent = structureGO.transform; - } CollisionDetectionMode collDet = CollisionDetectionMode.ContinuousSpeculative; if (!string.IsNullOrEmpty(house.proceduralParameters.collisionDetectionMode)) { Enum.TryParse(house.proceduralParameters.collisionDetectionMode, true, out collDet); } - foreach (var obj in house.objects) { spawnObjectHierarchy(obj, collDet); } var assetMap = ProceduralTools.getAssetMap(); - var doorsToWalls = windowsAndDoors.Select( - door => ( - door, - wall0: walls.First(w => w.id == door.wall0), - wall1: walls.FirstOrDefault(w => w.id == door.wall1) + var doorsToWalls = windowsAndDoors + .Select(door => + ( + door, + wall0: walls.First(w => w.id == door.wall0), + wall1: walls.FirstOrDefault(w => w.id == door.wall1) + ) ) - ).ToDictionary(d => d.door.id, d => (d.wall0, d.wall1)); + .ToDictionary(d => d.door.id, d => (d.wall0, d.wall1)); var count = 0; foreach (WallRectangularHole holeCover in windowsAndDoors) { var coverPrefab = assetMap.getAsset(holeCover.assetId); @@ -1416,12 +1646,17 @@ public static GameObject CreateHouse( Vector3 pos; var holeBB = getHoleBoundingBox(holeCover); - + bool positionFromCenter = true; Vector3 assetOffset = holeCover.assetPosition; - pos = wall.wall0.p0 + (p0p1_norm * (assetOffset.x)) + Vector3.up * (assetOffset.y); - - var rotY = getWallDegreesRotation(new Wall { p0 = wall.wall0.p1, p1 = wall.wall0.p0 }); + pos = + wall.wall0.p0 + + (p0p1_norm * (assetOffset.x)) + + Vector3.up * (assetOffset.y); + + var rotY = getWallDegreesRotation( + new Wall { p0 = wall.wall0.p1, p1 = wall.wall0.p0 } + ); var rotation = Quaternion.AngleAxis(rotY, Vector3.up); var go = spawnSimObjPrefab( @@ -1459,8 +1694,14 @@ public static GameObject CreateHouse( } var light = go.AddComponent(); //light.lightmapBakeType = LightmapBakeType.Realtime; //removed because this is editor only, and probably not needed since the light should default to Realtime Light Mode anyway? - light.type = (LightType)Enum.Parse(typeof(LightType), lightParams.type, ignoreCase: true); - light.color = new Color(lightParams.rgb.r, lightParams.rgb.g, lightParams.rgb.b, lightParams.rgb.a); + light.type = (LightType) + Enum.Parse(typeof(LightType), lightParams.type, ignoreCase: true); + light.color = new Color( + lightParams.rgb.r, + lightParams.rgb.g, + lightParams.rgb.b, + lightParams.rgb.a + ); light.intensity = lightParams.intensity; light.bounceIntensity = lightParams.indirectMultiplier; light.range = lightParams.range; @@ -1472,14 +1713,23 @@ public static GameObject CreateHouse( if (lightParams.shadow != null) { light.shadowStrength = lightParams.shadow.strength; - light.shadows = (LightShadows)Enum.Parse(typeof(LightShadows), lightParams.shadow.type, ignoreCase: true); + light.shadows = (LightShadows) + Enum.Parse( + typeof(LightShadows), + lightParams.shadow.type, + ignoreCase: true + ); light.shadowBias = lightParams.shadow.bias; light.shadowNormalBias = lightParams.shadow.normalBias; light.shadowNearPlane = lightParams.shadow.nearPlane; - light.shadowResolution = (UnityEngine.Rendering.LightShadowResolution)Enum.Parse(typeof(UnityEngine.Rendering.LightShadowResolution), lightParams.shadow.resolution, ignoreCase: true); + light.shadowResolution = (UnityEngine.Rendering.LightShadowResolution) + Enum.Parse( + typeof(UnityEngine.Rendering.LightShadowResolution), + lightParams.shadow.resolution, + ignoreCase: true + ); } go.transform.parent = lightingRoot.transform; - } } @@ -1489,7 +1739,9 @@ public static GameObject CreateHouse( go.transform.position = probe.position; var probeComp = go.AddComponent(); - probeComp.backgroundColor = (probe.background?.toUnityColor()).GetValueOrDefault(); + probeComp.backgroundColor = ( + probe.background?.toUnityColor() + ).GetValueOrDefault(); probeComp.center = probe.boxOffset; probeComp.intensity = probe.intensity; probeComp.mode = UnityEngine.Rendering.ReflectionProbeMode.Realtime; @@ -1504,24 +1756,28 @@ public static GameObject CreateHouse( buildNavMeshes(floorGameObject, house.metadata.navMeshes); - - if (string.IsNullOrEmpty(house.proceduralParameters.skyboxId) || !materialDb.ContainsKey(house.proceduralParameters.skyboxId)) { + if ( + string.IsNullOrEmpty(house.proceduralParameters.skyboxId) + || !materialDb.ContainsKey(house.proceduralParameters.skyboxId) + ) { var mat = new Material(Shader.Find("Standard")); mat.color = house.proceduralParameters.skyboxColor.toUnityColor(); RenderSettings.skybox = mat; - + // var cam = GameObject.FindObjectOfType(); var cam = GameObject.Find("FirstPersonCharacter").GetComponent(); cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = mat.color; - + // RenderSettings.ambientSkyColor = - } - else { + } else { RenderSettings.skybox = materialDb.getAsset(house.proceduralParameters.skyboxId); } DynamicGI.UpdateEnvironment(); - GameObject.FindObjectOfType().GetComponent().RenderProbe(); + GameObject + .FindObjectOfType() + .GetComponent() + .RenderProbe(); // generate objectId for newly created wall/floor objects // also add them to objectIdToSimObjPhysics dict so they can be found via @@ -1529,7 +1785,9 @@ public static GameObject CreateHouse( // also add their rigidbodies to the list of all rigid body objects in scene var sceneManager = GameObject.FindObjectOfType(); sceneManager.SetupScene(false); - var agentManager = GameObject.Find("PhysicsSceneManager").GetComponentInChildren(); + var agentManager = GameObject + .Find("PhysicsSceneManager") + .GetComponentInChildren(); agentManager.ResetSceneBounds(); setAgentPose(house: house, agentManager: agentManager); @@ -1575,10 +1833,16 @@ private static void setAgentPose(ProceduralHouse house, AgentManager agentManage } if (newHorizon.HasValue) { bfps.m_Camera.transform.localEulerAngles = new Vector3( - newHorizon.Value, bfps.m_Camera.transform.localEulerAngles.y, 0 + newHorizon.Value, + bfps.m_Camera.transform.localEulerAngles.y, + 0 ); } - if (agentManager.agentMode != "locobot" && agentManager.agentMode != "stretch" && newStanding != null) { + if ( + agentManager.agentMode != "locobot" + && agentManager.agentMode != "stretch" + && newStanding != null + ) { PhysicsRemoteFPSAgentController pfps = bfps as PhysicsRemoteFPSAgentController; if (newStanding == true) { pfps.stand(); @@ -1590,7 +1854,10 @@ private static void setAgentPose(ProceduralHouse house, AgentManager agentManage } } - public static void spawnObjectHierarchy(HouseObject houseObject, CollisionDetectionMode proceduralParamsCollisionDetMode) { + public static void spawnObjectHierarchy( + HouseObject houseObject, + CollisionDetectionMode proceduralParamsCollisionDetMode + ) { if (houseObject == null) { return; } @@ -1601,7 +1868,11 @@ public static void spawnObjectHierarchy(HouseObject houseObject, CollisionDetect } // Debug.Log($"----- obj {houseObject.id} , {houseObject.collisionDetectionMode} procPar {proceduralParamsCollisionDetMode} final: {collDet}"); - var go = ProceduralTools.spawnHouseObject(ProceduralTools.getAssetMap(), houseObject, collDet); + var go = ProceduralTools.spawnHouseObject( + ProceduralTools.getAssetMap(), + houseObject, + collDet + ); if (go != null) { tagObjectNavmesh(go, "Not Walkable"); } @@ -1611,10 +1882,13 @@ public static void spawnObjectHierarchy(HouseObject houseObject, CollisionDetect spawnObjectHierarchy(child, proceduralParamsCollisionDetMode); } } - } - public static void tagObjectNavmesh(GameObject gameObject, string navMeshAreaName = "Walkable", bool ignore = false) { + public static void tagObjectNavmesh( + GameObject gameObject, + string navMeshAreaName = "Walkable", + bool ignore = false + ) { var modifier = gameObject.GetComponent(); if (modifier == null) { modifier = gameObject.AddComponent(); @@ -1624,7 +1898,6 @@ public static void tagObjectNavmesh(GameObject gameObject, string navMeshAreaNam modifier.area = NavMesh.GetAreaFromName(navMeshAreaName); } - public static string NavMeshSurfaceName(int index) { return $"NavMeshSurface_{index}"; } @@ -1640,11 +1913,13 @@ public static GameObject buildNavMeshSurface(NavMeshBuildSettings buildSettings, } public static GameObject buildNavMeshSurface(NavMeshConfig navMeshConfig, int index) { - var go = new GameObject(NavMeshSurfaceName(index)); var navMeshSurface = go.AddComponent(); - var buildSettings = navMeshConfigToBuildSettings(navMeshConfig, NavMesh.GetSettingsByIndex(0)); + var buildSettings = navMeshConfigToBuildSettings( + navMeshConfig, + NavMesh.GetSettingsByIndex(0) + ); navMeshSurface.agentTypeID = buildSettings.agentTypeID; navMeshSurface.voxelSize = buildSettings.voxelSize; navMeshSurface.overrideVoxelSize = buildSettings.overrideVoxelSize; @@ -1652,45 +1927,55 @@ public static GameObject buildNavMeshSurface(NavMeshConfig navMeshConfig, int in return go; } - public static void activateAllNavmeshSurfaces(IEnumerable navmeshSurfaces) { - foreach(var nvms in navmeshSurfaces) { + public static void activateAllNavmeshSurfaces( + IEnumerable navmeshSurfaces + ) { + foreach (var nvms in navmeshSurfaces) { nvms.enabled = true; } } - public static NavMeshSurfaceExtended activateOnlyNavmeshSurface(IEnumerable navmeshSurfaces, int? navMeshId = null) { - #if UNITY_EDITOR - Debug.Log($"-----Navmesh Query {navMeshId} navmesh count: {navmeshSurfaces.Count()} extended active count: {NavMeshSurfaceExtended.activeSurfaces.Count} navmesh active count: {NavMeshSurface.activeSurfaces.Count}"); - #endif + public static NavMeshSurfaceExtended activateOnlyNavmeshSurface( + IEnumerable navmeshSurfaces, + int? navMeshId = null + ) { +#if UNITY_EDITOR + Debug.Log( + $"-----Navmesh Query {navMeshId} navmesh count: {navmeshSurfaces.Count()} extended active count: {NavMeshSurfaceExtended.activeSurfaces.Count} navmesh active count: {NavMeshSurface.activeSurfaces.Count}" + ); +#endif var queryAgentId = getNavMeshAgentId(navMeshId); // var useNavmeshSurface = queryAgentId.HasValue; var navMesh = getNavMeshSurfaceForAgentId(queryAgentId); - #if UNITY_EDITOR +#if UNITY_EDITOR Debug.Log("---- Reached agent navmeshid " + queryAgentId); - #endif +#endif // bool pathSuccess = navMeshAgent.CalculatePath( // targetHit.position, path // ); - + foreach (var nvms in navmeshSurfaces) { if (nvms != navMesh) { - nvms.enabled = false; + nvms.enabled = false; } } - #if UNITY_EDITOR - Debug.Log($"-----Navmesh Query {queryAgentId} navmesh count: {navmeshSurfaces.Count()}"); - #endif +#if UNITY_EDITOR + Debug.Log( + $"-----Navmesh Query {queryAgentId} navmesh count: {navmeshSurfaces.Count()}" + ); +#endif return navMesh; } - public static int getNavMeshAgentId(int? navMeshId = null) { - var idSet = new HashSet(NavMeshSurfaceExtended.activeSurfaces.Select(n => n.agentTypeID)); + var idSet = new HashSet( + NavMeshSurfaceExtended.activeSurfaces.Select(n => n.agentTypeID) + ); if (!navMeshId.HasValue) { if (NavMeshSurfaceExtended.activeSurfaces.Count > 0) { return NavMeshSurfaceExtended.activeSurfaces[0].agentTypeID; @@ -1699,35 +1984,51 @@ public static int getNavMeshAgentId(int? navMeshId = null) { // else { // return null; // } - } - else if (!idSet.Contains(navMeshId.GetValueOrDefault())) { + } else if (!idSet.Contains(navMeshId.GetValueOrDefault())) { // actionFinished(success: false, errorMessage: $"Invalid agent id: '{navMeshId.GetValueOrDefault()}' provide a valid agent id for using with the NavMeshes available or bake a new NavMesh. Available: '{string.Join(", ",idSet.Select(i => i.ToString()) )}'"); // errorMessage = $"Invalid agent id: '{navMeshId.GetValueOrDefault()}' provide a valid agent id for using with the NavMeshes available or bake a new NavMesh. Available: '{string.Join(", ",idSet.Select(i => i.ToString()) )}'"; throw new InvalidOperationException( - $"Invalid agent id: '{navMeshId.GetValueOrDefault()}' provide a valid agent id for using with the NavMeshes available or bake a new NavMesh. Available: '{string.Join(", ",idSet.Select(i => i.ToString()) )}'" - + $"Invalid agent id: '{navMeshId.GetValueOrDefault()}' provide a valid agent id for using with the NavMeshes available or bake a new NavMesh. Available: '{string.Join(", ", idSet.Select(i => i.ToString()))}'" ); } return navMeshId.GetValueOrDefault(); - } + } public static NavMeshSurfaceExtended getNavMeshSurfaceForAgentId(int agentId) { - return NavMeshSurface.activeSurfaces.Find(s => s.agentTypeID == agentId) as NavMeshSurfaceExtended; + return NavMeshSurface.activeSurfaces.Find(s => s.agentTypeID == agentId) + as NavMeshSurfaceExtended; } - public static NavMeshBuildSettings navMeshConfigToBuildSettings(NavMeshConfig config, NavMeshBuildSettings defaultBuildSettings) { + public static NavMeshBuildSettings navMeshConfigToBuildSettings( + NavMeshConfig config, + NavMeshBuildSettings defaultBuildSettings + ) { defaultBuildSettings.agentTypeID = config.id; defaultBuildSettings.agentRadius = config.agentRadius; - defaultBuildSettings.tileSize = config.tileSize.GetValueOrDefault(defaultBuildSettings.tileSize); - defaultBuildSettings.agentClimb = config.agentClimb.GetValueOrDefault(defaultBuildSettings.agentClimb); - defaultBuildSettings.agentHeight = config.agentHeight.GetValueOrDefault(defaultBuildSettings.agentHeight); - defaultBuildSettings.agentSlope = config.agentSlope.GetValueOrDefault(defaultBuildSettings.agentSlope); - defaultBuildSettings.voxelSize = config.voxelSize.GetValueOrDefault(defaultBuildSettings.voxelSize); - defaultBuildSettings.overrideVoxelSize = config.overrideVoxelSize.GetValueOrDefault(defaultBuildSettings.overrideVoxelSize); + defaultBuildSettings.tileSize = config.tileSize.GetValueOrDefault( + defaultBuildSettings.tileSize + ); + defaultBuildSettings.agentClimb = config.agentClimb.GetValueOrDefault( + defaultBuildSettings.agentClimb + ); + defaultBuildSettings.agentHeight = config.agentHeight.GetValueOrDefault( + defaultBuildSettings.agentHeight + ); + defaultBuildSettings.agentSlope = config.agentSlope.GetValueOrDefault( + defaultBuildSettings.agentSlope + ); + defaultBuildSettings.voxelSize = config.voxelSize.GetValueOrDefault( + defaultBuildSettings.voxelSize + ); + defaultBuildSettings.overrideVoxelSize = config.overrideVoxelSize.GetValueOrDefault( + defaultBuildSettings.overrideVoxelSize + ); return defaultBuildSettings; } - public static NavMeshConfig navMeshBuildSettingsToConfig(NavMeshBuildSettings navMeshBuildSettings) { + public static NavMeshConfig navMeshBuildSettingsToConfig( + NavMeshBuildSettings navMeshBuildSettings + ) { var navMeshConfig = new NavMeshConfig(); navMeshConfig.id = navMeshBuildSettings.agentTypeID; navMeshConfig.agentRadius = navMeshBuildSettings.agentRadius; @@ -1744,32 +2045,37 @@ public static NavMeshBuildSettings navMeshConfigToBuildSettings(NavMeshConfig co return navMeshConfigToBuildSettings(config, NavMesh.GetSettingsByIndex(0)); } - public static string NavMeshSurfaceParent() { return "NavMeshSurfaces"; } - + public static string NavMeshSurfaceParent() { + return "NavMeshSurfaces"; + } public static void buildNavMeshes(GameObject floorGameObject, List navMeshes) { - var defaultSettings = NavMesh.GetSettingsByIndex(0); if (navMeshes == null || navMeshes.Count == 0) { - navMeshes = new List() { + navMeshes = new List() + { navMeshBuildSettingsToConfig(defaultSettings) }; } - var navMeshAgent = GameObject.FindObjectOfType(); - tagObjectNavmesh(navMeshAgent.gameObject, ignore: true); + var navMeshAgent = GameObject.FindObjectOfType(); + tagObjectNavmesh(navMeshAgent.gameObject, ignore: true); - var navmeshesGameObject = new GameObject($"NavMeshSurfaces"); + var navmeshesGameObject = new GameObject($"NavMeshSurfaces"); - navmeshesGameObject.transform.parent = floorGameObject.transform; + navmeshesGameObject.transform.parent = floorGameObject.transform; - - - var newConfigs = navMeshes.Select(c => defaultSettings).Select((c, i) => { - return navMeshConfigToBuildSettings(navMeshes[i], c); - }); + var newConfigs = navMeshes + .Select(c => defaultSettings) + .Select( + (c, i) => { + return navMeshConfigToBuildSettings(navMeshes[i], c); + } + ); - Debug.Log($"Creating Navmeshes for Configs: {string.Join(", ", newConfigs.Select(c => $"{c.agentTypeID}: {c.agentRadius}, {c.voxelSize}"))}"); + Debug.Log( + $"Creating Navmeshes for Configs: {string.Join(", ", newConfigs.Select(c => $"{c.agentTypeID}: {c.agentRadius}, {c.voxelSize}"))}" + ); var count = 0; foreach (var config in newConfigs) { @@ -1779,18 +2085,14 @@ public static void buildNavMeshes(GameObject floorGameObject, List(); + tagObjectNavmesh(navMeshAgent.gameObject, ignore: true); - - var navMeshAgent = GameObject.FindObjectOfType(); - tagObjectNavmesh(navMeshAgent.gameObject, ignore: true); - - var navMesh = floorGameObject.AddComponent(); // TODO multiple agents - + // navMeshAgent.agentTypeID = 1; // var settingsNew = NavMesh.CreateSettings(); @@ -1799,7 +2101,7 @@ public static void buildNavMesh(GameObject floorGameObject, float? voxelSize = n // navMeshAgent.agentTypeID = sett.agentTypeID; // Debug.Log($"Radius navmesh build {sett.agentRadius} id {sett.agentTypeID}"); - + // // settingsNew. // // settingsNew.agentTypeID = 1; // settingsNew.agentRadius = 0.1f; @@ -1810,20 +2112,22 @@ public static void buildNavMesh(GameObject floorGameObject, float? voxelSize = n ///NavMeshBuildSettings s = ref NavMesh.GetSettingsByID(navMeshAgent.agentTypeID); //s.agentRadius = 0.2f; - + //Debug.Log($"--- NAVMESH AGENT type {navMeshAgent.agentTypeID}, settings id {settingsNew.agentTypeID} settings count {NavMesh.GetSettingsCount()} radius {NavMesh.GetSettingsByID(navMeshAgent.agentTypeID).agentRadius}"); // navMeshAgent.radius = 0.2f; - + navMesh.agentTypeID = navMeshAgent.agentTypeID; // navMesh.agentTypeID = 1; var settings = navMesh.GetBuildSettings(); - Debug.Log($"Current navmesh build settings, id {settings.agentTypeID} radius {settings.agentRadius}"); - + Debug.Log( + $"Current navmesh build settings, id {settings.agentTypeID} radius {settings.agentRadius}" + ); + navMesh.overrideVoxelSize = voxelSize != null; navMesh.voxelSize = voxelSize.GetValueOrDefault(0.0f); @@ -1831,7 +2135,7 @@ public static void buildNavMesh(GameObject floorGameObject, float? voxelSize = n navMesh.BuildNavMesh(); - // TODO: Move to code specified navmeshbuildsettings + // TODO: Move to code specified navmeshbuildsettings // new NavMeshBuildSettings() { // agentTypeID = navmeshAgent.agentTypeID, // agentRadius = 0.2f, @@ -1843,13 +2147,15 @@ public static void buildNavMesh(GameObject floorGameObject, float? voxelSize = n // overrideTileSize = false // }; // NavMeshSetup.SetNavMeshNotWalkable(GameObject.Find("Objects")); - } #if UNITY_EDITOR - public static List FindAssetsByType() where T : UnityEngine.Object { + public static List FindAssetsByType() + where T : UnityEngine.Object { List assets = new List(); - string[] guids = AssetDatabase.FindAssets(string.Format("t:{0}", typeof(T).ToString().Replace("UnityEngine.", ""))); + string[] guids = AssetDatabase.FindAssets( + string.Format("t:{0}", typeof(T).ToString().Replace("UnityEngine.", "")) + ); for (int i = 0; i < guids.Length; i++) { string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]); T asset = AssetDatabase.LoadAssetAtPath(assetPath); @@ -1904,9 +2210,8 @@ public static GameObject spawnHouseObject( CollisionDetectionMode collisionDetectionMode ) { if (goDb.ContainsKey(ho.assetId)) { - var go = goDb.getAsset(ho.assetId); - + return spawnSimObjPrefab( prefab: go, id: ho.id, @@ -1925,7 +2230,6 @@ CollisionDetectionMode collisionDetectionMode collisionDetectionMode: collisionDetectionMode ); } else { - Debug.LogError($"Asset not in Database: `{ho.assetId}`"); return null; } @@ -1947,7 +2251,8 @@ public static GameObject spawnSimObjPrefab( bool? isDirty = null, string layer = null, Vector3? scale = null, - CollisionDetectionMode collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative + CollisionDetectionMode collisionDetectionMode = + CollisionDetectionMode.ContinuousSpeculative ) { var go = prefab; @@ -1982,7 +2287,9 @@ public static GameObject spawnSimObjPrefab( } } - spawned.transform.parent = GameObject.Find(ProceduralTools.DefaultObjectsRootName).transform; + spawned.transform.parent = GameObject + .Find(ProceduralTools.DefaultObjectsRootName) + .transform; // scale the object if (scale.HasValue) { @@ -1998,7 +2305,9 @@ public static GameObject spawnSimObjPrefab( foreach (Transform t in children) { t.SetParent(spawned.transform); } - spawned.GetComponent().ContextSetUpBoundingBox(forceCacheReset: true); + spawned + .GetComponent() + .ContextSetUpBoundingBox(forceCacheReset: true); } // var rotaiton = Quaternion.AngleAxis(rotation.degrees, rotation.axis); @@ -2008,7 +2317,8 @@ public static GameObject spawnSimObjPrefab( // box.enabled = true; var centerObjectSpace = prefab.transform.TransformPoint(box.center); - spawned.transform.position = rotation * (spawned.transform.localPosition - box.center) + position; + spawned.transform.position = + rotation * (spawned.transform.localPosition - box.center) + position; spawned.transform.rotation = rotation; } else { spawned.transform.position = position; @@ -2034,26 +2344,32 @@ public static GameObject spawnSimObjPrefab( } if (materialProperties != null) { - var materials = toSpawn.GetComponentsInChildren().Select( - mr => mr.material - ); + var materials = toSpawn + .GetComponentsInChildren() + .Select(mr => mr.material); foreach (var mat in materials) { if (materialProperties.color != null) { mat.color = new Color( - materialProperties.color.r, - materialProperties.color.g, - materialProperties.color.b, + materialProperties.color.r, + materialProperties.color.g, + materialProperties.color.b, materialProperties.color.a ); } if (unlit) { mat.shader = unlitShader; } - if (materialProperties?.metallic != null) { - mat.SetFloat("_Metallic", materialProperties.metallic.GetValueOrDefault(0.0f)); + if (materialProperties?.metallic != null) { + mat.SetFloat( + "_Metallic", + materialProperties.metallic.GetValueOrDefault(0.0f) + ); } - if (materialProperties?.smoothness != null) { - mat.SetFloat("_Glossiness", materialProperties.smoothness.GetValueOrDefault(0.0f)); + if (materialProperties?.smoothness != null) { + mat.SetFloat( + "_Glossiness", + materialProperties.smoothness.GetValueOrDefault(0.0f) + ); } } } @@ -2063,7 +2379,8 @@ public static GameObject spawnSimObjPrefab( sceneManager.AddToObjectsInScene(toSpawn); toSpawn.transform.SetParent(GameObject.Find(DefaultObjectsRootName).transform); - SimObjPhysics[] childSimObjects = toSpawn.transform.gameObject.GetComponentsInChildren(); + SimObjPhysics[] childSimObjects = + toSpawn.transform.gameObject.GetComponentsInChildren(); int childNumber = 0; for (int i = 0; i < childSimObjects.Length; i++) { if (childSimObjects[i].objectID == id) { @@ -2088,7 +2405,12 @@ public static GameObject spawnObjectInReceptacle( var go = goDb.getAsset(prefabName); //TODO to potentially support multiagent down the line, reference fpsAgent via agentManager's array of active agents var sceneManager = GameObject.FindObjectOfType(); - var initialSpawnPosition = new Vector3(receptacleSimObj.transform.position.x, receptacleSimObj.transform.position.y + 100f, receptacleSimObj.transform.position.z); ; + var initialSpawnPosition = new Vector3( + receptacleSimObj.transform.position.x, + receptacleSimObj.transform.position.y + 100f, + receptacleSimObj.transform.position.z + ); + ; var spawned = GameObject.Instantiate( original: go, @@ -2177,7 +2499,12 @@ public static GameObject spawnObjectInReceptacleRandomly( var pos = spawnCoordinates.Shuffle_().First(); //to potentially support multiagent down the line, reference fpsAgent via agentManager's array of active agents var sceneManager = GameObject.FindObjectOfType(); - var initialSpawnPosition = new Vector3(receptacleSimObj.transform.position.x, receptacleSimObj.transform.position.y + 100f, receptacleSimObj.transform.position.z); ; + var initialSpawnPosition = new Vector3( + receptacleSimObj.transform.position.x, + receptacleSimObj.transform.position.y + 100f, + receptacleSimObj.transform.position.z + ); + ; var spawned = GameObject.Instantiate( original: go, @@ -2207,7 +2534,9 @@ public static GameObject spawnObjectInReceptacleRandomly( success = true; List corners = GetCorners(toSpawn); //this only attempts to check the first ReceptacleTriggerBox of the receptacle, does not handle multiple receptacle boxes - Contains con = receptacleSimObj.ReceptacleTriggerBoxes[0].GetComponent(); + Contains con = receptacleSimObj + .ReceptacleTriggerBoxes[0] + .GetComponent(); bool cornerCheck = true; foreach (Vector3 p in corners) { if (!con.CheckIfPointIsAboveReceptacleTriggerBox(p)) { @@ -2266,27 +2595,62 @@ private static List GetCorners(SimObjPhysics sop) { //keep track of all 8 corners of the OverlapBox List corners = new List(); //bottom forward right - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f + ) + ); //bottom forward left - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, bbcol.size.z) * 0.5f + ) + ); //bottom back left - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(-bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f + ) + ); //bottom back right - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(bbcol.size.x, -bbcol.size.y, -bbcol.size.z) * 0.5f + ) + ); //top forward right - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f + ) + ); //top forward left - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, bbcol.size.z) * 0.5f + ) + ); //top back left - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(-bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f + ) + ); //top back right - corners.Add(bb.transform.TransformPoint(bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f)); + corners.Add( + bb.transform.TransformPoint( + bbCenter + new Vector3(bbcol.size.x, bbcol.size.y, -bbcol.size.z) * 0.5f + ) + ); return corners; } public static bool withinArrayBoundary((int row, int col) current, int rows, int columns) { - return current.row >= 0 && current.row < rows && current.col >= 0 && current.col < columns; + return current.row >= 0 + && current.row < rows + && current.col >= 0 + && current.col < columns; } public static BoundingBoxWithOffset getHoleAssetBoundingBox(string holeAssetId) { @@ -2301,23 +2665,27 @@ public static BoundingBoxWithOffset getHoleAssetBoundingBox(string holeAssetId) var holeMetadata = asset.GetComponentInChildren(); if (holeMetadata == null) { return null; - - } - else { + } else { var diff = holeMetadata.Max - holeMetadata.Min; - diff = new Vector3(Math.Abs(diff.x), Math.Abs(diff.y), Math.Abs(diff.z));// - holeMetadata.Margin; + diff = new Vector3(Math.Abs(diff.x), Math.Abs(diff.y), Math.Abs(diff.z)); // - holeMetadata.Margin; // inverse offset for the asset var min = new Vector3(holeMetadata.Min.x, -holeMetadata.Min.y, -holeMetadata.Min.z); // var max = new Vector3(-holeMetadata.Max.x, holeMetadata.Max.y, holeMetadata.Max.z); - return new BoundingBoxWithOffset() { min=Vector3.zero, max=diff, offset=min}; + return new BoundingBoxWithOffset() { + min = Vector3.zero, + max = diff, + offset = min + }; } } public static AssetMap GetMaterials() { var assetDB = GameObject.FindObjectOfType(); if (assetDB != null) { - return new AssetMap(assetDB.materials.GroupBy(m => m.name).ToDictionary(m => m.Key, m => m.First())); + return new AssetMap( + assetDB.materials.GroupBy(m => m.name).ToDictionary(m => m.Key, m => m.First()) + ); } return null; } @@ -2325,13 +2693,17 @@ public static AssetMap GetMaterials() { public static AssetMap GetPrefabs() { var assetDB = GameObject.FindObjectOfType(); if (assetDB != null) { - return new AssetMap(assetDB.GetPrefabs().GroupBy(m => m.name).ToDictionary(m => m.Key, m => m.First())); + return new AssetMap( + assetDB + .GetPrefabs() + .GroupBy(m => m.name) + .ToDictionary(m => m.Key, m => m.First()) + ); } return null; } public static Dictionary getAssetMetadata(GameObject asset) { - if (asset.GetComponent() == null) { return null; } @@ -2343,7 +2715,9 @@ public static Dictionary getAssetMetadata(GameObject asset) { ["name"] = simObj.gameObject.name, ["objectType"] = simObj.Type.ToString(), ["primaryProperty"] = simObj.PrimaryProperty.ToString(), - ["secondaryProperties"] = simObj.SecondaryProperties.Select(s => s.ToString()).ToList(), + ["secondaryProperties"] = simObj + .SecondaryProperties.Select(s => s.ToString()) + .ToList(), ["boundingBox"] = new BoundingBox() { min = bb.center - bb.size / 2.0f, max = bb.center + bb.size / 2.0f @@ -2484,10 +2858,12 @@ public static Dictionary CreateAsset( Material mat = null; RuntimePrefab runtimePrefab = null; - + // load image from disk if (albedoTexturePath != null) { - albedoTexturePath = !Path.IsPathRooted(albedoTexturePath) ? Path.Combine(parentTexturesDir, albedoTexturePath) : albedoTexturePath; + albedoTexturePath = !Path.IsPathRooted(albedoTexturePath) + ? Path.Combine(parentTexturesDir, albedoTexturePath) + : albedoTexturePath; // textures aren't saved as part of the prefab, so we load them from disk runtimePrefab = go.AddComponent(); runtimePrefab.albedoTexturePath = albedoTexturePath; @@ -2511,8 +2887,10 @@ public static Dictionary CreateAsset( } if (metallicSmoothnessTexturePath != null) { - metallicSmoothnessTexturePath = !Path.IsPathRooted(metallicSmoothnessTexturePath) ? Path.Combine(parentTexturesDir, metallicSmoothnessTexturePath) : metallicSmoothnessTexturePath; - if (runtimePrefab == null) { + metallicSmoothnessTexturePath = !Path.IsPathRooted(metallicSmoothnessTexturePath) + ? Path.Combine(parentTexturesDir, metallicSmoothnessTexturePath) + : metallicSmoothnessTexturePath; + if (runtimePrefab == null) { runtimePrefab = go.AddComponent(); } runtimePrefab.metallicSmoothnessTexturePath = metallicSmoothnessTexturePath; @@ -2523,7 +2901,7 @@ public static Dictionary CreateAsset( tex = SwapChannelsRGBAtoRRRB(tex); } tex.LoadImage(imageBytes); - + mat.SetTexture("_MetallicGlossMap", tex); } else { mat.SetFloat("_Metallic", 0f); @@ -2531,7 +2909,9 @@ public static Dictionary CreateAsset( } if (normalTexturePath != null) { - normalTexturePath = !Path.IsPathRooted(normalTexturePath) ? Path.Combine(parentTexturesDir, normalTexturePath) : normalTexturePath; + normalTexturePath = !Path.IsPathRooted(normalTexturePath) + ? Path.Combine(parentTexturesDir, normalTexturePath) + : normalTexturePath; if (runtimePrefab == null) { runtimePrefab = go.AddComponent(); } @@ -2540,13 +2920,15 @@ public static Dictionary CreateAsset( byte[] imageBytes = File.ReadAllBytes(normalTexturePath); Texture2D tex = new Texture2D(2, 2); tex.LoadImage(imageBytes); - + mat.SetTexture("_BumpMap", tex); } if (emissionTexturePath != null) { - emissionTexturePath = !Path.IsPathRooted(emissionTexturePath) ? Path.Combine(parentTexturesDir, emissionTexturePath) : emissionTexturePath; - if (runtimePrefab == null) { + emissionTexturePath = !Path.IsPathRooted(emissionTexturePath) + ? Path.Combine(parentTexturesDir, emissionTexturePath) + : emissionTexturePath; + if (runtimePrefab == null) { runtimePrefab = go.AddComponent(); } runtimePrefab.emissionTexturePath = emissionTexturePath; @@ -2583,23 +2965,32 @@ public static Dictionary CreateAsset( if (annotations == null) { annotations = new ObjectAnnotations(); } - sop.PrimaryProperty = (SimObjPrimaryProperty)Enum.Parse( - typeof(SimObjPrimaryProperty), annotations.primaryProperty - ); + sop.PrimaryProperty = (SimObjPrimaryProperty) + Enum.Parse(typeof(SimObjPrimaryProperty), annotations.primaryProperty); sop.Type = (SimObjType)Enum.Parse(typeof(SimObjType), annotations.objectType); if (annotations.secondaryProperties == null) { annotations.secondaryProperties = new string[0]; } - sop.SecondaryProperties = annotations.secondaryProperties.Select( - p => (SimObjSecondaryProperty)Enum.Parse(typeof(SimObjSecondaryProperty), p) - ).ToArray(); - sop.syncBoundingBoxes(forceCacheReset: true, forceCreateObjectOrientedBoundingBox: true); + sop.SecondaryProperties = annotations + .secondaryProperties.Select(p => + (SimObjSecondaryProperty)Enum.Parse(typeof(SimObjSecondaryProperty), p) + ) + .ToArray(); + sop.syncBoundingBoxes( + forceCacheReset: true, + forceCreateObjectOrientedBoundingBox: true + ); if (receptacleCandidate) { BaseFPSAgentController.TryToAddReceptacleTriggerBox(sop: sop); - GameObject receptacleTriggerBoxes = go.transform.Find("ReceptacleTriggerBoxes").gameObject; + GameObject receptacleTriggerBoxes = go + .transform.Find("ReceptacleTriggerBoxes") + .gameObject; if (receptacleTriggerBoxes.transform.childCount > 0) { - sop.SecondaryProperties = new SimObjSecondaryProperty[] { SimObjSecondaryProperty.Receptacle }; + sop.SecondaryProperties = new SimObjSecondaryProperty[] + { + SimObjSecondaryProperty.Receptacle + }; } } @@ -2625,13 +3016,14 @@ public static Dictionary CreateAsset( // our bounding box computation code works where it ignores some unactive components of an object var assetMeta = getAssetMetadata(sop.gameObject); - var objectMeta = SimObjPhysics.ObjectMetadataFromSimObjPhysics(sop, true, true); - + var objectMeta = SimObjPhysics.ObjectMetadataFromSimObjPhysics(sop, true, true); + go.transform.parent = prefabParentTransform; - var result = new Dictionary{ - {"assetMetadata", assetMeta}, - {"objectMetadata", objectMeta} + var result = new Dictionary + { + { "assetMetadata", assetMeta }, + { "objectMetadata", objectMeta } }; MonoBehaviour.Destroy(oldGo); @@ -2644,5 +3036,4 @@ public static Dictionary CreateAsset( return result; } } - } diff --git a/unity/Assets/Scripts/Rearrangeable.cs b/unity/Assets/Scripts/Rearrangeable.cs index dc18067da0..3ff48e94b2 100644 --- a/unity/Assets/Scripts/Rearrangeable.cs +++ b/unity/Assets/Scripts/Rearrangeable.cs @@ -1,6 +1,6 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; public enum FurniturePosition { Undesirable, @@ -15,7 +15,9 @@ public class Rearrangeable : MonoBehaviour { public SimObj ParentSimObj; public FurniturePosition Position { get { - return ParentSimObj.Animator.GetBool("AnimState1") ? FurniturePosition.Undesirable : FurniturePosition.Desireable; + return ParentSimObj.Animator.GetBool("AnimState1") + ? FurniturePosition.Undesirable + : FurniturePosition.Desireable; } } @@ -45,7 +47,8 @@ void OnEnable() { if (ParentSimObj != null) { if (!ParentSimObj.IsAnimated) { Animator a = ParentSimObj.gameObject.AddComponent(); - a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; + a.runtimeAnimatorController = + Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; gameObject.SetActive(false); gameObject.SetActive(true); } @@ -101,8 +104,12 @@ void OnDrawGizmos() { MeshFilter mf = ParentSimObj.GetComponentInChildren(); if (mf != null) { - Gizmos.color = EditorPos ? Color.Lerp(Color.red, Color.clear, 0.5f) : Color.Lerp(Color.green, Color.clear, 0.5f); - Gizmos.matrix = EditorPos ? StartPosition.localToWorldMatrix : EndPosition.localToWorldMatrix; + Gizmos.color = EditorPos + ? Color.Lerp(Color.red, Color.clear, 0.5f) + : Color.Lerp(Color.green, Color.clear, 0.5f); + Gizmos.matrix = EditorPos + ? StartPosition.localToWorldMatrix + : EndPosition.localToWorldMatrix; Gizmos.DrawWireMesh(mf.sharedMesh); } } diff --git a/unity/Assets/Scripts/Receptacle.cs b/unity/Assets/Scripts/Receptacle.cs index b5e07d0a73..a37ba48b0f 100644 --- a/unity/Assets/Scripts/Receptacle.cs +++ b/unity/Assets/Scripts/Receptacle.cs @@ -1,6 +1,6 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; [RequireComponent(typeof(SimObj))] [ExecuteInEditMode] @@ -27,7 +27,9 @@ public bool IsClean { protected virtual void OnEnable() { if (VisibilityCollider == null) { - Debug.LogError("Visibility collider is not set on receptacle " + name + " - this should not happen"); + Debug.LogError( + "Visibility collider is not set on receptacle " + name + " - this should not happen" + ); return; } // this is guaranteed to run before sim objs @@ -43,7 +45,11 @@ protected virtual void OnEnable() { if (Pivots[i].childCount > 0) { startupItems[i] = Pivots[i].GetChild(0).GetComponent(); if (startupItems[i] == null) { - Debug.LogError("Found a non-SimObj child in a receptacle " + name + " pivot - this should not happen"); + Debug.LogError( + "Found a non-SimObj child in a receptacle " + + name + + " pivot - this should not happen" + ); } else { startupItems[i].transform.parent = null; } diff --git a/unity/Assets/Scripts/ResourceAssetManager.cs b/unity/Assets/Scripts/ResourceAssetManager.cs index 6c606c8b76..9541854540 100644 --- a/unity/Assets/Scripts/ResourceAssetManager.cs +++ b/unity/Assets/Scripts/ResourceAssetManager.cs @@ -1,12 +1,12 @@ +using System; using System.Collections.Generic; using System.IO; -using System; using Newtonsoft.Json; using UnityEditor; using UnityEngine; - -public class ResourceAssetReference where T : UnityEngine.Object { +public class ResourceAssetReference + where T : UnityEngine.Object { public readonly string Name; public readonly string ResourcePath; private T _asset; @@ -24,13 +24,11 @@ public T Load() { } } - public class ResourceAssetManager { - private class ResourceAsset { - // must have empty constructor for JSON deserialization public ResourceAsset() { } + #if UNITY_EDITOR public ResourceAsset(string assetPath) { var asset = AssetDatabase.LoadMainAssetAtPath(assetPath); @@ -61,17 +59,18 @@ public ResourceAssetCatalog() { private static readonly string CatalogPath = ResourcesPath + "ResourceAssetCatalog.json"; private static readonly string ProjectFolder = Path.GetDirectoryName(Application.dataPath); private ResourceAssetCatalog catalog; - private Dictionary> labelIndex = new Dictionary>(); - + private Dictionary> labelIndex = + new Dictionary>(); public ResourceAssetManager() { -#if UNITY_EDITOR +#if UNITY_EDITOR this.RefreshCatalog(); #else this.catalog = readCatalog(); - if (this.catalog == null) { - this.catalog = new ResourceAssetCatalog(); - } + if (this.catalog == null) + { + this.catalog = new ResourceAssetCatalog(); + } this.generateLabelIndex(); #endif } @@ -82,14 +81,16 @@ private string[] findResourceGuids() { return AssetDatabase.FindAssets("t:material", new[] { "Assets/Resources" }); } - public void RefreshCatalog() { this.catalog = new ResourceAssetCatalog(); foreach (string guid in this.findResourceGuids()) { // GUIDToAssetPath returns a relative path e.g "Assets/Resources/QuickMaterials/Blue.mat" var assetPath = AssetDatabase.GUIDToAssetPath(guid); // ignore FBX files with multiple sub-materials - if (assetPath.ToLower().EndsWith(".fbx") && AssetDatabase.LoadAllAssetsAtPath(assetPath).Length > 1) { + if ( + assetPath.ToLower().EndsWith(".fbx") + && AssetDatabase.LoadAllAssetsAtPath(assetPath).Length > 1 + ) { continue; } @@ -106,7 +107,6 @@ public void BuildCatalog() { #endif private void generateLabelIndex() { - foreach (var labeledAsset in this.catalog.assets) { foreach (var label in labeledAsset.labels) { if (!this.labelIndex.ContainsKey(label)) { @@ -121,7 +121,10 @@ private ResourceAssetCatalog readCatalog() { string catalogResourcePath = relativePath(ResourcesPath, CatalogPath); if (Path.HasExtension(catalogResourcePath)) { string ext = Path.GetExtension(catalogResourcePath); - catalogResourcePath = catalogResourcePath.Remove(catalogResourcePath.Length - ext.Length, ext.Length); + catalogResourcePath = catalogResourcePath.Remove( + catalogResourcePath.Length - ext.Length, + ext.Length + ); } var jsonResource = Resources.Load(catalogResourcePath); @@ -150,21 +153,27 @@ private void writeCatalog() { if (File.Exists(CatalogPath)) { File.Delete(CatalogPath); } - // Doing a delete + move to make the write atomic and avoid writing a possibly invalid JSON + // Doing a delete + move to make the write atomic and avoid writing a possibly invalid JSON // document File.Move(tmpCatalogPath, CatalogPath); } - public List> FindResourceAssetReferences(string label) where T : UnityEngine.Object { - + public List> FindResourceAssetReferences(string label) + where T : UnityEngine.Object { string typeName = typeof(T).FullName; List> assetRefs = new List>(); if (this.labelIndex.ContainsKey(label)) { foreach (var res in this.labelIndex[label]) { if (res.assetType == typeName) { string resourcePath = relativePath("Assets/Resources/", res.path); - resourcePath = Path.Combine(Path.GetDirectoryName(resourcePath), Path.GetFileNameWithoutExtension(resourcePath)); - ResourceAssetReference assetRef = new ResourceAssetReference(resourcePath: resourcePath, name: res.name); + resourcePath = Path.Combine( + Path.GetDirectoryName(resourcePath), + Path.GetFileNameWithoutExtension(resourcePath) + ); + ResourceAssetReference assetRef = new ResourceAssetReference( + resourcePath: resourcePath, + name: res.name + ); assetRefs.Add(assetRef); } } @@ -186,5 +195,4 @@ private string serialize(ResourceAssetCatalog catalog) { } ); } - -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/RobotArmTest/Adjust_Slider.cs b/unity/Assets/Scripts/RobotArmTest/Adjust_Slider.cs index 67d3300a5a..e5ef9cef0d 100644 --- a/unity/Assets/Scripts/RobotArmTest/Adjust_Slider.cs +++ b/unity/Assets/Scripts/RobotArmTest/Adjust_Slider.cs @@ -14,11 +14,23 @@ void Start() { void Update() { if (robotArmRoot.localPosition.y < minThreshold) { - this.transform.localPosition = new Vector3(this.transform.localPosition.x, localStartingPoint.y - Mathf.Abs(robotArmRoot.localPosition.y - minThreshold), this.transform.localPosition.z); + this.transform.localPosition = new Vector3( + this.transform.localPosition.x, + localStartingPoint.y - Mathf.Abs(robotArmRoot.localPosition.y - minThreshold), + this.transform.localPosition.z + ); } else if (robotArmRoot.localPosition.y > maxThreshold) { - this.transform.localPosition = new Vector3(this.transform.localPosition.x, localStartingPoint.y + Mathf.Abs(robotArmRoot.localPosition.y - maxThreshold), this.transform.localPosition.z); + this.transform.localPosition = new Vector3( + this.transform.localPosition.x, + localStartingPoint.y + Mathf.Abs(robotArmRoot.localPosition.y - maxThreshold), + this.transform.localPosition.z + ); } - this.transform.GetChild(0).position = new Vector3(this.transform.GetChild(0).position.x, robotArmRoot.position.y, this.transform.GetChild(0).position.z); + this.transform.GetChild(0).position = new Vector3( + this.transform.GetChild(0).position.x, + robotArmRoot.position.y, + this.transform.GetChild(0).position.z + ); } } diff --git a/unity/Assets/Scripts/RobotArmTest/Align_to_Joint_Normal.cs b/unity/Assets/Scripts/RobotArmTest/Align_to_Joint_Normal.cs index 302a31cf24..1581969b15 100644 --- a/unity/Assets/Scripts/RobotArmTest/Align_to_Joint_Normal.cs +++ b/unity/Assets/Scripts/RobotArmTest/Align_to_Joint_Normal.cs @@ -9,7 +9,8 @@ public class Align_to_Joint_Normal : MonoBehaviour { public bool isMidJointAngler; Vector3 joint1; Vector3 joint2; - Vector3 jointNormal, jointTangent; + Vector3 jointNormal, + jointTangent; Transform positionAlignedJoint; void Update() { @@ -27,4 +28,4 @@ void Update() { transform.LookAt(positionAlignedJoint, jointTangent); } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/RobotArmTest/FK_IK_Solver.cs b/unity/Assets/Scripts/RobotArmTest/FK_IK_Solver.cs index c7fdf6e3a0..4a7cf5950c 100644 --- a/unity/Assets/Scripts/RobotArmTest/FK_IK_Solver.cs +++ b/unity/Assets/Scripts/RobotArmTest/FK_IK_Solver.cs @@ -4,15 +4,42 @@ public class FK_IK_Solver : MonoBehaviour { public bool isIKDriven; - public Transform armRoot, armShoulder, armElbow, armWrist, armHand; - public float bone1Length, bone2Length, bone3Length; - public Transform FKRootTarget, FKShoulderTarget, FKElbowTarget, FKWristTarget; - public Transform IKTarget, IKPole; + public Transform armRoot, + armShoulder, + armElbow, + armWrist, + armHand; + public float bone1Length, + bone2Length, + bone3Length; + public Transform FKRootTarget, + FKShoulderTarget, + FKElbowTarget, + FKWristTarget; + public Transform IKTarget, + IKPole; Transform IKHint; + // public Transform centerTest, hintProjectionTest; // public Transform bone1Extents, bone3Extents; - float p1x, p1y, p1z, p2x, p2y, p2z, p3x, p3y, p3z, overlapA, overlapB, overlapC, overlapD, overlapParameter, overlapRadius; - Vector3 overlapCenter, hintProjection, elbowPosition; + float p1x, + p1y, + p1z, + p2x, + p2y, + p2z, + p3x, + p3y, + p3z, + overlapA, + overlapB, + overlapC, + overlapD, + overlapParameter, + overlapRadius; + Vector3 overlapCenter, + hintProjection, + elbowPosition; // this must be Awake vs Start since when the Arm is activated, Start() will not have been called void Awake() { @@ -32,12 +59,15 @@ void Update() { public void ManipulateArm() { // Check if arm is driven by IK or FK if (isIKDriven == true) { - // Adjust pole position + // Adjust pole position IKPole.parent.position = IKTarget.position; IKPole.parent.forward = IKTarget.position - armShoulder.position; // Check if manipulator location is reachable by arm, with 1e-5 bias towards hyperextension when comparing values, to account for rounding errors - if ((IKTarget.position - armShoulder.position).sqrMagnitude < Mathf.Pow(bone2Length + bone3Length - 1e-5f, 2)) { + if ( + (IKTarget.position - armShoulder.position).sqrMagnitude + < Mathf.Pow(bone2Length + bone3Length - 1e-5f, 2) + ) { // Define variables to optimize logic p1x = armShoulder.position.x; p1y = armShoulder.position.y; @@ -53,19 +83,54 @@ public void ManipulateArm() { overlapA = 2 * p2x - 2 * p1x; overlapB = 2 * p2y - 2 * p1y; overlapC = 2 * p2z - 2 * p1z; - overlapD = Mathf.Pow(bone2Length, 2) - Mathf.Pow(bone3Length, 2) - Mathf.Pow(p1x, 2) - Mathf.Pow(p1y, 2) - Mathf.Pow(p1z, 2) + Mathf.Pow(p2x, 2) + Mathf.Pow(p2y, 2) + Mathf.Pow(p2z, 2); + overlapD = + Mathf.Pow(bone2Length, 2) + - Mathf.Pow(bone3Length, 2) + - Mathf.Pow(p1x, 2) + - Mathf.Pow(p1y, 2) + - Mathf.Pow(p1z, 2) + + Mathf.Pow(p2x, 2) + + Mathf.Pow(p2y, 2) + + Mathf.Pow(p2z, 2); // Find center of ring of overlap by projecting shoulder position onto overlap-plane, since the center will always be on the direct line between shoulder and wrist, which has the same direction vector as the overlap-plane normal - overlapParameter = FindParameter(p1x, p1y, p1z, overlapA, overlapB, overlapC, overlapD); - overlapCenter = new Vector3(p1x + overlapA * overlapParameter, p1y + overlapB * overlapParameter, p1z + overlapC * overlapParameter); + overlapParameter = FindParameter( + p1x, + p1y, + p1z, + overlapA, + overlapB, + overlapC, + overlapD + ); + overlapCenter = new Vector3( + p1x + overlapA * overlapParameter, + p1y + overlapB * overlapParameter, + p1z + overlapC * overlapParameter + ); // Find radius of ring of overlap via Pythagorean Theorem using shoulder-to-elbow bone length as hypotenuse, and shoulder-to-overlap-center distance as adjacent - overlapRadius = Mathf.Sqrt(Mathf.Pow(bone2Length, 2) - (overlapCenter - armShoulder.position).sqrMagnitude); + overlapRadius = Mathf.Sqrt( + Mathf.Pow(bone2Length, 2) - (overlapCenter - armShoulder.position).sqrMagnitude + ); // Find elbow position by projecting IK_Hint position onto overlap-plane, and then moving the ring of overlap's center-point in the ring-center-to-projected-IK_Hint direction vector by a magnitude of the ring's radius - overlapParameter = FindParameter(p3x, p3y, p3z, overlapA, overlapB, overlapC, overlapD); - hintProjection = new Vector3(p3x + overlapA * overlapParameter, p3y + overlapB * overlapParameter, p3z + overlapC * overlapParameter); - elbowPosition = overlapCenter + overlapRadius * (hintProjection - overlapCenter).normalized; + overlapParameter = FindParameter( + p3x, + p3y, + p3z, + overlapA, + overlapB, + overlapC, + overlapD + ); + hintProjection = new Vector3( + p3x + overlapA * overlapParameter, + p3y + overlapB * overlapParameter, + p3z + overlapC * overlapParameter + ); + elbowPosition = + overlapCenter + overlapRadius * (hintProjection - overlapCenter).normalized; // Move joint transforms to calculated positions armElbow.position = elbowPosition; @@ -88,7 +153,7 @@ public void ManipulateArm() { armWrist.rotation = FKWristTarget.rotation; } - // Align individual arm components to their correct joint-angles + // Align individual arm components to their correct joint-angles AlignToJointNormal(armRoot.GetChild(1), armRoot, armShoulder, armElbow, false); AlignToJointNormal(armShoulder.GetChild(0), armRoot, armShoulder, armElbow, true); AlignToJointNormal(armShoulder.GetChild(1), armShoulder, armElbow, armWrist, false); @@ -98,11 +163,19 @@ public void ManipulateArm() { } float FindParameter(float p0x, float p0y, float p0z, float a, float b, float c, float d) { - float parameter = (d - a * p0x - b * p0y - c * p0z) / (Mathf.Pow(a, 2) + Mathf.Pow(b, 2) + Mathf.Pow(c, 2)); + float parameter = + (d - a * p0x - b * p0y - c * p0z) + / (Mathf.Pow(a, 2) + Mathf.Pow(b, 2) + Mathf.Pow(c, 2)); return parameter; } - void AlignToJointNormal(Transform armComponent, Transform root, Transform mid, Transform tip, bool isMidJointAngled) { + void AlignToJointNormal( + Transform armComponent, + Transform root, + Transform mid, + Transform tip, + bool isMidJointAngled + ) { Vector3 bone1 = mid.position - root.position; Vector3 bone2 = tip.position - mid.position; Vector3 jointNormal = Vector3.Cross(bone1, bone2); @@ -120,4 +193,4 @@ void AlignToJointNormal(Transform armComponent, Transform root, Transform mid, T armComponent.LookAt(positionAlignedJoint, jointTangent); } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/RobotArmTest/Manipulator_Clamp.cs b/unity/Assets/Scripts/RobotArmTest/Manipulator_Clamp.cs index 5ccf7962a5..daa07e3475 100644 --- a/unity/Assets/Scripts/RobotArmTest/Manipulator_Clamp.cs +++ b/unity/Assets/Scripts/RobotArmTest/Manipulator_Clamp.cs @@ -28,7 +28,6 @@ void Start() { shoulderJoint = transform; } } - } void Update() { @@ -42,7 +41,9 @@ void Update() { // Debug.Log("Z from " + rootJoint.gameObject.name + " to shoulder: " + shoulderJoint.gameObject.name + ": " + rootToShoulder); if (rootToWrist.z - 0.01f <= rootToShoulder.z) { Debug.Log("Wrist is behind shoulder!"); - transform.position += rootJoint.TransformDirection(Vector3.forward * (rootToShoulder.z - rootToWrist.z + 0.01f)); + transform.position += rootJoint.TransformDirection( + Vector3.forward * (rootToShoulder.z - rootToWrist.z + 0.01f) + ); } rootToWrist = rootJoint.InverseTransformPoint(transform.position); @@ -52,7 +53,9 @@ void Update() { // Debug.Log(shoulderToWrist.magnitude + " vs " + shoulderJoint.InverseTransformPoint(transform.position).magnitude); if (shoulderToWrist.sqrMagnitude >= Mathf.Pow(0.6335f, 2) && shoulderToWrist.z > 0) { // Debug.Log("Arm is overreaching!"); - transform.position += rootJoint.TransformDirection((shoulderToWrist.normalized * 0.6325f) - shoulderToWrist); + transform.position += rootJoint.TransformDirection( + (shoulderToWrist.normalized * 0.6325f) - shoulderToWrist + ); } } diff --git a/unity/Assets/Scripts/RobotArmTest/Stretch_Arm_Solver.cs b/unity/Assets/Scripts/RobotArmTest/Stretch_Arm_Solver.cs index b72cc96056..415f5a35ee 100644 --- a/unity/Assets/Scripts/RobotArmTest/Stretch_Arm_Solver.cs +++ b/unity/Assets/Scripts/RobotArmTest/Stretch_Arm_Solver.cs @@ -3,16 +3,27 @@ using UnityEngine; public class Stretch_Arm_Solver : MonoBehaviour { - public Transform armRoot, armTarget; - Transform arm1, arm2, arm3, arm4, arm5, wrist1; - float liftInitialLocalHeightOffset = 0f, armHeight, armExtensionLength; - private float lowerArmHeightLimit = -0.056f, upperArmHeightLimit = 1.045f, backArmExtensionLimit = 0f, frontArmExtensionLimit = 0.516f; + public Transform armRoot, + armTarget; + Transform arm1, + arm2, + arm3, + arm4, + arm5, + wrist1; + float liftInitialLocalHeightOffset = 0f, + armHeight, + armExtensionLength; + private float lowerArmHeightLimit = -0.056f, + upperArmHeightLimit = 1.045f, + backArmExtensionLimit = 0f, + frontArmExtensionLimit = 0.516f; - #if UNITY_EDITOR - void Update() { - ManipulateStretchArm(); - } - #endif +#if UNITY_EDITOR + void Update() { + ManipulateStretchArm(); + } +#endif public void ManipulateStretchArm() { arm1 = armRoot.GetChild(0); @@ -23,21 +34,33 @@ public void ManipulateStretchArm() { wrist1 = arm5.GetChild(0); // Set height from target input, checking for overextension - armHeight = Mathf.Clamp(armTarget.localPosition.y, lowerArmHeightLimit, upperArmHeightLimit); + armHeight = Mathf.Clamp( + armTarget.localPosition.y, + lowerArmHeightLimit, + upperArmHeightLimit + ); // Set arm extension from target input, checking for overextension - armExtensionLength = Mathf.Clamp(armTarget.localPosition.z, backArmExtensionLimit, frontArmExtensionLimit); + armExtensionLength = Mathf.Clamp( + armTarget.localPosition.z, + backArmExtensionLimit, + frontArmExtensionLimit + ); // Move arm base height - armRoot.localPosition = new Vector3(armRoot.localPosition.x, armHeight + liftInitialLocalHeightOffset, armRoot.localPosition.z); + armRoot.localPosition = new Vector3( + armRoot.localPosition.x, + armHeight + liftInitialLocalHeightOffset, + armRoot.localPosition.z + ); // Extend each part of arm by one-quarter of extension length, in local z-direction - arm2.localPosition = new Vector3 (0, 0, armExtensionLength / 4 + 0.01300028f); - arm3.localPosition = new Vector3 (0, 0, armExtensionLength / 4 + 0.01300049f); - arm4.localPosition = new Vector3 (0, 0, armExtensionLength / 4 + 0.01300025f); - arm5.localPosition = new Vector3 (0, 0, armExtensionLength / 4 + 0.0117463f); + arm2.localPosition = new Vector3(0, 0, armExtensionLength / 4 + 0.01300028f); + arm3.localPosition = new Vector3(0, 0, armExtensionLength / 4 + 0.01300049f); + arm4.localPosition = new Vector3(0, 0, armExtensionLength / 4 + 0.01300025f); + arm5.localPosition = new Vector3(0, 0, armExtensionLength / 4 + 0.0117463f); // Adjust rotation - wrist1.eulerAngles = new Vector3 (0, armTarget.eulerAngles.y, 0); + wrist1.eulerAngles = new Vector3(0, armTarget.eulerAngles.y, 0); } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/RoomProperties.cs b/unity/Assets/Scripts/RoomProperties.cs index 614ce39a52..fb7e0d5843 100644 --- a/unity/Assets/Scripts/RoomProperties.cs +++ b/unity/Assets/Scripts/RoomProperties.cs @@ -6,13 +6,10 @@ public class RoomProperties : MonoBehaviour { // TODO make an enum once we have a final set of room types //public enum RoomType {} public string RoomType; - // Start is called before the first frame update - void Start() { - } + // Start is called before the first frame update + void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } } diff --git a/unity/Assets/Scripts/RuntimePrefab.cs b/unity/Assets/Scripts/RuntimePrefab.cs index c6f25fb9ac..5155bd59e5 100644 --- a/unity/Assets/Scripts/RuntimePrefab.cs +++ b/unity/Assets/Scripts/RuntimePrefab.cs @@ -1,20 +1,17 @@ using System; -using System.IO; +using System.Collections; using System.Collections.Generic; +using System.IO; using System.Reflection; -using System.Collections; +using EasyButtons; using UnityEngine; - - #if UNITY_EDITOR using EasyButtons.Editor; using UnityEditor.SceneManagement; #endif -using EasyButtons; [ExecuteInEditMode] public class RuntimePrefab : MonoBehaviour { - // Textures for runtime objects are stored on disk // so that they can easily be used across builds, // and do not make the build size massive. Here, @@ -46,7 +43,7 @@ Texture2D SwapChannelsRGBAtoRRRB(Texture2D originalTexture) { } private void reloadtextures() { - GameObject mesh = transform.Find("mesh").gameObject; + GameObject mesh = transform.Find("mesh").gameObject; // load the texture from disk if (!string.IsNullOrEmpty(albedoTexturePath)) { if (sharedMaterial.mainTexture == null) { @@ -77,7 +74,8 @@ private void reloadtextures() { } if (!string.IsNullOrEmpty(emissionTexturePath)) { - sharedMaterial.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive; + sharedMaterial.globalIlluminationFlags = + MaterialGlobalIlluminationFlags.RealtimeEmissive; sharedMaterial.EnableKeyword("_EMISSION"); byte[] imageBytes = File.ReadAllBytes(emissionTexturePath); Texture2D tex = new Texture2D(2, 2); @@ -88,17 +86,14 @@ private void reloadtextures() { } public void Awake() { - - reloadtextures(); + reloadtextures(); } - #if UNITY_EDITOR +#if UNITY_EDITOR [Button(Expanded = true)] - public void RealoadTextures() { + public void RealoadTextures() { reloadtextures(); } - #endif - - -} \ No newline at end of file +#endif +} diff --git a/unity/Assets/Scripts/SceneManager.cs b/unity/Assets/Scripts/SceneManager.cs index 3a87637b5c..ea4ccab543 100644 --- a/unity/Assets/Scripts/SceneManager.cs +++ b/unity/Assets/Scripts/SceneManager.cs @@ -1,14 +1,12 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; +using System.Collections; using System.Collections.Generic; using System.Reflection; - - +using UnityEngine; +using UnityStandardAssets.Characters.FirstPerson; #if UNITY_EDITOR using UnityEditor; #endif -using System.Collections; -using UnityStandardAssets.Characters.FirstPerson; [ExecuteInEditMode] public class SceneManager : MonoBehaviour { @@ -65,7 +63,6 @@ void OnEnable() { } #endif this.AnimationMode = SceneAnimationMode.Instant; - } // generates a object ID for a sim object @@ -91,7 +88,6 @@ public void GatherSimObjsInScene() { #if UNITY_EDITOR // returns an array of required types NOT found in scene public SimObjType[] CheckSceneForRequiredTypes() { - List typesToCheck = null; switch (LocalSceneType) { case SceneType.Kitchen: @@ -137,11 +133,20 @@ public void AutoStructureNavigation() { GameObjectUtility.SetNavMeshArea(t.gameObject, PlacementManager.NavmeshFloorArea); } else { // if it's not already set to none (ie sittable objects) set it to 'shelves' - if (GameObjectUtility.GetNavMeshArea(t.gameObject) != PlacementManager.NavemeshNoneArea) { - GameObjectUtility.SetNavMeshArea(t.gameObject, PlacementManager.NavmeshShelfArea); + if ( + GameObjectUtility.GetNavMeshArea(t.gameObject) + != PlacementManager.NavemeshNoneArea + ) { + GameObjectUtility.SetNavMeshArea( + t.gameObject, + PlacementManager.NavmeshShelfArea + ); } } - GameObjectUtility.SetStaticEditorFlags(t.gameObject, StaticEditorFlags.BatchingStatic | StaticEditorFlags.NavigationStatic); + GameObjectUtility.SetStaticEditorFlags( + t.gameObject, + StaticEditorFlags.BatchingStatic | StaticEditorFlags.NavigationStatic + ); } } @@ -158,16 +163,20 @@ public void GatherObjectsUnderParents() { } } - GameObject[] rootObjects = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects(); + GameObject[] rootObjects = UnityEngine + .SceneManagement.SceneManager.GetActiveScene() + .GetRootGameObjects(); foreach (GameObject rootObject in rootObjects) { // make sure it's not a parent - if (rootObject != gameObject + if ( + rootObject != gameObject && rootObject.transform != LightingParent && rootObject.transform != ObjectsParent && rootObject.transform != StructureParent && rootObject.transform != TargetsParent && rootObject.transform != ControlsParent - && rootObject.name != FPSControllerPrefab.name) { + && rootObject.name != FPSControllerPrefab.name + ) { rootObject.transform.parent = StructureParent; EditorUtility.SetDirty(rootObject); } @@ -206,11 +215,14 @@ public void ReplaceGenerics() { foreach (SimObj platonic in PlatonicPrefabs) { if (generic.Type == platonic.Type) { // make sure one isn't a prefab of the other - GameObject prefab = PrefabUtility.GetCorrespondingObjectFromSource(generic.gameObject) as GameObject; + GameObject prefab = + PrefabUtility.GetCorrespondingObjectFromSource(generic.gameObject) + as GameObject; if (prefab == null || prefab != platonic.gameObject) { Debug.Log("Replacing " + generic.name + " with " + platonic.name); // as long as it's not a prefab, swap it out with the prefab - GameObject newSimObj = PrefabUtility.InstantiatePrefab(platonic.gameObject) as GameObject; + GameObject newSimObj = + PrefabUtility.InstantiatePrefab(platonic.gameObject) as GameObject; newSimObj.transform.position = generic.transform.position; newSimObj.transform.rotation = generic.transform.rotation; newSimObj.transform.parent = generic.transform.parent; @@ -227,19 +239,23 @@ public void ReplaceGenerics() { public void SetUpLighting() { // thanks for not exposing these props, Unity :P // this may break in later versions - var getLightmapSettingsMethod = typeof(LightmapEditorSettings).GetMethod("GetLightmapSettings", BindingFlags.Static | BindingFlags.NonPublic); + var getLightmapSettingsMethod = typeof(LightmapEditorSettings).GetMethod( + "GetLightmapSettings", + BindingFlags.Static | BindingFlags.NonPublic + ); var lightmapSettings = getLightmapSettingsMethod.Invoke(null, null) as Object; SerializedObject settingsObject = new SerializedObject(lightmapSettings); /*var iter = settingsObject.GetIterator(); - do { - Debug.Log("member: " + iter.name); - } while (iter.Next(true));*/ + do { + Debug.Log("member: " + iter.name); + } while (iter.Next(true));*/ settingsObject.FindProperty("m_GISettings.m_EnableBakedLightmaps").boolValue = false; settingsObject.FindProperty("m_GISettings.m_EnableRealtimeLightmaps").boolValue = false; settingsObject.FindProperty("m_LightmapEditorSettings.m_FinalGather").boolValue = false; - settingsObject.FindProperty("m_LightmapEditorSettings.m_LightmapsBakeMode").boolValue = false; + settingsObject.FindProperty("m_LightmapEditorSettings.m_LightmapsBakeMode").boolValue = + false; settingsObject.ApplyModifiedProperties(); } @@ -247,12 +263,14 @@ public void SetUpLighting() { public void SetUpNavigation() { // thanks for not exposing these props, Unity :P // this may break in later versions - SerializedObject settingsObject = new SerializedObject(UnityEditor.AI.NavMeshBuilder.navMeshSettingsObject); + SerializedObject settingsObject = new SerializedObject( + UnityEditor.AI.NavMeshBuilder.navMeshSettingsObject + ); /*var iter = settingsObject.GetIterator(); - do { - Debug.Log("member: " + iter.displayName); - } while (iter.Next(true));*/ + do { + Debug.Log("member: " + iter.displayName); + } while (iter.Next(true));*/ settingsObject.FindProperty("m_BuildSettings.agentRadius").floatValue = 0.05f; settingsObject.FindProperty("m_BuildSettings.agentHeight").floatValue = .25f; @@ -279,7 +297,8 @@ public void SetUpFPSController() { fpsObj.name = FPSControllerPrefab.name; } else { // re-attach to prefab - GameObject prefabParent = PrefabUtility.GetCorrespondingObjectFromSource(fpsObj) as GameObject; + GameObject prefabParent = + PrefabUtility.GetCorrespondingObjectFromSource(fpsObj) as GameObject; if (prefabParent == null) { // if it's not attached to a prefab, delete and start over Vector3 pos = fpsObj.transform.position; @@ -310,7 +329,8 @@ public void SetUpFPSController() { rb.isKinematic = true; rb.interpolation = RigidbodyInterpolation.None; rb.collisionDetectionMode = CollisionDetectionMode.Discrete; - rb.constraints = RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotationY; + rb.constraints = + RigidbodyConstraints.FreezePositionY | RigidbodyConstraints.FreezeRotationY; cam.fieldOfView = 60f; cam.farClipPlane = 1000f; diff --git a/unity/Assets/Scripts/ScreenShotFromCamera.cs b/unity/Assets/Scripts/ScreenShotFromCamera.cs index 84c4301a8a..99f009cf7f 100644 --- a/unity/Assets/Scripts/ScreenShotFromCamera.cs +++ b/unity/Assets/Scripts/ScreenShotFromCamera.cs @@ -1,5 +1,5 @@ -using UnityEngine; -using System.Collections; +using System.Collections; +using UnityEngine; public class ScreenShotFromCamera : MonoBehaviour { public int resWidth = 3840; @@ -8,10 +8,13 @@ public class ScreenShotFromCamera : MonoBehaviour { private bool takeHiResShot = false; public static string ScreenShotName(int width, int height) { - return string.Format("{0}/screenshots/screen_{1}x{2}_{3}.png", - Application.dataPath, - width, height, - System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss")); + return string.Format( + "{0}/screenshots/screen_{1}x{2}_{3}.png", + Application.dataPath, + width, + height, + System.DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ); } public void TakeHiResShot() { diff --git a/unity/Assets/Scripts/Screenshot360.cs b/unity/Assets/Scripts/Screenshot360.cs index aff562688c..8090785b7e 100644 --- a/unity/Assets/Scripts/Screenshot360.cs +++ b/unity/Assets/Scripts/Screenshot360.cs @@ -2,7 +2,6 @@ using System.IO; using UnityEngine; using UnityEngine.SceneManagement; - #if UNITY_EDITOR using UnityEditor; #endif @@ -22,10 +21,25 @@ private static void Generate360Screenshot() { if (bytes != null) { while (!newFileName) { - if (File.Exists("Assets/360Photos/360Render_" + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + "_" + currentCount + (saveAsJPEG ? ".jpeg" : ".png"))) { + if ( + File.Exists( + "Assets/360Photos/360Render_" + + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + + "_" + + currentCount + + (saveAsJPEG ? ".jpeg" : ".png") + ) + ) { currentCount++; } else { - path = Path.Combine("Assets/360Photos", "360Render_" + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + "_" + currentCount + (saveAsJPEG ? ".jpeg" : ".png")); + path = Path.Combine( + "Assets/360Photos", + "360Render_" + + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + + "_" + + currentCount + + (saveAsJPEG ? ".jpeg" : ".png") + ); File.WriteAllBytes(path, bytes); Debug.Log("360 render saved to " + path); newFileName = true; diff --git a/unity/Assets/Scripts/SerializeMesh.cs b/unity/Assets/Scripts/SerializeMesh.cs index f3b119a312..8f0e53c8ad 100644 --- a/unity/Assets/Scripts/SerializeMesh.cs +++ b/unity/Assets/Scripts/SerializeMesh.cs @@ -1,15 +1,13 @@ using System; +using System.IO; using System.Linq; +using Newtonsoft.Json.Linq; +using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif -using UnityEngine; -using Newtonsoft.Json.Linq; -using System.IO; - -namespace Thor.Utils -{ +namespace Thor.Utils { [System.Serializable] public class SerializableMesh { // [SerializeField] public Vector2[] uv; @@ -23,44 +21,69 @@ public class SerializableMesh { public Vector3[] normals; public int[] triangles; } - + [ExecuteInEditMode] [RequireComponent(typeof(MeshFilter))] - public class SerializeMesh : MonoBehaviour - { + public class SerializeMesh : MonoBehaviour { // [HideInInspector] [SerializeField] Vector2[] uv; // [HideInInspector] [SerializeField] Vector3[] verticies; // [HideInInspector] [SerializeField] Vector3[] normals; // [HideInInspector] [SerializeField] int[] triangles; - [SerializeField] public SerializableMesh model; - [SerializeField] SerializableMesh[] collisionMeshes; - [HideInInspector] [SerializeField] bool serialized = false; - + [SerializeField] + public SerializableMesh model; + + [SerializeField] + SerializableMesh[] collisionMeshes; + + [HideInInspector] + [SerializeField] + bool serialized = false; private static int materialCount = 0; - private static string getAssetRelativePath(string absPath) { - return string.Join("/", absPath.Split('/').SkipWhile(x=> x != "Assets")); + private static string getAssetRelativePath(string absPath) { + return string.Join("/", absPath.Split('/').SkipWhile(x => x != "Assets")); } public static string MeshToObj(string name, Mesh mesh) { var objString = $"o {name}"; - var verts = string.Join("\n", mesh.vertices.Select(v => $"v {-v.x:F6} {v.y:F6} {v.z:F6}")); + var verts = string.Join( + "\n", + mesh.vertices.Select(v => $"v {-v.x:F6} {v.y:F6} {v.z:F6}") + ); var uvs = string.Join("\n", mesh.uv.Select(v => $"vt {v.x:F6} {v.y:F6}")); - var normals = string.Join("\n", mesh.normals.Select(v => $"vn {-v.x:F6} {v.y:F6} {v.z:F6}")); + var normals = string.Join( + "\n", + mesh.normals.Select(v => $"vn {-v.x:F6} {v.y:F6} {v.z:F6}") + ); var triangles = mesh.triangles.Reverse().ToArray(); - var faces = string.Join("\n", Enumerable.Range(0, mesh.triangles.Length / 3) - .Select(i => - ( i0: triangles[i * 3]+1, i1: triangles[i * 3 + 1]+1, i2: triangles[i * 3 + 2]+1)) - .Select(indx => $"f {indx.i0}/{indx.i0}/{indx.i0} {indx.i1}/{indx.i1}/{indx.i1} {indx.i2}/{indx.i2}/{indx.i2}") - //.Select(indx => $"f {indx.i2}/{indx.i2}/{indx.i2} {indx.i1}/{indx.i1}/{indx.i1} {indx.i0}/{indx.i0}/{indx.i0}") + var faces = string.Join( + "\n", + Enumerable + .Range(0, mesh.triangles.Length / 3) + .Select(i => + ( + i0: triangles[i * 3] + 1, + i1: triangles[i * 3 + 1] + 1, + i2: triangles[i * 3 + 2] + 1 + ) + ) + .Select(indx => + $"f {indx.i0}/{indx.i0}/{indx.i0} {indx.i1}/{indx.i1}/{indx.i1} {indx.i2}/{indx.i2}/{indx.i2}" + ) + //.Select(indx => $"f {indx.i2}/{indx.i2}/{indx.i2} {indx.i1}/{indx.i1}/{indx.i1} {indx.i0}/{indx.i0}/{indx.i0}") ); return $"{objString}\n{verts}\n{uvs}\n{normals}\ns 1\n{faces}"; } - private static string SaveAsObj( Mesh mesh, string assetId, string outPath, string prefix = "", bool overwite = true) { - + private static string SaveAsObj( + Mesh mesh, + string assetId, + string outPath, + string prefix = "", + bool overwite = true + ) { var obj = MeshToObj(assetId, mesh); if (!Directory.Exists(outPath)) { @@ -70,22 +93,27 @@ private static string SaveAsObj( Mesh mesh, string assetId, string outPath, stri // var f = File.Create($"{outModelsBasePath}/{assetId}.obj"); var sep = prefix == "" ? "" : "_"; var fileObj = $"{outPath}/{prefix}_{assetId}.obj"; - + if (!File.Exists(fileObj) || overwite) { Debug.Log($"Writing obj to `{fileObj}`"); File.WriteAllText(fileObj, obj); - } - else { + } else { Debug.Log($"File `{fileObj}` exists, skipping"); - } return fileObj; } #if UNITY_EDITOR - public static void SaveMeshesAsObjAndReplaceReferences(GameObject go, string assetId, string modelsOutPath, string collidersOutPath, bool overwrite = true, GameObject sourceGo =null) { + public static void SaveMeshesAsObjAndReplaceReferences( + GameObject go, + string assetId, + string modelsOutPath, + string collidersOutPath, + bool overwrite = true, + GameObject sourceGo = null + ) { var meshGo = go.transform.Find("mesh"); var useOriginalAssetGeo = sourceGo != null; @@ -96,67 +124,84 @@ public static void SaveMeshesAsObjAndReplaceReferences(GameObject go, string ass var collidersSourceMeshes = colliders.Select(c => c.sharedMesh); if (useOriginalAssetGeo) { - - mainMesh = sourceGo.transform.Find("mesh").GetComponentInChildren().sharedMesh; - collidersSourceMeshes = go.transform.Find("Colliders").GetComponentsInChildren().Select(mc => mc.sharedMesh); + mainMesh = sourceGo + .transform.Find("mesh") + .GetComponentInChildren() + .sharedMesh; + collidersSourceMeshes = go + .transform.Find("Colliders") + .GetComponentsInChildren() + .Select(mc => mc.sharedMesh); } var objPath = SaveAsObj(mainMesh, assetId, modelsOutPath, overwite: overwrite); - - var colliderObjPaths = collidersSourceMeshes.Select((m, i) => SaveAsObj(m, assetId, collidersOutPath, prefix: $"col_{i}", overwite: overwrite)).ToArray(); - + var colliderObjPaths = collidersSourceMeshes + .Select( + (m, i) => + SaveAsObj( + m, + assetId, + collidersOutPath, + prefix: $"col_{i}", + overwite: overwrite + ) + ) + .ToArray(); + AssetDatabase.Refresh(); - + // is this necessary? if (mainMesh.indexFormat == UnityEngine.Rendering.IndexFormat.UInt32) { var mi = AssetImporter.GetAtPath(getAssetRelativePath(objPath)) as ModelImporter; mi.indexFormat = ModelImporterIndexFormat.UInt32; } - - var mesh = (Mesh)AssetDatabase.LoadAssetAtPath(getAssetRelativePath(objPath),typeof(Mesh)); + var mesh = (Mesh) + AssetDatabase.LoadAssetAtPath(getAssetRelativePath(objPath), typeof(Mesh)); mf.sharedMesh = mesh; - var collisionMeshes = colliderObjPaths.Select(path => (Mesh)AssetDatabase.LoadAssetAtPath(getAssetRelativePath(path), typeof(Mesh))).ToArray(); + var collisionMeshes = colliderObjPaths + .Select(path => + (Mesh)AssetDatabase.LoadAssetAtPath(getAssetRelativePath(path), typeof(Mesh)) + ) + .ToArray(); for (var i = 0; i < colliders.Length; i++) { - // is this necessary? if (colliders[i].sharedMesh.indexFormat == UnityEngine.Rendering.IndexFormat.UInt32) { - var mi = AssetImporter.GetAtPath(getAssetRelativePath(colliderObjPaths[i])) as ModelImporter; + var mi = + AssetImporter.GetAtPath(getAssetRelativePath(colliderObjPaths[i])) + as ModelImporter; mi.indexFormat = ModelImporterIndexFormat.UInt32; } // collisionMeshes[i].RecalculateNormals(); colliders[i].sharedMesh = collisionMeshes[i]; } - colliders = go.transform.Find("TriggerColliders").GetComponentsInChildren(); + colliders = go + .transform.Find("TriggerColliders") + .GetComponentsInChildren(); for (var i = 0; i < colliders.Length; i++) { - colliders[i].sharedMesh = collisionMeshes[i]; + colliders[i].sharedMesh = collisionMeshes[i]; } - } #endif - - void Awake() - { + + void Awake() { Debug.Log("--- Awake called on object " + transform.parent.gameObject.name); - if (serialized) - { + if (serialized) { GetComponent().sharedMesh = Rebuild(); } // else { // this.model = new SerializableMesh(); // } } - - void Start() - { - if (serialized) - { + + void Start() { + if (serialized) { return; } - + Serialize(); } @@ -177,12 +222,11 @@ private Mesh deSerializeMesh(SerializableMesh serializedMesh) { mesh.uv = serializedMesh.uv; return mesh; } - - public void Serialize() - { + + public void Serialize() { Debug.Log("--- Serialize called " + transform.parent.gameObject.name); var mesh = GetComponent().mesh; - + // model.uv = mesh.uv; // model.verticies = mesh.vertices; // model.triangles = mesh.triangles; @@ -190,9 +234,11 @@ public void Serialize() model = serializeMesh(mesh); - var colliders = transform.parent.Find("Colliders").GetComponentsInChildren(); + var colliders = transform + .parent.Find("Colliders") + .GetComponentsInChildren(); // if (this.collisionMeshes == null || colliders.Length != this.collisionMeshes.Length) { - this.collisionMeshes = new SerializableMesh[colliders.Length]; + this.collisionMeshes = new SerializableMesh[colliders.Length]; // } Debug.Log($"----- Serializing collider meshes {colliders.Length}"); @@ -200,25 +246,23 @@ public void Serialize() var collisionMesh = colliders[i].sharedMesh; this.collisionMeshes[i] = this.serializeMesh(collisionMesh); } - + serialized = true; var matName = transform.parent.gameObject.name; - - // UnityEditor.AssetDatabase.CreateAsset( // GetComponent().sharedMaterial, $"{serializeMaterialsPath}/{matName}.mat" // ); // try { - // UnityEditor.AssetDatabase.CreateAsset( - // GetComponentInChildren().material, $"{serializeMaterialsPath}/{matName}.mat" - // ); + // UnityEditor.AssetDatabase.CreateAsset( + // GetComponentInChildren().material, $"{serializeMaterialsPath}/{matName}.mat" + // ); // } // // There are some restricted material names so if it fails name it with scheme _ // catch (Exception e) { - + // var sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; // matName = $"{sceneName}_{materialCount}"; // UnityEditor.AssetDatabase.CreateAsset( @@ -227,9 +271,8 @@ public void Serialize() // materialCount++; // } } - - public Mesh Rebuild() - { + + public Mesh Rebuild() { Mesh mesh = this.deSerializeMesh(model); // Mesh mesh = new Mesh(); @@ -238,58 +281,55 @@ public Mesh Rebuild() // mesh.normals = model.normals; // mesh.uv = model.uv; - - + + // mesh.RecalculateNormals(); mesh.RecalculateBounds(); - var colliders = transform.parent.Find("Colliders").GetComponentsInChildren(); + var colliders = transform + .parent.Find("Colliders") + .GetComponentsInChildren(); for (var i = 0; i < colliders.Length; i++) { colliders[i].sharedMesh = deSerializeMesh(this.collisionMeshes[i]); } - colliders = transform.parent.Find("TriggerColliders").GetComponentsInChildren(); + colliders = transform + .parent.Find("TriggerColliders") + .GetComponentsInChildren(); for (var i = 0; i < colliders.Length; i++) { colliders[i].sharedMesh = deSerializeMesh(this.collisionMeshes[i]); } - + return mesh; } } #if UNITY_EDITOR [CustomEditor(typeof(SerializeMesh))] - class SerializeMeshEditor : Editor - { + class SerializeMeshEditor : Editor { SerializeMesh obj; - - void OnSceneGUI() - { + + void OnSceneGUI() { obj = (SerializeMesh)target; } - - public override void OnInspectorGUI() - { + + public override void OnInspectorGUI() { base.OnInspectorGUI(); - - if (GUILayout.Button("Rebuild")) - { - if (obj) - { + + if (GUILayout.Button("Rebuild")) { + if (obj) { obj.gameObject.GetComponent().mesh = obj.Rebuild(); } } - - if (GUILayout.Button("Serialize")) - { - if (obj) - { - obj.Serialize(); + + if (GUILayout.Button("Serialize")) { + if (obj) { + obj.Serialize(); } } } } #endif -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/SimObj.cs b/unity/Assets/Scripts/SimObj.cs index 21c4f58ccc..06b2440068 100644 --- a/unity/Assets/Scripts/SimObj.cs +++ b/unity/Assets/Scripts/SimObj.cs @@ -1,18 +1,14 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System; using System.Collections; using System.Collections.Generic; +using UnityEngine; [ExecuteInEditMode] [RequireComponent(typeof(Rigidbody))] public class SimObj : MonoBehaviour, SimpleSimObj { - public string ObjectID { - get { - return objectID; - } - + get { return objectID; } set { // TODO add an ID lock objectID = value; @@ -20,44 +16,67 @@ public string ObjectID { } public bool IsVisible { - get { - return isVisible; - } - - set { - isVisible = value; - } + get { return isVisible; } + set { isVisible = value; } } - public SimObjType Type = SimObjType.Undefined; public SimObjManipType Manipulation = SimObjManipType.Inventory; - public static SimObjType[] OpenableTypes = new SimObjType[] { SimObjType.Fridge, SimObjType.Cabinet, SimObjType.Microwave, SimObjType.LightSwitch, SimObjType.Blinds, SimObjType.Book, SimObjType.Toilet }; - public static SimObjType[] ImmobileTypes = new SimObjType[] { SimObjType.Chair, SimObjType.Toaster, SimObjType.CoffeeMachine, SimObjType.Television, SimObjType.StoveKnob }; - private static Dictionary> OPEN_CLOSE_STATES = new Dictionary>{ - {SimObjType.Microwave, new Dictionary{{"open", 2}, {"close", 1}}}, - {SimObjType.Laptop, new Dictionary{{"open", 2}, {"close", 1}}}, - {SimObjType.Book, new Dictionary{{"open", 1}, {"close", 2}}}, - {SimObjType.Toilet, new Dictionary{{"open", 2}, {"close", 3}}}, - {SimObjType.Sink, new Dictionary{{"open", 2}, {"close", 1}}} + public static SimObjType[] OpenableTypes = new SimObjType[] + { + SimObjType.Fridge, + SimObjType.Cabinet, + SimObjType.Microwave, + SimObjType.LightSwitch, + SimObjType.Blinds, + SimObjType.Book, + SimObjType.Toilet + }; + public static SimObjType[] ImmobileTypes = new SimObjType[] + { + SimObjType.Chair, + SimObjType.Toaster, + SimObjType.CoffeeMachine, + SimObjType.Television, + SimObjType.StoveKnob }; + private static Dictionary> OPEN_CLOSE_STATES = + new Dictionary> + { + { + SimObjType.Microwave, + new Dictionary { { "open", 2 }, { "close", 1 } } + }, + { + SimObjType.Laptop, + new Dictionary { { "open", 2 }, { "close", 1 } } + }, + { + SimObjType.Book, + new Dictionary { { "open", 1 }, { "close", 2 } } + }, + { + SimObjType.Toilet, + new Dictionary { { "open", 2 }, { "close", 3 } } + }, + { + SimObjType.Sink, + new Dictionary { { "open", 2 }, { "close", 1 } } + } + }; public bool UseCustomBounds = false; public bool isVisible = false; public bool UseWidthSearch = false; public bool hasCollision = false; public Transform BoundsTransform; + // stores the location of the simObj on startup public SimObjType ObjType { - - get { - return Type; - - } + get { return Type; } } public List ReceptacleObjectIds { - get { List objectIds = new List(); foreach (SimObj o in SimUtil.GetItemsFromReceptacle(this.Receptacle)) { @@ -68,40 +87,26 @@ public List ReceptacleObjectIds { } public Transform StartupTransform { - get { - return startupTransform; - } + get { return startupTransform; } } public Animator Animator { - get { - return animator; - } + get { return animator; } } public Receptacle Receptacle { - get { - return receptacle; - } + get { return receptacle; } } public Rearrangeable Rearrangeable { - get { - return rearrangeable; - } + get { return rearrangeable; } } public bool IsReceptacle { - get { - return receptacle != null; - } + get { return receptacle != null; } } public bool IsAnimated { - get { - return animator != null; - } + get { return animator != null; } } public bool IsAnimating { - get { - return isAnimating; - } + get { return isAnimating; } set { #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(this); @@ -136,7 +141,6 @@ public bool Open() { bool res = false; if (OPEN_CLOSE_STATES.ContainsKey(this.Type)) { res = updateAnimState(this.Animator, OPEN_CLOSE_STATES[this.Type]["open"]); - } else if (this.IsAnimated) { res = updateAnimState(this.Animator, true); } @@ -156,14 +160,13 @@ public bool Close() { } public bool VisibleToRaycasts { - get { - return visibleToRaycasts; - } - + get { return visibleToRaycasts; } set { if (colliders == null) { #if UNITY_EDITOR - Debug.LogWarning("Warning: Tried to set colliders enabled before item was initialized in " + name); + Debug.LogWarning( + "Warning: Tried to set colliders enabled before item was initialized in " + name + ); #endif visibleToRaycasts = value; return; @@ -171,35 +174,31 @@ public bool VisibleToRaycasts { if (visibleToRaycasts != value) { visibleToRaycasts = value; - gameObject.layer = (visibleToRaycasts ? SimUtil.RaycastVisibleLayer : SimUtil.RaycastHiddenLayer); + gameObject.layer = ( + visibleToRaycasts ? SimUtil.RaycastVisibleLayer : SimUtil.RaycastHiddenLayer + ); for (int i = 0; i < colliders.Length; i++) { - colliders[i].gameObject.layer = (visibleToRaycasts ? SimUtil.RaycastVisibleLayer : SimUtil.RaycastHiddenLayer); + colliders[i].gameObject.layer = ( + visibleToRaycasts ? SimUtil.RaycastVisibleLayer : SimUtil.RaycastHiddenLayer + ); } } } } public Vector3 CenterPoint { - get { - return centerPoint; - } + get { return centerPoint; } } public Vector3 TopPoint { - get { - return topPoint; - } + get { return topPoint; } } public Vector3 BottomPoint { - get { - return bottomPoint; - } + get { return bottomPoint; } } public Bounds Bounds { - get { - return bounds; - } + get { return bounds; } } public bool VisibleNow = false; @@ -207,9 +206,7 @@ public Bounds Bounds { #if UNITY_EDITOR // used for debugging object visibility public string Error { - get { - return error; - } + get { return error; } } string error = string.Empty; #endif @@ -230,7 +227,6 @@ public string Error { private Transform startupTransform; private Bounds bounds; - // this guy right here caused the giant groceries... should only be an issue with pivots public void ResetScale() { Transform tempParent = transform.parent; @@ -241,9 +237,10 @@ public void ResetScale() { public bool IsPickupable { get { - return !this.IsOpenable && !this.IsReceptacle && !(Array.IndexOf(ImmobileTypes, this.Type) >= 0); + return !this.IsOpenable + && !this.IsReceptacle + && !(Array.IndexOf(ImmobileTypes, this.Type) >= 0); } - } public bool IsOpen { @@ -259,14 +256,10 @@ public bool IsOpen { } public bool IsOpenable { - get { - return Array.IndexOf(OpenableTypes, this.Type) >= 0 && this.IsAnimated; - } - + get { return Array.IndexOf(OpenableTypes, this.Type) >= 0 && this.IsAnimated; } } public void RecalculatePoints() { - // get first renderer in object, use that object's bounds to get center point Renderer r = null; if (!IsReceptacle) { @@ -276,8 +269,14 @@ public void RecalculatePoints() { if (r != null) { centerPoint = r.bounds.center; if (UseWidthSearch) { - topPoint = centerPoint + (Vector3.left * r.bounds.extents.x) + (Vector3.forward * r.bounds.extents.z); - bottomPoint = centerPoint + (Vector3.right * r.bounds.extents.x) + (Vector3.back * r.bounds.extents.z); + topPoint = + centerPoint + + (Vector3.left * r.bounds.extents.x) + + (Vector3.forward * r.bounds.extents.z); + bottomPoint = + centerPoint + + (Vector3.right * r.bounds.extents.x) + + (Vector3.back * r.bounds.extents.z); } else { topPoint = centerPoint + (Vector3.up * r.bounds.extents.y); bottomPoint = centerPoint + (Vector3.down * r.bounds.extents.y); @@ -295,8 +294,14 @@ public void RecalculatePoints() { if (c != null) { centerPoint = c.bounds.center; if (UseWidthSearch) { - topPoint = centerPoint + (Vector3.left * c.bounds.extents.x) + (Vector3.forward * c.bounds.extents.z); - bottomPoint = centerPoint + (Vector3.right * c.bounds.extents.x) + (Vector3.back * c.bounds.extents.z); + topPoint = + centerPoint + + (Vector3.left * c.bounds.extents.x) + + (Vector3.forward * c.bounds.extents.z); + bottomPoint = + centerPoint + + (Vector3.right * c.bounds.extents.x) + + (Vector3.back * c.bounds.extents.z); } else { topPoint = centerPoint + (Vector3.up * c.bounds.extents.y); bottomPoint = centerPoint + (Vector3.down * c.bounds.extents.y); @@ -306,12 +311,12 @@ public void RecalculatePoints() { Debug.Log("Couldn't calculate center point in " + gameObject.name); } } - } void OnCollisionEnter(Collision col) { this.hasCollision = true; } + // we do this to handle the case when an object is moved into by navigation into an object; since we reset the hasCollision flag to false prior // to the moveHand we check if we are leaving a collider and consider that to be a collision as well void OnCollisionExit(Collision col) { @@ -345,14 +350,17 @@ protected virtual void OnEnable() { case SimObjManipType.Static: case SimObjManipType.StaticNoPlacement: - Manipulation = (rearrangeable != null) ? SimObjManipType.Rearrangeable : Manipulation; + Manipulation = + (rearrangeable != null) ? SimObjManipType.Rearrangeable : Manipulation; break; } #if UNITY_EDITOR if (Type == SimObjType.Undefined) { // check our prefab just in case the enum has gotten disconnected - GameObject prefabParent = UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(gameObject) as GameObject; + GameObject prefabParent = + UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(gameObject) + as GameObject; if (prefabParent != null) { SimObj ps = prefabParent.GetComponent(); if (ps != null) { @@ -372,19 +380,36 @@ protected virtual void OnEnable() { switch (Manipulation) { case SimObjManipType.Static: mr.gameObject.isStatic = true; - UnityEditor.GameObjectUtility.SetNavMeshArea(mr.gameObject, PlacementManager.NavmeshShelfArea); - UnityEditor.GameObjectUtility.SetStaticEditorFlags(mr.gameObject, UnityEditor.StaticEditorFlags.NavigationStatic | UnityEditor.StaticEditorFlags.BatchingStatic); + UnityEditor.GameObjectUtility.SetNavMeshArea( + mr.gameObject, + PlacementManager.NavmeshShelfArea + ); + UnityEditor.GameObjectUtility.SetStaticEditorFlags( + mr.gameObject, + UnityEditor.StaticEditorFlags.NavigationStatic + | UnityEditor.StaticEditorFlags.BatchingStatic + ); break; case SimObjManipType.StaticNoPlacement: mr.gameObject.isStatic = true; - UnityEditor.GameObjectUtility.SetNavMeshArea(mr.gameObject, PlacementManager.NavemeshNoneArea); - UnityEditor.GameObjectUtility.SetStaticEditorFlags(mr.gameObject, UnityEditor.StaticEditorFlags.NavigationStatic | UnityEditor.StaticEditorFlags.BatchingStatic); + UnityEditor.GameObjectUtility.SetNavMeshArea( + mr.gameObject, + PlacementManager.NavemeshNoneArea + ); + UnityEditor.GameObjectUtility.SetStaticEditorFlags( + mr.gameObject, + UnityEditor.StaticEditorFlags.NavigationStatic + | UnityEditor.StaticEditorFlags.BatchingStatic + ); break; default: mr.gameObject.isStatic = false; - UnityEditor.GameObjectUtility.SetNavMeshArea(mr.gameObject, PlacementManager.NavemeshNoneArea); + UnityEditor.GameObjectUtility.SetNavMeshArea( + mr.gameObject, + PlacementManager.NavemeshNoneArea + ); UnityEditor.GameObjectUtility.SetStaticEditorFlags(mr.gameObject, 0); break; } @@ -504,7 +529,11 @@ void OnDrawGizmos() { Gizmos.matrix = transform.localToWorldMatrix; Gizmos.color = VisibleNow ? Color.yellow : Color.cyan; Gizmos.DrawWireCube(BoundsTransform.localPosition, BoundsTransform.localScale); - Gizmos.color = Color.Lerp(VisibleNow ? Color.yellow : Color.cyan, Color.clear, 0.45f); + Gizmos.color = Color.Lerp( + VisibleNow ? Color.yellow : Color.cyan, + Color.clear, + 0.45f + ); Gizmos.DrawCube(BoundsTransform.localPosition, BoundsTransform.localScale); // reset matrix Gizmos.matrix = Matrix4x4.identity; @@ -524,7 +553,13 @@ void OnDrawGizmos() { MeshFilter mf = gameObject.GetComponentInChildren(false); if (mf != null) { Gizmos.color = Color.yellow; - Gizmos.DrawWireMesh(mf.sharedMesh, -1, mf.transform.position, mf.transform.rotation, mf.transform.lossyScale); + Gizmos.DrawWireMesh( + mf.sharedMesh, + -1, + mf.transform.position, + mf.transform.rotation, + mf.transform.lossyScale + ); } else { // probably a visibility collider only sim obj if (IsReceptacle) { diff --git a/unity/Assets/Scripts/SimObjInfo.cs b/unity/Assets/Scripts/SimObjInfo.cs index 56ccae0c28..2f8e22be8d 100644 --- a/unity/Assets/Scripts/SimObjInfo.cs +++ b/unity/Assets/Scripts/SimObjInfo.cs @@ -65,5 +65,3 @@ public enum SimObjProperty : int // Properties of a SimObjPhysics that determine CanBeLitOnFire, CanLightOnFire } - - diff --git a/unity/Assets/Scripts/SimObjPhysics.cs b/unity/Assets/Scripts/SimObjPhysics.cs index e045170cca..9a5eacc116 100644 --- a/unity/Assets/Scripts/SimObjPhysics.cs +++ b/unity/Assets/Scripts/SimObjPhysics.cs @@ -1,17 +1,16 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using UnityEngine; -using UnityStandardAssets.Characters.FirstPerson; using UnityEngine.SceneManagement; -using System.Linq; - +using UnityStandardAssets.Characters.FirstPerson; #if UNITY_EDITOR using UnityEditor; using UnityEditor.SceneManagement; #endif -public class SimObjPhysics : MonoBehaviour, SimpleSimObj { +public class SimObjPhysics : MonoBehaviour, SimpleSimObj { [Header("Unique String ID of this Object In Scene")] [SerializeField] public string objectID = string.Empty; @@ -76,7 +75,8 @@ public class SimObjPhysics : MonoBehaviour, SimpleSimObj { private PhysicsMaterialValues[] OriginalPhysicsMaterialValuesForAllMyColliders = null; - public Dictionary contactPointsDictionary = new Dictionary(); + public Dictionary contactPointsDictionary = + new Dictionary(); // if this object is a receptacle, get all valid spawn points from any child ReceptacleTriggerBoxes and sort them by distance to Agent public List MySpawnPoints = new List(); @@ -88,7 +88,7 @@ public class SimObjPhysics : MonoBehaviour, SimpleSimObj { public float HowManySecondsUntilRoomTemp = 10f; private float TimerResetValue; - private PhysicsSceneManager sceneManager;// reference to scene manager object + private PhysicsSceneManager sceneManager; // reference to scene manager object public bool inMotion = false; @@ -98,7 +98,7 @@ public class SimObjPhysics : MonoBehaviour, SimpleSimObj { public int numStructureHit = 0; // the velocity of this object from the last frame - public float lastVelocity = 0;// start at zero assuming at rest + public float lastVelocity = 0; // start at zero assuming at rest // reference to this gameobject's rigidbody private Rigidbody myRigidbody; @@ -124,10 +124,12 @@ public class SimObjPhysics : MonoBehaviour, SimpleSimObj { private AxisAlignedBoundingBox cachedAxisAlignedBoundingBox; private bool forceCreateObjectOrientedBoundingBox = false; - + private bool shouldCreateObjectOrientedBoundingBox { get { - return this.forceCreateObjectOrientedBoundingBox || this.IsPickupable || this.IsMoveable; + return this.forceCreateObjectOrientedBoundingBox + || this.IsPickupable + || this.IsMoveable; } } @@ -143,6 +145,7 @@ public void SetHowManySecondsUntilRoomTemp(float f) { TimerResetValue = f; HowManySecondsUntilRoomTemp = f; } + private bool StartRoomTempTimer = false; public void SetStartRoomTempTimer(bool b) { @@ -182,29 +185,30 @@ public void syncBoundingBoxes( bool forceCacheReset = false, bool forceCreateObjectOrientedBoundingBox = false ) { - if (forceCreateObjectOrientedBoundingBox) { bool shouldCreateBefore = this.shouldCreateObjectOrientedBoundingBox; this.forceCreateObjectOrientedBoundingBox = forceCreateObjectOrientedBoundingBox; - forceCacheReset = forceCacheReset || shouldCreateBefore != this.shouldCreateObjectOrientedBoundingBox; + forceCacheReset = + forceCacheReset || shouldCreateBefore != this.shouldCreateObjectOrientedBoundingBox; } Vector3 position = this.gameObject.transform.position; Quaternion rotation = this.gameObject.transform.rotation; // position and rotation will vary slightly due to floating point errors - // so we use a very small epsilon value for comparison instead of + // so we use a very small epsilon value for comparison instead of // checking equality if ( (!forceCacheReset) && this.boundingBoxCacheKey != null && ( - !this.IsOpenable || ( + !this.IsOpenable + || ( this.IsOpen == this.boundingBoxCacheKey.IsOpen && Math.Abs(this.openness - this.boundingBoxCacheKey.openness) < .0001f ) - ) + ) && (!this.IsSliceable || this.IsSliced == this.boundingBoxCacheKey.IsSliced) && (!this.IsBreakable || this.IsBroken == this.boundingBoxCacheKey.IsBroken) && Quaternion.Angle(rotation, this.boundingBoxCacheKey.rotation) < 0.0001f @@ -230,7 +234,6 @@ public void syncBoundingBoxes( } private AxisAlignedBoundingBox axisAlignedBoundingBox() { - AxisAlignedBoundingBox b = new AxisAlignedBoundingBox(); // unparent child simobjects during bounding box generation @@ -261,7 +264,10 @@ private AxisAlignedBoundingBox axisAlignedBoundingBox() { SimObjPhysics sopc = this.GetComponent(); if (sopc.IsBroken || sopc.IsSliced) { #if UNITY_EDITOR - Debug.Log("Object is broken or sliced in pieces, no AxisAligned box generated: " + this.name); + Debug.Log( + "Object is broken or sliced in pieces, no AxisAligned box generated: " + + this.name + ); #endif return b; } else { @@ -289,15 +295,18 @@ private AxisAlignedBoundingBox axisAlignedBoundingBox() { // ok now we have a bounds that encapsulates all the colliders of the object, EXCLUDING trigger colliders List cornerPoints = new List(); - float[] xs = new float[]{ + float[] xs = new float[] + { bounding.center.x + bounding.size.x / 2f, bounding.center.x - bounding.size.x / 2f }; - float[] ys = new float[]{ + float[] ys = new float[] + { bounding.center.y + bounding.size.y / 2f, bounding.center.y - bounding.size.y / 2f }; - float[] zs = new float[]{ + float[] zs = new float[] + { bounding.center.z + bounding.size.z / 2f, bounding.center.z - bounding.size.z / 2f }; @@ -314,7 +323,6 @@ private AxisAlignedBoundingBox axisAlignedBoundingBox() { b.size = bounding.size; // also return the size in the x, y, z axes of the bounding box in world coordinates return b; - } private ObjectOrientedBoundingBox objectOrientedBoundingBox() { @@ -342,12 +350,13 @@ private ObjectOrientedBoundingBox objectOrientedBoundingBox() { // unparent child simobjects during bounding box generation List childSimObjects = new List(); - foreach (SimObjPhysics simObject in this.transform.GetComponentsInChildren()) { + foreach ( + SimObjPhysics simObject in this.transform.GetComponentsInChildren() + ) { if (simObject != this) { childSimObjects.Add(simObject.transform); simObject.transform.parent = null; } - } // The GameObject is cloned instead of teleporting/rotating to avoid @@ -355,7 +364,6 @@ private ObjectOrientedBoundingBox objectOrientedBoundingBox() { // since it will never sleep. GameObject clone = Instantiate(this.gameObject, Vector3.zero, Quaternion.identity); - // Get all colliders on the sop, excluding colliders if they are not enabled List<(Collider, LayerMask)> cols = new List<(Collider, LayerMask)>(); var nonInteractiveLayer = LayerMask.NameToLayer("NonInteractive"); @@ -404,14 +412,46 @@ private ObjectOrientedBoundingBox objectOrientedBoundingBox() { // Get corner points of SimObject's new BoundingBox, in its correct transformation List points = new List(); - points.Add(this.transform.TransformPoint(newBB.center + new Vector3(newBB.size.x, -newBB.size.y, newBB.size.z) * 0.5f)); - points.Add(this.transform.TransformPoint(newBB.center + new Vector3(-newBB.size.x, -newBB.size.y, newBB.size.z) * 0.5f)); - points.Add(this.transform.TransformPoint(newBB.center + new Vector3(-newBB.size.x, -newBB.size.y, -newBB.size.z) * 0.5f)); - points.Add(this.transform.TransformPoint(newBB.center + new Vector3(newBB.size.x, -newBB.size.y, -newBB.size.z) * 0.5f)); - points.Add(this.transform.TransformPoint(newBB.center + new Vector3(newBB.size.x, newBB.size.y, newBB.size.z) * 0.5f)); - points.Add(this.transform.TransformPoint(newBB.center + new Vector3(-newBB.size.x, newBB.size.y, newBB.size.z) * 0.5f)); - points.Add(this.transform.TransformPoint(newBB.center + new Vector3(-newBB.size.x, +newBB.size.y, -newBB.size.z) * 0.5f)); - points.Add(this.transform.TransformPoint(newBB.center + new Vector3(newBB.size.x, newBB.size.y, -newBB.size.z) * 0.5f)); + points.Add( + this.transform.TransformPoint( + newBB.center + new Vector3(newBB.size.x, -newBB.size.y, newBB.size.z) * 0.5f + ) + ); + points.Add( + this.transform.TransformPoint( + newBB.center + new Vector3(-newBB.size.x, -newBB.size.y, newBB.size.z) * 0.5f + ) + ); + points.Add( + this.transform.TransformPoint( + newBB.center + new Vector3(-newBB.size.x, -newBB.size.y, -newBB.size.z) * 0.5f + ) + ); + points.Add( + this.transform.TransformPoint( + newBB.center + new Vector3(newBB.size.x, -newBB.size.y, -newBB.size.z) * 0.5f + ) + ); + points.Add( + this.transform.TransformPoint( + newBB.center + new Vector3(newBB.size.x, newBB.size.y, newBB.size.z) * 0.5f + ) + ); + points.Add( + this.transform.TransformPoint( + newBB.center + new Vector3(-newBB.size.x, newBB.size.y, newBB.size.z) * 0.5f + ) + ); + points.Add( + this.transform.TransformPoint( + newBB.center + new Vector3(-newBB.size.x, +newBB.size.y, -newBB.size.z) * 0.5f + ) + ); + points.Add( + this.transform.TransformPoint( + newBB.center + new Vector3(newBB.size.x, newBB.size.y, -newBB.size.z) * 0.5f + ) + ); List cornerPoints = new List(); foreach (Vector3 p in points) { @@ -425,14 +465,12 @@ private ObjectOrientedBoundingBox objectOrientedBoundingBox() { return null; } + public void DropContainedObjectsStationary() { this.DropContainedObjects(reparentContainedObjects: false, forceKinematic: true); } - public void DropContainedObjects( - bool reparentContainedObjects, - bool forceKinematic - ) { + public void DropContainedObjects(bool reparentContainedObjects, bool forceKinematic) { if (this.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { GameObject topObject = null; @@ -456,7 +494,6 @@ bool forceKinematic rb.constraints = RigidbodyConstraints.None; rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; } - } this.ClearContainedObjectReferences(); } @@ -481,61 +518,41 @@ public void ClearContainedObjectReferences() { } public string ObjectID { - get { - return objectID; - } - - set { - objectID = value; - } + get { return objectID; } + set { objectID = value; } } public SimObjType ObjType { - get { - return Type; - } - set { - Type = value; - } + get { return Type; } + set { Type = value; } } public int ReceptacleCount { - get { - return 0; - } + get { return 0; } } public List ReceptacleObjectIds { - get { - return this.GetAllSimObjectsInReceptacleTriggersByObjectID(); - } + get { return this.GetAllSimObjectsInReceptacleTriggersByObjectID(); } } // get all objects contained by this receptacle object as a list of SimObjPhysics public List SimObjectsContainedByReceptacle { - get { - return this.GetAllSimObjectsInReceptacleTriggers(); - } - + get { return this.GetAllSimObjectsInReceptacleTriggers(); } } // return mass of object public float Mass { get { var rb = this.GetComponent(); - return rb != null? rb.mass : 0.0f; + return rb != null ? rb.mass : 0.0f; } } - // if this pickupable object is being held by the agent right public bool isPickedUp { - get { - return this.isInAgentHand; - } + get { return this.isInAgentHand; } } - // note some objects are not toggleable, but can still return the IsToggled meta value (ex: stove burners) // stove burners are not toggleable directly, a stove knob controls them. private bool isToggleable { @@ -545,7 +562,6 @@ private bool isToggleable { if (this.GetComponent().ReturnSelfControlled()) { return true; } - // if it is not self controlled (meaning controlled by another sim object) return not toggleable // although if this object is not toggleable, it may still return isToggled as a state (see IsToggled below) else { @@ -554,7 +570,7 @@ private bool isToggleable { } else { return false; } - // return this.GetComponent(); + // return this.GetComponent(); } } @@ -574,7 +590,6 @@ public bool IsToggled { } } - public float openness { get { return this.GetComponent().currentOpenness; } } @@ -657,22 +672,17 @@ public bool IsSliced { /// these aren't in yet, just placeholder public bool CanBeUsedUp { - get { - return false; - } + get { return false; } } public bool IsUsedUp { - get { - return false; - } + get { return false; } } + /// end placeholder stuff // return temperature enum here public Temperature CurrentObjTemp { - get { - return CurrentTemperature; - } + get { return CurrentTemperature; } } private void FindMySpawnPoints(BaseFPSAgentController agent = null) { @@ -683,29 +693,43 @@ private void FindMySpawnPoints(BaseFPSAgentController agent = null) { } if (agent != null) { - temp.Sort(delegate (ReceptacleSpawnPoint one, ReceptacleSpawnPoint two) { - return Vector3.Distance(agent.transform.position, one.Point).CompareTo(Vector3.Distance(agent.transform.position, two.Point)); - }); + temp.Sort( + delegate (ReceptacleSpawnPoint one, ReceptacleSpawnPoint two) { + return Vector3 + .Distance(agent.transform.position, one.Point) + .CompareTo(Vector3.Distance(agent.transform.position, two.Point)); + } + ); } MySpawnPoints = temp; } // return spawn points for this receptacle objects based on the top part of all trigger boxes - public List FindMySpawnPointsFromTriggerBox(bool forceVisible = false, bool top = false) { + public List FindMySpawnPointsFromTriggerBox( + bool forceVisible = false, + bool top = false + ) { List points = new List(); foreach (GameObject rtb in ReceptacleTriggerBoxes) { - points.AddRange(rtb.GetComponent().GetValidSpawnPointsFromTriggerBox(top: top)); + points.AddRange( + rtb.GetComponent().GetValidSpawnPointsFromTriggerBox(top: top) + ); } return points; } // return spawn points for this receptacle objects based on the top part of all trigger boxes - public List FindMySpawnPointsFromTriggerBoxInLocalSpace(bool forceVisible = false, bool top = false) { + public List FindMySpawnPointsFromTriggerBoxInLocalSpace( + bool forceVisible = false, + bool top = false + ) { List points = new List(); foreach (GameObject rtb in ReceptacleTriggerBoxes) { - points.AddRange(rtb.GetComponent().GetValidSpawnPointsFromTriggerBoxLocalSpace(top: top)); + points.AddRange( + rtb.GetComponent().GetValidSpawnPointsFromTriggerBoxLocalSpace(top: top) + ); } return points; @@ -746,8 +770,6 @@ void OnCollisionEnter(Collision col) { } } } - - // add a check for if the hitting one is a structure object else if (col.transform.GetComponentInParent()) { // add a check for if it's for initialization @@ -760,7 +782,10 @@ void OnCollisionEnter(Collision col) { if (!contactPointsDictionary.ContainsKey(col.collider)) { numStructureHit++; // check if structure hit is a floor - if (col.transform.GetComponentInParent().WhatIsMyStructureObjectTag == StructureObjectTag.Floor) { + if ( + col.transform.GetComponentInParent().WhatIsMyStructureObjectTag + == StructureObjectTag.Floor + ) { numFloorHit++; } } @@ -794,7 +819,7 @@ public static void CreateRBCollider() { // default tag and layer so that nothing is raycast against this. The only thing this exists for is to make physics real inst.tag = "Untagged"; - inst.layer = 0;// default layer + inst.layer = 0; // default layer // EditorUtility.GetPrefabParent(Selection.activeGameObject); // PrefabUtility.InstantiatePrefab(prefabRoot); @@ -844,8 +869,6 @@ public static void ResetTransformScale() { foreach (Transform t in selectedchildren) { t.SetParent(selected.transform); } - - } [UnityEditor.MenuItem("SimObjectPhysics/Set All Transforms to Defaults &d")] @@ -871,8 +894,6 @@ public static void ResetTransform() { foreach (Transform t in selectedchildren) { t.SetParent(selected.transform); } - - } [UnityEditor.MenuItem("SimObjectPhysics/Rotate Box Flap 90 on Y &s")] @@ -902,11 +923,12 @@ public static void RotateTheBoxFlap() { t.SetParent(selected.transform); } } - #endif private void initializeProperties() { - this.IsReceptacle = Array.IndexOf(SecondaryProperties, SimObjSecondaryProperty.Receptacle) > -1 && ReceptacleTriggerBoxes != null; + this.IsReceptacle = + Array.IndexOf(SecondaryProperties, SimObjSecondaryProperty.Receptacle) > -1 + && ReceptacleTriggerBoxes != null; this.IsPickupable = this.PrimaryProperty == SimObjPrimaryProperty.CanPickup; this.IsMoveable = this.PrimaryProperty == SimObjPrimaryProperty.Moveable; this.isStatic = this.PrimaryProperty == SimObjPrimaryProperty.Static; @@ -917,9 +939,12 @@ private void initializeProperties() { this.IsDirtyable = this.GetComponent(); this.IsCookable = this.GetComponent(); this.IsSliceable = this.GetComponent(); - this.isHeatSource = DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.isHeatSource); - this.isColdSource = DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.isColdSource); - + this.isHeatSource = DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.isHeatSource + ); + this.isColdSource = DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.isColdSource + ); } // Use this for initialization @@ -929,7 +954,9 @@ void Start() { List temp = new List(SecondaryProperties); if (temp.Contains(SimObjSecondaryProperty.Receptacle)) { if (ReceptacleTriggerBoxes.Length == 0) { - Debug.LogError(this.name + " is missing ReceptacleTriggerBoxes please hook them up"); + Debug.LogError( + this.name + " is missing ReceptacleTriggerBoxes please hook them up" + ); } } @@ -955,14 +982,20 @@ void Start() { #endif // end debug setup stuff - OriginalPhysicsMaterialValuesForAllMyColliders = new PhysicsMaterialValues[MyColliders.Length]; + OriginalPhysicsMaterialValuesForAllMyColliders = new PhysicsMaterialValues[ + MyColliders.Length + ]; for (int i = 0; i < MyColliders.Length; i++) { - OriginalPhysicsMaterialValuesForAllMyColliders[i] = - new PhysicsMaterialValues(MyColliders[i].material.dynamicFriction, MyColliders[i].material.staticFriction, MyColliders[i].material.bounciness); + OriginalPhysicsMaterialValuesForAllMyColliders[i] = new PhysicsMaterialValues( + MyColliders[i].material.dynamicFriction, + MyColliders[i].material.staticFriction, + MyColliders[i].material.bounciness + ); } - myRigidbody = gameObject.GetComponent(); myRigidbody = gameObject.GetComponent(); + myRigidbody = gameObject.GetComponent(); + myRigidbody = gameObject.GetComponent(); if (myRigidbody != null) { Rigidbody rb = myRigidbody; @@ -990,14 +1023,13 @@ void Start() { if (onlyForThisObject) { if (sceneManager.placeDecalSurfaceOnReceptacles && this.IsReceptacle) { foreach (GameObject go in ReceptacleTriggerBoxes) { - var dgo = GameObject.Instantiate(sceneManager.receptaclesDirtyDecalSurface); // unity provided quad's mesh is XY plane, repplace with custom XZ one and remove line below dgo.GetComponent().isTrigger = true; dgo.transform.parent = go.transform; dgo.transform.localEulerAngles = new Vector3(-90.0f, 0.0f, 0.0f); - // This is where the decal plane goes in y, if receptacle box is too high it could lead to + // This is where the decal plane goes in y, if receptacle box is too high it could lead to // decals bleeding to other objects that are below it in y, so tune appropiately, should be // an annotation of prefab var yOffset = 0.001f; @@ -1010,8 +1042,12 @@ void Start() { } } - //spawn dirt on receptacle - public void SpawnDirtOnReceptacle(int howManyDirt, int randomSeed, DirtSpawnPosition[] spawnPoints = null) { + //spawn dirt on receptacle + public void SpawnDirtOnReceptacle( + int howManyDirt, + int randomSeed, + DirtSpawnPosition[] spawnPoints = null + ) { DecalSpawner decalSpawner = this.gameObject.GetComponentInChildren(); decalSpawner.SpawnDirt(howManyDirt, randomSeed, spawnPoints); } @@ -1031,9 +1067,10 @@ public bool DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty prop return result; } + // Update is called once per frame void Update() { - if (sceneManager.AllowDecayTemperature)// only do this if the scene is initialized to use Temperature decay over time + if (sceneManager.AllowDecayTemperature) // only do this if the scene is initialized to use Temperature decay over time { // if this object is either hot or col, begin a timer that counts until the object becomes room temperature again if (CurrentTemperature != Temperature.RoomTemp && StartRoomTempTimer == true) { @@ -1053,7 +1090,9 @@ void LateUpdate() { if (sceneManager.physicsSimulationPaused == false && myRigidbody != null) // record this object's current velocity { - lastVelocity = Math.Abs(myRigidbody.angularVelocity.sqrMagnitude + myRigidbody.velocity.sqrMagnitude); + lastVelocity = Math.Abs( + myRigidbody.angularVelocity.sqrMagnitude + myRigidbody.velocity.sqrMagnitude + ); } } @@ -1073,7 +1112,6 @@ public void ApplyForce(ServerAction action) { // overload that doesn't use a server action public void ApplyForce(Vector3 dir, float magnitude) { - Rigidbody myrb = gameObject.GetComponent(); if (myrb.IsSleeping()) { @@ -1092,7 +1130,9 @@ public List GetAllSimObjectsInReceptacleTriggers() { if (DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { if (ReceptacleTriggerBoxes != null) { foreach (GameObject go in ReceptacleTriggerBoxes) { - foreach (SimObjPhysics sop in go.GetComponent().CurrentlyContainedObjects()) { + foreach ( + SimObjPhysics sop in go.GetComponent().CurrentlyContainedObjects() + ) { if (!objs.Contains(sop)) { // print(sop.transform.name); objs.Add(sop); @@ -1131,7 +1171,9 @@ public List ContainedGameObjects() { // get box collider dimensions of ReceptacleTriggerBox if this is a receptacle if (IsReceptacle) { foreach (GameObject rtb in ReceptacleTriggerBoxes) { - foreach (GameObject g in rtb.GetComponent().CurrentlyContainedGameObjects()) { + foreach ( + GameObject g in rtb.GetComponent().CurrentlyContainedGameObjects() + ) { if (!objs.Contains(g)) { objs.Add(g); } @@ -1148,7 +1190,12 @@ public List ContainedGameObjects() { public void OnTriggerEnter(Collider other) { // is colliding only needs to be set for pickupable objects. Also drag/friction values only need to change for pickupable objects not all sim objects - if ((PrimaryProperty == SimObjPrimaryProperty.CanPickup || PrimaryProperty == SimObjPrimaryProperty.Moveable)) { + if ( + ( + PrimaryProperty == SimObjPrimaryProperty.CanPickup + || PrimaryProperty == SimObjPrimaryProperty.Moveable + ) + ) { if (other.CompareTag("HighFriction")) //&& (PrimaryProperty == SimObjPrimaryProperty.CanPickup || PrimaryProperty == SimObjPrimaryProperty.Moveable)) { Rigidbody rb = gameObject.GetComponent(); @@ -1167,7 +1214,13 @@ public void OnTriggerEnter(Collider other) { } public void OnTriggerExit(Collider other) { - if (other.CompareTag("HighFriction") && (PrimaryProperty == SimObjPrimaryProperty.CanPickup || PrimaryProperty == SimObjPrimaryProperty.Moveable)) { + if ( + other.CompareTag("HighFriction") + && ( + PrimaryProperty == SimObjPrimaryProperty.CanPickup + || PrimaryProperty == SimObjPrimaryProperty.Moveable + ) + ) { // print( "resetting to default trigger exit"); Rigidbody rb = gameObject.GetComponent(); @@ -1176,23 +1229,30 @@ public void OnTriggerExit(Collider other) { rb.angularDrag = RBoriginalAngularDrag; for (int i = 0; i < MyColliders.Length; i++) { - MyColliders[i].material.dynamicFriction = OriginalPhysicsMaterialValuesForAllMyColliders[i].DynamicFriction; - MyColliders[i].material.staticFriction = OriginalPhysicsMaterialValuesForAllMyColliders[i].StaticFriction; - MyColliders[i].material.bounciness = OriginalPhysicsMaterialValuesForAllMyColliders[i].Bounciness; + MyColliders[i].material.dynamicFriction = + OriginalPhysicsMaterialValuesForAllMyColliders[i].DynamicFriction; + MyColliders[i].material.staticFriction = + OriginalPhysicsMaterialValuesForAllMyColliders[i].StaticFriction; + MyColliders[i].material.bounciness = OriginalPhysicsMaterialValuesForAllMyColliders[ + i + ].Bounciness; } } } //note breakForce and breakTorque are exposed here so we may use that later I guess - public void BeingPickedUpByArticulatedAgent(ArticulatedArmController arm, float breakForce = 20.0f, float breakTorque = 20.0f) - { + public void BeingPickedUpByArticulatedAgent( + ArticulatedArmController arm, + float breakForce = 20.0f, + float breakTorque = 20.0f + ) { articulatedArmHoldingMe = arm; myRigidbody.isKinematic = false; //add fixed joint //add a fixed joint to this picked up object FixedJoint ultraHand = this.transform.gameObject.AddComponent(); - //add reference to the wrist joint as connected articulated body + //add reference to the wrist joint as connected articulated body ultraHand.connectedArticulationBody = arm.FinalJoint.GetComponent(); ultraHand.breakForce = breakForce; ultraHand.breakTorque = breakTorque; @@ -1232,14 +1292,26 @@ void OnDrawGizmos() { if (debugIsVisible == true && gameObject.GetComponentInChildren()) { MeshFilter mf = gameObject.GetComponentInChildren(false); Gizmos.color = Color.yellow; - Gizmos.DrawWireMesh(mf.sharedMesh, -1, mf.transform.position, mf.transform.rotation, mf.transform.lossyScale); + Gizmos.DrawWireMesh( + mf.sharedMesh, + -1, + mf.transform.position, + mf.transform.rotation, + mf.transform.lossyScale + ); } // interactable drawn in magenta if (debugIsInteractable && gameObject.GetComponentInChildren()) { MeshFilter mf = gameObject.GetComponentInChildren(false); Gizmos.color = Color.magenta; - Gizmos.DrawWireMesh(mf.sharedMesh, -1, mf.transform.position, mf.transform.rotation, mf.transform.lossyScale); + Gizmos.DrawWireMesh( + mf.sharedMesh, + -1, + mf.transform.position, + mf.transform.rotation, + mf.transform.lossyScale + ); } // draw visibility points for editor @@ -1299,7 +1371,6 @@ void SetUpCabinet() { Transform door = transform.Find("CabinetDoor"); - if (!gameObject.transform.Find("StaticVisPoints")) { GameObject svp = new GameObject("StaticVisPoints"); svp.transform.position = gameObject.transform.position; @@ -1381,7 +1452,11 @@ void SetUpCabinet() { if (col.childCount == 0) { GameObject prefabRoot = col.gameObject; - GameObject inst = Instantiate(prefabRoot, col.gameObject.transform, true); + GameObject inst = Instantiate( + prefabRoot, + col.gameObject.transform, + true + ); // inst.transform.SetParent(Selection.activeGameObject.transform); @@ -1392,7 +1467,7 @@ void SetUpCabinet() { // default tag and layer so that nothing is raycast against this. The only thing this exists for is to make physics real inst.tag = "Untagged"; - inst.layer = 0;// default layer + inst.layer = 0; // default layer } } } @@ -1432,11 +1507,15 @@ void SetUpCabinet() { // this.GetComponent().SetMovementToRotate(); } + //[ContextMenu("Table")] void SetUpTable() { this.Type = SimObjType.DiningTable; this.PrimaryProperty = SimObjPrimaryProperty.Static; - this.SecondaryProperties = new SimObjSecondaryProperty[] { SimObjSecondaryProperty.Receptacle }; + this.SecondaryProperties = new SimObjSecondaryProperty[] + { + SimObjSecondaryProperty.Receptacle + }; ContextSetUpSimObjPhysics(); @@ -1471,7 +1550,9 @@ void FloorSetupContext() { this.PrimaryProperty = SimObjPrimaryProperty.Static; this.SecondaryProperties = new SimObjSecondaryProperty[] - {SimObjSecondaryProperty.Receptacle}; + { + SimObjSecondaryProperty.Receptacle + }; if (!gameObject.GetComponent()) { gameObject.AddComponent(); @@ -1492,14 +1573,17 @@ void FloorSetupContext() { bb.size = r.bounds.size * 1.1f; meshbox.enabled = false; - } //[ContextMenu("Drawer")] void SetUpDrawer() { this.Type = SimObjType.Drawer; this.PrimaryProperty = SimObjPrimaryProperty.Static; - this.SecondaryProperties = new SimObjSecondaryProperty[] { SimObjSecondaryProperty.Receptacle, SimObjSecondaryProperty.CanOpen }; + this.SecondaryProperties = new SimObjSecondaryProperty[] + { + SimObjSecondaryProperty.Receptacle, + SimObjSecondaryProperty.CanOpen + }; ContextSetUpSimObjPhysics(); @@ -1563,13 +1647,11 @@ void SetUpDrawer() { // make trigger colliders, if there is "Colliders" already, duplicate them, parant to this object // then go through and set them all to istrigger. - } //[ContextMenu("Find BoundingBox")] void ContextFindBoundingBox() { BoundingBox = gameObject.transform.Find("BoundingBox").gameObject; - } //[ContextMenu("Set Up Microwave")] @@ -1630,7 +1712,6 @@ void ContextSetUpMicrowave() { col.transform.tag = "SimObjPhysics"; col.layer = 8; - } if (!door.Find("VisPoints")) { @@ -1663,14 +1744,20 @@ void ContextSetUpMicrowave() { coo.SetMovementToRotate(); if (gameObject.transform.Find("ReceptacleTriggerBox")) { - GameObject[] rtb = new GameObject[] { gameObject.transform.Find("ReceptacleTriggerBox").transform.gameObject }; + GameObject[] rtb = new GameObject[] + { + gameObject.transform.Find("ReceptacleTriggerBox").transform.gameObject + }; ReceptacleTriggerBoxes = rtb; } } //[ContextMenu("Static Mesh Collider with Receptacle")] void SetUpSimObjWithStaticMeshCollider() { - if (this.Type == SimObjType.Undefined || this.PrimaryProperty == SimObjPrimaryProperty.Undefined) { + if ( + this.Type == SimObjType.Undefined + || this.PrimaryProperty == SimObjPrimaryProperty.Undefined + ) { Debug.Log("Type / Primary Property is missing"); return; } @@ -1808,7 +1895,10 @@ public static void ContextSetupLightSwitch() { SimObjPhysics sop = c.GetComponent(); sop.PrimaryProperty = SimObjPrimaryProperty.Static; sop.Type = SimObjType.LightSwitch; - sop.SecondaryProperties = new SimObjSecondaryProperty[] { SimObjSecondaryProperty.CanToggleOnOff }; + sop.SecondaryProperties = new SimObjSecondaryProperty[] + { + SimObjSecondaryProperty.CanToggleOnOff + }; } c.tag = "SimObjPhysics"; @@ -1870,7 +1960,6 @@ public static void ContextSetupLightSwitch() { } } - [ContextMenu("Setup Colliders, VisPoints, and Bounding Box")] public void SetupCollidersVisPoints() { ContextSetUpColliders(); @@ -1969,7 +2058,10 @@ void ToasterSetupReferences() { [ContextMenu("Setup")] public void ContextSetUpSimObjPhysics() { - if (this.Type == SimObjType.Undefined || this.PrimaryProperty == SimObjPrimaryProperty.Undefined) { + if ( + this.Type == SimObjType.Undefined + || this.PrimaryProperty == SimObjPrimaryProperty.Undefined + ) { Debug.Log("Type / Primary Property is missing"); return; } @@ -2074,8 +2166,6 @@ public void ContextSetUpSimObjPhysics() { ContextSetUpBoundingBox(); } - - //[ContextMenu("Set Up Colliders")] public void ContextSetUpColliders() { List listColliders = new List(); @@ -2122,7 +2212,6 @@ public void ContextSetUpColliders() { } MyColliders = listColliders.ToArray(); - } //[ContextMenu("Set Up TriggerColliders")] @@ -2145,7 +2234,6 @@ void ContextSetUpTriggerColliders() { child.GetComponent().enabled = true; child.GetComponent().isTrigger = true; } - } // MyTriggerColliders = listtc.ToArray(); @@ -2199,10 +2287,10 @@ public void ContextSetUpBoundingBox(bool forceCacheReset = false) { BoundingBox.transform.localScale = Vector3.one; } - BoundingBox.transform.localScale = Vector3.one;// make sure to default existing BoundingBox to 1 as well + BoundingBox.transform.localScale = Vector3.one; // make sure to default existing BoundingBox to 1 as well // This collider is used as a size reference for the Agent's Rotation checking boxes, so it does not need - // to be enabled. To ensure this doesn't interact with anything else, set the Tag to Untagged, the layer to + // to be enabled. To ensure this doesn't interact with anything else, set the Tag to Untagged, the layer to // SimObjInvisible, and disable this component. Component values can still be accessed if the component itself // is not enabled. BoundingBox.tag = "Untagged"; @@ -2212,9 +2300,10 @@ public void ContextSetUpBoundingBox(bool forceCacheReset = false) { Physics.SyncTransforms(); } - Collider[] colliders = transform.GetComponentsInChildren().Where( - c => c.enabled && !c.isTrigger - ).ToArray(); + Collider[] colliders = transform + .GetComponentsInChildren() + .Where(c => c.enabled && !c.isTrigger) + .ToArray(); MeshFilter[] meshes = transform.GetComponentsInChildren(); // SkinnedMeshRenderer[] skinnedMeshes = transform.GetComponentsInChildren(); @@ -2298,7 +2387,8 @@ public void ContextSetUpBoundingBox(bool forceCacheReset = false) { // Debug.Log("Min/max of BoundingBox: " + newBoundingBox.min + ", " + newBoundingBox.max); BoundingBox.GetComponent().center = newBoundingBox.center; // Set Bounding Box Buffer Here!!! - BoundingBox.GetComponent().size = newBoundingBox.size + new Vector3(0.01f, 0.01f, 0.01f); + BoundingBox.GetComponent().size = + newBoundingBox.size + new Vector3(0.01f, 0.01f, 0.01f); BoundingBox.GetComponent().enabled = false; // var currentBoundingBox = currentGameObject.transform.Find("BoundingBox").GetComponent(); @@ -2314,118 +2404,124 @@ public void ContextSetUpBoundingBox(bool forceCacheReset = false) { } // generates object metatada based on sim object's properties - public static ObjectMetadata ObjectMetadataFromSimObjPhysics(SimObjPhysics simObj, bool isVisible, bool isInteractable) { - ObjectMetadata objMeta = new ObjectMetadata(); - GameObject o = simObj.gameObject; - objMeta.name = o.name; - objMeta.position = o.transform.position; - objMeta.rotation = o.transform.eulerAngles; - objMeta.objectType = Enum.GetName(typeof(SimObjType), simObj.Type); - objMeta.receptacle = simObj.IsReceptacle; - - objMeta.openable = simObj.IsOpenable; - if (objMeta.openable) { - objMeta.isOpen = simObj.IsOpen; - objMeta.openness = simObj.openness; - } - - objMeta.toggleable = simObj.IsToggleable; - //note: not all objects that report back `isToggled` are themselves `toggleable`, however they all do have the `CanToggleOnOff` secondary sim object property - //this is to account for cases like a [stove burner], which can report `isToggled` but cannot have the "ToggleObjectOn" action performed on them directly, and instead - //a [stove knob] linked to the [stove burner] must have a "ToggleObjectOn" action performed on it to have both the knob and burner set to a state of `isToggled = true` - if (simObj.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanToggleOnOff)) { - objMeta.isToggled = simObj.IsToggled; - } - - objMeta.breakable = simObj.IsBreakable; - if (objMeta.breakable) { - objMeta.isBroken = simObj.IsBroken; - } + public static ObjectMetadata ObjectMetadataFromSimObjPhysics( + SimObjPhysics simObj, + bool isVisible, + bool isInteractable + ) { + ObjectMetadata objMeta = new ObjectMetadata(); + GameObject o = simObj.gameObject; + objMeta.name = o.name; + objMeta.position = o.transform.position; + objMeta.rotation = o.transform.eulerAngles; + objMeta.objectType = Enum.GetName(typeof(SimObjType), simObj.Type); + objMeta.receptacle = simObj.IsReceptacle; - objMeta.canFillWithLiquid = simObj.IsFillable; - if (objMeta.canFillWithLiquid) { - objMeta.isFilledWithLiquid = simObj.IsFilled; - objMeta.fillLiquid = simObj.FillLiquid; - } + objMeta.openable = simObj.IsOpenable; + if (objMeta.openable) { + objMeta.isOpen = simObj.IsOpen; + objMeta.openness = simObj.openness; + } - objMeta.dirtyable = simObj.IsDirtyable; - if (objMeta.dirtyable) { - objMeta.isDirty = simObj.IsDirty; - } + objMeta.toggleable = simObj.IsToggleable; + //note: not all objects that report back `isToggled` are themselves `toggleable`, however they all do have the `CanToggleOnOff` secondary sim object property + //this is to account for cases like a [stove burner], which can report `isToggled` but cannot have the "ToggleObjectOn" action performed on them directly, and instead + //a [stove knob] linked to the [stove burner] must have a "ToggleObjectOn" action performed on it to have both the knob and burner set to a state of `isToggled = true` + if (simObj.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanToggleOnOff)) { + objMeta.isToggled = simObj.IsToggled; + } - objMeta.cookable = simObj.IsCookable; - if (objMeta.cookable) { - objMeta.isCooked = simObj.IsCooked; - } + objMeta.breakable = simObj.IsBreakable; + if (objMeta.breakable) { + objMeta.isBroken = simObj.IsBroken; + } - // if the sim object is moveable or pickupable - if (simObj.IsPickupable || simObj.IsMoveable || (simObj.salientMaterials != null && simObj.salientMaterials.Length > 0)) { - // this object should report back mass and salient materials + objMeta.canFillWithLiquid = simObj.IsFillable; + if (objMeta.canFillWithLiquid) { + objMeta.isFilledWithLiquid = simObj.IsFilled; + objMeta.fillLiquid = simObj.FillLiquid; + } - string[] salientMaterialsToString = new string[simObj.salientMaterials.Length]; + objMeta.dirtyable = simObj.IsDirtyable; + if (objMeta.dirtyable) { + objMeta.isDirty = simObj.IsDirty; + } - for (int i = 0; i < simObj.salientMaterials.Length; i++) { - salientMaterialsToString[i] = simObj.salientMaterials[i].ToString(); - } + objMeta.cookable = simObj.IsCookable; + if (objMeta.cookable) { + objMeta.isCooked = simObj.IsCooked; + } - objMeta.salientMaterials = salientMaterialsToString; + // if the sim object is moveable or pickupable + if ( + simObj.IsPickupable + || simObj.IsMoveable + || (simObj.salientMaterials != null && simObj.salientMaterials.Length > 0) + ) { + // this object should report back mass and salient materials - // this object should also report back mass since it is moveable/pickupable - objMeta.mass = simObj.Mass; + string[] salientMaterialsToString = new string[simObj.salientMaterials.Length]; + for (int i = 0; i < simObj.salientMaterials.Length; i++) { + salientMaterialsToString[i] = simObj.salientMaterials[i].ToString(); } - // can this object change others to hot? - objMeta.isHeatSource = simObj.isHeatSource; + objMeta.salientMaterials = salientMaterialsToString; - // can this object change others to cold? - objMeta.isColdSource = simObj.isColdSource; + // this object should also report back mass since it is moveable/pickupable + objMeta.mass = simObj.Mass; + } - // placeholder for heatable objects -kettle, pot, pan - // objMeta.abletocook = simObj.abletocook; - // if(objMeta.abletocook) { - // objMeta.isReadyToCook = simObj.IsHeated; - // } + // can this object change others to hot? + objMeta.isHeatSource = simObj.isHeatSource; - objMeta.sliceable = simObj.IsSliceable; - if (objMeta.sliceable) { - objMeta.isSliced = simObj.IsSliced; - } + // can this object change others to cold? + objMeta.isColdSource = simObj.isColdSource; - objMeta.canBeUsedUp = simObj.CanBeUsedUp; - if (objMeta.canBeUsedUp) { - objMeta.isUsedUp = simObj.IsUsedUp; - } + // placeholder for heatable objects -kettle, pot, pan + // objMeta.abletocook = simObj.abletocook; + // if(objMeta.abletocook) { + // objMeta.isReadyToCook = simObj.IsHeated; + // } - // object temperature to string - objMeta.temperature = simObj.CurrentObjTemp.ToString(); + objMeta.sliceable = simObj.IsSliceable; + if (objMeta.sliceable) { + objMeta.isSliced = simObj.IsSliced; + } - objMeta.pickupable = simObj.IsPickupable; - objMeta.isPickedUp = simObj.isPickedUp;// returns true for if this object is currently being held by the agent + objMeta.canBeUsedUp = simObj.CanBeUsedUp; + if (objMeta.canBeUsedUp) { + objMeta.isUsedUp = simObj.IsUsedUp; + } - objMeta.moveable = simObj.IsMoveable; + // object temperature to string + objMeta.temperature = simObj.CurrentObjTemp.ToString(); - objMeta.objectId = simObj.ObjectID; + objMeta.pickupable = simObj.IsPickupable; + objMeta.isPickedUp = simObj.isPickedUp; // returns true for if this object is currently being held by the agent - objMeta.assetId = simObj.assetID; + objMeta.moveable = simObj.IsMoveable; - // TODO: using the isVisible flag on the object causes weird problems - // in the multiagent setting, explicitly giving this information for now. - objMeta.visible = isVisible; // simObj.isVisible; + objMeta.objectId = simObj.ObjectID; - //determines if the objects is unobstructed and interactable. Objects visible behind see-through geometry like glass will be isInteractable=False even if visible - //note using forceAction=True will ignore the isInteractable requirement - objMeta.isInteractable = isInteractable; + objMeta.assetId = simObj.assetID; - objMeta.isMoving = simObj.inMotion;// keep track of if this object is actively moving + // TODO: using the isVisible flag on the object causes weird problems + // in the multiagent setting, explicitly giving this information for now. + objMeta.visible = isVisible; // simObj.isVisible; - objMeta.objectOrientedBoundingBox = simObj.ObjectOrientedBoundingBox; + //determines if the objects is unobstructed and interactable. Objects visible behind see-through geometry like glass will be isInteractable=False even if visible + //note using forceAction=True will ignore the isInteractable requirement + objMeta.isInteractable = isInteractable; - objMeta.axisAlignedBoundingBox = simObj.AxisAlignedBoundingBox; + objMeta.isMoving = simObj.inMotion; // keep track of if this object is actively moving - return objMeta; - } + objMeta.objectOrientedBoundingBox = simObj.ObjectOrientedBoundingBox; + + objMeta.axisAlignedBoundingBox = simObj.AxisAlignedBoundingBox; + return objMeta; + } class BoundingBoxCacheKey { public Vector3 position; diff --git a/unity/Assets/Scripts/SimObjType.cs b/unity/Assets/Scripts/SimObjType.cs index ac4f9980f3..339fb07c27 100644 --- a/unity/Assets/Scripts/SimObjType.cs +++ b/unity/Assets/Scripts/SimObjType.cs @@ -1,8 +1,8 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; +using System; using System.Collections; using System.Collections.Generic; -using System; +using UnityEngine; [Serializable] public enum SimObjManipType : int { // We aren't using these manip types for the Physics Implementation, they are being replaced with the SimObjPrimaryProperty below @@ -44,7 +44,7 @@ public enum SimObjSecondaryProperty : int // EACH SimObjPhysics can have any num CanBeCleanedDishware = 2, CanBeCleanedGlass = 3, - // OTHER SECONDARY PROPERTIES + // OTHER SECONDARY PROPERTIES CanBeDirty = 4, CanBeFilled = 5, CanBeUsedUp = 6, @@ -53,8 +53,8 @@ public enum SimObjSecondaryProperty : int // EACH SimObjPhysics can have any num CanBeSliced = 9, CanSlice = 10, CanBreak = 11, - isHeatSource = 12,// this object can change temperature of other objects to hot - isColdSource = 13,// this object can change temperature of other objects to cold + isHeatSource = 12, // this object can change temperature of other objects to hot + isColdSource = 13, // this object can change temperature of other objects to cold CanBeHeatedCookware = 14, CanHeatCookware = 15, CanBeStoveTopCooked = 16, @@ -93,6 +93,7 @@ public enum SimObjSecondaryProperty : int // EACH SimObjPhysics can have any num CanBeMountedSmall = 46, CanBeMountedMedium = 47, CanBeMountedLarge = 48, + // End Painting Mount Stuff CanBeLitOnFire = 49, @@ -105,6 +106,7 @@ public enum SimObjSecondaryProperty : int // EACH SimObjPhysics can have any num public enum SimObjType : int { // undefined is always the first value Undefined = 0, + // ADD NEW VALUES BELOW // DO NOT RE-ARRANGE OLDER VALUES Apple = 1, @@ -154,14 +156,14 @@ public enum SimObjType : int { HousePlant = 45, TissueBox = 46, VacuumCleaner = 47, - Painting = 48,// delineated sizes in physics + Painting = 48, // delineated sizes in physics WateringCan = 49, Laptop = 50, RemoteControl = 51, Box = 52, Newspaper = 53, - TissueBoxEmpty = 54,// will be a state of TissuBox in physics - PaintingHanger = 55,// delineated sizes in physics + TissueBoxEmpty = 54, // will be a state of TissuBox in physics + PaintingHanger = 55, // delineated sizes in physics KeyChain = 56, Dirt = 57, // physics will use a different cleaning system entirely CellPhone = 58, @@ -174,18 +176,18 @@ public enum SimObjType : int { ToiletPaper = 65, ToiletPaperHanger = 66, SoapBottle = 67, - SoapBottleFilled = 68,// DO NOT USE: Soap bottle now just has two states + SoapBottleFilled = 68, // DO NOT USE: Soap bottle now just has two states SoapBar = 69, ShowerDoor = 70, SprayBottle = 71, ScrubBrush = 72, - ToiletPaperRoll = 73,// DO NOT USE ANYMORE - ToiletPaper is now a single object that toggles states + ToiletPaperRoll = 73, // DO NOT USE ANYMORE - ToiletPaper is now a single object that toggles states Lamp = 74, // DO NOT USE: don't use this, use either FloorLamp or DeskLamp LightSwitch = 75, Bed = 76, Book = 77, AlarmClock = 78, - SportsEquipment = 79,// DO NOT USE: delineated into specific objects in physics - see Basketball etc + SportsEquipment = 79, // DO NOT USE: delineated into specific objects in physics - see Basketball etc Pen = 80, Pencil = 81, Blinds = 82, @@ -193,7 +195,7 @@ public enum SimObjType : int { TowelHolder = 84, Towel = 85, Watch = 86, - MiscTableObject = 87,// DO NOT USE: not sure what this is, not used for physics + MiscTableObject = 87, // DO NOT USE: not sure what this is, not used for physics ArmChair = 88, BaseballBat = 89, @@ -221,7 +223,7 @@ public enum SimObjType : int { PotLid = 111, SaltShaker = 112, Safe = 113, - SmallMirror = 114,// maybe don't use this, use just 'Mirror' instead + SmallMirror = 114, // maybe don't use this, use just 'Mirror' instead Sofa = 115, SoapContainer = 116, Spatula = 117, @@ -279,395 +281,1510 @@ public enum SimObjType : int { } public static class ReceptacleRestrictions { - // these objects generate ObjectIDs based on their parent object to show that they are related. ie: "Bathtub|1|1|1|" has a child sim object BathtubBasin with the ID "Bathtub|1|1|1|BathtubBasin" // this is specifically used for objects that have distinct zones that should be individually interactable (outer part vs inner part) but share the same geometry, like a bathtub. // Objets like a Coffeetable with inset Drawers should NOT be on this list because those objects do not share geometry (table vs drawer) public static List UseParentObjectIDasPrefix = new List() - {SimObjType.BathtubBasin,SimObjType.SinkBasin}; + { + SimObjType.BathtubBasin, + SimObjType.SinkBasin + }; // Objects are "placed into/placed in" these receptacles // The object placed must have the entirety of it's object oriented bounding box (all 8 corners) enclosed within the Receptacle's Box public static List InReceptacles = new List() - {SimObjType.Drawer, SimObjType.Cabinet, SimObjType.Fridge, SimObjType.Microwave, SimObjType.LaundryHamper, SimObjType.Box}; + { + SimObjType.Drawer, + SimObjType.Cabinet, + SimObjType.Fridge, + SimObjType.Microwave, + SimObjType.LaundryHamper, + SimObjType.Box + }; // Objects are "placed on top of/placed on" these receptacles // the object placed only needs the bottom most 4 corners within the Receptacle Box to be placed validly, this allows // things like a tall cup to have the top half of it sticking out of the receptacle box when placed on a table without requiring the table's receptacle box to be gigantic and unweildy public static List OnReceptacles = new List() - {SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.Desk, SimObjType.Dresser, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.ArmChair, - SimObjType.Sofa, SimObjType.Ottoman, SimObjType.StoveBurner,SimObjType.Bathtub, SimObjType.Plate, SimObjType.Floor}; + { + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.Desk, + SimObjType.Dresser, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.ArmChair, + SimObjType.Sofa, + SimObjType.Ottoman, + SimObjType.StoveBurner, + SimObjType.Bathtub, + SimObjType.Plate, + SimObjType.Floor + }; // Objects are "placed into/placed in" to these receptacles // while these receptacles have things placed "in" them, they use the logic of OnReceptacles - Only the bottom 4 corners must be within the // receptacle box for the placement to be valid. This means we can have a Spoon placed IN a cup, but the top half of the spoon is still allowed to stick out // this distinction is made in case we ever want to do some sort of semantic tests with placing things in/on instead of a generic "place" as the action descriptor - public static List InReceptaclesThatOnlyCheckBottomFourCorners = new List() - { SimObjType.Cup, SimObjType.Bowl, SimObjType.GarbageCan, SimObjType.Sink, SimObjType.BathtubBasin, SimObjType.Pan, SimObjType.Pot, }; - + public static List InReceptaclesThatOnlyCheckBottomFourCorners = + new List() + { + SimObjType.Cup, + SimObjType.Bowl, + SimObjType.GarbageCan, + SimObjType.Sink, + SimObjType.BathtubBasin, + SimObjType.Pan, + SimObjType.Pot, + }; public static List SpawnOnlyOutsideReceptacles = new List() { - SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.Desk, SimObjType.Dresser, SimObjType.CounterTop, SimObjType.Sofa, SimObjType.Bench, SimObjType.Bed, - SimObjType.Ottoman, SimObjType.StoveBurner, SimObjType.Shelf, SimObjType.Bathtub, SimObjType.Sink, SimObjType.BathtubBasin, SimObjType.SinkBasin, - SimObjType.CoffeeMachine, SimObjType.ToiletPaperHanger, SimObjType.Toilet, SimObjType.Floor, SimObjType.Chair, SimObjType.ArmChair, SimObjType.Footstool, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.Desk, + SimObjType.Dresser, + SimObjType.CounterTop, + SimObjType.Sofa, + SimObjType.Bench, + SimObjType.Bed, + SimObjType.Ottoman, + SimObjType.StoveBurner, + SimObjType.Shelf, + SimObjType.Bathtub, + SimObjType.Sink, + SimObjType.BathtubBasin, + SimObjType.SinkBasin, + SimObjType.CoffeeMachine, + SimObjType.ToiletPaperHanger, + SimObjType.Toilet, + SimObjType.Floor, + SimObjType.Chair, + SimObjType.ArmChair, + SimObjType.Footstool, }; // objects in this list should always return all spawn points inside of it when trying to place an object from the hand into the object // this elminiates the need for visibly seeing the bottommost point on the object, which would restrict the valid placement positions greatly due to these objects being viewed at extreme angles public static List ReturnAllPoints = new List() { - SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.GarbageCan, SimObjType.Plate, SimObjType.Box, SimObjType.Drawer, SimObjType.Mug, SimObjType.Cup, + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.GarbageCan, + SimObjType.Plate, + SimObjType.Box, + SimObjType.Drawer, + SimObjType.Mug, + SimObjType.Cup, }; // These receptacle sim objects MUST be in the open state before objects can be placed in them public static List MustBeOpenToPlaceObjectsIn = new List() { - SimObjType.Drawer, SimObjType.Cabinet, SimObjType.LaundryHamper, SimObjType.Microwave, SimObjType.Fridge, SimObjType.Box + SimObjType.Drawer, + SimObjType.Cabinet, + SimObjType.LaundryHamper, + SimObjType.Microwave, + SimObjType.Fridge, + SimObjType.Box }; // these objects should always be placed upright and not in weird angles. For example, you wouldn't place a pot sideways, you would always place // it with the opening facing up! public static List AlwaysPlaceUpright = new List() { - SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Plate, SimObjType.Bread, SimObjType.Cup, SimObjType.Mug, SimObjType.Laptop, - SimObjType.SaltShaker, SimObjType.PepperShaker, SimObjType.AlarmClock, SimObjType.Box, SimObjType.SoapBottle, SimObjType.SoapBottleFilled, SimObjType.Kettle, - SimObjType.Bottle, SimObjType.CreditCard, SimObjType.RemoteControl, SimObjType.Candle, SimObjType.SprayBottle, SimObjType.Statue, SimObjType.Vase, - SimObjType.KeyChain, SimObjType.CD, SimObjType.Book, SimObjType.EggCracked, SimObjType.Dumbbell, SimObjType.TableTopDecor + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Plate, + SimObjType.Bread, + SimObjType.Cup, + SimObjType.Mug, + SimObjType.Laptop, + SimObjType.SaltShaker, + SimObjType.PepperShaker, + SimObjType.AlarmClock, + SimObjType.Box, + SimObjType.SoapBottle, + SimObjType.SoapBottleFilled, + SimObjType.Kettle, + SimObjType.Bottle, + SimObjType.CreditCard, + SimObjType.RemoteControl, + SimObjType.Candle, + SimObjType.SprayBottle, + SimObjType.Statue, + SimObjType.Vase, + SimObjType.KeyChain, + SimObjType.CD, + SimObjType.Book, + SimObjType.EggCracked, + SimObjType.Dumbbell, + SimObjType.TableTopDecor }; // Each sim object type keeps track of what sort of Receptacles it can be placed in // add to this as more pickupable sim objects are created - public static Dictionary> PlacementRestrictions = new Dictionary>() + public static Dictionary> PlacementRestrictions = new Dictionary< + SimObjType, + List + >() { - // ALARM CLOCK - {SimObjType.AlarmClock, new List() - {SimObjType.Box, SimObjType.Dresser, SimObjType.Desk, SimObjType.SideTable, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.CounterTop, SimObjType.Shelf, - SimObjType.Chair, SimObjType.Stool}}, - - // APPLE - {SimObjType.Apple, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Microwave, SimObjType.Fridge, SimObjType.Plate, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.Desk, - SimObjType.CounterTop, SimObjType.GarbageCan, SimObjType.Dresser}}, - - // APPLE SLICED - {SimObjType.AppleSliced, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Microwave, SimObjType.Fridge, SimObjType.Plate, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.Desk, - SimObjType.CounterTop, SimObjType.GarbageCan, SimObjType.Dresser}}, - - // BASEBALL BAT - {SimObjType.BaseballBat, new List() - {SimObjType.Bed, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.Desk, SimObjType.CounterTop, SimObjType.Floor}}, /// place on floor? - - // BASKETBALL - {SimObjType.BasketBall, new List() - {SimObjType.Sofa, SimObjType.ArmChair, SimObjType.Dresser, SimObjType.Desk, SimObjType.Bed, SimObjType.DiningTable,SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, - SimObjType.Stool, SimObjType.Chair, SimObjType.Floor}}, - - // BOOK - {SimObjType.Book, new List() - {SimObjType.Sofa, SimObjType.ArmChair, SimObjType.Box, SimObjType.Ottoman, SimObjType.Dresser, SimObjType.Desk, SimObjType.Bed, SimObjType.Cabinet, SimObjType.DiningTable,SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, - SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, SimObjType.Stool, SimObjType.Chair, SimObjType.Floor}}, - - // BOOTS - {SimObjType.Boots, new List() + // ALARM CLOCK { - SimObjType.Floor// nothing yet? put on floor? - }}, - - // BOTTLE (Glassbottle) - {SimObjType.Bottle, new List() - {SimObjType.Fridge, SimObjType.Box, SimObjType.Dresser, SimObjType.Desk, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, - SimObjType.CounterTop, SimObjType.Shelf, SimObjType.GarbageCan, - }}, - - // BOWL - {SimObjType.Bowl, new List() - {SimObjType.Microwave, SimObjType.Fridge, SimObjType.Dresser, SimObjType.Desk, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, - SimObjType.CounterTop, SimObjType.Shelf, - }}, - - // BOX - {SimObjType.Box, new List() - {SimObjType.Sofa, SimObjType.ArmChair, SimObjType.Dresser, SimObjType.Desk, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Ottoman - ,SimObjType.Stool, SimObjType.Chair, SimObjType.Floor - }}, - - // BREAD - {SimObjType.Bread, new List() - {SimObjType.Microwave, SimObjType.Fridge, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.Desk, SimObjType.CounterTop, SimObjType.GarbageCan, SimObjType.Plate}}, - - // BREAD SLICED - {SimObjType.BreadSliced, new List() - {SimObjType.Microwave, SimObjType.Fridge, SimObjType.DiningTable,SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.Desk, SimObjType.CounterTop, SimObjType.GarbageCan, SimObjType.Toaster, SimObjType.Plate}}, - - // BUTTER KNIFE - {SimObjType.ButterKnife, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Mug, SimObjType.Plate, SimObjType.Cup, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.Desk, SimObjType.CounterTop, - SimObjType.Drawer}}, - - // CANDLE - {SimObjType.Candle, new List () - {SimObjType.Box, SimObjType.Dresser, SimObjType.Desk, SimObjType.Toilet, SimObjType.Cart, SimObjType.Bathtub, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, - SimObjType.Shelf, SimObjType.Drawer, SimObjType.Stool, SimObjType.Chair - }}, - - // CD - {SimObjType.CD, new List() - {SimObjType.Box, SimObjType.Ottoman, SimObjType.Dresser, SimObjType.Desk, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, - SimObjType.GarbageCan, SimObjType.Safe, SimObjType.Sofa, SimObjType.ArmChair, SimObjType.Stool, SimObjType.Chair, SimObjType.Footstool}}, - - // CELL PHONE - {SimObjType.CellPhone, new List() - {SimObjType.Sofa, SimObjType.ArmChair, SimObjType.Box, SimObjType.Ottoman, SimObjType.Dresser, SimObjType.Desk, SimObjType.Bed, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, - SimObjType.Shelf, SimObjType.Drawer, SimObjType.Safe, SimObjType.Stool, SimObjType.Chair, SimObjType.Footstool, - }}, - - // CLOTH - {SimObjType.Cloth, new List() - {SimObjType.Sofa, SimObjType.ArmChair, SimObjType.Box, SimObjType.Ottoman, SimObjType.Dresser, SimObjType.LaundryHamper, SimObjType.Desk, SimObjType.Toilet, SimObjType.Cart, - SimObjType.BathtubBasin, SimObjType.Bathtub, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, - SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, SimObjType.GarbageCan, SimObjType.Stool, SimObjType.Chair, SimObjType.Footstool, SimObjType.Floor - }}, - - // CREDIT CARD - {SimObjType.CreditCard, new List() - {SimObjType.Sofa, SimObjType.ArmChair, SimObjType.Box, SimObjType.Ottoman, SimObjType.Dresser, SimObjType.Desk, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, - SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, SimObjType.Shelf, SimObjType.Stool, SimObjType.Chair, SimObjType.Footstool,}}, - - // CUP - {SimObjType.Cup, new List() - {SimObjType.Microwave, SimObjType.Fridge, SimObjType.Dresser, SimObjType.Desk, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, - SimObjType.CounterTop, SimObjType.Shelf }}, // might want to add this to coffee machines later, but right now they don't fit, only mugs were created to fit coffee machines initially - - // DISH SPONGE - {SimObjType.DishSponge, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Plate, SimObjType.Box, SimObjType.Toilet, SimObjType.Cart, SimObjType.Cart, SimObjType.BathtubBasin, SimObjType.Bathtub, SimObjType.Sink, - SimObjType.SinkBasin, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, SimObjType.GarbageCan}}, - - // EGG - {SimObjType.Egg, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Microwave, SimObjType.Fridge, SimObjType.Plate, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, - SimObjType.CounterTop, SimObjType.GarbageCan}}, - - // EGG CRACKED - {SimObjType.EggCracked, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Microwave, SimObjType.Fridge, SimObjType.Plate, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, - SimObjType.CounterTop, SimObjType.GarbageCan}}, - - // FORK - {SimObjType.Fork, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Mug, SimObjType.Plate, SimObjType.Cup, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, - SimObjType.CounterTop, SimObjType.Drawer,}}, - - // HAND TOWEL- small hand towel - {SimObjType.HandTowel, new List() - {SimObjType.HandTowelHolder,}}, - - // KETTLE - {SimObjType.Kettle, new List() - {SimObjType.DiningTable,SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.Cabinet, SimObjType.StoveBurner, SimObjType.Shelf}}, - - // KEYCHAIN - {SimObjType.KeyChain, new List() - {SimObjType.Sofa, SimObjType.ArmChair, SimObjType.Box, SimObjType.Ottoman, SimObjType.Dresser, SimObjType.Desk, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, - SimObjType.Safe, SimObjType.Stool, SimObjType.Chair}}, - - // KNIFE - Big chef's knife - {SimObjType.Knife, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Mug, SimObjType.Plate, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Drawer, }}, - - // LADLE - {SimObjType.Ladle, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Plate, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Drawer}}, - - // LAPTOP - {SimObjType.Laptop, new List() - {SimObjType.Sofa, SimObjType.ArmChair, SimObjType.Ottoman, SimObjType.Dresser, SimObjType.Desk, SimObjType.Bed, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, - SimObjType.Stool, SimObjType.Chair, SimObjType.Footstool,}}, - - // LETTUCE - {SimObjType.Lettuce, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Fridge, SimObjType.Plate, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.GarbageCan}}, - - // LETTUCE SLICED - {SimObjType.LettuceSliced, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Fridge, SimObjType.Plate, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.GarbageCan}}, - - // MUG - {SimObjType.Mug, new List() - {SimObjType.CoffeeMachine, SimObjType.Microwave, SimObjType.Fridge, SimObjType.Plate, SimObjType.Box, SimObjType.Dresser, SimObjType.Desk, SimObjType.Cart, SimObjType.Sink, - SimObjType.SinkBasin, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, - }}, - - // NEWSPAPER - {SimObjType.Newspaper, new List() - {SimObjType.Sofa, SimObjType.ArmChair, SimObjType.Ottoman, SimObjType.Dresser, SimObjType.Desk, SimObjType.Bed, SimObjType.Toilet, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, - SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, SimObjType.GarbageCan, SimObjType.Stool, SimObjType.Chair, SimObjType.Footstool, SimObjType.Floor - }}, - - // PAN - {SimObjType.Pan, new List() - {SimObjType.DiningTable, SimObjType.CounterTop, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.Cabinet, SimObjType.StoveBurner, SimObjType.Fridge}}, - - // PAPER TOWEL - {SimObjType.PaperTowelRoll, new List() - {SimObjType.Box, SimObjType.Toilet, SimObjType.Cart, SimObjType.Bathtub, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.GarbageCan}}, - - // PEN - {SimObjType.Pen, new List() - {SimObjType.Mug, SimObjType.Box, SimObjType.Dresser, SimObjType.Desk, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, SimObjType.GarbageCan, - SimObjType.Stool, SimObjType.Chair, SimObjType.Footstool,}}, - - // PENCIL - {SimObjType.Pencil, new List() - {SimObjType.Mug, SimObjType.Box, SimObjType.Dresser, SimObjType.Desk, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, SimObjType.GarbageCan, - SimObjType.Stool, SimObjType.Chair, SimObjType.Footstool,}}, - - // PEPPER SHAKER - {SimObjType.PepperShaker, new List() - {SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Drawer, SimObjType.Cabinet, SimObjType.Shelf}}, - - // PILLOW - {SimObjType.Pillow, new List() - {SimObjType.Sofa, SimObjType.ArmChair, SimObjType.Ottoman, SimObjType.Bed, SimObjType.Stool, SimObjType.Chair}}, - - // Plate - {SimObjType.Plate, new List() - {SimObjType.Microwave, SimObjType.Fridge, SimObjType.Dresser, SimObjType.Desk, SimObjType.Sink,SimObjType.Sink, SimObjType.SinkBasin, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, - SimObjType.CounterTop, SimObjType.Shelf - }}, - - // PLUNGER - {SimObjType.Plunger, new List() - {SimObjType.Cart, SimObjType.Cabinet, SimObjType.Floor}}, - - // POT - {SimObjType.Pot, new List() - {SimObjType.StoveBurner, SimObjType.Fridge, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf}}, - - // POTATO - {SimObjType.Potato, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Microwave, SimObjType.Fridge, SimObjType.Plate, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.GarbageCan}}, - - // POTATO SLICED - {SimObjType.PotatoSliced, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Microwave, SimObjType.Fridge, SimObjType.Plate, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.GarbageCan}}, - - // REMOTE CONTROL - {SimObjType.RemoteControl, new List() - {SimObjType.Sofa, SimObjType.ArmChair, SimObjType.Box, SimObjType.Ottoman, SimObjType.Dresser, SimObjType.Desk, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, - SimObjType.Drawer, SimObjType.Stool, SimObjType.Chair, SimObjType.Footstool,}}, - - // SALT SHAKER - {SimObjType.SaltShaker, new List() - {SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Drawer, SimObjType.Cabinet, SimObjType.Shelf}}, - - // SOAP BAR - {SimObjType.SoapBar, new List () - {SimObjType.Toilet, SimObjType.Cart, SimObjType.Bathtub, SimObjType.BathtubBasin, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, - SimObjType.Drawer, SimObjType.GarbageCan, - }}, - - // SOAP BOTTLE - {SimObjType.SoapBottle, new List () - {SimObjType.Dresser, SimObjType.Desk, SimObjType.Toilet, SimObjType.Cart, SimObjType.Bathtub, SimObjType.Sink, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, - SimObjType.Shelf, SimObjType.Drawer, SimObjType.GarbageCan, - }}, - - // SPATULA - {SimObjType.Spatula, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Plate, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Drawer,}}, - - // SPOON - {SimObjType.Spoon, new List() - {SimObjType.Pot, SimObjType.Pan, SimObjType.Bowl, SimObjType.Mug, SimObjType.Plate, SimObjType.Cup, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Drawer, }}, - - // SPRAY BOTTLE - {SimObjType.SprayBottle, new List () - {SimObjType.Dresser, SimObjType.Desk, SimObjType.Toilet, SimObjType.Cart, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, - SimObjType.GarbageCan - }}, - - // STATUE - {SimObjType.Statue, new List() - {SimObjType.Box, SimObjType.Dresser, SimObjType.Desk, SimObjType.Cart, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, - SimObjType.Safe,}}, - - // TEDDY BEAR - {SimObjType.TeddyBear, new List() - {SimObjType.Bed, SimObjType.Sofa, SimObjType.ArmChair, SimObjType.Ottoman, SimObjType.Dresser, SimObjType.Desk, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Safe, - SimObjType.Stool, SimObjType.Chair}}, - - // TENNIS RACKET - {SimObjType.TennisRacket, new List() - {SimObjType.Dresser, SimObjType.Desk, SimObjType.Bed, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Stool, SimObjType.Chair, SimObjType.Floor}}, /// place on floor? - - // TISSUE BOX - {SimObjType.TissueBox, new List() - {SimObjType.Box, SimObjType.Dresser, SimObjType.Desk, SimObjType.Toilet, SimObjType.Cart, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, - SimObjType.Drawer, SimObjType.GarbageCan, SimObjType.Stool, SimObjType.Chair, SimObjType.Footstool,}}, - - // TOILET PAPER - {SimObjType.ToiletPaper, new List () - {SimObjType.Dresser, SimObjType.Desk, SimObjType.Toilet, SimObjType.ToiletPaperHanger, SimObjType.Cart, SimObjType.Bathtub, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, - SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, SimObjType.GarbageCan, SimObjType.Stool, SimObjType.Chair - }}, - - // TOILET PAPER ROLL - should be same as Toilet Paper's list - {SimObjType.ToiletPaperRoll, new List () - {SimObjType.Dresser, SimObjType.Desk, SimObjType.Toilet, SimObjType.ToiletPaperHanger, SimObjType.Cart, SimObjType.Bathtub, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, - SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, SimObjType.GarbageCan, SimObjType.Stool - }}, - - // TOMATO - {SimObjType.Tomato, new List() - {SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.Pot, - SimObjType.Bowl, SimObjType.Fridge, SimObjType.GarbageCan, SimObjType.Plate}}, - - // TOMATO SLICED - {SimObjType.TomatoSliced, new List() - {SimObjType.DiningTable, SimObjType.CounterTop, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.Sink, SimObjType.SinkBasin, SimObjType.Pot, - SimObjType.Bowl, SimObjType.Fridge, SimObjType.GarbageCan, SimObjType.Plate}}, - - // TOWEL - large bath towel - {SimObjType.Towel, new List() - {SimObjType.TowelHolder,}}, - - // VASE - {SimObjType.Vase, new List() - {SimObjType.Box, SimObjType.Dresser, SimObjType.Desk, SimObjType.Cart, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Safe}}, - - // WATCH - {SimObjType.Watch, new List() - {SimObjType.Box, SimObjType.Dresser, SimObjType.Desk, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, SimObjType.Safe, SimObjType.Stool, - SimObjType.Chair, SimObjType.Footstool,}}, - - // WATERING CAN - {SimObjType.WateringCan, new List() - {SimObjType.Dresser, SimObjType.Desk, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Drawer, SimObjType.Stool, SimObjType.Chair, SimObjType.Floor}}, - - // WINE BOTTLE - {SimObjType.WineBottle, new List() - {SimObjType.Fridge, SimObjType.Dresser, SimObjType.Desk, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.GarbageCan}}, - - // DUMBBELL - {SimObjType.Dumbbell, new List() - {SimObjType.Dresser, SimObjType.Desk, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Bed, SimObjType.Chair, SimObjType.ArmChair, - SimObjType.Sofa, SimObjType.Stool, SimObjType.Footstool, SimObjType.Floor}}, - - // ALUMINUMFOIL - {SimObjType.AluminumFoil, new List() - {SimObjType.Dresser, SimObjType.Drawer, SimObjType.Desk, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf}}, - - // TABLETOP DECOR - {SimObjType.TableTopDecor, new List() - {SimObjType.Dresser, SimObjType.Desk, SimObjType.Cabinet, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable, SimObjType.CounterTop, SimObjType.Shelf}}, - + SimObjType.AlarmClock, + new List() + { + SimObjType.Box, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.SideTable, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Chair, + SimObjType.Stool + } + }, + // APPLE + { + SimObjType.Apple, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Microwave, + SimObjType.Fridge, + SimObjType.Plate, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.Desk, + SimObjType.CounterTop, + SimObjType.GarbageCan, + SimObjType.Dresser + } + }, + // APPLE SLICED + { + SimObjType.AppleSliced, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Microwave, + SimObjType.Fridge, + SimObjType.Plate, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.Desk, + SimObjType.CounterTop, + SimObjType.GarbageCan, + SimObjType.Dresser + } + }, + // BASEBALL BAT + { + SimObjType.BaseballBat, + new List() + { + SimObjType.Bed, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.Desk, + SimObjType.CounterTop, + SimObjType.Floor + } + }, + /// place on floor? + + // BASKETBALL + { + SimObjType.BasketBall, + new List() + { + SimObjType.Sofa, + SimObjType.ArmChair, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Bed, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Floor + } + }, + // BOOK + { + SimObjType.Book, + new List() + { + SimObjType.Sofa, + SimObjType.ArmChair, + SimObjType.Box, + SimObjType.Ottoman, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Bed, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Floor + } + }, + // BOOTS + { + SimObjType.Boots, + new List() + { + SimObjType.Floor // nothing yet? put on floor? + } + }, + // BOTTLE (Glassbottle) + { + SimObjType.Bottle, + new List() + { + SimObjType.Fridge, + SimObjType.Box, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.GarbageCan, + } + }, + // BOWL + { + SimObjType.Bowl, + new List() + { + SimObjType.Microwave, + SimObjType.Fridge, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + } + }, + // BOX + { + SimObjType.Box, + new List() + { + SimObjType.Sofa, + SimObjType.ArmChair, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Ottoman, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Floor + } + }, + // BREAD + { + SimObjType.Bread, + new List() + { + SimObjType.Microwave, + SimObjType.Fridge, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.Desk, + SimObjType.CounterTop, + SimObjType.GarbageCan, + SimObjType.Plate + } + }, + // BREAD SLICED + { + SimObjType.BreadSliced, + new List() + { + SimObjType.Microwave, + SimObjType.Fridge, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.Desk, + SimObjType.CounterTop, + SimObjType.GarbageCan, + SimObjType.Toaster, + SimObjType.Plate + } + }, + // BUTTER KNIFE + { + SimObjType.ButterKnife, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Mug, + SimObjType.Plate, + SimObjType.Cup, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.Desk, + SimObjType.CounterTop, + SimObjType.Drawer + } + }, + // CANDLE + { + SimObjType.Candle, + new List() + { + SimObjType.Box, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Toilet, + SimObjType.Cart, + SimObjType.Bathtub, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.Stool, + SimObjType.Chair + } + }, + // CD + { + SimObjType.CD, + new List() + { + SimObjType.Box, + SimObjType.Ottoman, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.GarbageCan, + SimObjType.Safe, + SimObjType.Sofa, + SimObjType.ArmChair, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Footstool + } + }, + // CELL PHONE + { + SimObjType.CellPhone, + new List() + { + SimObjType.Sofa, + SimObjType.ArmChair, + SimObjType.Box, + SimObjType.Ottoman, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Bed, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.Safe, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Footstool, + } + }, + // CLOTH + { + SimObjType.Cloth, + new List() + { + SimObjType.Sofa, + SimObjType.ArmChair, + SimObjType.Box, + SimObjType.Ottoman, + SimObjType.Dresser, + SimObjType.LaundryHamper, + SimObjType.Desk, + SimObjType.Toilet, + SimObjType.Cart, + SimObjType.BathtubBasin, + SimObjType.Bathtub, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.GarbageCan, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Footstool, + SimObjType.Floor + } + }, + // CREDIT CARD + { + SimObjType.CreditCard, + new List() + { + SimObjType.Sofa, + SimObjType.ArmChair, + SimObjType.Box, + SimObjType.Ottoman, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.Shelf, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Footstool, + } + }, + // CUP + { + SimObjType.Cup, + new List() + { + SimObjType.Microwave, + SimObjType.Fridge, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf + } + }, // might want to add this to coffee machines later, but right now they don't fit, only mugs were created to fit coffee machines initially + // DISH SPONGE + { + SimObjType.DishSponge, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Plate, + SimObjType.Box, + SimObjType.Toilet, + SimObjType.Cart, + SimObjType.Cart, + SimObjType.BathtubBasin, + SimObjType.Bathtub, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.GarbageCan + } + }, + // EGG + { + SimObjType.Egg, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Microwave, + SimObjType.Fridge, + SimObjType.Plate, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.GarbageCan + } + }, + // EGG CRACKED + { + SimObjType.EggCracked, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Microwave, + SimObjType.Fridge, + SimObjType.Plate, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.GarbageCan + } + }, + // FORK + { + SimObjType.Fork, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Mug, + SimObjType.Plate, + SimObjType.Cup, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Drawer, + } + }, + // HAND TOWEL- small hand towel + { + SimObjType.HandTowel, + new List() { SimObjType.HandTowelHolder, } + }, + // KETTLE + { + SimObjType.Kettle, + new List() + { + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Cabinet, + SimObjType.StoveBurner, + SimObjType.Shelf + } + }, + // KEYCHAIN + { + SimObjType.KeyChain, + new List() + { + SimObjType.Sofa, + SimObjType.ArmChair, + SimObjType.Box, + SimObjType.Ottoman, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.Safe, + SimObjType.Stool, + SimObjType.Chair + } + }, + // KNIFE - Big chef's knife + { + SimObjType.Knife, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Mug, + SimObjType.Plate, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Drawer, + } + }, + // LADLE + { + SimObjType.Ladle, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Plate, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Drawer + } + }, + // LAPTOP + { + SimObjType.Laptop, + new List() + { + SimObjType.Sofa, + SimObjType.ArmChair, + SimObjType.Ottoman, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Bed, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Footstool, + } + }, + // LETTUCE + { + SimObjType.Lettuce, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Fridge, + SimObjType.Plate, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.GarbageCan + } + }, + // LETTUCE SLICED + { + SimObjType.LettuceSliced, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Fridge, + SimObjType.Plate, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.GarbageCan + } + }, + // MUG + { + SimObjType.Mug, + new List() + { + SimObjType.CoffeeMachine, + SimObjType.Microwave, + SimObjType.Fridge, + SimObjType.Plate, + SimObjType.Box, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Cart, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + } + }, + // NEWSPAPER + { + SimObjType.Newspaper, + new List() + { + SimObjType.Sofa, + SimObjType.ArmChair, + SimObjType.Ottoman, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Bed, + SimObjType.Toilet, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.GarbageCan, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Footstool, + SimObjType.Floor + } + }, + // PAN + { + SimObjType.Pan, + new List() + { + SimObjType.DiningTable, + SimObjType.CounterTop, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Cabinet, + SimObjType.StoveBurner, + SimObjType.Fridge + } + }, + // PAPER TOWEL + { + SimObjType.PaperTowelRoll, + new List() + { + SimObjType.Box, + SimObjType.Toilet, + SimObjType.Cart, + SimObjType.Bathtub, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.GarbageCan + } + }, + // PEN + { + SimObjType.Pen, + new List() + { + SimObjType.Mug, + SimObjType.Box, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.GarbageCan, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Footstool, + } + }, + // PENCIL + { + SimObjType.Pencil, + new List() + { + SimObjType.Mug, + SimObjType.Box, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.GarbageCan, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Footstool, + } + }, + // PEPPER SHAKER + { + SimObjType.PepperShaker, + new List() + { + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Drawer, + SimObjType.Cabinet, + SimObjType.Shelf + } + }, + // PILLOW + { + SimObjType.Pillow, + new List() + { + SimObjType.Sofa, + SimObjType.ArmChair, + SimObjType.Ottoman, + SimObjType.Bed, + SimObjType.Stool, + SimObjType.Chair + } + }, + // Plate + { + SimObjType.Plate, + new List() + { + SimObjType.Microwave, + SimObjType.Fridge, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Sink, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf + } + }, + // PLUNGER + { + SimObjType.Plunger, + new List() { SimObjType.Cart, SimObjType.Cabinet, SimObjType.Floor } + }, + // POT + { + SimObjType.Pot, + new List() + { + SimObjType.StoveBurner, + SimObjType.Fridge, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf + } + }, + // POTATO + { + SimObjType.Potato, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Microwave, + SimObjType.Fridge, + SimObjType.Plate, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.GarbageCan + } + }, + // POTATO SLICED + { + SimObjType.PotatoSliced, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Microwave, + SimObjType.Fridge, + SimObjType.Plate, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.GarbageCan + } + }, + // REMOTE CONTROL + { + SimObjType.RemoteControl, + new List() + { + SimObjType.Sofa, + SimObjType.ArmChair, + SimObjType.Box, + SimObjType.Ottoman, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Footstool, + } + }, + // SALT SHAKER + { + SimObjType.SaltShaker, + new List() + { + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Drawer, + SimObjType.Cabinet, + SimObjType.Shelf + } + }, + // SOAP BAR + { + SimObjType.SoapBar, + new List() + { + SimObjType.Toilet, + SimObjType.Cart, + SimObjType.Bathtub, + SimObjType.BathtubBasin, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.GarbageCan, + } + }, + // SOAP BOTTLE + { + SimObjType.SoapBottle, + new List() + { + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Toilet, + SimObjType.Cart, + SimObjType.Bathtub, + SimObjType.Sink, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.GarbageCan, + } + }, + // SPATULA + { + SimObjType.Spatula, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Plate, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Drawer, + } + }, + // SPOON + { + SimObjType.Spoon, + new List() + { + SimObjType.Pot, + SimObjType.Pan, + SimObjType.Bowl, + SimObjType.Mug, + SimObjType.Plate, + SimObjType.Cup, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Drawer, + } + }, + // SPRAY BOTTLE + { + SimObjType.SprayBottle, + new List() + { + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Toilet, + SimObjType.Cart, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.GarbageCan + } + }, + // STATUE + { + SimObjType.Statue, + new List() + { + SimObjType.Box, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Cart, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Safe, + } + }, + // TEDDY BEAR + { + SimObjType.TeddyBear, + new List() + { + SimObjType.Bed, + SimObjType.Sofa, + SimObjType.ArmChair, + SimObjType.Ottoman, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Safe, + SimObjType.Stool, + SimObjType.Chair + } + }, + // TENNIS RACKET + { + SimObjType.TennisRacket, + new List() + { + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Bed, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Floor + } + }, + /// place on floor? + + // TISSUE BOX + { + SimObjType.TissueBox, + new List() + { + SimObjType.Box, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Toilet, + SimObjType.Cart, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.GarbageCan, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Footstool, + } + }, + // TOILET PAPER + { + SimObjType.ToiletPaper, + new List() + { + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Toilet, + SimObjType.ToiletPaperHanger, + SimObjType.Cart, + SimObjType.Bathtub, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.GarbageCan, + SimObjType.Stool, + SimObjType.Chair + } + }, + // TOILET PAPER ROLL - should be same as Toilet Paper's list + { + SimObjType.ToiletPaperRoll, + new List() + { + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Toilet, + SimObjType.ToiletPaperHanger, + SimObjType.Cart, + SimObjType.Bathtub, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.GarbageCan, + SimObjType.Stool + } + }, + // TOMATO + { + SimObjType.Tomato, + new List() + { + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Pot, + SimObjType.Bowl, + SimObjType.Fridge, + SimObjType.GarbageCan, + SimObjType.Plate + } + }, + // TOMATO SLICED + { + SimObjType.TomatoSliced, + new List() + { + SimObjType.DiningTable, + SimObjType.CounterTop, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.Sink, + SimObjType.SinkBasin, + SimObjType.Pot, + SimObjType.Bowl, + SimObjType.Fridge, + SimObjType.GarbageCan, + SimObjType.Plate + } + }, + // TOWEL - large bath towel + { + SimObjType.Towel, + new List() { SimObjType.TowelHolder, } + }, + // VASE + { + SimObjType.Vase, + new List() + { + SimObjType.Box, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Cart, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Safe + } + }, + // WATCH + { + SimObjType.Watch, + new List() + { + SimObjType.Box, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.Safe, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Footstool, + } + }, + // WATERING CAN + { + SimObjType.WateringCan, + new List() + { + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Drawer, + SimObjType.Stool, + SimObjType.Chair, + SimObjType.Floor + } + }, + // WINE BOTTLE + { + SimObjType.WineBottle, + new List() + { + SimObjType.Fridge, + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.GarbageCan + } + }, + // DUMBBELL + { + SimObjType.Dumbbell, + new List() + { + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Bed, + SimObjType.Chair, + SimObjType.ArmChair, + SimObjType.Sofa, + SimObjType.Stool, + SimObjType.Footstool, + SimObjType.Floor + } + }, + // ALUMINUMFOIL + { + SimObjType.AluminumFoil, + new List() + { + SimObjType.Dresser, + SimObjType.Drawer, + SimObjType.Desk, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf + } + }, + // TABLETOP DECOR + { + SimObjType.TableTopDecor, + new List() + { + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.Cabinet, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf + } + }, // TARGET CIRCLE - for Moveable test and use with SpawnTargetCircles - {SimObjType.TargetCircle, new List() - {SimObjType.Dresser, SimObjType.Desk, SimObjType.DiningTable, SimObjType.TVStand, SimObjType.CoffeeTable, SimObjType.SideTable,SimObjType.CounterTop, SimObjType.Shelf, SimObjType.Floor}}, - + { + SimObjType.TargetCircle, + new List() + { + SimObjType.Dresser, + SimObjType.Desk, + SimObjType.DiningTable, + SimObjType.TVStand, + SimObjType.CoffeeTable, + SimObjType.SideTable, + SimObjType.CounterTop, + SimObjType.Shelf, + SimObjType.Floor + } + }, }; - } diff --git a/unity/Assets/Scripts/SimTesting.cs b/unity/Assets/Scripts/SimTesting.cs index 726da18b64..2f3f109eb2 100644 --- a/unity/Assets/Scripts/SimTesting.cs +++ b/unity/Assets/Scripts/SimTesting.cs @@ -1,11 +1,10 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; -using System.Collections; using System; +using System.Collections; +using UnityEngine; // class for testing SimUtil functions public class SimTesting : MonoBehaviour { - public enum TestMethod { SpherecastAll, CheckVisibility, @@ -25,6 +24,7 @@ public enum TestMethod { public float SpherecastRadius; public Camera Cam; RaycastHit hit; + // RaycastHit[] hits = new RaycastHit[MaxHits]; public Vector3 placementPoint; public bool foundPlacementPoint; @@ -50,12 +50,20 @@ void OnGUI() { GUILayout.BeginHorizontal(); horzIndex = 0; } - GUILayout.Button(o.ObjectID, UnityEditor.EditorStyles.miniButton, GUILayout.MaxWidth(200f)); + GUILayout.Button( + o.ObjectID, + UnityEditor.EditorStyles.miniButton, + GUILayout.MaxWidth(200f) + ); } GUILayout.EndHorizontal(); } else { foreach (SimObj o in SimObjsInView) { - GUILayout.Button(o.ObjectID, UnityEditor.EditorStyles.miniButton, GUILayout.MinWidth(100f)); + GUILayout.Button( + o.ObjectID, + UnityEditor.EditorStyles.miniButton, + GUILayout.MinWidth(100f) + ); } } } @@ -73,9 +81,15 @@ void OnDisable() { #endif void Update() { - // check for a navmesh hit - foundPlacementPoint = PlacementManager.GetPlacementPoint(transform.position, Cam.transform.forward, Cam, ReachDistance, MaxPlaceDistance, ref placementPoint); + foundPlacementPoint = PlacementManager.GetPlacementPoint( + transform.position, + Cam.transform.forward, + Cam, + ReachDistance, + MaxPlaceDistance, + ref placementPoint + ); if (inventoryObject != null && Input.GetKeyDown(KeyCode.P)) { if (inventoryObject.gameObject.activeSelf) { @@ -94,7 +108,6 @@ void Update() { break; } - // resize the array to avoid confusion in the test if (SimObjsInView.Length != NumItems) { Array.Resize(ref SimObjsInView, NumItems); @@ -106,13 +119,22 @@ void OnDrawGizmos() { Gizmos.DrawSphere(Cam.transform.position, 0.1f); Gizmos.color = Color.grey; Gizmos.DrawWireSphere(Cam.transform.position, SpherecastRadius); - Gizmos.DrawWireSphere(Cam.transform.position + (Cam.transform.forward * MaxDistance), SpherecastRadius); - Gizmos.DrawLine(Cam.transform.position, Cam.transform.position + (Cam.transform.forward * MaxDistance)); + Gizmos.DrawWireSphere( + Cam.transform.position + (Cam.transform.forward * MaxDistance), + SpherecastRadius + ); + Gizmos.DrawLine( + Cam.transform.position, + Cam.transform.position + (Cam.transform.forward * MaxDistance) + ); Gizmos.color = foundPlacementPoint ? Color.green : Color.gray; Gizmos.DrawSphere(transform.position + (Cam.transform.forward * ReachDistance), 0.05f); if (foundPlacementPoint) { - Gizmos.DrawLine(transform.position + (Cam.transform.forward * ReachDistance), placementPoint); + Gizmos.DrawLine( + transform.position + (Cam.transform.forward * ReachDistance), + placementPoint + ); Gizmos.DrawWireCube(placementPoint, Vector3.one * 0.05f); } } diff --git a/unity/Assets/Scripts/SimUtil.cs b/unity/Assets/Scripts/SimUtil.cs index e9a7dcabd1..f0d4d3bdb5 100644 --- a/unity/Assets/Scripts/SimUtil.cs +++ b/unity/Assets/Scripts/SimUtil.cs @@ -1,14 +1,13 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; -using System.Collections; using System; -using System.Linq; +using System.Collections; using System.Collections.Generic; +using System.Linq; using UnityEditor; +using UnityEngine; using UnityEngine.SceneManagement; public static class SimUtil { - // how fast smooth-animated s / cabinets / etc animate public const float SmoothAnimationSpeed = 0.5f; @@ -18,12 +17,12 @@ public static class SimUtil { public const int RaycastHiddenLayerMask = 1 << RaycastHiddenLayer; public const string ReceptacleTag = "Receptacle"; public const string SimObjTag = "SimObj"; - public const string StructureTag = "Structure";// what is this used for? + public const string StructureTag = "Structure"; // what is this used for? public const float ViewPointRangeHigh = 1f; public const float ViewPointRangeLow = 0f; public const int VisibilityCheckSteps = 10; - public const float DownwardRangeExtension = 2.0f;// 1.45f; changed this so the agent can see low enough to open all drawers + public const float DownwardRangeExtension = 2.0f; // 1.45f; changed this so the agent can see low enough to open all drawers public const float MinDownwardLooKangle = 15f; public const float MaxDownwardLookAngle = 60f; @@ -50,7 +49,6 @@ public static SimObj[] GetAllVisibleSimObjs(Camera agentCamera, float maxDistanc } } - #endif // the final list of visible items List items = new List(); @@ -59,13 +57,20 @@ public static SimObj[] GetAllVisibleSimObjs(Camera agentCamera, float maxDistanc HashSet uniqueItems = new HashSet(); - // get a list of all the colliders we intersect with in a sphere Vector3 agentCameraPos = agentCamera.transform.position; - Collider[] colliders = Physics.OverlapSphere(agentCameraPos, maxDistance * DownwardRangeExtension, SimUtil.RaycastVisibleLayerMask, QueryTriggerInteraction.Collide); + Collider[] colliders = Physics.OverlapSphere( + agentCameraPos, + maxDistance * DownwardRangeExtension, + SimUtil.RaycastVisibleLayerMask, + QueryTriggerInteraction.Collide + ); // go through them one by one and determine if they're actually simObjs for (int i = 0; i < colliders.Length; i++) { - if (colliders[i].CompareTag(SimUtil.SimObjTag) || colliders[i].CompareTag(SimUtil.ReceptacleTag)) { + if ( + colliders[i].CompareTag(SimUtil.SimObjTag) + || colliders[i].CompareTag(SimUtil.ReceptacleTag) + ) { SimObj o = null; if (GetSimObjFromCollider(colliders[i], out o)) { // this may result in duplicates because of 'open' receptacles @@ -78,7 +83,6 @@ public static SimObj[] GetAllVisibleSimObjs(Camera agentCamera, float maxDistanc // now check to see if they're actually visible RaycastHit hit = new RaycastHit(); foreach (SimObj item in uniqueItems) { - if (!CheckItemBounds(item, agentCameraPos)) { // if the camera isn't in bounds, skip this item continue; @@ -98,7 +102,8 @@ public static SimObj[] GetAllVisibleSimObjs(Camera agentCamera, float maxDistanc SimUtil.RaycastVisibleLayerMask, true, maxDistance, - out hit); + out hit + ); // if we can see it no need for more checks! if (canSeeItem) { break; @@ -110,13 +115,18 @@ public static SimObj[] GetAllVisibleSimObjs(Camera agentCamera, float maxDistanc for (int i = 0; i < VisibilityCheckSteps; i++) { canSeeItem = CheckPointVisibility( item, - Vector3.Lerp(item.TopPoint, item.BottomPoint, (float)i / VisibilityCheckSteps), + Vector3.Lerp( + item.TopPoint, + item.BottomPoint, + (float)i / VisibilityCheckSteps + ), agentCamera, agentCameraPos, SimUtil.RaycastVisibleLayerMask, true, maxDistance, - out hit); + out hit + ); // if we can see it no need for more checks! if (canSeeItem) { @@ -134,12 +144,24 @@ public static SimObj[] GetAllVisibleSimObjs(Camera agentCamera, float maxDistanc // now check to see if it's a receptacle interior if (item.IsReceptacle && hit.collider.CompareTag(SimUtil.ReceptacleTag)) { // if it is, add the items in the receptacle as well - items.AddRange(GetVisibleItemsFromReceptacle(item.Receptacle, agentCamera, agentCameraPos, maxDistance)); + items.AddRange( + GetVisibleItemsFromReceptacle( + item.Receptacle, + agentCamera, + agentCameraPos, + maxDistance + ) + ); } } } // now sort the items by distance to camera - items.Sort((x, y) => Vector3.Distance(x.transform.position, agentCameraPos).CompareTo(Vector3.Distance(y.transform.position, agentCameraPos))); + items.Sort( + (x, y) => + Vector3 + .Distance(x.transform.position, agentCameraPos) + .CompareTo(Vector3.Distance(y.transform.position, agentCameraPos)) + ); // we're done! return items.ToArray(); } @@ -147,9 +169,13 @@ public static SimObj[] GetAllVisibleSimObjs(Camera agentCamera, float maxDistanc // checks whether a point is in view of the camera public static bool CheckPointVisibility(Vector3 itemTargetPoint, Camera agentCamera) { Vector3 viewPoint = agentCamera.WorldToViewportPoint(itemTargetPoint); - if (viewPoint.z > 0// in front of camera - && viewPoint.x < ViewPointRangeHigh && viewPoint.x > ViewPointRangeLow// within x bounds - && viewPoint.y < ViewPointRangeHigh && viewPoint.y > ViewPointRangeLow) { // within y bounds + if ( + viewPoint.z > 0 // in front of camera + && viewPoint.x < ViewPointRangeHigh + && viewPoint.x > ViewPointRangeLow // within x bounds + && viewPoint.y < ViewPointRangeHigh + && viewPoint.y > ViewPointRangeLow + ) { // within y bounds return true; } return false; @@ -157,13 +183,26 @@ public static bool CheckPointVisibility(Vector3 itemTargetPoint, Camera agentCam // checks whether a point is in view of the camera // and whether it can be seen via raycast - static bool CheckPointVisibility(SimObj item, Vector3 itemTargetPoint, Camera agentCamera, Vector3 agentCameraPos, int raycastLayerMask, bool checkTrigger, float maxDistance, out RaycastHit hit) { + static bool CheckPointVisibility( + SimObj item, + Vector3 itemTargetPoint, + Camera agentCamera, + Vector3 agentCameraPos, + int raycastLayerMask, + bool checkTrigger, + float maxDistance, + out RaycastHit hit + ) { hit = new RaycastHit(); Vector3 viewPoint = agentCamera.WorldToViewportPoint(itemTargetPoint); - if (viewPoint.z > 0// in front of camera - && viewPoint.x < ViewPointRangeHigh && viewPoint.x > ViewPointRangeLow// within x bounds - && viewPoint.y < ViewPointRangeHigh && viewPoint.y > ViewPointRangeLow) { // within y bounds + if ( + viewPoint.z > 0 // in front of camera + && viewPoint.x < ViewPointRangeHigh + && viewPoint.x > ViewPointRangeLow // within x bounds + && viewPoint.y < ViewPointRangeHigh + && viewPoint.y > ViewPointRangeLow + ) { // within y bounds Vector3 itemDirection = Vector3.zero; // do a raycast in the direction of the item itemDirection = (itemTargetPoint - agentCameraPos).normalized; @@ -174,21 +213,41 @@ static bool CheckPointVisibility(SimObj item, Vector3 itemTargetPoint, Camera ag agentForward.Normalize(); // clap the angle so we can't wrap around float maxDistanceLerp = 0f; - float lookAngle = Mathf.Clamp(Vector3.Angle(agentForward, itemDirection), 0f, MaxDownwardLookAngle) - MinDownwardLooKangle; + float lookAngle = + Mathf.Clamp(Vector3.Angle(agentForward, itemDirection), 0f, MaxDownwardLookAngle) + - MinDownwardLooKangle; maxDistanceLerp = lookAngle / MaxDownwardLookAngle; - maxDistance = Mathf.Lerp(maxDistance, maxDistance * DownwardRangeExtension, maxDistanceLerp); + maxDistance = Mathf.Lerp( + maxDistance, + maxDistance * DownwardRangeExtension, + maxDistanceLerp + ); // try to raycast for the object - if (Physics.Raycast( + if ( + Physics.Raycast( agentCameraPos, itemDirection, out hit, maxDistance, raycastLayerMask, - (checkTrigger ? QueryTriggerInteraction.Collide : QueryTriggerInteraction.Ignore))) { + ( + checkTrigger + ? QueryTriggerInteraction.Collide + : QueryTriggerInteraction.Ignore + ) + ) + ) { // check to see if we hit the item we're after - if (hit.collider.attachedRigidbody != null && hit.collider.attachedRigidbody.gameObject == item.gameObject) { + if ( + hit.collider.attachedRigidbody != null + && hit.collider.attachedRigidbody.gameObject == item.gameObject + ) { #if UNITY_EDITOR - Debug.DrawLine(agentCameraPos, hit.point, Color.Lerp(Color.green, Color.blue, maxDistanceLerp)); + Debug.DrawLine( + agentCameraPos, + hit.point, + Color.Lerp(Color.green, Color.blue, maxDistanceLerp) + ); #endif return true; } @@ -222,7 +281,9 @@ public static bool PutItemBackInStartupPosition(SimObj item) { item.gameObject.SetActive(true); result = true; } else { - Debug.LogWarning("Item had no startup transform. This probably means it was spawned in a receptacle."); + Debug.LogWarning( + "Item had no startup transform. This probably means it was spawned in a receptacle." + ); } break; @@ -258,7 +319,10 @@ public static bool CheckItemBounds(SimObj item, Vector3 agentPosition) { // use the item's bounds transform as a bounding box // this is NOT axis-aligned so objects rotated strangely may return unexpected results // but it should work for 99% of cases - Bounds itemBounds = new Bounds(item.BoundsTransform.position, item.BoundsTransform.lossyScale); + Bounds itemBounds = new Bounds( + item.BoundsTransform.position, + item.BoundsTransform.lossyScale + ); return itemBounds.Contains(agentPosition); } @@ -294,7 +358,11 @@ public static bool FindItemFromReceptacleByID(string itemID, Receptacle r, out S // searches for a SimObj item under a receptacle by ID // this does not TAKE the item, it just searches for it - public static bool FindItemFromReceptacleByType(SimObjType itemType, Receptacle r, out SimObj item) { + public static bool FindItemFromReceptacleByType( + SimObjType itemType, + Receptacle r, + out SimObj item + ) { item = null; // make sure we're not doing something insane if (r == null) { @@ -347,7 +415,6 @@ public static bool AddItemToVisibleReceptacle(SimObj item, Receptacle r, Camera return AddItemToReceptaclePivot(item, emptyPivot); } - // adds the item to a receptacle // enabled the object, parents it under an empty pivot, then makes it invisible to raycasts // returns false if there are no available pivots in the receptacle @@ -378,14 +445,17 @@ public static bool AddItemToReceptacle(SimObj item, Receptacle r) { // enabled the object, parents it under an empty pivot, then makes it invisible to raycasts // returns false if there are no available pivots in the receptacle public static bool AddItemToReceptaclePivot(SimObj item, Transform pivot) { - if (item == null) { Debug.LogError("SimObj item was null in AddItemToReceptaclePivot, not adding"); return false; } if (pivot == null) { - Debug.LogError("Pivot was null when attempting to add item " + item.name + " to Receptacle pivot, not adding"); + Debug.LogError( + "Pivot was null when attempting to add item " + + item.name + + " to Receptacle pivot, not adding" + ); return false; } @@ -417,8 +487,11 @@ public static bool GetFirstEmptyReceptaclePivot(Receptacle r, out Transform empt return emptyPivot != null; } - - public static bool GetFirstEmptyVisibleReceptaclePivot(Receptacle r, Camera camera, out Transform emptyPivot) { + public static bool GetFirstEmptyVisibleReceptaclePivot( + Receptacle r, + Camera camera, + out Transform emptyPivot + ) { Plane[] planes = GeometryUtility.CalculateFrustumPlanes(camera); emptyPivot = null; @@ -470,7 +543,12 @@ public static SimObj[] GetItemsFromReceptacle(Receptacle r) { // gets all VISIBILE SimObjs contained in a receptacle // this does not TAKE any of these items - public static SimObj[] GetVisibleItemsFromReceptacle(Receptacle r, Camera agentCamera, Vector3 agentCameraPos, float maxDistance) { + public static SimObj[] GetVisibleItemsFromReceptacle( + Receptacle r, + Camera agentCamera, + Vector3 agentCameraPos, + float maxDistance + ) { List items = new List(); // RaycastHit hit = new RaycastHit(); foreach (Transform t in r.Pivots) { @@ -517,7 +595,13 @@ public static void SetUpBaseObjects() { } } - public static void BuildScene(string scenePath, string buildName, string outputPath, UnityEditor.BuildTarget buildTarget, bool launchOnBuild) { + public static void BuildScene( + string scenePath, + string buildName, + string outputPath, + UnityEditor.BuildTarget buildTarget, + bool launchOnBuild + ) { Debug.Log("Building scene '" + scenePath + "' to '" + outputPath + "'"); // set up the player correctly UnityEditor.PlayerSettings.companyName = "Allen Institute for Artificial Intelligence"; @@ -534,12 +618,14 @@ public static void BuildScene(string scenePath, string buildName, string outputP UnityEditor.PlayerSettings.allowFullscreenSwitch = true; UnityEditor.BuildPipeline.BuildPlayer( - new UnityEditor.EditorBuildSettingsScene[] { - new UnityEditor.EditorBuildSettingsScene (scenePath, true) + new UnityEditor.EditorBuildSettingsScene[] + { + new UnityEditor.EditorBuildSettingsScene(scenePath, true) }, System.IO.Path.Combine(outputPath, buildName), buildTarget, - launchOnBuild ? UnityEditor.BuildOptions.AutoRunPlayer : UnityEditor.BuildOptions.None); + launchOnBuild ? UnityEditor.BuildOptions.AutoRunPlayer : UnityEditor.BuildOptions.None + ); } [UnityEditor.MenuItem("AI2-THOR/RandomizeMaterials/Bin Materials")] @@ -549,8 +635,12 @@ HashSet getMaterialsInScene() { HashSet sceneMaterials = new HashSet(); // Get all MeshRenderers under Objects and Structures groups - sceneMeshRenderers.UnionWith(GameObject.Find("Objects").GetComponentsInChildren()); - sceneMeshRenderers.UnionWith(GameObject.Find("Structure").GetComponentsInChildren()); + sceneMeshRenderers.UnionWith( + GameObject.Find("Objects").GetComponentsInChildren() + ); + sceneMeshRenderers.UnionWith( + GameObject.Find("Structure").GetComponentsInChildren() + ); // Get all shared Materials from MeshRenderers foreach (MeshRenderer meshRenderer in sceneMeshRenderers) { @@ -560,7 +650,10 @@ HashSet getMaterialsInScene() { return sceneMaterials; } - Dictionary> materialMetadata = new Dictionary>() { + Dictionary> materialMetadata = new Dictionary< + string, + HashSet + >() { ["RawTrainMaterials"] = new HashSet(), ["RawValMaterials"] = new HashSet(), ["RawTestMaterials"] = new HashSet(), @@ -646,16 +739,22 @@ HashSet getMaterialsInScene() { } // overrides the saved values on the prefab - UnityEditor.PrefabUtility.SaveAsPrefabAsset(instanceRoot: physicsSceneManager, assetPath: prefabPath); + UnityEditor.PrefabUtility.SaveAsPrefabAsset( + instanceRoot: physicsSceneManager, + assetPath: prefabPath + ); } - [UnityEditor.MenuItem("AI2-THOR/Replace Generic Prefabs in All Scenes")] static void ReplacePrefabsInAllScenes() { UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes(); for (int i = 1; i <= 30; i++) { string scenePath = "Assets/Scenes/FloorPlan" + i.ToString() + ".unity"; - UnityEditor.EditorUtility.DisplayProgressBar("Replacing generics...", scenePath, (1f / 30) * i); + UnityEditor.EditorUtility.DisplayProgressBar( + "Replacing generics...", + scenePath, + (1f / 30) * i + ); UnityEngine.SceneManagement.Scene openScene = new UnityEngine.SceneManagement.Scene(); try { openScene = UnityEditor.SceneManagement.EditorSceneManager.OpenScene(scenePath); @@ -680,7 +779,11 @@ static void SetSceneManagerSceneNumber() { UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes(); for (int i = 1; i <= 30; i++) { string scenePath = "Assets/Scenes/FloorPlan" + (i + 200).ToString() + ".unity"; - UnityEditor.EditorUtility.DisplayProgressBar("Setting scene numbers...", scenePath, (1f / 30) * i); + UnityEditor.EditorUtility.DisplayProgressBar( + "Setting scene numbers...", + scenePath, + (1f / 30) * i + ); UnityEngine.SceneManagement.Scene openScene = new UnityEngine.SceneManagement.Scene(); try { openScene = UnityEditor.SceneManagement.EditorSceneManager.OpenScene(scenePath); @@ -707,7 +810,9 @@ static void SetPivotScalesToOne() { if (t.name.Contains("Pivot")) { GameObject prefabParent = null; if (UnityEditor.EditorUtility.IsPersistent(t)) { - prefabParent = UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(t.gameObject) as GameObject; + prefabParent = + UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(t.gameObject) + as GameObject; } Transform pivot = t; Transform tempParent = pivot.parent; @@ -718,7 +823,12 @@ static void SetPivotScalesToOne() { } pivot.parent = null; if (pivot.localScale != Vector3.one) { - Debug.Log("Found pivot with non-uniform scale (" + pivot.localScale.ToString() + ") " + pivot.name); + Debug.Log( + "Found pivot with non-uniform scale (" + + pivot.localScale.ToString() + + ") " + + pivot.name + ); } pivot.localScale = Vector3.one; if (child != null) { @@ -727,31 +837,35 @@ static void SetPivotScalesToOne() { pivot.parent = tempParent; if (prefabParent != null) { Debug.Log("Reconnecting to " + prefabParent.name); - UnityEditor.PrefabUtility.RevertPrefabInstance(t.gameObject, UnityEditor.InteractionMode.AutomatedAction); + UnityEditor.PrefabUtility.RevertPrefabInstance( + t.gameObject, + UnityEditor.InteractionMode.AutomatedAction + ); } } } - UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEngine.SceneManagement.SceneManager.GetActiveScene());//(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene ()); - + UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty( + UnityEngine.SceneManagement.SceneManager.GetActiveScene() + ); //(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene ()); } [UnityEditor.MenuItem("AI2-THOR/Add Pickupable Objects to Physics Scene Manager")] static void AddPickupableObjectsToPhysicsSceneManager() { - PhysicsSceneManager physicsSceneManager = GameObject.FindObjectOfType(); - - SimObjPhysics[] simObjPhysicsArray = GameObject.FindObjectsOfType(); + PhysicsSceneManager physicsSceneManager = + GameObject.FindObjectOfType(); + SimObjPhysics[] simObjPhysicsArray = GameObject.FindObjectsOfType(); - if (physicsSceneManager.RequiredObjects.Count != 0 || physicsSceneManager.SpawnedObjects.Count != 0) - { + if ( + physicsSceneManager.RequiredObjects.Count != 0 + || physicsSceneManager.SpawnedObjects.Count != 0 + ) { physicsSceneManager.RequiredObjects.Clear(); physicsSceneManager.RequiredObjects.Clear(); } - foreach (SimObjPhysics simObj in simObjPhysicsArray) - { - if (simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup) - { + foreach (SimObjPhysics simObj in simObjPhysicsArray) { + if (simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup) { physicsSceneManager.RequiredObjects.Add(simObj.gameObject); physicsSceneManager.SpawnedObjects.Add(simObj.gameObject); } diff --git a/unity/Assets/Scripts/SliceObject.cs b/unity/Assets/Scripts/SliceObject.cs index 467bddd5af..7a80f9af98 100644 --- a/unity/Assets/Scripts/SliceObject.cs +++ b/unity/Assets/Scripts/SliceObject.cs @@ -1,9 +1,9 @@ using System.Collections; using System.Collections.Generic; +using System.IO; using UnityEngine; -using UnityStandardAssets.Characters.FirstPerson; using UnityEngine.Rendering; -using System.IO; +using UnityStandardAssets.Characters.FirstPerson; public class SliceObject : MonoBehaviour { // prefab that this object should change to when "sliced" @@ -23,8 +23,14 @@ public bool IsSliced() { void OnEnable() { #if UNITY_EDITOR // debug check for missing property - if (!gameObject.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeSliced)) { - Debug.LogError(gameObject.transform.name + " is missing the Secondary Property CanBeSliced!"); + if ( + !gameObject + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeSliced) + ) { + Debug.LogError( + gameObject.transform.name + " is missing the Secondary Property CanBeSliced!" + ); } if (ObjectToChangeTo == null) { @@ -43,14 +49,10 @@ void OnEnable() { } // Start is called before the first frame update - void Start() { - - } + void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } // action to be called from PhysicsRemoteFPSAgentController public void Slice() { @@ -71,7 +73,11 @@ public void Slice() { GameObject resultObject; - if (!gameObject.GetComponent().DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeCooked)) { + if ( + !gameObject + .GetComponent() + .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeCooked) + ) { // instantiate the normal object if this object is not cooked, otherwise.... resultObject = Instantiate( original: ObjectToChangeTo, @@ -81,7 +87,6 @@ public void Slice() { resultObject.transform.parent = GameObject.Find("Objects").transform; isSliced = true; } - // if the object can be cooked, check if it is cooked and then spawn the cooked object to change to, otherwise spawn the normal object else { // instantiate the normal object if this object is not cooked, otherwise.... @@ -99,20 +104,24 @@ public void Slice() { t.GetComponent().Cook(); } } - } - - PhysicsSceneManager psm = GameObject.Find("PhysicsSceneManager").GetComponent(); + PhysicsSceneManager psm = GameObject + .Find("PhysicsSceneManager") + .GetComponent(); if (psm != null) { // if the spawned object is not a sim object itself, but if it's holding a ton of sim objects let's go if (!resultObject.transform.GetComponent()) { - // each instantiated sliced version of the object is a bunch of sim objects held by a master parent transform, so go into each one and assign the id to each based on the parent's id so + // each instantiated sliced version of the object is a bunch of sim objects held by a master parent transform, so go into each one and assign the id to each based on the parent's id so // there is an association with the original source object int count = 0; foreach (Transform t in resultObject.transform) { SimObjPhysics tsop = t.GetComponent(); - psm.Generate_InheritedObjectID(gameObject.GetComponent(), tsop, count); + psm.Generate_InheritedObjectID( + gameObject.GetComponent(), + tsop, + count + ); count++; // also turn on the kinematics of this object @@ -124,7 +133,6 @@ public void Slice() { psm.AddToRBSInScene(trb); } } - // the spawned object is a sim object itself, so make an ID for it else { // quick if the result object is an egg hard set it's rotation because EGGS ARE WEIRD and are not the same form as their shelled version @@ -133,7 +141,11 @@ public void Slice() { } SimObjPhysics resultsop = resultObject.GetComponent(); - psm.Generate_InheritedObjectID(gameObject.GetComponent(), resultsop, 0); + psm.Generate_InheritedObjectID( + gameObject.GetComponent(), + resultsop, + 0 + ); Rigidbody resultrb = resultsop.GetComponent(); resultrb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; @@ -142,19 +154,20 @@ public void Slice() { // also add the spawned object's RB to the cache of all rigidbodies in scene psm.AddToRBSInScene(resultrb); } - } else { Debug.LogError("Physics Scene Manager object is missing from scene!"); } // if image synthesis is active, make sure to update the renderers for image synthesis since now there are new objects with renderes in the scene - BaseFPSAgentController primaryAgent = GameObject.Find("PhysicsSceneManager").GetComponent().PrimaryAgent; + BaseFPSAgentController primaryAgent = GameObject + .Find("PhysicsSceneManager") + .GetComponent() + .PrimaryAgent; if (primaryAgent.imageSynthesis) { if (primaryAgent.imageSynthesis.enabled) { primaryAgent.imageSynthesis.OnSceneChange(); } } - } // void OnApplicationQuit() diff --git a/unity/Assets/Scripts/SpongeClean.cs b/unity/Assets/Scripts/SpongeClean.cs index 80cd0945fa..d173766440 100644 --- a/unity/Assets/Scripts/SpongeClean.cs +++ b/unity/Assets/Scripts/SpongeClean.cs @@ -2,19 +2,13 @@ using System.Collections.Generic; using UnityEngine; -public class SpongeClean : MonoBehaviour -{ +public class SpongeClean : MonoBehaviour { // Start is called before the first frame update - void Start() - { - - } + void Start() { } // Update is called once per frame - void Update() - { + void Update() { } - } public void OnTriggerEnter(Collider other) { if (other.CompareTag("Dirt") || other.CompareTag("Pen")) { //other.transform.position = other.transform.position + new Vector3(0, 1.0f, 0); diff --git a/unity/Assets/Scripts/StandardShaderUtils.cs b/unity/Assets/Scripts/StandardShaderUtils.cs index 1a486ac470..3089a6267f 100644 --- a/unity/Assets/Scripts/StandardShaderUtils.cs +++ b/unity/Assets/Scripts/StandardShaderUtils.cs @@ -13,8 +13,14 @@ public enum BlendMode { public static void ChangeRenderMode(Material standardShaderMaterial, BlendMode blendMode) { switch (blendMode) { case BlendMode.Opaque: - standardShaderMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); - standardShaderMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); + standardShaderMaterial.SetInt( + "_SrcBlend", + (int)UnityEngine.Rendering.BlendMode.One + ); + standardShaderMaterial.SetInt( + "_DstBlend", + (int)UnityEngine.Rendering.BlendMode.Zero + ); standardShaderMaterial.SetInt("_ZWrite", 1); standardShaderMaterial.DisableKeyword("_ALPHATEST_ON"); standardShaderMaterial.DisableKeyword("_ALPHABLEND_ON"); @@ -22,8 +28,14 @@ public static void ChangeRenderMode(Material standardShaderMaterial, BlendMode b standardShaderMaterial.renderQueue = -1; break; case BlendMode.Cutout: - standardShaderMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); - standardShaderMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero); + standardShaderMaterial.SetInt( + "_SrcBlend", + (int)UnityEngine.Rendering.BlendMode.One + ); + standardShaderMaterial.SetInt( + "_DstBlend", + (int)UnityEngine.Rendering.BlendMode.Zero + ); standardShaderMaterial.SetInt("_ZWrite", 1); standardShaderMaterial.EnableKeyword("_ALPHATEST_ON"); standardShaderMaterial.DisableKeyword("_ALPHABLEND_ON"); @@ -31,8 +43,14 @@ public static void ChangeRenderMode(Material standardShaderMaterial, BlendMode b standardShaderMaterial.renderQueue = 2450; break; case BlendMode.Fade: - standardShaderMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); - standardShaderMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); + standardShaderMaterial.SetInt( + "_SrcBlend", + (int)UnityEngine.Rendering.BlendMode.SrcAlpha + ); + standardShaderMaterial.SetInt( + "_DstBlend", + (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha + ); standardShaderMaterial.SetInt("_ZWrite", 0); standardShaderMaterial.DisableKeyword("_ALPHATEST_ON"); standardShaderMaterial.EnableKeyword("_ALPHABLEND_ON"); @@ -40,8 +58,14 @@ public static void ChangeRenderMode(Material standardShaderMaterial, BlendMode b standardShaderMaterial.renderQueue = 3000; break; case BlendMode.Transparent: - standardShaderMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One); - standardShaderMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); + standardShaderMaterial.SetInt( + "_SrcBlend", + (int)UnityEngine.Rendering.BlendMode.One + ); + standardShaderMaterial.SetInt( + "_DstBlend", + (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha + ); standardShaderMaterial.SetInt("_ZWrite", 0); standardShaderMaterial.DisableKeyword("_ALPHATEST_ON"); standardShaderMaterial.DisableKeyword("_ALPHABLEND_ON"); @@ -49,6 +73,5 @@ public static void ChangeRenderMode(Material standardShaderMaterial, BlendMode b standardShaderMaterial.renderQueue = 3000; break; } - } } diff --git a/unity/Assets/Scripts/StoveTopElectric.cs b/unity/Assets/Scripts/StoveTopElectric.cs index 1f6e2af04f..564f0c9986 100644 --- a/unity/Assets/Scripts/StoveTopElectric.cs +++ b/unity/Assets/Scripts/StoveTopElectric.cs @@ -1,9 +1,8 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; public class StoveTopElectric : MonoBehaviour { - public SimObj ParentObj; public Material BurnerOnMat; public int MatIndex; @@ -20,6 +19,8 @@ void Awake() { } void Update() { - BurnerRenderer.sharedMaterials = ParentObj.Animator.GetBool("AnimState1") ? matArrayOn : matArrayOff; + BurnerRenderer.sharedMaterials = ParentObj.Animator.GetBool("AnimState1") + ? matArrayOn + : matArrayOff; } } diff --git a/unity/Assets/Scripts/StretchAgentController.cs b/unity/Assets/Scripts/StretchAgentController.cs index acab05d186..b28e9de058 100644 --- a/unity/Assets/Scripts/StretchAgentController.cs +++ b/unity/Assets/Scripts/StretchAgentController.cs @@ -1,30 +1,40 @@ +using System; using System.Collections; using System.Collections.Generic; -using UnityEngine; -using System; using System.Linq; using RandomExtensions; +using UnityEngine; using UnityEngine.AI; using UnityEngine.Rendering.PostProcessing; using UnityEngine.UIElements; namespace UnityStandardAssets.Characters.FirstPerson { - public partial class StretchAgentController : ArmAgentController { public int gripperOpennessState = 0; //define default parameters for both main camera and secondary camera, specific to real-life stretch bot rig //these are kind of magic numbers, but can be adjusted via UpdateMainCamera and UpdateThirdPartyCamera as needed if our //real rig changes - private Vector3 defaultMainCameraLocalPosition = new Vector3(0.001920350f, 0.544700900f, 0.067880400f); + private Vector3 defaultMainCameraLocalPosition = new Vector3( + 0.001920350f, + 0.544700900f, + 0.067880400f + ); private Vector3 defaultMainCameraLocalRotation = new Vector3(30f, 0, 0); private float defaultMainCameraFieldOfView = 59f; - private Vector3 defaultSecondaryCameraLocalPosition = new Vector3(0.053905130f, 0.523833600f, -0.058848570f); - private Vector3 defaultSecondaryCameraLocalRotation =new Vector3(50f, 90f, 0); + private Vector3 defaultSecondaryCameraLocalPosition = new Vector3( + 0.053905130f, + 0.523833600f, + -0.058848570f + ); + private Vector3 defaultSecondaryCameraLocalRotation = new Vector3(50f, 90f, 0); private float defaultSecondaryCameraFieldOfView = 59f; - public StretchAgentController(BaseAgentComponent baseAgentComponent, AgentManager agentManager) : base(baseAgentComponent, agentManager) { - } + public StretchAgentController( + BaseAgentComponent baseAgentComponent, + AgentManager agentManager + ) + : base(baseAgentComponent, agentManager) { } public override void updateImageSynthesis(bool status) { base.updateImageSynthesis(status); @@ -60,7 +70,9 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { var secondaryCameraName = "SecondaryCamera"; // activate arm-camera - Camera fp_camera_2 = m_CharacterController.transform.Find(secondaryCameraName).GetComponent(); + Camera fp_camera_2 = m_CharacterController + .transform.Find(secondaryCameraName) + .GetComponent(); fp_camera_2.gameObject.SetActive(true); agentManager.registerAsThirdPartyCamera(fp_camera_2); if (initializeAction.antiAliasing != null) { @@ -94,7 +106,10 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { } var secondaryCameraParams = new CameraParameters(); - var setSecondaryParams = initializeAction.thirdPartyCameraParameters?.TryGetValue(secondaryCameraName, out secondaryCameraParams); + var setSecondaryParams = initializeAction.thirdPartyCameraParameters?.TryGetValue( + secondaryCameraName, + out secondaryCameraParams + ); if (setSecondaryParams.GetValueOrDefault()) { CameraParameters.setCameraParameters(fp_camera_2, secondaryCameraParams); @@ -106,7 +121,9 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { //initialize all things needed for the stretch arm controller SArm = this.GetComponentInChildren(); SArm.PhysicsController = this; - var armTarget = SArm.transform.Find("stretch_robot_arm_rig").Find("stretch_robot_pos_rot_manipulator"); + var armTarget = SArm + .transform.Find("stretch_robot_arm_rig") + .Find("stretch_robot_pos_rot_manipulator"); Vector3 pos = armTarget.transform.localPosition; pos.z = 0.0f; // pulls the arm in to be fully contracted armTarget.transform.localPosition = pos; @@ -117,28 +134,29 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { } private ArmController getArmImplementation() { - Stretch_Robot_Arm_Controller arm = GetComponentInChildren(); + Stretch_Robot_Arm_Controller arm = + GetComponentInChildren(); if (arm == null) { throw new InvalidOperationException( - "Agent does not have Stretch arm or is not enabled.\n" + - $"Make sure there is a '{typeof(Stretch_Robot_Arm_Controller).Name}' component as a child of this agent." + "Agent does not have Stretch arm or is not enabled.\n" + + $"Make sure there is a '{typeof(Stretch_Robot_Arm_Controller).Name}' component as a child of this agent." ); } return arm; } - protected override ArmController getArm() { + protected override ArmController getArm() { return getArmImplementation(); } - public bool teleportArm( Vector3? position = null, float? rotation = null, bool worldRelative = false, bool forceAction = false ) { - Stretch_Robot_Arm_Controller arm = getArmImplementation() as Stretch_Robot_Arm_Controller; + Stretch_Robot_Arm_Controller arm = + getArmImplementation() as Stretch_Robot_Arm_Controller; GameObject posRotManip = arm.GetArmTarget(); // cache old values in case there's a failure @@ -157,10 +175,10 @@ public bool teleportArm( // teleport arm! if (!worldRelative) { posRotManip.transform.localPosition = (Vector3)position; - posRotManip.transform.localEulerAngles = new Vector3 (0, (float)rotation % 360, 0); + posRotManip.transform.localEulerAngles = new Vector3(0, (float)rotation % 360, 0); } else { posRotManip.transform.position = (Vector3)position; - posRotManip.transform.eulerAngles = new Vector3 (0, (float)rotation % 360, 0); + posRotManip.transform.eulerAngles = new Vector3(0, (float)rotation % 360, 0); } bool success = false; @@ -216,17 +234,15 @@ public ActionFinished TryReachObject( ) { if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { errorMessage = $"Cannot find object with id {objectId}."; - return new ActionFinished() { - success = false, - toEmitState = true - }; + return new ActionFinished() { success = false, toEmitState = true }; } SimObjPhysics target = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; Vector3 oldPos = transform.position; Quaternion oldRot = transform.rotation; - Stretch_Robot_Arm_Controller arm = getArmImplementation() as Stretch_Robot_Arm_Controller; + Stretch_Robot_Arm_Controller arm = + getArmImplementation() as Stretch_Robot_Arm_Controller; GameObject armTarget = arm.GetArmTarget(); Vector3 oldArmLocalPosition = armTarget.transform.localPosition; @@ -243,7 +259,8 @@ public ActionFinished TryReachObject( objectId: objectId, point: new Vector3( transform.position.x, - target.AxisAlignedBoundingBox.center.y + target.AxisAlignedBoundingBox.size.y / 2f, // Y from the object + target.AxisAlignedBoundingBox.center.y + + target.AxisAlignedBoundingBox.size.y / 2f, // Y from the object transform.position.z ) ); @@ -262,17 +279,10 @@ public ActionFinished TryReachObject( foreach (Vector3 point in closePoints) { #if UNITY_EDITOR - Debug.DrawLine( - point, - point + transform.up * 0.3f, - Color.red, - 20f - ); + Debug.DrawLine(point, point + transform.up * 0.3f, Color.red, 20f); #endif transform.LookAt( - worldPosition: new Vector3( - point.x, transform.position.y, point.z - ), + worldPosition: new Vector3(point.x, transform.position.y, point.z), worldUp: transform.up ); @@ -297,7 +307,11 @@ public ActionFinished TryReachObject( Physics.SyncTransforms(); agentToMagnetSphere = arm.MagnetSphereWorldCenter() - transform.position; - Vector3 agentToMagnetSphereDir2D = new Vector3(agentToMagnetSphere.x, 0f, agentToMagnetSphere.z).normalized; + Vector3 agentToMagnetSphereDir2D = new Vector3( + agentToMagnetSphere.x, + 0f, + agentToMagnetSphere.z + ).normalized; if ( !teleportArm( @@ -339,7 +353,6 @@ public ActionFinished TryReachObject( continue; } - # if UNITY_EDITOR Debug.Log($"Found successful position {point}."); # endif @@ -350,12 +363,13 @@ public ActionFinished TryReachObject( Dictionary actionReturn = null; if (success) { - actionReturn = new Dictionary() { - {"position", transform.position}, - {"rotation", transform.rotation.eulerAngles}, - {"localArmPosition", armTarget.transform.localPosition}, - {"localArmRotation", armTarget.transform.localEulerAngles}, - {"pointOnObject", pointOnObject} + actionReturn = new Dictionary() + { + { "position", transform.position }, + { "rotation", transform.rotation.eulerAngles }, + { "localArmPosition", armTarget.transform.localPosition }, + { "localArmRotation", armTarget.transform.localEulerAngles }, + { "pointOnObject", pointOnObject } }; } @@ -401,14 +415,11 @@ public ActionFinished GetTouchingPoses( string objectId, Vector3[] positions = null, float maxDistance = 1f, - int maxPoses = int.MaxValue // works like infinity + int maxPoses = int.MaxValue // works like infinity ) { if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { errorMessage = $"Cannot find object with id {objectId}."; - return new ActionFinished() { - success = false, - toEmitState = true - }; + return new ActionFinished() { success = false, toEmitState = true }; } if (maxPoses <= 0) { throw new ArgumentOutOfRangeException("maxPoses must be > 0."); @@ -423,9 +434,14 @@ public ActionFinished GetTouchingPoses( positions = getReachablePositions(); } - List filteredPositions = positions.Where( - p => (Vector3.Distance(a: p, b: sop.transform.position) <= maxDistance + fudgeFactor + gridSize) - ).ToList(); + List filteredPositions = positions + .Where(p => + ( + Vector3.Distance(a: p, b: sop.transform.position) + <= maxDistance + fudgeFactor + gridSize + ) + ) + .ToList(); List poses = new List(); foreach (Vector3 position in filteredPositions) { @@ -440,7 +456,7 @@ public ActionFinished GetTouchingPoses( # if UNITY_EDITOR Debug.DrawLine( start: position, - end: ((Dictionary) af.actionReturn)["pointOnObject"], + end: ((Dictionary)af.actionReturn)["pointOnObject"], color: Color.green, duration: 15f ); @@ -459,7 +475,6 @@ public ActionFinished GetTouchingPoses( return new ActionFinished() { success = true, actionReturn = poses }; } - public override IEnumerator RotateWristRelative( float pitch = 0f, float yaw = 0f, @@ -469,7 +484,9 @@ public override IEnumerator RotateWristRelative( ) { // pitch and roll are not supported for the stretch and so we throw an error if (pitch != 0f || roll != 0f) { - throw new System.NotImplementedException("Pitch and roll are not supported for the stretch agent."); + throw new System.NotImplementedException( + "Pitch and roll are not supported for the stretch agent." + ); } var arm = getArmImplementation() as Stretch_Robot_Arm_Controller; @@ -495,7 +512,9 @@ public IEnumerator RotateWrist( ) { // pitch and roll are not supported for the stretch and so we throw an error if (pitch != 0f || roll != 0f) { - throw new System.NotImplementedException("Pitch and roll are not supported for the stretch agent."); + throw new System.NotImplementedException( + "Pitch and roll are not supported for the stretch agent." + ); } // GameObject posRotManip = this.GetComponent().StretchArm.GetComponent().GetArmTarget(); @@ -547,6 +566,7 @@ protected int gripperOpenFloatToState(float openness) { ); } } + public ActionFinished SetGripperOpenness(float? openness, int? openState = null) { if (openness.HasValue == openState.HasValue) { throw new InvalidOperationException( @@ -560,39 +580,38 @@ public ActionFinished SetGripperOpenness(float? openness, int? openState = null) foreach (GameObject opennessState in GripperOpennessStates) { opennessState.SetActive(false); } - + GripperOpennessStates[openState.Value].SetActive(true); gripperOpennessState = openState.Value; return ActionFinished.Success; } -// public void RotateCameraBase(float yawDegrees, float rollDegrees) { -// var target = gimbalBase; -// var maxDegree = maxBaseXYRotation; -// Debug.Log("yaw is " + yawDegrees + " and roll is " + rollDegrees); -// if (yawDegrees < -maxDegree || maxDegree < yawDegrees) { -// throw new InvalidOperationException( -// $"Invalid value for `yawDegrees`: '{yawDegrees}'. Value should be between '{-maxDegree}' and '{maxDegree}'." -// ); -// } else if (rollDegrees < -maxDegree || maxDegree < rollDegrees) { -// throw new InvalidOperationException( -// $"Invalid value for `rollDegrees`: '{rollDegrees}'. Value should be between '{-maxDegree}' and '{maxDegree}'." -// ); -// } else { -// gimbalBase.localEulerAngles = new Vector3( -// gimbalBaseStartingXRotation + rollDegrees, -// gimbalBaseStartingYRotation + yawDegrees, -// gimbalBase.transform.localEulerAngles.z -// ); -// } -// actionFinished(true); -// } + // public void RotateCameraBase(float yawDegrees, float rollDegrees) { + // var target = gimbalBase; + // var maxDegree = maxBaseXYRotation; + // Debug.Log("yaw is " + yawDegrees + " and roll is " + rollDegrees); + // if (yawDegrees < -maxDegree || maxDegree < yawDegrees) { + // throw new InvalidOperationException( + // $"Invalid value for `yawDegrees`: '{yawDegrees}'. Value should be between '{-maxDegree}' and '{maxDegree}'." + // ); + // } else if (rollDegrees < -maxDegree || maxDegree < rollDegrees) { + // throw new InvalidOperationException( + // $"Invalid value for `rollDegrees`: '{rollDegrees}'. Value should be between '{-maxDegree}' and '{maxDegree}'." + // ); + // } else { + // gimbalBase.localEulerAngles = new Vector3( + // gimbalBaseStartingXRotation + rollDegrees, + // gimbalBaseStartingYRotation + yawDegrees, + // gimbalBase.transform.localEulerAngles.z + // ); + // } + // actionFinished(true); + // } public void RotateCameraMount(float degrees, bool secondary = false) { var minDegree = -80.00001f; var maxDegree = 80.00001f; if (degrees >= minDegree && degrees <= maxDegree) { - Camera cam; if (secondary) { cam = agentManager.thirdPartyCameras[0]; @@ -600,7 +619,9 @@ public void RotateCameraMount(float degrees, bool secondary = false) { cam = m_Camera; } AgentManager.OptionalVector3 localEulerAngles = new AgentManager.OptionalVector3( - x: degrees, y: cam.transform.localEulerAngles.y, z: cam.transform.localEulerAngles.z + x: degrees, + y: cam.transform.localEulerAngles.y, + z: cam.transform.localEulerAngles.z ); int agentId = -1; @@ -626,13 +647,11 @@ public void RotateCameraMount(float degrees, bool secondary = false) { } else { agentManager.UpdateMainCamera(rotation: localEulerAngles); } - } - else { - errorMessage = $"Invalid value for `degrees`: '{degrees}'. Value should be between '{minDegree}' and '{maxDegree}'."; + } else { + errorMessage = + $"Invalid value for `degrees`: '{degrees}'. Value should be between '{minDegree}' and '{maxDegree}'."; actionFinished(false); } } - } - } diff --git a/unity/Assets/Scripts/Stretch_Robot_Arm_Controller.cs b/unity/Assets/Scripts/Stretch_Robot_Arm_Controller.cs index 24af6c7439..a0b91362b4 100644 --- a/unity/Assets/Scripts/Stretch_Robot_Arm_Controller.cs +++ b/unity/Assets/Scripts/Stretch_Robot_Arm_Controller.cs @@ -1,19 +1,21 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -using System.Linq; + public partial class Stretch_Robot_Arm_Controller : ArmController { - [SerializeField] - private Transform armBase, handCameraTransform, FirstJoint; + private Transform armBase, + handCameraTransform, + FirstJoint; [SerializeField] public PhysicsRemoteFPSAgentController PhysicsController; // Distance from joint containing gripper camera to armTarget - private Vector3 WristToManipulator = new Vector3 (0, -0.09872628f, 0); + private Vector3 WristToManipulator = new Vector3(0, -0.09872628f, 0); private Stretch_Arm_Solver solver; @@ -26,9 +28,12 @@ public override Transform pickupParent() { return magnetSphere.transform; } - public override Vector3 wristSpaceOffsetToWorldPos(Vector3 offset) { - return handCameraTransform.TransformPoint(offset) - handCameraTransform.position + WristToManipulator; + public override Vector3 wristSpaceOffsetToWorldPos(Vector3 offset) { + return handCameraTransform.TransformPoint(offset) + - handCameraTransform.position + + WristToManipulator; } + public override Vector3 armBaseSpaceOffsetToWorldPos(Vector3 offset) { return this.transform.TransformPoint(offset) - this.transform.position; } @@ -36,6 +41,7 @@ public override Vector3 armBaseSpaceOffsetToWorldPos(Vector3 offset) { public override Vector3 pointToWristSpace(Vector3 point) { return handCameraTransform.TransformPoint(point) + WristToManipulator; } + public override Vector3 pointToArmBaseSpace(Vector3 point) { return armBase.transform.TransformPoint(point); } @@ -46,10 +52,10 @@ public override void ContinuousUpdate(float fixedDeltaTime) { private bool DeadZoneCheck() { if (deadZoneCheck) { - float currentYaw = armTarget.localRotation.eulerAngles.y; + float currentYaw = armTarget.localRotation.eulerAngles.y; float cLimit = wristClockwiseLocalRotationLimit; float ccLimit = wristCounterClockwiseLocalRotationLimit; - + // Consolidate reachable euler-rotations (which are normally bounded by [0, 360)) into a continuous number line, // bounded instead by [continuousCounterClockwiseLocalRotationLimit, continuousClockwiseLocalRotationLimit + 360) if (cLimit < ccLimit) { @@ -64,13 +70,12 @@ private bool DeadZoneCheck() { } else { return false; } - } - else { + } else { return false; } } - public override bool ShouldHalt() { + public override bool ShouldHalt() { return base.ShouldHalt() || DeadZoneCheck(); } @@ -78,7 +83,10 @@ public override string GetHaltMessage() { var errorMessage = base.GetHaltMessage(); if (errorMessage == "") { if (DeadZoneCheck()) { - errorMessage = "Rotated up against Stretch arm wrist's dead-zone, could not reach target: '" + armTarget.rotation + "'."; + errorMessage = + "Rotated up against Stretch arm wrist's dead-zone, could not reach target: '" + + armTarget.rotation + + "'."; } } return errorMessage; @@ -139,20 +147,19 @@ void Start() { public void resetPosRotManipulator() { Physics.SyncTransforms(); - armTarget.position = handCameraTransform.transform.position + WristToManipulator;; + armTarget.position = handCameraTransform.transform.position + WristToManipulator; + ; } protected override void lastStepCallback() { resetPosRotManipulator(); setDeadZoneCheck(false); } - public void setDeadZoneCheck(bool enabled) { deadZoneCheck = enabled; } - - + public IEnumerator rotateWrist( PhysicsRemoteFPSAgentController controller, float rotation, @@ -161,12 +168,14 @@ public IEnumerator rotateWrist( bool returnToStartPositionIfFailed = false, bool isRelativeRotation = true ) { - // float clockwiseLocalRotationLimit = 77.5f; // float counterClockwiseLocalRotationLimit = 102.5f; - float currentContinuousRotation, targetRelativeRotation=0.0f, targetContinuousRotation; + float currentContinuousRotation, + targetRelativeRotation = 0.0f, + targetContinuousRotation; float continuousClockwiseLocalRotationLimit = wristClockwiseLocalRotationLimit; - float continuousCounterClockwiseLocalRotationLimit = wristCounterClockwiseLocalRotationLimit; + float continuousCounterClockwiseLocalRotationLimit = + wristCounterClockwiseLocalRotationLimit; currentContinuousRotation = armTarget.transform.localEulerAngles.y; Quaternion targetRotation; @@ -182,13 +191,16 @@ public IEnumerator rotateWrist( } else { // Calculate target and secTargetRotation targetRelativeRotation = rotation / 2; - targetRotation = armTarget.transform.rotation * Quaternion.Euler(0, targetRelativeRotation, 0); + targetRotation = + armTarget.transform.rotation * Quaternion.Euler(0, targetRelativeRotation, 0); secTargetRotation = targetRotation * Quaternion.Euler(0, targetRelativeRotation, 0); } } else { // Consolidate reachable euler-rotations (which are normally bounded by [0, 360)) into a continuous number line, // bounded instead by [continuousCounterClockwiseLocalRotationLimit, continuousClockwiseLocalRotationLimit + 360) - if (continuousClockwiseLocalRotationLimit < continuousCounterClockwiseLocalRotationLimit) { + if ( + continuousClockwiseLocalRotationLimit < continuousCounterClockwiseLocalRotationLimit + ) { continuousClockwiseLocalRotationLimit += 360; if (currentContinuousRotation < continuousCounterClockwiseLocalRotationLimit) { currentContinuousRotation += 360; @@ -198,45 +210,62 @@ public IEnumerator rotateWrist( targetContinuousRotation = currentContinuousRotation + rotation; // if angle is reachable via non-reflex rotation - if (targetContinuousRotation > continuousCounterClockwiseLocalRotationLimit - && targetContinuousRotation < continuousClockwiseLocalRotationLimit) { - targetRotation = armTarget.transform.rotation * Quaternion.Euler(0,rotation,0); - - // if angle is NOT reachable, find how close it can get from that direction + if ( + targetContinuousRotation > continuousCounterClockwiseLocalRotationLimit + && targetContinuousRotation < continuousClockwiseLocalRotationLimit + ) { + targetRotation = armTarget.transform.rotation * Quaternion.Euler(0, rotation, 0); + + // if angle is NOT reachable, find how close it can get from that direction } else { - float nonReflexAngularDistance, reflexAngularDistance; + float nonReflexAngularDistance, + reflexAngularDistance; // Calculate proximity of non-reflex angle extreme to target if (targetContinuousRotation < continuousCounterClockwiseLocalRotationLimit) { - nonReflexAngularDistance = continuousCounterClockwiseLocalRotationLimit - targetContinuousRotation; + nonReflexAngularDistance = + continuousCounterClockwiseLocalRotationLimit - targetContinuousRotation; } else { - nonReflexAngularDistance = targetContinuousRotation - continuousClockwiseLocalRotationLimit; + nonReflexAngularDistance = + targetContinuousRotation - continuousClockwiseLocalRotationLimit; } // Reflex targetContinuousRotation calculation targetRelativeRotation = (Mathf.Abs(rotation) - 360) * Mathf.Sign(rotation) / 2; - float secTargetContinuousRotation = currentContinuousRotation + 2 * targetRelativeRotation; + float secTargetContinuousRotation = + currentContinuousRotation + 2 * targetRelativeRotation; // If angle is reachable via reflex rotation - if (secTargetContinuousRotation > continuousCounterClockwiseLocalRotationLimit - && secTargetContinuousRotation < continuousClockwiseLocalRotationLimit) - { - targetRotation = armTarget.transform.rotation * Quaternion.Euler(0,targetRelativeRotation,0); - secTargetRotation = targetRotation * Quaternion.Euler(0,targetRelativeRotation,0); + if ( + secTargetContinuousRotation > continuousCounterClockwiseLocalRotationLimit + && secTargetContinuousRotation < continuousClockwiseLocalRotationLimit + ) { + targetRotation = + armTarget.transform.rotation + * Quaternion.Euler(0, targetRelativeRotation, 0); + secTargetRotation = + targetRotation * Quaternion.Euler(0, targetRelativeRotation, 0); } else { // Calculate proximity of reflex angle extreme to target if (secTargetContinuousRotation < continuousCounterClockwiseLocalRotationLimit) { - reflexAngularDistance = continuousCounterClockwiseLocalRotationLimit - secTargetContinuousRotation; - } else {// if (secTargetContinuousRotation > continuousClockwiseLocalRotationLimit) { - reflexAngularDistance = secTargetContinuousRotation - continuousClockwiseLocalRotationLimit; + reflexAngularDistance = + continuousCounterClockwiseLocalRotationLimit + - secTargetContinuousRotation; + } else { // if (secTargetContinuousRotation > continuousClockwiseLocalRotationLimit) { + reflexAngularDistance = + secTargetContinuousRotation - continuousClockwiseLocalRotationLimit; } // Calculate which distance gets wrist closer to target if (nonReflexAngularDistance <= reflexAngularDistance) { - targetRotation = armTarget.transform.rotation * Quaternion.Euler(0,rotation,0); + targetRotation = + armTarget.transform.rotation * Quaternion.Euler(0, rotation, 0); } else { - targetRotation = armTarget.transform.rotation * Quaternion.Euler(0,targetRelativeRotation,0); - secTargetRotation = targetRotation * Quaternion.Euler(0,targetRelativeRotation,0); + targetRotation = + armTarget.transform.rotation + * Quaternion.Euler(0, targetRelativeRotation, 0); + secTargetRotation = + targetRotation * Quaternion.Euler(0, targetRelativeRotation, 0); } } } @@ -248,7 +277,9 @@ public IEnumerator rotateWrist( // Debug.Log("Rotating to " + targetRotation.eulerAngles + " degrees, and then to " + currentSecTargetRotation.eulerAngles); // } - Debug.Log($"Rotate wrist args rotation: {targetRelativeRotation}, rotation {targetRotation.eulerAngles} sec {secTargetRotation?.eulerAngles}"); + Debug.Log( + $"Rotate wrist args rotation: {targetRelativeRotation}, rotation {targetRotation.eulerAngles} sec {secTargetRotation?.eulerAngles}" + ); // Rotate wrist collisionListener.Reset(); @@ -287,12 +318,10 @@ public override ArmMetadata GenerateMetadata() { for (int i = 1; i <= 8; i++) { if (i == 1) { joint = joint.Find("stretch_robot_lift_jnt"); - } - else if (i <= 6) { - joint = joint.Find("stretch_robot_arm_" + (i-1) + "_jnt"); - } - else { - joint = joint.Find("stretch_robot_wrist_" + (i-6) + "_jnt"); + } else if (i <= 6) { + joint = joint.Find("stretch_robot_arm_" + (i - 1) + "_jnt"); + } else { + joint = joint.Find("stretch_robot_wrist_" + (i - 6) + "_jnt"); } JointMetadata jointMeta = new JointMetadata(); @@ -317,7 +346,12 @@ public override ArmMetadata GenerateMetadata() { // Check that world-relative rotation is angle-axis-notation-compatible if (currentRotation != new Quaternion(0, 0, 0, -1)) { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); - jointMeta.rotation = new Vector4(vectorRot.x, Mathf.Abs(vectorRot.y), vectorRot.z, ConvertAngleToZeroCentricRange(angleRot * Mathf.Sign(vectorRot.y))); + jointMeta.rotation = new Vector4( + vectorRot.x, + Mathf.Abs(vectorRot.y), + vectorRot.z, + ConvertAngleToZeroCentricRange(angleRot * Mathf.Sign(vectorRot.y)) + ); } else { jointMeta.rotation = new Vector4(1, 0, 0, 0); } @@ -333,7 +367,12 @@ public override ArmMetadata GenerateMetadata() { // Check that root-relative rotation is angle-axis-notation-compatible if (currentRotation != new Quaternion(0, 0, 0, -1)) { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); - jointMeta.rootRelativeRotation = new Vector4(vectorRot.x, Mathf.Abs(vectorRot.y), vectorRot.z, ConvertAngleToZeroCentricRange(angleRot * Mathf.Sign(vectorRot.y))); + jointMeta.rootRelativeRotation = new Vector4( + vectorRot.x, + Mathf.Abs(vectorRot.y), + vectorRot.z, + ConvertAngleToZeroCentricRange(angleRot * Mathf.Sign(vectorRot.y)) + ); } else { jointMeta.rootRelativeRotation = new Vector4(1, 0, 0, 0); } @@ -352,7 +391,12 @@ public override ArmMetadata GenerateMetadata() { // Check that parent-relative rotation is angle-axis-notation-compatible if (currentRotation != new Quaternion(0, 0, 0, -1)) { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); - jointMeta.localRotation = new Vector4(vectorRot.x, Mathf.Abs(vectorRot.y), vectorRot.z, ConvertAngleToZeroCentricRange(angleRot * Mathf.Sign(vectorRot.y))); + jointMeta.localRotation = new Vector4( + vectorRot.x, + Mathf.Abs(vectorRot.y), + vectorRot.z, + ConvertAngleToZeroCentricRange(angleRot * Mathf.Sign(vectorRot.y)) + ); } else { jointMeta.localRotation = new Vector4(1, 0, 0, 0); } @@ -383,24 +427,27 @@ public override ArmMetadata GenerateMetadata() { meta.handSphereRadius = magnetSphere.radius; List objectsInMagnet = WhatObjectsAreInsideMagnetSphereAsSOP(false); - meta.pickupableObjects = objectsInMagnet.Where( - x => x.PrimaryProperty == SimObjPrimaryProperty.CanPickup - ).Select(x => x.ObjectID).ToList(); + meta.pickupableObjects = objectsInMagnet + .Where(x => x.PrimaryProperty == SimObjPrimaryProperty.CanPickup) + .Select(x => x.ObjectID) + .ToList(); meta.touchedNotHeldObjects = objectsInMagnet.Select(x => x.ObjectID).ToList(); - meta.gripperOpennessState = ((StretchAgentController) PhysicsController).gripperOpennessState; - + meta.gripperOpennessState = ( + (StretchAgentController)PhysicsController + ).gripperOpennessState; + return meta; } -float ConvertAngleToZeroCentricRange(float degrees) { - if (degrees < 0) { - degrees = (degrees % 360f) + 360f; - } - if (degrees > 180f) { - degrees = (degrees % 360f) - 360f; + float ConvertAngleToZeroCentricRange(float degrees) { + if (degrees < 0) { + degrees = (degrees % 360f) + 360f; + } + if (degrees > 180f) { + degrees = (degrees % 360f) - 360f; + } + return degrees; } - return degrees; -} #if UNITY_EDITOR public class GizmoDrawCapsule { diff --git a/unity/Assets/Scripts/StructureObject.cs b/unity/Assets/Scripts/StructureObject.cs index 32068f82de..d102b57bab 100644 --- a/unity/Assets/Scripts/StructureObject.cs +++ b/unity/Assets/Scripts/StructureObject.cs @@ -1,8 +1,8 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; +using System; using System.Collections; using System.Collections.Generic; -using System; +using UnityEngine; // this is used to tag Structural objects in the scene. Structural objects are objects with physical collision and are rendered, but are not SimObjects themselves. // these objects are all located under the "Structure" object in the Heirarchy, and are always static and purely environmental. @@ -11,14 +11,10 @@ public class StructureObject : MonoBehaviour { public StructureObjectTag WhatIsMyStructureObjectTag; // Start is called before the first frame update - void Start() { - - } + void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } } [Serializable] @@ -27,9 +23,9 @@ public enum StructureObjectTag : int { Wall = 1, Floor = 2, Ceiling = 3, - LightFixture = 4,// for all hanging lights or other lights protruding out of something - CeilingLight = 5,// for embedded lights in the ceiling - Stove = 6,// for the uninteractable body of the stove + LightFixture = 4, // for all hanging lights or other lights protruding out of something + CeilingLight = 5, // for embedded lights in the ceiling + Stove = 6, // for the uninteractable body of the stove DishWasher = 7, KitchenIsland = 8, Door = 9, @@ -41,8 +37,4 @@ public enum StructureObjectTag : int { Rug = 15, FirePlace = 16, DecorativeSticks = 17, - - - } - diff --git a/unity/Assets/Scripts/SyncTransform.cs b/unity/Assets/Scripts/SyncTransform.cs index 5994785fb5..e888c945ca 100644 --- a/unity/Assets/Scripts/SyncTransform.cs +++ b/unity/Assets/Scripts/SyncTransform.cs @@ -3,7 +3,10 @@ using UnityEngine; public class SyncTransform : MonoBehaviour { - protected enum WhatToTrack { Rotation, Position }; + protected enum WhatToTrack { + Rotation, + Position + }; [SerializeField] protected WhatToTrack WhichTransformPropertyAmITracking; @@ -14,11 +17,8 @@ protected enum WhatToTrack { Rotation, Position }; // used to stop syncing the upper body when the ToggleMapView function is called public bool StopSyncingForASecond = false; - // Start is called before the first frame update - void Start() { - - } + void Start() { } // Update is called once per frame void Update() { diff --git a/unity/Assets/Scripts/THORDocumentationExporter.cs b/unity/Assets/Scripts/THORDocumentationExporter.cs index d167cf2d0a..88a310bab6 100644 --- a/unity/Assets/Scripts/THORDocumentationExporter.cs +++ b/unity/Assets/Scripts/THORDocumentationExporter.cs @@ -1,16 +1,14 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; +using System.IO; using UnityEngine; using UnityEngine.SceneManagement; -using System.IO; -using System; - #if UNITY_EDITOR using UnityEditor; using UnityEditor.SceneManagement; public class THORDocumentationExporter : MonoBehaviour { - // export the placement restrictions for each pickupable object [MenuItem("SimObjectPhysics/Generate Placement Restrictions to Text File")] private static void ExportPlacementRestrictionsToTextFile() { @@ -18,7 +16,12 @@ private static void ExportPlacementRestrictionsToTextFile() { var create = File.CreateText("Assets/DebugTextFiles/" + file); - foreach (KeyValuePair> kvp in ReceptacleRestrictions.PlacementRestrictions) { + foreach ( + KeyValuePair< + SimObjType, + List + > kvp in ReceptacleRestrictions.PlacementRestrictions + ) { // create.WriteLine("/////////////////////////////"); create.WriteLine("Receptacle Restrictions for: " + kvp.Key.ToString()); foreach (SimObjType sop in kvp.Value) { @@ -33,16 +36,18 @@ private static void ExportPlacementRestrictionsToTextFile() { public class TotalSimObjectsInScene { // count of total number of sim objects in this scene public int TotalSimObjCountInScene; + // track the count of each object type that exists in this scene public Dictionary ObjectType_to_Count = new Dictionary(); } public class UniqueSimObjectsInScene { // name of the asset if it is a prefab- via PrefabUtility.GetCorrsepondingObjectFromOriginalSource() - public string assetName = "n/a";// default to n/a in the case this isn't a prefab + public string assetName = "n/a"; // default to n/a in the case this isn't a prefab // int count of the number of times this unique sim object appears across all scenes. public int count; + // dict of scenes that this unique sim object appears in and what that object's scene name is within the scene // key is the scene name, value is the name of the sim object in heirarchy public Dictionary Scenes_To_hName; @@ -56,22 +61,29 @@ private static void GetInstanceCount() { int totalInstanceCount = 0; // keep track of the count of each object type across all scenes - Dictionary ObjectTypeInAllScenes_to_Count = new Dictionary(); + Dictionary ObjectTypeInAllScenes_to_Count = + new Dictionary(); // keep track of which object types exist in which scene - Dictionary> ObjectType_To_Scenes = new Dictionary>(); + Dictionary> ObjectType_To_Scenes = + new Dictionary>(); // Keep track of the total instance count and oobject type: count in individual scenes - Dictionary SceneName_to_Counts = new Dictionary(); + Dictionary SceneName_to_Counts = + new Dictionary(); // track the number of times a Unique prefab shows up across all scenes. // ie: Pillow_1 might show up in scene 1, scene 2, scene 3, so total 3 duplicates of this instance - Dictionary UniquePrefab_to_Count = new Dictionary(); + Dictionary UniquePrefab_to_Count = + new Dictionary(); // Be sure to have the scenes you want to check for instances (and ONLY those scenes) int the build settings! // for each scene in the build do these things for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; i++) { - UnityEditor.SceneManagement.EditorSceneManager.OpenScene(SceneUtility.GetScenePathByBuildIndex(i), OpenSceneMode.Single); + UnityEditor.SceneManagement.EditorSceneManager.OpenScene( + SceneUtility.GetScenePathByBuildIndex(i), + OpenSceneMode.Single + ); var simObjects = FindObjectsOfType(); // for every child object in "Objects" - simObjects @@ -80,8 +92,9 @@ private static void GetInstanceCount() { // keep track of the count of each object type in this specific Dictionary sceneObjectTypeCounts = new Dictionary(); - - string currentSceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; + string currentSceneName = UnityEngine + .SceneManagement.SceneManager.GetActiveScene() + .name; if (!SceneName_to_Counts.ContainsKey(currentSceneName)) { TotalSimObjectsInScene tsois = new TotalSimObjectsInScene(); tsois.TotalSimObjCountInScene = simObjects.Length; @@ -90,7 +103,6 @@ private static void GetInstanceCount() { } foreach (SimObjPhysics currentSimObject in simObjects) { - // keep track of total object type count if (ObjectTypeInAllScenes_to_Count.ContainsKey(currentSimObject.Type)) { ObjectTypeInAllScenes_to_Count[currentSimObject.Type]++; @@ -122,27 +134,38 @@ private static void GetInstanceCount() { // check if this object is a prefab // if so, store that prefab as one we have encountered already // if this is not a prefab, assume that it is unique to this scene - GameObject testObj = PrefabUtility.GetCorrespondingObjectFromOriginalSource(currentSimObject.gameObject); + GameObject testObj = PrefabUtility.GetCorrespondingObjectFromOriginalSource( + currentSimObject.gameObject + ); if (testObj != null) { // this prefab already exists in our dictionary if (UniquePrefab_to_Count.ContainsKey(testObj)) { // increment how many times this prefab has shown up UniquePrefab_to_Count[testObj].count++; - if (!UniquePrefab_to_Count[testObj].Scenes_To_hName.ContainsKey(currentSceneName)) { + if ( + !UniquePrefab_to_Count[testObj] + .Scenes_To_hName.ContainsKey(currentSceneName) + ) { // add any scenes where this prefab shows up - UniquePrefab_to_Count[testObj].Scenes_To_hName.Add(currentSceneName, currentSimObject.gameObject.name); + UniquePrefab_to_Count[testObj] + .Scenes_To_hName.Add( + currentSceneName, + currentSimObject.gameObject.name + ); } } else { UniqueSimObjectsInScene usois = new UniqueSimObjectsInScene(); usois.count = 1; usois.Scenes_To_hName = new Dictionary(); - usois.Scenes_To_hName.Add(currentSceneName, currentSimObject.gameObject.name); - usois.assetName = "" + testObj;// this allows me to conver the testObj gameobject into a string so yeah i guess? + usois.Scenes_To_hName.Add( + currentSceneName, + currentSimObject.gameObject.name + ); + usois.assetName = "" + testObj; // this allows me to conver the testObj gameobject into a string so yeah i guess? UniquePrefab_to_Count.Add(testObj, usois); } } - // this sim object is not a prefab so assume it is unique to this scene only else { UniqueSimObjectsInScene usois = new UniqueSimObjectsInScene(); @@ -152,17 +175,23 @@ private static void GetInstanceCount() { // use default usois.assetName since this isn't a prefab UniquePrefab_to_Count.Add(currentSimObject.gameObject, usois); } - } - } // generate text file for counts across ALL SCENES var file = "ObjectTypesInAllScenes.txt"; var create = File.CreateText("Assets/DebugTextFiles/" + file); - create.WriteLine("Total number of OBJECT TYPES that apear across ALL Scenes: " + ObjectTypeInAllScenes_to_Count.Count + "\n"); - create.WriteLine("The total number of OBJECT INSTANCES across ALL scenes: " + totalInstanceCount + "\n"); - create.WriteLine("The following is the number of INSTANCES of each OBJECT TYPE that appears across ALL scenes:"); + create.WriteLine( + "Total number of OBJECT TYPES that apear across ALL Scenes: " + + ObjectTypeInAllScenes_to_Count.Count + + "\n" + ); + create.WriteLine( + "The total number of OBJECT INSTANCES across ALL scenes: " + totalInstanceCount + "\n" + ); + create.WriteLine( + "The following is the number of INSTANCES of each OBJECT TYPE that appears across ALL scenes:" + ); foreach (KeyValuePair typeSet in ObjectTypeInAllScenes_to_Count) { create.WriteLine(typeSet.Key + ": " + typeSet.Value); } @@ -175,9 +204,16 @@ private static void GetInstanceCount() { foreach (KeyValuePair entry in SceneName_to_Counts) { create2.WriteLine("\n" + "Scene Name: " + entry.Key); // key: scene, value: object with total count of instances in scene, count of each object by type in scene - create2.WriteLine("Total Number of Sim Objects in " + entry.Key + ": " + entry.Value.TotalSimObjCountInScene); + create2.WriteLine( + "Total Number of Sim Objects in " + + entry.Key + + ": " + + entry.Value.TotalSimObjCountInScene + ); foreach (KeyValuePair pair in entry.Value.ObjectType_to_Count) { - create2.WriteLine(pair.Key + " | Total Instances In " + entry.Key + ": " + pair.Value); + create2.WriteLine( + pair.Key + " | Total Instances In " + entry.Key + ": " + pair.Value + ); } } create2.Close(); @@ -186,7 +222,9 @@ private static void GetInstanceCount() { // object type: scenes where there is at least 1 instance of this object type var file3 = "ScenesThatContainObjectType.txt"; var create3 = File.CreateText("Assets/DebugTextFiles/" + file3); - create3.WriteLine("This contains a list of all Object Types and the Scenes which have at least one instance of the Object Type."); + create3.WriteLine( + "This contains a list of all Object Types and the Scenes which have at least one instance of the Object Type." + ); foreach (KeyValuePair> typeToScene in ObjectType_To_Scenes) { create3.WriteLine("\n" + typeToScene.Key + ":"); foreach (string s in typeToScene.Value) { @@ -199,17 +237,29 @@ private static void GetInstanceCount() { // this file includes a breakdown of each object instance and how many times it is duplicated across all scenes var file4 = "UniqueObjectInstances.txt"; var create4 = File.CreateText("Assets/DebugTextFiles/" + file4); - create4.WriteLine("This includes a count of the total number of unique sim objects that exist across all scenes"); - create4.WriteLine("Afterwards is a breakdown of how many times a unique sim object is re-used across all scenes"); - create4.WriteLine("NOTE: if prefab name is n/a, it is not a prefab but is instead a game object unique to some scene)"); - - create4.WriteLine("\nTotal number of UNIQUE Sim Object instances: " + UniquePrefab_to_Count.Count); + create4.WriteLine( + "This includes a count of the total number of unique sim objects that exist across all scenes" + ); + create4.WriteLine( + "Afterwards is a breakdown of how many times a unique sim object is re-used across all scenes" + ); + create4.WriteLine( + "NOTE: if prefab name is n/a, it is not a prefab but is instead a game object unique to some scene)" + ); + + create4.WriteLine( + "\nTotal number of UNIQUE Sim Object instances: " + UniquePrefab_to_Count.Count + ); foreach (KeyValuePair p in UniquePrefab_to_Count) { create4.WriteLine("\nbase prefab name (in assets): " + p.Value.assetName); - create4.WriteLine("number of times this object shows up across all Scenes: " + p.Value.count); + create4.WriteLine( + "number of times this object shows up across all Scenes: " + p.Value.count + ); create4.WriteLine("list of scenes that this unique object shows up in: "); foreach (KeyValuePair s in p.Value.Scenes_To_hName) { - create4.WriteLine(s.Key + " | name of instance of this object in scene: " + s.Value); + create4.WriteLine( + s.Key + " | name of instance of this object in scene: " + s.Value + ); } } create4.Close(); diff --git a/unity/Assets/Scripts/Television.cs b/unity/Assets/Scripts/Television.cs index 11982beee1..462b5fa536 100644 --- a/unity/Assets/Scripts/Television.cs +++ b/unity/Assets/Scripts/Television.cs @@ -1,10 +1,9 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; [ExecuteInEditMode] public class Television : MonoBehaviour { - public SimObj ParentSimObj; public Renderer[] ScreenRenderers; public int[] ScreenMatIndexes; diff --git a/unity/Assets/Scripts/TestCabinetVisibility.cs b/unity/Assets/Scripts/TestCabinetVisibility.cs index 47b8a285e7..3dae38ed40 100644 --- a/unity/Assets/Scripts/TestCabinetVisibility.cs +++ b/unity/Assets/Scripts/TestCabinetVisibility.cs @@ -1,10 +1,10 @@ // Copyright Allen Institute for Artificial Intelligence 2017 +using System.Collections; +using System.Collections.Generic; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif -using System.Collections; -using System.Collections.Generic; public class TestCabinetVisibility : MonoBehaviour { #if UNITY_EDITOR @@ -88,14 +88,31 @@ public IEnumerator Start() { } RaycastHit hit; // check to see if the agent is above the floor - bool aboveGround = Physics.Raycast(randomPos, Vector3.down, out hit, 1.1f, SimUtil.RaycastVisibleLayerMask, QueryTriggerInteraction.Ignore); - if (!aboveGround || !hit.collider.CompareTag(SimUtil.StructureTag) || !hit.collider.name.Equals("Floor")) { + bool aboveGround = Physics.Raycast( + randomPos, + Vector3.down, + out hit, + 1.1f, + SimUtil.RaycastVisibleLayerMask, + QueryTriggerInteraction.Ignore + ); + if ( + !aboveGround + || !hit.collider.CompareTag(SimUtil.StructureTag) + || !hit.collider.name.Equals("Floor") + ) { numSkippedPositions++; } else { aboveGround = true; } bool hasOverlap = false; - Collider[] overlap = Physics.OverlapCapsule(randomPos + Vector3.up, randomPos + Vector3.down, 0.1f, SimUtil.RaycastVisibleLayerMask, QueryTriggerInteraction.Ignore); + Collider[] overlap = Physics.OverlapCapsule( + randomPos + Vector3.up, + randomPos + Vector3.down, + 0.1f, + SimUtil.RaycastVisibleLayerMask, + QueryTriggerInteraction.Ignore + ); foreach (Collider collider in overlap) { if (!collider.name.Equals("Floor")) { hasOverlap = true; @@ -120,12 +137,13 @@ public IEnumerator Start() { EditorUtility.DisplayProgressBar( "Testing " + cabinets.Count.ToString() + " cabinets", currentCabinet.ObjectID + " (position " + i.ToString() + ")", - ((float)cabinetNum / cabinets.Count) + (((float)i / ChecksPerCabinet) * progressInterval)); + ((float)cabinetNum / cabinets.Count) + + (((float)i / ChecksPerCabinet) * progressInterval) + ); for (int j = 0; j < horizonAngles.Length; j++) { float horizonAngle = horizonAngles[j]; float headingAngle = 0f; for (int k = 0; k < headingAngles.Length; k++) { - headingAngle = headingAngles[k]; // at each step, check whether we can see the cabinet bool cabinetVisibleClosed = false; @@ -137,7 +155,9 @@ public IEnumerator Start() { // currentCabinet.Animator.SetBool ("AnimState1", false); // yield return null; // get visible again - foreach (SimObj visibleSimObj in SimUtil.GetAllVisibleSimObjs(cam, MaxDistance)) { + foreach ( + SimObj visibleSimObj in SimUtil.GetAllVisibleSimObjs(cam, MaxDistance) + ) { if (visibleSimObj == currentCabinet) { cabinetVisibleClosed = true; // seenAtLeastOnce = true; @@ -155,7 +175,9 @@ public IEnumerator Start() { yield return null; yield return new WaitForEndOfFrame(); // get visible objects again - foreach (SimObj visibleSimObj in SimUtil.GetAllVisibleSimObjs(cam, MaxDistance)) { + foreach ( + SimObj visibleSimObj in SimUtil.GetAllVisibleSimObjs(cam, MaxDistance) + ) { if (visibleSimObj == currentCabinet) { cabinetVisibleOpen = true; // seenAtLeastOnce = true; @@ -185,11 +207,11 @@ public IEnumerator Start() { } } /*if (!seenAtLeastOnce) { - ProblemCabinets.Add (currentCabinet); - ProblemPositions.Add (Vector3.zero); - ProblemHeadingAngles.Add (0f); - ProblemhHorizonAngles.Add (0f); - }*/ + ProblemCabinets.Add (currentCabinet); + ProblemPositions.Add (Vector3.zero); + ProblemHeadingAngles.Add (0f); + ProblemhHorizonAngles.Add (0f); + }*/ yield return null; cabinetNum++; } diff --git a/unity/Assets/Scripts/ThorContractlessStandardResolver.cs b/unity/Assets/Scripts/ThorContractlessStandardResolver.cs index feab7b8c84..bfcaf6d5ef 100644 --- a/unity/Assets/Scripts/ThorContractlessStandardResolver.cs +++ b/unity/Assets/Scripts/ThorContractlessStandardResolver.cs @@ -2,23 +2,29 @@ #undef ENABLE_IL2CPP #endif // CloudRendering does not set ENABLE_IL2CPP correctly when using Mono -using System.Linq; using System; using System.Collections.Generic; -using UnityEngine; -using UnityEngine.AI; +using System.Linq; using MessagePack; using MessagePack.Formatters; -using MessagePack.Resolvers; using MessagePack.Internal; +using MessagePack.Resolvers; +using UnityEngine; +using UnityEngine.AI; + /* This resolver is necessary because the MessagePack library does not allow modification to the FormatMap within the UnityResolver and we want our output to match the json output for Vector3. */ namespace MessagePack.Resolvers { - public class NavMeshPathFormatter : global::MessagePack.Formatters.IMessagePackFormatter { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.AI.NavMeshPath value, global::MessagePack.MessagePackSerializerOptions options) { + public class NavMeshPathFormatter + : global::MessagePack.Formatters.IMessagePackFormatter { + public void Serialize( + ref MessagePackWriter writer, + global::UnityEngine.AI.NavMeshPath value, + global::MessagePack.MessagePackSerializerOptions options + ) { writer.WriteMapHeader(2); writer.Write("corners"); writer.WriteArrayHeader(value.corners.Length); @@ -29,19 +35,30 @@ public void Serialize(ref MessagePackWriter writer, global::UnityEngine.AI.NavMe writer.Write("status"); writer.Write(value.status.ToString()); } - public global::UnityEngine.AI.NavMeshPath Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) { + + public global::UnityEngine.AI.NavMeshPath Deserialize( + ref MessagePackReader reader, + global::MessagePack.MessagePackSerializerOptions options + ) { throw new System.NotImplementedException(); } - } - + // MessagePack doesn't support serializing sub-types that have been assigned to a parameter with the // base type, such as the case for droneAgent and droneObjectMetadata. This is purely for performance (on msgpack's part) // The following two formatters examine the types of the values to be serialized and use the appropriate formatter. - public class ObjectMetadataFormatter : global::MessagePack.Formatters.IMessagePackFormatter { - private IMessagePackFormatter formatter = DynamicGenericResolver.Instance.GetFormatter(); - private IMessagePackFormatter droneFormatter = DynamicObjectResolver.Instance.GetFormatter(); - public void Serialize(ref MessagePackWriter writer, ObjectMetadata[] value, global::MessagePack.MessagePackSerializerOptions options) { + public class ObjectMetadataFormatter + : global::MessagePack.Formatters.IMessagePackFormatter { + private IMessagePackFormatter formatter = + DynamicGenericResolver.Instance.GetFormatter(); + private IMessagePackFormatter droneFormatter = + DynamicObjectResolver.Instance.GetFormatter(); + + public void Serialize( + ref MessagePackWriter writer, + ObjectMetadata[] value, + global::MessagePack.MessagePackSerializerOptions options + ) { if (value == null) { writer.WriteNil(); return; @@ -55,13 +72,22 @@ public void Serialize(ref MessagePackWriter writer, ObjectMetadata[] value, glob formatter.Serialize(ref writer, value, options); } } - public ObjectMetadata[] Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) { + + public ObjectMetadata[] Deserialize( + ref MessagePackReader reader, + global::MessagePack.MessagePackSerializerOptions options + ) { throw new System.NotImplementedException(); } } - public class Vector4Formatter : global::MessagePack.Formatters.IMessagePackFormatter { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector4 value, global::MessagePack.MessagePackSerializerOptions options) { + public class Vector4Formatter + : global::MessagePack.Formatters.IMessagePackFormatter { + public void Serialize( + ref MessagePackWriter writer, + global::UnityEngine.Vector4 value, + global::MessagePack.MessagePackSerializerOptions options + ) { writer.WriteMapHeader(4); writer.Write("x"); writer.Write(value.x); @@ -72,13 +98,20 @@ public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector4 writer.Write("w"); writer.Write(value.w); } - public global::UnityEngine.Vector4 Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) { - if (reader.TryReadNil()) { + + public global::UnityEngine.Vector4 Deserialize( + ref MessagePackReader reader, + global::MessagePack.MessagePackSerializerOptions options + ) { + if (reader.TryReadNil()) { throw new InvalidOperationException("Cannot deserialize a nil value to a Vector3."); } int mapLength = reader.ReadMapHeader(); - float x = 0, y = 0, z = 0, w = 0; + float x = 0, + y = 0, + z = 0, + w = 0; for (int i = 0; i < mapLength; i++) { string property = reader.ReadString(); @@ -93,7 +126,7 @@ public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector4 case "z": z = reader.ReadSingle(); break; - case "w": + case "w": w = reader.ReadSingle(); break; default: @@ -104,14 +137,20 @@ public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector4 return new global::UnityEngine.Vector4(x, y, z, w); } - - } - - public class AgentMetadataFormatter : global::MessagePack.Formatters.IMessagePackFormatter { - private IMessagePackFormatter formatter = DynamicObjectResolver.Instance.GetFormatter(); - private IMessagePackFormatter droneFormatter = DynamicObjectResolver.Instance.GetFormatter(); - public void Serialize(ref MessagePackWriter writer, AgentMetadata value, global::MessagePack.MessagePackSerializerOptions options) { + + public class AgentMetadataFormatter + : global::MessagePack.Formatters.IMessagePackFormatter { + private IMessagePackFormatter formatter = + DynamicObjectResolver.Instance.GetFormatter(); + private IMessagePackFormatter droneFormatter = + DynamicObjectResolver.Instance.GetFormatter(); + + public void Serialize( + ref MessagePackWriter writer, + AgentMetadata value, + global::MessagePack.MessagePackSerializerOptions options + ) { if (value == null) { writer.WriteNil(); return; @@ -123,15 +162,22 @@ public void Serialize(ref MessagePackWriter writer, AgentMetadata value, global: formatter.Serialize(ref writer, value, options); } } - public AgentMetadata Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) { + + public AgentMetadata Deserialize( + ref MessagePackReader reader, + global::MessagePack.MessagePackSerializerOptions options + ) { throw new System.NotImplementedException(); } - } - - - public class Vector3Formatter : global::MessagePack.Formatters.IMessagePackFormatter { - public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector3 value, global::MessagePack.MessagePackSerializerOptions options) { + + public class Vector3Formatter + : global::MessagePack.Formatters.IMessagePackFormatter { + public void Serialize( + ref MessagePackWriter writer, + global::UnityEngine.Vector3 value, + global::MessagePack.MessagePackSerializerOptions options + ) { writer.WriteMapHeader(3); writer.Write("x"); writer.Write(value.x); @@ -140,13 +186,19 @@ public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector3 writer.Write("z"); writer.Write(value.z); } - public global::UnityEngine.Vector3 Deserialize(ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options) { + + public global::UnityEngine.Vector3 Deserialize( + ref MessagePackReader reader, + global::MessagePack.MessagePackSerializerOptions options + ) { if (reader.TryReadNil()) { throw new InvalidOperationException("Cannot deserialize a nil value to a Vector3."); } int mapLength = reader.ReadMapHeader(); - float x = 0, y = 0, z = 0; + float x = 0, + y = 0, + z = 0; for (int i = 0; i < mapLength; i++) { string property = reader.ReadString(); @@ -169,23 +221,23 @@ public void Serialize(ref MessagePackWriter writer, global::UnityEngine.Vector3 return new global::UnityEngine.Vector3(x, y, z); } - } public class ThorContractlessStandardResolver : IFormatterResolver { public static readonly MessagePackSerializerOptions Options; public static readonly ThorContractlessStandardResolver Instance; - private static readonly IFormatterResolver[] Resolvers = new IFormatterResolver[]{ + private static readonly IFormatterResolver[] Resolvers = new IFormatterResolver[] + { ThorUnityResolver.Instance, BuiltinResolver.Instance, // Try Builtin - #if !ENABLE_IL2CPP +#if !ENABLE_IL2CPP DynamicEnumResolver.Instance, // Try Enum DynamicGenericResolver.Instance, // Try Array, Tuple, Collection, Enum(Generic Fallback) DynamicUnionResolver.Instance, // Try Union(Interface) DynamicObjectResolver.Instance, // Try Object DynamicContractlessObjectResolver.Instance // Serializes keys as strings - #endif +#endif }; static ThorContractlessStandardResolver() { @@ -193,8 +245,7 @@ static ThorContractlessStandardResolver() { Options = MessagePackSerializerOptions.Standard.WithResolver(Instance); } - private ThorContractlessStandardResolver() { - } + private ThorContractlessStandardResolver() { } public IMessagePackFormatter GetFormatter() { return FormatterCache.Formatter; @@ -207,7 +258,8 @@ static FormatterCache() { if (typeof(T) == typeof(object)) { // final fallback #if !ENABLE_IL2CPP - Formatter = (IMessagePackFormatter)DynamicObjectTypeFallbackFormatter.Instance; + Formatter = + (IMessagePackFormatter)DynamicObjectTypeFallbackFormatter.Instance; #else Formatter = PrimitiveObjectResolver.Instance.GetFormatter(); #endif @@ -228,8 +280,7 @@ static FormatterCache() { public class ThorUnityResolver : IFormatterResolver { public static readonly ThorUnityResolver Instance = new ThorUnityResolver(); - private ThorUnityResolver() { - } + private ThorUnityResolver() { } public IMessagePackFormatter GetFormatter() { return FormatterCache.Formatter; @@ -237,15 +288,18 @@ public IMessagePackFormatter GetFormatter() { private static class FormatterCache { public static readonly IMessagePackFormatter Formatter; - private static readonly Dictionary FormatterMap = new Dictionary() + private static readonly Dictionary FormatterMap = new Dictionary< + Type, + object + >() { - // standard - { typeof(Vector3), new Vector3Formatter() }, - { typeof(NavMeshPath), new NavMeshPathFormatter() }, - { typeof(Vector4), new Vector4Formatter() }, - { typeof(AgentMetadata), new AgentMetadataFormatter() }, - { typeof(ObjectMetadata[]), new ObjectMetadataFormatter() } - }; + // standard + { typeof(Vector3), new Vector3Formatter() }, + { typeof(NavMeshPath), new NavMeshPathFormatter() }, + { typeof(Vector4), new Vector4Formatter() }, + { typeof(AgentMetadata), new AgentMetadataFormatter() }, + { typeof(ObjectMetadata[]), new ObjectMetadataFormatter() } + }; static FormatterCache() { Formatter = (IMessagePackFormatter)GetFormatter(typeof(T)); diff --git a/unity/Assets/Scripts/Toaster.cs b/unity/Assets/Scripts/Toaster.cs index 4eec62bcbe..1ffb2eec6f 100644 --- a/unity/Assets/Scripts/Toaster.cs +++ b/unity/Assets/Scripts/Toaster.cs @@ -1,9 +1,8 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; public class Toaster : MonoBehaviour { - // private ObjectSpecificReceptacle osr; // private CanToggleOnOff onOff; @@ -11,6 +10,7 @@ void Start() { // osr = gameObject.GetComponent(); // onOff = gameObject.GetComponent(); } + void Update() { // Note: Moved This call to the HeatZone that is turned on when the toaster is turned on @@ -20,7 +20,6 @@ void Update() { // { // Toast(); // } - } // public void Toast() @@ -37,5 +36,4 @@ void Update() { // toast.Cook(); // } // } - } diff --git a/unity/Assets/Scripts/Toilet.cs b/unity/Assets/Scripts/Toilet.cs index 70a65b61c1..20a2957b3e 100644 --- a/unity/Assets/Scripts/Toilet.cs +++ b/unity/Assets/Scripts/Toilet.cs @@ -1,15 +1,15 @@ // Copyright Allen Institute for Artificial Intelligence 2017 -using UnityEngine; using System.Collections; +using UnityEngine; [ExecuteInEditMode] public class Toilet : MonoBehaviour { - public SimObj ParentSimObj; public Transform Lid; public Vector3 OpenRotation; public Vector3 ClosedRotation; public GameObject DirtObject; + [Range(0, 2)] public int EditorState = 0; @@ -24,10 +24,12 @@ void OnEnable() { Animator a = ParentSimObj.gameObject.GetComponent(); if (a == null) { a = ParentSimObj.gameObject.AddComponent(); - a.runtimeAnimatorController = Resources.Load("StateAnimController") as RuntimeAnimatorController; + a.runtimeAnimatorController = + Resources.Load("StateAnimController") as RuntimeAnimatorController; } } } + // Update is called once per frame void Update() { int state = EditorState; diff --git a/unity/Assets/Scripts/TransformExtension.cs b/unity/Assets/Scripts/TransformExtension.cs index 79d4965dd0..eaff8b3a74 100644 --- a/unity/Assets/Scripts/TransformExtension.cs +++ b/unity/Assets/Scripts/TransformExtension.cs @@ -14,6 +14,5 @@ public static Transform FirstChildOrDefault(this Transform parent, Func(); // set colliders to ones active while used up diff --git a/unity/Assets/Scripts/UtilityFunctions.cs b/unity/Assets/Scripts/UtilityFunctions.cs index c16cbdbd45..de2407d4e2 100644 --- a/unity/Assets/Scripts/UtilityFunctions.cs +++ b/unity/Assets/Scripts/UtilityFunctions.cs @@ -3,27 +3,29 @@ using System.Collections.Generic; using System.IO; using System.Linq; +using System.Reflection; +using Thor.Procedural.Data; using UnityEngine; using UnityEngine.SceneManagement; using UnityStandardAssets.CrossPlatformInput; using UnityStandardAssets.Utility; -using System.Reflection; -using Thor.Procedural.Data; - #if UNITY_EDITOR using UnityEditor; using UnityEditor.SceneManagement; #endif public static class UtilityFunctions { - //store the max number of layers unity supports in its layer system. By default this is 32 //and will likely not change but here it is just in case public const int maxUnityLayerCount = 32; public static Bounds CreateEmptyBounds() { Bounds b = new Bounds(); - Vector3 inf = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); + Vector3 inf = new Vector3( + float.PositiveInfinity, + float.PositiveInfinity, + float.PositiveInfinity + ); b.SetMinMax(min: inf, max: -inf); return b; } @@ -55,7 +57,9 @@ private static IEnumerable Combinations(int m, int n) { public static IEnumerable Combinations(T[] array, int m) { // Taken from https://codereview.stackexchange.com/questions/194967/get-all-combinations-of-selecting-k-elements-from-an-n-sized-array if (array.Length < m) { - throw new ArgumentException("Array length can't be less than number of selected elements"); + throw new ArgumentException( + "Array length can't be less than number of selected elements" + ); } if (m < 1) { throw new ArgumentException("Number of selected elements can't be less than 1"); @@ -74,13 +78,14 @@ public static bool isObjectColliding( List ignoreGameObjects = null, float expandBy = 0.0f, bool useBoundingBoxInChecks = false - ) { - return null != firstColliderObjectCollidingWith( - go: go, - ignoreGameObjects: ignoreGameObjects, - expandBy: expandBy, - useBoundingBoxInChecks: useBoundingBoxInChecks - ); + ) { + return null + != firstColliderObjectCollidingWith( + go: go, + ignoreGameObjects: ignoreGameObjects, + expandBy: expandBy, + useBoundingBoxInChecks: useBoundingBoxInChecks + ); } public static Collider firstColliderObjectCollidingWith( @@ -88,7 +93,7 @@ public static Collider firstColliderObjectCollidingWith( List ignoreGameObjects = null, float expandBy = 0.0f, bool useBoundingBoxInChecks = false - ) { + ) { if (ignoreGameObjects == null) { ignoreGameObjects = new List(); } @@ -100,12 +105,26 @@ public static Collider firstColliderObjectCollidingWith( } } - int layerMask = LayerMask.GetMask("Agent", "SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"); + int layerMask = LayerMask.GetMask( + "Agent", + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ); foreach (CapsuleCollider cc in go.GetComponentsInChildren()) { if (cc.isTrigger) { continue; } - foreach (Collider c in PhysicsExtensions.OverlapCapsule(cc, layerMask, QueryTriggerInteraction.Ignore, expandBy)) { + foreach ( + Collider c in PhysicsExtensions.OverlapCapsule( + cc, + layerMask, + QueryTriggerInteraction.Ignore, + expandBy + ) + ) { if (!ignoreColliders.Contains(c)) { return c; } @@ -115,7 +134,14 @@ public static Collider firstColliderObjectCollidingWith( if (bc.isTrigger || ("BoundingBox" == bc.gameObject.name && (!useBoundingBoxInChecks))) { continue; } - foreach (Collider c in PhysicsExtensions.OverlapBox(bc, layerMask, QueryTriggerInteraction.Ignore, expandBy)) { + foreach ( + Collider c in PhysicsExtensions.OverlapBox( + bc, + layerMask, + QueryTriggerInteraction.Ignore, + expandBy + ) + ) { if (!ignoreColliders.Contains(c)) { return c; } @@ -125,7 +151,14 @@ public static Collider firstColliderObjectCollidingWith( if (sc.isTrigger) { continue; } - foreach (Collider c in PhysicsExtensions.OverlapSphere(sc, layerMask, QueryTriggerInteraction.Ignore, expandBy)) { + foreach ( + Collider c in PhysicsExtensions.OverlapSphere( + sc, + layerMask, + QueryTriggerInteraction.Ignore, + expandBy + ) + ) { if (!ignoreColliders.Contains(c)) { return c; } @@ -139,7 +172,7 @@ public static Collider[] collidersObjectCollidingWith( List ignoreGameObjects = null, float expandBy = 0.0f, bool useBoundingBoxInChecks = false - ) { + ) { if (ignoreGameObjects == null) { ignoreGameObjects = new List(); } @@ -154,7 +187,14 @@ public static Collider[] collidersObjectCollidingWith( HashSet collidersSet = new HashSet(); int layerMask = LayerMask.GetMask("SimObjVisible", "Agent"); foreach (CapsuleCollider cc in go.GetComponentsInChildren()) { - foreach (Collider c in PhysicsExtensions.OverlapCapsule(cc, layerMask, QueryTriggerInteraction.Ignore, expandBy)) { + foreach ( + Collider c in PhysicsExtensions.OverlapCapsule( + cc, + layerMask, + QueryTriggerInteraction.Ignore, + expandBy + ) + ) { if (!ignoreColliders.Contains(c)) { collidersSet.Add(c); } @@ -164,14 +204,28 @@ public static Collider[] collidersObjectCollidingWith( if ("BoundingBox" == bc.gameObject.name && (!useBoundingBoxInChecks)) { continue; } - foreach (Collider c in PhysicsExtensions.OverlapBox(bc, layerMask, QueryTriggerInteraction.Ignore, expandBy)) { + foreach ( + Collider c in PhysicsExtensions.OverlapBox( + bc, + layerMask, + QueryTriggerInteraction.Ignore, + expandBy + ) + ) { if (!ignoreColliders.Contains(c)) { collidersSet.Add(c); } } } foreach (SphereCollider sc in go.GetComponentsInChildren()) { - foreach (Collider c in PhysicsExtensions.OverlapSphere(sc, layerMask, QueryTriggerInteraction.Ignore, expandBy)) { + foreach ( + Collider c in PhysicsExtensions.OverlapSphere( + sc, + layerMask, + QueryTriggerInteraction.Ignore, + expandBy + ) + ) { if (!ignoreColliders.Contains(c)) { collidersSet.Add(c); } @@ -180,28 +234,58 @@ public static Collider[] collidersObjectCollidingWith( return collidersSet.ToArray(); } - public static RaycastHit[] CastAllPrimitiveColliders(GameObject go, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal) { + public static RaycastHit[] CastAllPrimitiveColliders( + GameObject go, + Vector3 direction, + float maxDistance = Mathf.Infinity, + int layerMask = Physics.DefaultRaycastLayers, + QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal + ) { HashSet transformsToIgnore = new HashSet(); foreach (Transform t in go.GetComponentsInChildren()) { transformsToIgnore.Add(t); } List hits = new List(); foreach (CapsuleCollider cc in go.GetComponentsInChildren()) { - foreach (RaycastHit h in PhysicsExtensions.CapsuleCastAll(cc, direction, maxDistance, layerMask, queryTriggerInteraction)) { + foreach ( + RaycastHit h in PhysicsExtensions.CapsuleCastAll( + cc, + direction, + maxDistance, + layerMask, + queryTriggerInteraction + ) + ) { if (!transformsToIgnore.Contains(h.transform)) { hits.Add(h); } } } foreach (BoxCollider bc in go.GetComponentsInChildren()) { - foreach (RaycastHit h in PhysicsExtensions.BoxCastAll(bc, direction, maxDistance, layerMask, queryTriggerInteraction)) { + foreach ( + RaycastHit h in PhysicsExtensions.BoxCastAll( + bc, + direction, + maxDistance, + layerMask, + queryTriggerInteraction + ) + ) { if (!transformsToIgnore.Contains(h.transform)) { hits.Add(h); } } } foreach (SphereCollider sc in go.GetComponentsInChildren()) { - foreach (RaycastHit h in PhysicsExtensions.SphereCastAll(sc, direction, maxDistance, layerMask, queryTriggerInteraction)) { + foreach ( + RaycastHit h in PhysicsExtensions.SphereCastAll( + sc, + direction, + maxDistance, + layerMask, + queryTriggerInteraction + ) + ) { if (!transformsToIgnore.Contains(h.transform)) { hits.Add(h); } @@ -212,13 +296,19 @@ public static RaycastHit[] CastAllPrimitiveColliders(GameObject go, Vector3 dire // get a copy of a specific component and apply it to another object at runtime // usage: var copy = myComp.GetCopyOf(someOtherComponent); - public static T GetCopyOf(this Component comp, T other) where T : Component { + public static T GetCopyOf(this Component comp, T other) + where T : Component { Type type = comp.GetType(); if (type != other.GetType()) { return null; // type mis-match } - BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Default | BindingFlags.DeclaredOnly; + BindingFlags flags = + BindingFlags.Public + | BindingFlags.NonPublic + | BindingFlags.Instance + | BindingFlags.Default + | BindingFlags.DeclaredOnly; PropertyInfo[] pinfos = type.GetProperties(flags); foreach (var pinfo in pinfos) { if (pinfo.CanWrite) { @@ -235,11 +325,11 @@ public static T GetCopyOf(this Component comp, T other) where T : Component { } // usage: Health myHealth = gameObject.AddComponent(enemy.health); or something like that - public static T AddComponent(this GameObject go, T toAdd) where T : Component { + public static T AddComponent(this GameObject go, T toAdd) + where T : Component { return go.AddComponent().GetCopyOf(toAdd) as T; } - // Taken from https://answers.unity.com/questions/589983/using-mathfround-for-a-vector3.html public static Vector3 Round(this Vector3 vector3, int decimalPlaces = 2) { float multiplier = 1; @@ -249,103 +339,126 @@ public static Vector3 Round(this Vector3 vector3, int decimalPlaces = 2) { return new Vector3( Mathf.Round(vector3.x * multiplier) / multiplier, Mathf.Round(vector3.y * multiplier) / multiplier, - Mathf.Round(vector3.z * multiplier) / multiplier); + Mathf.Round(vector3.z * multiplier) / multiplier + ); } public static Vector3[] CornerCoordinatesOfBoxColliderToWorld(BoxCollider b) { Vector3[] corners = new Vector3[8]; - corners[0] = b.transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, b.size.z) * 0.5f); - corners[1] = b.transform.TransformPoint(b.center + new Vector3(-b.size.x, -b.size.y, b.size.z) * 0.5f); - corners[2] = b.transform.TransformPoint(b.center + new Vector3(-b.size.x, -b.size.y, -b.size.z) * 0.5f); - corners[3] = b.transform.TransformPoint(b.center + new Vector3(b.size.x, -b.size.y, -b.size.z) * 0.5f); + corners[0] = b.transform.TransformPoint( + b.center + new Vector3(b.size.x, -b.size.y, b.size.z) * 0.5f + ); + corners[1] = b.transform.TransformPoint( + b.center + new Vector3(-b.size.x, -b.size.y, b.size.z) * 0.5f + ); + corners[2] = b.transform.TransformPoint( + b.center + new Vector3(-b.size.x, -b.size.y, -b.size.z) * 0.5f + ); + corners[3] = b.transform.TransformPoint( + b.center + new Vector3(b.size.x, -b.size.y, -b.size.z) * 0.5f + ); - corners[4] = b.transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, b.size.z) * 0.5f); - corners[5] = b.transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, b.size.z) * 0.5f); - corners[6] = b.transform.TransformPoint(b.center + new Vector3(-b.size.x, b.size.y, -b.size.z) * 0.5f); - corners[7] = b.transform.TransformPoint(b.center + new Vector3(b.size.x, b.size.y, -b.size.z) * 0.5f); + corners[4] = b.transform.TransformPoint( + b.center + new Vector3(b.size.x, b.size.y, b.size.z) * 0.5f + ); + corners[5] = b.transform.TransformPoint( + b.center + new Vector3(-b.size.x, b.size.y, b.size.z) * 0.5f + ); + corners[6] = b.transform.TransformPoint( + b.center + new Vector3(-b.size.x, b.size.y, -b.size.z) * 0.5f + ); + corners[7] = b.transform.TransformPoint( + b.center + new Vector3(b.size.x, b.size.y, -b.size.z) * 0.5f + ); return corners; } public static List GetLightPropertiesOfScene() { + Debug.Log("we are inside GetLIghtPropertiesOfScene"); + var lightsInScene = UnityEngine.Object.FindObjectsOfType(true); - Debug.Log("we are inside GetLIghtPropertiesOfScene"); - var lightsInScene = UnityEngine.Object.FindObjectsOfType(true); - - List allOfTheLights = new List(); - - //generate the LightParameters for all lights in the scene - foreach (Light hikari in lightsInScene) { + List allOfTheLights = new List(); - LightParameters lp = new LightParameters(); + //generate the LightParameters for all lights in the scene + foreach (Light hikari in lightsInScene) { + LightParameters lp = new LightParameters(); - lp.id = hikari.transform.name; + lp.id = hikari.transform.name; - lp.type = LightType.GetName(typeof(LightType), hikari.type); + lp.type = LightType.GetName(typeof(LightType), hikari.type); - lp.position = hikari.transform.position; + lp.position = hikari.transform.position; - lp.localPosition = hikari.transform.localPosition; + lp.localPosition = hikari.transform.localPosition; - //culling mask stuff - List cullingMaskOff = new List(); + //culling mask stuff + List cullingMaskOff = new List(); - for (int i = 0; i < UtilityFunctions.maxUnityLayerCount; ++i) { - //check what layers are off for this light's mask - if (((1 << i) & hikari.cullingMask) == 0) { - //check if this layer is actually being used (ie: has a name) - if (LayerMask.LayerToName(i).Length != 0) { - cullingMaskOff.Add(LayerMask.LayerToName(i)); - } + for (int i = 0; i < UtilityFunctions.maxUnityLayerCount; ++i) { + //check what layers are off for this light's mask + if (((1 << i) & hikari.cullingMask) == 0) { + //check if this layer is actually being used (ie: has a name) + if (LayerMask.LayerToName(i).Length != 0) { + cullingMaskOff.Add(LayerMask.LayerToName(i)); } } + } - lp.cullingMaskOff = cullingMaskOff.ToArray(); - - lp.rotation = FlexibleRotation.fromQuaternion(hikari.transform.rotation); - - lp.intensity = hikari.intensity; - - lp.indirectMultiplier = hikari.bounceIntensity; - - lp.range = hikari.range; - - //only do this if this is a spot light - if(hikari.type == LightType.Spot) { - lp.spotAngle = hikari.spotAngle; - } + lp.cullingMaskOff = cullingMaskOff.ToArray(); - lp.rgb = new SerializableColor() { r = hikari.color.r, g = hikari.color.g, b = hikari.color.b, a = hikari.color.a }; - - //generate shadow params - ShadowParameters xemnas = new ShadowParameters() { - strength = hikari.shadowStrength, - type = Enum.GetName(typeof(LightShadows), hikari.shadows), - normalBias = hikari.shadowNormalBias, - bias = hikari.shadowBias, - nearPlane = hikari.shadowNearPlane, - resolution = Enum.GetName(typeof(UnityEngine.Rendering.LightShadowResolution), hikari.shadowResolution) - }; + lp.rotation = FlexibleRotation.fromQuaternion(hikari.transform.rotation); - lp.shadow = xemnas; + lp.intensity = hikari.intensity; - //linked sim object - //lp.linkedSimObj = ; + lp.indirectMultiplier = hikari.bounceIntensity; - lp.enabled = hikari.enabled; + lp.range = hikari.range; - if(hikari.GetComponentInParent()) { - lp.parentSimObjId = hikari.GetComponentInParent().objectID; - lp.parentSimObjName = hikari.GetComponentInParent().transform.name; - } + //only do this if this is a spot light + if (hikari.type == LightType.Spot) { + lp.spotAngle = hikari.spotAngle; + } - allOfTheLights.Add(lp); + lp.rgb = new SerializableColor() { + r = hikari.color.r, + g = hikari.color.g, + b = hikari.color.b, + a = hikari.color.a + }; + + //generate shadow params + ShadowParameters xemnas = new ShadowParameters() { + strength = hikari.shadowStrength, + type = Enum.GetName(typeof(LightShadows), hikari.shadows), + normalBias = hikari.shadowNormalBias, + bias = hikari.shadowBias, + nearPlane = hikari.shadowNearPlane, + resolution = Enum.GetName( + typeof(UnityEngine.Rendering.LightShadowResolution), + hikari.shadowResolution + ) + }; + + lp.shadow = xemnas; + + //linked sim object + //lp.linkedSimObj = ; + + lp.enabled = hikari.enabled; + + if (hikari.GetComponentInParent()) { + lp.parentSimObjId = hikari.GetComponentInParent().objectID; + lp.parentSimObjName = hikari.GetComponentInParent().transform.name; } - //find all sim obj physics in scene + allOfTheLights.Add(lp); + } + + //find all sim obj physics in scene - return allOfTheLights; + return allOfTheLights; } #if UNITY_EDITOR @@ -425,7 +538,10 @@ public static void debugGetLightPropertiesOfScene(List lights) [MenuItem("SimObjectPhysics/Toggle Off PlaceableSurface Material")] private static void ToggleOffPlaceableSurface() { for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; i++) { - UnityEditor.SceneManagement.EditorSceneManager.OpenScene(SceneUtility.GetScenePathByBuildIndex(i), OpenSceneMode.Single); + UnityEditor.SceneManagement.EditorSceneManager.OpenScene( + SceneUtility.GetScenePathByBuildIndex(i), + OpenSceneMode.Single + ); var meshes = UnityEngine.Object.FindObjectsOfType(); foreach (MeshRenderer m in meshes) { @@ -433,14 +549,19 @@ private static void ToggleOffPlaceableSurface() { m.enabled = false; } } - UnityEditor.SceneManagement.EditorSceneManager.SaveScene(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene()); + UnityEditor.SceneManagement.EditorSceneManager.SaveScene( + UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene() + ); } } [MenuItem("SimObjectPhysics/Toggle On PlaceableSurface Material")] private static void ToggleOnPlaceableSurface() { for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; i++) { - UnityEditor.SceneManagement.EditorSceneManager.OpenScene(SceneUtility.GetScenePathByBuildIndex(i), OpenSceneMode.Single); + UnityEditor.SceneManagement.EditorSceneManager.OpenScene( + SceneUtility.GetScenePathByBuildIndex(i), + OpenSceneMode.Single + ); var meshes = UnityEngine.Object.FindObjectsOfType(); foreach (MeshRenderer m in meshes) { @@ -448,15 +569,19 @@ private static void ToggleOnPlaceableSurface() { m.enabled = true; } } - UnityEditor.SceneManagement.EditorSceneManager.SaveScene(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene()); - + UnityEditor.SceneManagement.EditorSceneManager.SaveScene( + UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene() + ); } } [UnityEditor.MenuItem("AI2-THOR/Add GUID to Object Names")] public static void AddGUIDToSimObjPhys() { for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; i++) { - UnityEditor.SceneManagement.EditorSceneManager.OpenScene(SceneUtility.GetScenePathByBuildIndex(i), OpenSceneMode.Single); + UnityEditor.SceneManagement.EditorSceneManager.OpenScene( + SceneUtility.GetScenePathByBuildIndex(i), + OpenSceneMode.Single + ); SimObjPhysics[] objects = GameObject.FindObjectsOfType(true); //explicitly track used Guids since we are only using the first 8 characters in the generated ID and want to be sure they are universally unique @@ -467,18 +592,16 @@ public static void AddGUIDToSimObjPhys() { bool isThisNew = true; string uid = ""; - while(isThisNew) { + while (isThisNew) { g = Guid.NewGuid(); string first8 = g.ToString("N").Substring(0, 8); //this guid is new and has not been used before - if(!usedGuidsJustInCaseCauseIDunnoThisIsRandom.Contains(first8)) { + if (!usedGuidsJustInCaseCauseIDunnoThisIsRandom.Contains(first8)) { usedGuidsJustInCaseCauseIDunnoThisIsRandom.Add(first8); isThisNew = false; uid = first8; - } - - else { + } else { Debug.Log($"wow what are the odds that {first8} was generated again!?!?"); } } @@ -486,7 +609,9 @@ public static void AddGUIDToSimObjPhys() { sop.name = sop.GetComponent().Type.ToString() + "_" + uid; } - UnityEditor.SceneManagement.EditorSceneManager.SaveScene(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene()); + UnityEditor.SceneManagement.EditorSceneManager.SaveScene( + UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene() + ); } } @@ -496,7 +621,10 @@ public static void AddGUIDToSimObjPhys() { //dynamically spawned in by something like a Procedural action. private static void NameAllSceneLightObjects() { for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; i++) { - UnityEditor.SceneManagement.EditorSceneManager.OpenScene(SceneUtility.GetScenePathByBuildIndex(i), OpenSceneMode.Single); + UnityEditor.SceneManagement.EditorSceneManager.OpenScene( + SceneUtility.GetScenePathByBuildIndex(i), + OpenSceneMode.Single + ); var lights = UnityEngine.Object.FindObjectsOfType(true); //separate lights into scene-level lights, and lights that are children of sim objects cause they have to be handled separately @@ -505,17 +633,15 @@ private static void NameAllSceneLightObjects() { Dictionary simObjChildLights = new Dictionary(); foreach (Light l in lights) { - if(!l.GetComponentInParent()) { + if (!l.GetComponentInParent()) { //one caveat here is that light switch objects do control specific "scene" lights //because they are not children of the light switches, these referenced lights must be set up in editor first //or at initialization in a Procedural scene. Check the member to see if some scene light //is actually controlled by a light switch sim object. sceneLights.Add(l, l.type); - } - - else { + } else { simObjChildLights.Add(l, l.type); - } + } } int directionalInstance = 0; @@ -526,102 +652,114 @@ private static void NameAllSceneLightObjects() { //sort the scene lights into point, directional, or spot foreach (KeyValuePair l in sceneLights) { //Debug.Log(directionalInstance); - if(l.Value == LightType.Spot) { - l.Key.name = "scene|" + l.Value.ToString()+ "|" + spotInstance.ToString(); + if (l.Value == LightType.Spot) { + l.Key.name = "scene|" + l.Value.ToString() + "|" + spotInstance.ToString(); spotInstance++; - } - - else if(l.Value == LightType.Directional) { - l.Key.name = "scene|" + l.Value.ToString()+ "|" + directionalInstance.ToString(); + } else if (l.Value == LightType.Directional) { + l.Key.name = + "scene|" + l.Value.ToString() + "|" + directionalInstance.ToString(); directionalInstance++; - } - - else if(l.Value == LightType.Point) { - l.Key.name = "scene|" + l.Value.ToString()+ "|" + pointInstance.ToString(); + } else if (l.Value == LightType.Point) { + l.Key.name = "scene|" + l.Value.ToString() + "|" + pointInstance.ToString(); pointInstance++; - } - - else if(l.Value == LightType.Area) { - l.Key.name = "scene|" + l.Value.ToString()+ "|" + areaInstance.ToString(); + } else if (l.Value == LightType.Area) { + l.Key.name = "scene|" + l.Value.ToString() + "|" + areaInstance.ToString(); areaInstance++; } } //make new dictionary to pair specific Sim Object instances with potentially multiple child lights, so multiple child light keys might have same SimObj parent value - Dictionary, SimObjPhysics> lightAndTypeToSimObjPhys = new Dictionary, SimObjPhysics>(); - + Dictionary, SimObjPhysics> lightAndTypeToSimObjPhys = + new Dictionary, SimObjPhysics>(); + //map each light/lightType pair to the sim object that they are associated with foreach (KeyValuePair l in simObjChildLights) { lightAndTypeToSimObjPhys.Add(l, l.Key.GetComponentInParent()); } //track if multiple key lights in simObjChildLIghts are children of the same SimObjPhysics - Dictionary simObjToSpotInstanceCountInThatSimObj = new Dictionary(); - Dictionary simObjToDirectionalInstanceCountInThatSimObj = new Dictionary(); - Dictionary simObjToPointInstanceCountInThatSimObj = new Dictionary(); - Dictionary simObjToAreaInstanceCountInThatSimObj = new Dictionary(); - - foreach(KeyValuePair< KeyValuePair, SimObjPhysics> light in lightAndTypeToSimObjPhys) { - - if(light.Key.Value == LightType.Spot) { - if(!simObjToSpotInstanceCountInThatSimObj.ContainsKey(light.Value)){ + Dictionary simObjToSpotInstanceCountInThatSimObj = + new Dictionary(); + Dictionary simObjToDirectionalInstanceCountInThatSimObj = + new Dictionary(); + Dictionary simObjToPointInstanceCountInThatSimObj = + new Dictionary(); + Dictionary simObjToAreaInstanceCountInThatSimObj = + new Dictionary(); + + foreach ( + KeyValuePair< + KeyValuePair, + SimObjPhysics + > light in lightAndTypeToSimObjPhys + ) { + if (light.Key.Value == LightType.Spot) { + if (!simObjToSpotInstanceCountInThatSimObj.ContainsKey(light.Value)) { //this is the first instance of a Spot light found in this sim object simObjToSpotInstanceCountInThatSimObj.Add(light.Value, 0); - } - - else { + } else { //we have found another instance of this type of light in this previously found sim object before simObjToSpotInstanceCountInThatSimObj[light.Value]++; } - light.Key.Key.name = light.Value.transform.name + "|" + light.Key.Value.ToString() + "|" + simObjToSpotInstanceCountInThatSimObj[light.Value].ToString(); - } - - else if(light.Key.Value == LightType.Directional) { - if(!simObjToDirectionalInstanceCountInThatSimObj.ContainsKey(light.Value)){ + light.Key.Key.name = + light.Value.transform.name + + "|" + + light.Key.Value.ToString() + + "|" + + simObjToSpotInstanceCountInThatSimObj[light.Value].ToString(); + } else if (light.Key.Value == LightType.Directional) { + if (!simObjToDirectionalInstanceCountInThatSimObj.ContainsKey(light.Value)) { //this is the first instance of a Directional light found in this sim object (PROBS DONT PUT A DIRECTIONAL LIGHT IN A SIM OBJ PREFAB BUT YOU DO YOU I GUESS) simObjToDirectionalInstanceCountInThatSimObj.Add(light.Value, 0); - } - - else { + } else { //we have found another instance of this type of light in this previously found sim object before simObjToDirectionalInstanceCountInThatSimObj[light.Value]++; } - light.Key.Key.name = light.Value.transform.name + "|" + light.Key.Value.ToString() + "|" + simObjToDirectionalInstanceCountInThatSimObj[light.Value].ToString(); - } - - else if(light.Key.Value == LightType.Point) { - if(!simObjToPointInstanceCountInThatSimObj.ContainsKey(light.Value)){ + light.Key.Key.name = + light.Value.transform.name + + "|" + + light.Key.Value.ToString() + + "|" + + simObjToDirectionalInstanceCountInThatSimObj[light.Value].ToString(); + } else if (light.Key.Value == LightType.Point) { + if (!simObjToPointInstanceCountInThatSimObj.ContainsKey(light.Value)) { //this is the first instance of a Point light found in this sim object simObjToPointInstanceCountInThatSimObj.Add(light.Value, 0); - } - - else { + } else { //we have found another instance of a Point light in this previously found sim object before simObjToPointInstanceCountInThatSimObj[light.Value]++; } - light.Key.Key.name = light.Value.transform.name + "|" + light.Key.Value.ToString() + "|" + simObjToPointInstanceCountInThatSimObj[light.Value].ToString(); + light.Key.Key.name = + light.Value.transform.name + + "|" + + light.Key.Value.ToString() + + "|" + + simObjToPointInstanceCountInThatSimObj[light.Value].ToString(); } - - //we currently don't really use area lights since they are baked only but this is here just in case - else if(light.Key.Value == LightType.Area) { - - if(!simObjToAreaInstanceCountInThatSimObj.ContainsKey(light.Value)){ + //we currently don't really use area lights since they are baked only but this is here just in case + else if (light.Key.Value == LightType.Area) { + if (!simObjToAreaInstanceCountInThatSimObj.ContainsKey(light.Value)) { simObjToAreaInstanceCountInThatSimObj.Add(light.Value, 0); - } - - else { + } else { simObjToAreaInstanceCountInThatSimObj[light.Value]++; } - light.Key.Key.name = light.Value.transform.name + "|" + light.Key.Value.ToString() + "|" + simObjToAreaInstanceCountInThatSimObj[light.Value].ToString(); + light.Key.Key.name = + light.Value.transform.name + + "|" + + light.Key.Value.ToString() + + "|" + + simObjToAreaInstanceCountInThatSimObj[light.Value].ToString(); } } - UnityEditor.SceneManagement.EditorSceneManager.SaveScene(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene()); + UnityEditor.SceneManagement.EditorSceneManager.SaveScene( + UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene() + ); } } #endif -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/VisualizationHeatmapCSV.cs b/unity/Assets/Scripts/VisualizationHeatmapCSV.cs index f9fc08dc44..6a0f99e550 100644 --- a/unity/Assets/Scripts/VisualizationHeatmapCSV.cs +++ b/unity/Assets/Scripts/VisualizationHeatmapCSV.cs @@ -16,7 +16,9 @@ public class VisualizationHeatmapCSV : MonoBehaviour { // Use this for initialization void Start() { string[] data = CSVFile.text.Split(new char[] { '\n' }); - float x, z, r; + float x, + z, + r; for (int i = 1; i < data.Length - 1; i++) { string[] row = data[i].Split(new char[] { ',' }); @@ -41,7 +43,5 @@ void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } } diff --git a/unity/Assets/Scripts/WhatIsInsideMagnetSphere.cs b/unity/Assets/Scripts/WhatIsInsideMagnetSphere.cs index 3e54b30594..00fd8d4b48 100644 --- a/unity/Assets/Scripts/WhatIsInsideMagnetSphere.cs +++ b/unity/Assets/Scripts/WhatIsInsideMagnetSphere.cs @@ -1,11 +1,11 @@ using System.Collections; using System.Collections.Generic; -using UnityEngine; using System.Linq; +using UnityEngine; public class WhatIsInsideMagnetSphere : MonoBehaviour { - - [SerializeField] protected List CurrentlyContainedSOP = new List(); + [SerializeField] + protected List CurrentlyContainedSOP = new List(); SphereCollider sphereCol = null; // check if the sphere is actively colliding with anything @@ -28,7 +28,13 @@ public List CurrentlyContainedSimObjects(bool onlyPickupable) { Collider[] hitColliders = Physics.OverlapSphere( position: center, radius: radius, - layerMask: LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0"), + layerMask: LayerMask.GetMask( + "SimObjVisible", + "Procedural1", + "Procedural2", + "Procedural3", + "Procedural0" + ), queryTriggerInteraction: QueryTriggerInteraction.Ignore ); foreach (var col in hitColliders) { @@ -40,11 +46,7 @@ public List CurrentlyContainedSimObjects(bool onlyPickupable) { } } List toReturn = currentlyContainedObjects.ToList(); - toReturn.Sort( - (a, b) => a.ObjectID.CompareTo(b.ObjectID) - ); + toReturn.Sort((a, b) => a.ObjectID.CompareTo(b.ObjectID)); return toReturn; } - - } diff --git a/unity/Assets/Scripts/agent_trackball_rotation.cs b/unity/Assets/Scripts/agent_trackball_rotation.cs index e08e7fdc04..1c2e0e5cdc 100644 --- a/unity/Assets/Scripts/agent_trackball_rotation.cs +++ b/unity/Assets/Scripts/agent_trackball_rotation.cs @@ -1,6 +1,7 @@ using System.Collections; using System.Collections.Generic; using UnityEngine; + public class agent_trackball_rotation : MonoBehaviour { float ballPositionToRotationRatio = 3 * Mathf.PI / 1200; // Circumference over 360 euler degrees float changeInPosition; // How far agent has moved @@ -16,12 +17,20 @@ public class agent_trackball_rotation : MonoBehaviour { void Start() // Initialize "previous" values { - prevPosition = new Vector3(gameObject.transform.position.x, 0, gameObject.transform.position.z); + prevPosition = new Vector3( + gameObject.transform.position.x, + 0, + gameObject.transform.position.z + ); prevLookDirection = gameObject.transform.parent.transform.rotation.eulerAngles.y; } void Update() { - currentPosition = new Vector3(gameObject.transform.position.x, 0, gameObject.transform.position.z); // Ball's current position + currentPosition = new Vector3( + gameObject.transform.position.x, + 0, + gameObject.transform.position.z + ); // Ball's current position currentLookDirection = gameObject.transform.parent.transform.rotation.eulerAngles.y; // Direction agent is looking in directionVector = currentPosition - prevPosition; // Direction of ball's movement @@ -30,7 +39,9 @@ void Update() { { changeInPosition = Mathf.Abs(Vector3.Magnitude(directionVector)); // How far agent has moved axisOfRotation = Vector3.Cross(Vector3.up, directionVector); // Axis of ball's rotation - rotationVector = Quaternion.AngleAxis(changeInPosition / ballPositionToRotationRatio, axisOfRotation).eulerAngles; // Ball's rotation values + rotationVector = Quaternion + .AngleAxis(changeInPosition / ballPositionToRotationRatio, axisOfRotation) + .eulerAngles; // Ball's rotation values gameObject.transform.Rotate(rotationVector, Space.World); // Rotate ball prevPosition = currentPosition; // Record position to compare against next frame } else // If agent is still @@ -44,4 +55,4 @@ void Update() { } } } -} \ No newline at end of file +} diff --git a/unity/Assets/Scripts/childcollider.cs b/unity/Assets/Scripts/childcollider.cs index 8475d7b1cc..efcced8b7c 100644 --- a/unity/Assets/Scripts/childcollider.cs +++ b/unity/Assets/Scripts/childcollider.cs @@ -3,16 +3,11 @@ using UnityEngine; public class childcollider : MonoBehaviour { - // Use this for initialization - void Start() { - - } + void Start() { } // Update is called once per frame - void Update() { - - } + void Update() { } void OnCollisionEnter(Collision collision) { print("collision enteR!"); diff --git a/unity/Assets/Scripts/coffeemachine.cs b/unity/Assets/Scripts/coffeemachine.cs index 0ccd2dcfde..cdef27f6e3 100644 --- a/unity/Assets/Scripts/coffeemachine.cs +++ b/unity/Assets/Scripts/coffeemachine.cs @@ -20,7 +20,10 @@ void Update() { public void Serve() { SimObjPhysics target; - if (osr.attachPoint.transform.GetComponentInChildren() && onOff.isTurnedOnOrOff()) { + if ( + osr.attachPoint.transform.GetComponentInChildren() + && onOff.isTurnedOnOrOff() + ) { target = osr.attachPoint.transform.GetComponentInChildren(); Fill f = target.GetComponent(); diff --git a/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs b/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs index ae9c29d15a..c81654cb2d 100755 --- a/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs +++ b/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/FirstPersonController.cs @@ -6,23 +6,51 @@ namespace UnityStandardAssets.Characters.FirstPerson { - [RequireComponent(typeof (CharacterController))] + [RequireComponent(typeof(CharacterController))] public class FirstPersonController : MonoBehaviour { - [SerializeField] private bool m_IsWalking; - [SerializeField] private float m_WalkSpeed = 0; - [SerializeField] private float m_RunSpeed = 0; - [SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten = 0.0f; - [SerializeField] private float m_JumpSpeed = 0; - [SerializeField] private float m_StickToGroundForce = 0; - [SerializeField] private float m_GravityMultiplier = 0; - [SerializeField] private MouseLook m_MouseLook = null; - [SerializeField] private bool m_UseFovKick = false; - [SerializeField] private FOVKick m_FovKick = new FOVKick(); - [SerializeField] private bool m_UseHeadBob = false; - [SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob(); - [SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob(); - [SerializeField] private float m_StepInterval = 0f; + [SerializeField] + private bool m_IsWalking; + + [SerializeField] + private float m_WalkSpeed = 0; + + [SerializeField] + private float m_RunSpeed = 0; + + [SerializeField] + [Range(0f, 1f)] + private float m_RunstepLenghten = 0.0f; + + [SerializeField] + private float m_JumpSpeed = 0; + + [SerializeField] + private float m_StickToGroundForce = 0; + + [SerializeField] + private float m_GravityMultiplier = 0; + + [SerializeField] + private MouseLook m_MouseLook = null; + + [SerializeField] + private bool m_UseFovKick = false; + + [SerializeField] + private FOVKick m_FovKick = new FOVKick(); + + [SerializeField] + private bool m_UseHeadBob = false; + + [SerializeField] + private CurveControlledBob m_HeadBob = new CurveControlledBob(); + + [SerializeField] + private LerpControlledBob m_JumpBob = new LerpControlledBob(); + + [SerializeField] + private float m_StepInterval = 0f; private Camera m_Camera; private bool m_Jump; @@ -46,12 +74,11 @@ private void Start() m_FovKick.Setup(m_Camera); m_HeadBob.Setup(m_Camera, m_StepInterval); m_StepCycle = 0f; - m_NextStep = m_StepCycle/2f; + m_NextStep = m_StepCycle / 2f; m_Jumping = false; - m_MouseLook.Init(transform , m_Camera.transform); + m_MouseLook.Init(transform, m_Camera.transform); } - // Update is called once per frame private void Update() { @@ -76,23 +103,28 @@ private void Update() m_PreviouslyGrounded = m_CharacterController.isGrounded; } - private void FixedUpdate() { float speed; GetInput(out speed); // always move along the camera forward as it is the direction that it being aimed at - Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x; + Vector3 desiredMove = transform.forward * m_Input.y + transform.right * m_Input.x; // get a normal for the surface that is being touched to move along it RaycastHit hitInfo; - Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo, - m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore); + Physics.SphereCast( + transform.position, + m_CharacterController.radius, + Vector3.down, + out hitInfo, + m_CharacterController.height / 2f, + Physics.AllLayers, + QueryTriggerInteraction.Ignore + ); desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized; - m_MoveDir.x = desiredMove.x*speed; - m_MoveDir.z = desiredMove.z*speed; - + m_MoveDir.x = desiredMove.x * speed; + m_MoveDir.z = desiredMove.z * speed; if (m_CharacterController.isGrounded) { @@ -107,9 +139,9 @@ private void FixedUpdate() } else { - m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime; + m_MoveDir += Physics.gravity * m_GravityMultiplier * Time.fixedDeltaTime; } - m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime); + m_CollisionFlags = m_CharacterController.Move(m_MoveDir * Time.fixedDeltaTime); ProgressStepCycle(speed); UpdateCameraPosition(speed); @@ -119,10 +151,16 @@ private void FixedUpdate() private void ProgressStepCycle(float speed) { - if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0)) + if ( + m_CharacterController.velocity.sqrMagnitude > 0 + && (m_Input.x != 0 || m_Input.y != 0) + ) { - m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))* - Time.fixedDeltaTime; + m_StepCycle += + ( + m_CharacterController.velocity.magnitude + + (speed * (m_IsWalking ? 1f : m_RunstepLenghten)) + ) * Time.fixedDeltaTime; } if (!(m_StepCycle > m_NextStep)) @@ -131,7 +169,6 @@ private void ProgressStepCycle(float speed) } m_NextStep = m_StepCycle + m_StepInterval; - } private void UpdateCameraPosition(float speed) @@ -143,9 +180,10 @@ private void UpdateCameraPosition(float speed) } if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded) { - m_Camera.transform.localPosition = - m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude + - (speed*(m_IsWalking ? 1f : m_RunstepLenghten))); + m_Camera.transform.localPosition = m_HeadBob.DoHeadBob( + m_CharacterController.velocity.magnitude + + (speed * (m_IsWalking ? 1f : m_RunstepLenghten)) + ); newCameraPosition = m_Camera.transform.localPosition; newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset(); } @@ -157,7 +195,6 @@ private void UpdateCameraPosition(float speed) m_Camera.transform.localPosition = newCameraPosition; } - private void GetInput(out float speed) { // Read input @@ -183,20 +220,22 @@ private void GetInput(out float speed) // handle speed change to give an fov kick // only if the player is going to a run, is running and the fovkick is to be used - if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0) + if ( + m_IsWalking != waswalking + && m_UseFovKick + && m_CharacterController.velocity.sqrMagnitude > 0 + ) { StopAllCoroutines(); StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown()); } } - private void RotateView() { - m_MouseLook.LookRotation (transform, m_Camera.transform); + m_MouseLook.LookRotation(transform, m_Camera.transform); } - private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; @@ -210,7 +249,11 @@ private void OnControllerColliderHit(ControllerColliderHit hit) { return; } - body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse); + body.AddForceAtPosition( + m_CharacterController.velocity * 0.1f, + hit.point, + ForceMode.Impulse + ); } } } diff --git a/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/HeadBob.cs b/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/HeadBob.cs index d33f136b85..53bd7501d2 100755 --- a/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/HeadBob.cs +++ b/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/HeadBob.cs @@ -11,28 +11,34 @@ public class HeadBob : MonoBehaviour public LerpControlledBob jumpAndLandingBob = new LerpControlledBob(); public RigidbodyFirstPersonController rigidbodyFirstPersonController; public float StrideInterval; - [Range(0f, 1f)] public float RunningStrideLengthen; - // private CameraRefocus m_CameraRefocus; + [Range(0f, 1f)] + public float RunningStrideLengthen; + + // private CameraRefocus m_CameraRefocus; private bool m_PreviouslyGrounded; private Vector3 m_OriginalCameraPosition; - private void Start() { motionBob.Setup(Camera, StrideInterval); m_OriginalCameraPosition = Camera.transform.localPosition; - // m_CameraRefocus = new CameraRefocus(Camera, transform.root.transform, Camera.transform.localPosition); + // m_CameraRefocus = new CameraRefocus(Camera, transform.root.transform, Camera.transform.localPosition); } - private void Update() { - // m_CameraRefocus.GetFocusPoint(); + // m_CameraRefocus.GetFocusPoint(); Vector3 newCameraPosition; - if (rigidbodyFirstPersonController.Velocity.magnitude > 0 && rigidbodyFirstPersonController.Grounded) + if ( + rigidbodyFirstPersonController.Velocity.magnitude > 0 + && rigidbodyFirstPersonController.Grounded + ) { - Camera.transform.localPosition = motionBob.DoHeadBob(rigidbodyFirstPersonController.Velocity.magnitude*(rigidbodyFirstPersonController.Running ? RunningStrideLengthen : 1f)); + Camera.transform.localPosition = motionBob.DoHeadBob( + rigidbodyFirstPersonController.Velocity.magnitude + * (rigidbodyFirstPersonController.Running ? RunningStrideLengthen : 1f) + ); newCameraPosition = Camera.transform.localPosition; newCameraPosition.y = Camera.transform.localPosition.y - jumpAndLandingBob.Offset(); } @@ -49,7 +55,7 @@ private void Update() } m_PreviouslyGrounded = rigidbodyFirstPersonController.Grounded; - // m_CameraRefocus.SetFocusPoint(); + // m_CameraRefocus.SetFocusPoint(); } } } diff --git a/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/MouseLook.cs b/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/MouseLook.cs index 88b2d1a305..7c902d0990 100755 --- a/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/MouseLook.cs +++ b/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/MouseLook.cs @@ -16,7 +16,6 @@ public class MouseLook public float smoothTime = 5f; public bool lockCursor = true; - private Quaternion m_CharacterTargetRot; private Quaternion m_CameraTargetRot; private bool m_cursorIsLocked = true; @@ -27,24 +26,29 @@ public void Init(Transform character, Transform camera) m_CameraTargetRot = camera.localRotation; } - public void LookRotation(Transform character, Transform camera) { float yRot = CrossPlatformInputManager.GetAxis("Mouse X") * XSensitivity; float xRot = CrossPlatformInputManager.GetAxis("Mouse Y") * YSensitivity; - m_CharacterTargetRot *= Quaternion.Euler (0f, yRot, 0f); - m_CameraTargetRot *= Quaternion.Euler (-xRot, 0f, 0f); + m_CharacterTargetRot *= Quaternion.Euler(0f, yRot, 0f); + m_CameraTargetRot *= Quaternion.Euler(-xRot, 0f, 0f); - if(clampVerticalRotation) - m_CameraTargetRot = ClampRotationAroundXAxis (m_CameraTargetRot); + if (clampVerticalRotation) + m_CameraTargetRot = ClampRotationAroundXAxis(m_CameraTargetRot); - if(smooth) + if (smooth) { - character.localRotation = Quaternion.Slerp (character.localRotation, m_CharacterTargetRot, - smoothTime * Time.deltaTime); - camera.localRotation = Quaternion.Slerp (camera.localRotation, m_CameraTargetRot, - smoothTime * Time.deltaTime); + character.localRotation = Quaternion.Slerp( + character.localRotation, + m_CharacterTargetRot, + smoothTime * Time.deltaTime + ); + camera.localRotation = Quaternion.Slerp( + camera.localRotation, + m_CameraTargetRot, + smoothTime * Time.deltaTime + ); } else { @@ -58,8 +62,8 @@ public void LookRotation(Transform character, Transform camera) public void SetCursorLock(bool value) { lockCursor = value; - if(!lockCursor) - {// we force unlock the cursor if the user disable the cursor locking helper + if (!lockCursor) + { // we force unlock the cursor if the user disable the cursor locking helper Cursor.lockState = CursorLockMode.None; Cursor.visible = true; } @@ -74,11 +78,11 @@ public void UpdateCursorLock() private void InternalLockUpdate() { - if(Input.GetKeyUp(KeyCode.Escape)) + if (Input.GetKeyUp(KeyCode.Escape)) { m_cursorIsLocked = false; } - else if(Input.GetMouseButtonUp(0)) + else if (Input.GetMouseButtonUp(0)) { m_cursorIsLocked = true; } @@ -102,14 +106,13 @@ Quaternion ClampRotationAroundXAxis(Quaternion q) q.z /= q.w; q.w = 1.0f; - float angleX = 2.0f * Mathf.Rad2Deg * Mathf.Atan (q.x); + float angleX = 2.0f * Mathf.Rad2Deg * Mathf.Atan(q.x); - angleX = Mathf.Clamp (angleX, MinimumX, MaximumX); + angleX = Mathf.Clamp(angleX, MinimumX, MaximumX); - q.x = Mathf.Tan (0.5f * Mathf.Deg2Rad * angleX); + q.x = Mathf.Tan(0.5f * Mathf.Deg2Rad * angleX); return q; } - } } diff --git a/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/RigidbodyFirstPersonController.cs b/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/RigidbodyFirstPersonController.cs index dc89f41cb8..f2970b77c2 100755 --- a/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/RigidbodyFirstPersonController.cs +++ b/unity/Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/RigidbodyFirstPersonController.cs @@ -4,21 +4,27 @@ namespace UnityStandardAssets.Characters.FirstPerson { - [RequireComponent(typeof (Rigidbody))] - [RequireComponent(typeof (CapsuleCollider))] + [RequireComponent(typeof(Rigidbody))] + [RequireComponent(typeof(CapsuleCollider))] public class RigidbodyFirstPersonController : MonoBehaviour { [Serializable] public class MovementSettings { - public float ForwardSpeed = 8.0f; // Speed when walking forward - public float BackwardSpeed = 4.0f; // Speed when walking backwards - public float StrafeSpeed = 4.0f; // Speed when walking sideways - public float RunMultiplier = 2.0f; // Speed when sprinting - public KeyCode RunKey = KeyCode.LeftShift; + public float ForwardSpeed = 8.0f; // Speed when walking forward + public float BackwardSpeed = 4.0f; // Speed when walking backwards + public float StrafeSpeed = 4.0f; // Speed when walking sideways + public float RunMultiplier = 2.0f; // Speed when sprinting + public KeyCode RunKey = KeyCode.LeftShift; public float JumpForce = 30f; - public AnimationCurve SlopeCurveModifier = new AnimationCurve(new Keyframe(-90.0f, 1.0f), new Keyframe(0.0f, 1.0f), new Keyframe(90.0f, 0.0f)); - [HideInInspector] public float CurrentTargetSpeed = 8f; + public AnimationCurve SlopeCurveModifier = new AnimationCurve( + new Keyframe(-90.0f, 1.0f), + new Keyframe(0.0f, 1.0f), + new Keyframe(90.0f, 0.0f) + ); + + [HideInInspector] + public float CurrentTargetSpeed = 8f; #if !MOBILE_INPUT private bool m_Running; @@ -26,33 +32,34 @@ public class MovementSettings public void UpdateDesiredTargetSpeed(Vector2 input) { - if (input == Vector2.zero) return; - if (input.x > 0 || input.x < 0) - { - // strafe - CurrentTargetSpeed = StrafeSpeed; - } - if (input.y < 0) - { - // backwards - CurrentTargetSpeed = BackwardSpeed; - } - if (input.y > 0) - { - // forwards - // handled last as if strafing and moving forward at the same time forwards speed should take precedence - CurrentTargetSpeed = ForwardSpeed; - } + if (input == Vector2.zero) + return; + if (input.x > 0 || input.x < 0) + { + // strafe + CurrentTargetSpeed = StrafeSpeed; + } + if (input.y < 0) + { + // backwards + CurrentTargetSpeed = BackwardSpeed; + } + if (input.y > 0) + { + // forwards + // handled last as if strafing and moving forward at the same time forwards speed should take precedence + CurrentTargetSpeed = ForwardSpeed; + } #if !MOBILE_INPUT - if (Input.GetKey(RunKey)) - { - CurrentTargetSpeed *= RunMultiplier; - m_Running = true; - } - else - { - m_Running = false; - } + if (Input.GetKey(RunKey)) + { + CurrentTargetSpeed *= RunMultiplier; + m_Running = true; + } + else + { + m_Running = false; + } #endif } @@ -64,7 +71,6 @@ public bool Running #endif } - [Serializable] public class AdvancedSettings { @@ -72,23 +78,24 @@ public class AdvancedSettings public float stickToGroundHelperDistance = 0.5f; // stops the character public float slowDownRate = 20f; // rate at which the controller comes to a stop when there is no input public bool airControl; // can the user control the direction that is being moved in the air + [Tooltip("set it to 0.1 or more if you get stuck in wall")] public float shellOffset; // reduce the radius by that ratio to avoid getting stuck in wall (a value of 0.1f is nice) } - public Camera cam; public MovementSettings movementSettings = new MovementSettings(); public MouseLook mouseLook = new MouseLook(); public AdvancedSettings advancedSettings = new AdvancedSettings(); - private Rigidbody m_RigidBody; private CapsuleCollider m_Capsule; private float m_YRotation; private Vector3 m_GroundContactNormal; - private bool m_Jump, m_PreviouslyGrounded, m_Jumping, m_IsGrounded; - + private bool m_Jump, + m_PreviouslyGrounded, + m_Jumping, + m_IsGrounded; public Vector3 Velocity { @@ -109,23 +116,21 @@ public bool Running { get { - #if !MOBILE_INPUT - return movementSettings.Running; +#if !MOBILE_INPUT + return movementSettings.Running; #else - return false; + return false; #endif } } - private void Start() { m_RigidBody = GetComponent(); m_Capsule = GetComponent(); - mouseLook.Init (transform, cam.transform); + mouseLook.Init(transform, cam.transform); } - private void Update() { RotateView(); @@ -136,25 +141,30 @@ private void Update() } } - private void FixedUpdate() { GroundCheck(); Vector2 input = GetInput(); - if ((Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) && (advancedSettings.airControl || m_IsGrounded)) + if ( + (Mathf.Abs(input.x) > float.Epsilon || Mathf.Abs(input.y) > float.Epsilon) + && (advancedSettings.airControl || m_IsGrounded) + ) { // always move along the camera forward as it is the direction that it being aimed at - Vector3 desiredMove = cam.transform.forward*input.y + cam.transform.right*input.x; + Vector3 desiredMove = + cam.transform.forward * input.y + cam.transform.right * input.x; desiredMove = Vector3.ProjectOnPlane(desiredMove, m_GroundContactNormal).normalized; - desiredMove.x = desiredMove.x*movementSettings.CurrentTargetSpeed; - desiredMove.z = desiredMove.z*movementSettings.CurrentTargetSpeed; - desiredMove.y = desiredMove.y*movementSettings.CurrentTargetSpeed; - if (m_RigidBody.velocity.sqrMagnitude < - (movementSettings.CurrentTargetSpeed*movementSettings.CurrentTargetSpeed)) + desiredMove.x = desiredMove.x * movementSettings.CurrentTargetSpeed; + desiredMove.z = desiredMove.z * movementSettings.CurrentTargetSpeed; + desiredMove.y = desiredMove.y * movementSettings.CurrentTargetSpeed; + if ( + m_RigidBody.velocity.sqrMagnitude + < (movementSettings.CurrentTargetSpeed * movementSettings.CurrentTargetSpeed) + ) { - m_RigidBody.AddForce(desiredMove*SlopeMultiplier(), ForceMode.Impulse); + m_RigidBody.AddForce(desiredMove * SlopeMultiplier(), ForceMode.Impulse); } } @@ -165,12 +175,24 @@ private void FixedUpdate() if (m_Jump) { m_RigidBody.drag = 0f; - m_RigidBody.velocity = new Vector3(m_RigidBody.velocity.x, 0f, m_RigidBody.velocity.z); - m_RigidBody.AddForce(new Vector3(0f, movementSettings.JumpForce, 0f), ForceMode.Impulse); + m_RigidBody.velocity = new Vector3( + m_RigidBody.velocity.x, + 0f, + m_RigidBody.velocity.z + ); + m_RigidBody.AddForce( + new Vector3(0f, movementSettings.JumpForce, 0f), + ForceMode.Impulse + ); m_Jumping = true; } - if (!m_Jumping && Mathf.Abs(input.x) < float.Epsilon && Mathf.Abs(input.y) < float.Epsilon && m_RigidBody.velocity.magnitude < 1f) + if ( + !m_Jumping + && Mathf.Abs(input.x) < float.Epsilon + && Mathf.Abs(input.y) < float.Epsilon + && m_RigidBody.velocity.magnitude < 1f + ) { m_RigidBody.Sleep(); } @@ -186,57 +208,68 @@ private void FixedUpdate() m_Jump = false; } - private float SlopeMultiplier() { float angle = Vector3.Angle(m_GroundContactNormal, Vector3.up); return movementSettings.SlopeCurveModifier.Evaluate(angle); } - private void StickToGroundHelper() { RaycastHit hitInfo; - if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo, - ((m_Capsule.height/2f) - m_Capsule.radius) + - advancedSettings.stickToGroundHelperDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore)) + if ( + Physics.SphereCast( + transform.position, + m_Capsule.radius * (1.0f - advancedSettings.shellOffset), + Vector3.down, + out hitInfo, + ((m_Capsule.height / 2f) - m_Capsule.radius) + + advancedSettings.stickToGroundHelperDistance, + Physics.AllLayers, + QueryTriggerInteraction.Ignore + ) + ) { if (Mathf.Abs(Vector3.Angle(hitInfo.normal, Vector3.up)) < 85f) { - m_RigidBody.velocity = Vector3.ProjectOnPlane(m_RigidBody.velocity, hitInfo.normal); + m_RigidBody.velocity = Vector3.ProjectOnPlane( + m_RigidBody.velocity, + hitInfo.normal + ); } } } - private Vector2 GetInput() { - Vector2 input = new Vector2 - { - x = CrossPlatformInputManager.GetAxis("Horizontal"), - y = CrossPlatformInputManager.GetAxis("Vertical") - }; - movementSettings.UpdateDesiredTargetSpeed(input); + { + x = CrossPlatformInputManager.GetAxis("Horizontal"), + y = CrossPlatformInputManager.GetAxis("Vertical") + }; + movementSettings.UpdateDesiredTargetSpeed(input); return input; } - private void RotateView() { // avoids the mouse looking if the game is effectively paused - if (Mathf.Abs(Time.timeScale) < float.Epsilon) return; + if (Mathf.Abs(Time.timeScale) < float.Epsilon) + return; // get the rotation before it's changed float oldYRotation = transform.eulerAngles.y; - mouseLook.LookRotation (transform, cam.transform); + mouseLook.LookRotation(transform, cam.transform); if (m_IsGrounded || advancedSettings.airControl) { // Rotate the rigidbody velocity to match the new direction that the character is looking - Quaternion velRotation = Quaternion.AngleAxis(transform.eulerAngles.y - oldYRotation, Vector3.up); - m_RigidBody.velocity = velRotation*m_RigidBody.velocity; + Quaternion velRotation = Quaternion.AngleAxis( + transform.eulerAngles.y - oldYRotation, + Vector3.up + ); + m_RigidBody.velocity = velRotation * m_RigidBody.velocity; } } @@ -245,8 +278,18 @@ private void GroundCheck() { m_PreviouslyGrounded = m_IsGrounded; RaycastHit hitInfo; - if (Physics.SphereCast(transform.position, m_Capsule.radius * (1.0f - advancedSettings.shellOffset), Vector3.down, out hitInfo, - ((m_Capsule.height/2f) - m_Capsule.radius) + advancedSettings.groundCheckDistance, Physics.AllLayers, QueryTriggerInteraction.Ignore)) + if ( + Physics.SphereCast( + transform.position, + m_Capsule.radius * (1.0f - advancedSettings.shellOffset), + Vector3.down, + out hitInfo, + ((m_Capsule.height / 2f) - m_Capsule.radius) + + advancedSettings.groundCheckDistance, + Physics.AllLayers, + QueryTriggerInteraction.Ignore + ) + ) { m_IsGrounded = true; m_GroundContactNormal = hitInfo.normal; diff --git a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/AxisTouchButton.cs b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/AxisTouchButton.cs index 75db18a2aa..a075e5511d 100755 --- a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/AxisTouchButton.cs +++ b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/AxisTouchButton.cs @@ -4,72 +4,72 @@ namespace UnityStandardAssets.CrossPlatformInput { - public class AxisTouchButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler - { - // designed to work in a pair with another axis touch button - // (typically with one having -1 and one having 1 axisValues) - public string axisName = "Horizontal"; // The name of the axis - public float axisValue = 1; // The axis that the value has - public float responseSpeed = 3; // The speed at which the axis touch button responds - public float returnToCentreSpeed = 3; // The speed at which the button will return to its centre + public class AxisTouchButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler + { + // designed to work in a pair with another axis touch button + // (typically with one having -1 and one having 1 axisValues) + public string axisName = "Horizontal"; // The name of the axis + public float axisValue = 1; // The axis that the value has + public float responseSpeed = 3; // The speed at which the axis touch button responds + public float returnToCentreSpeed = 3; // The speed at which the button will return to its centre - AxisTouchButton m_PairedWith; // Which button this one is paired with - CrossPlatformInputManager.VirtualAxis m_Axis; // A reference to the virtual axis as it is in the cross platform input + AxisTouchButton m_PairedWith; // Which button this one is paired with + CrossPlatformInputManager.VirtualAxis m_Axis; // A reference to the virtual axis as it is in the cross platform input - void OnEnable() - { - if (!CrossPlatformInputManager.AxisExists(axisName)) - { - // if the axis doesnt exist create a new one in cross platform input - m_Axis = new CrossPlatformInputManager.VirtualAxis(axisName); - CrossPlatformInputManager.RegisterVirtualAxis(m_Axis); - } - else - { - m_Axis = CrossPlatformInputManager.VirtualAxisReference(axisName); - } - FindPairedButton(); - } + void OnEnable() + { + if (!CrossPlatformInputManager.AxisExists(axisName)) + { + // if the axis doesnt exist create a new one in cross platform input + m_Axis = new CrossPlatformInputManager.VirtualAxis(axisName); + CrossPlatformInputManager.RegisterVirtualAxis(m_Axis); + } + else + { + m_Axis = CrossPlatformInputManager.VirtualAxisReference(axisName); + } + FindPairedButton(); + } - void FindPairedButton() - { - // find the other button witch which this button should be paired - // (it should have the same axisName) - var otherAxisButtons = FindObjectsOfType(typeof(AxisTouchButton)) as AxisTouchButton[]; + void FindPairedButton() + { + // find the other button witch which this button should be paired + // (it should have the same axisName) + var otherAxisButtons = FindObjectsOfType(typeof(AxisTouchButton)) as AxisTouchButton[]; - if (otherAxisButtons != null) - { - for (int i = 0; i < otherAxisButtons.Length; i++) - { - if (otherAxisButtons[i].axisName == axisName && otherAxisButtons[i] != this) - { - m_PairedWith = otherAxisButtons[i]; - } - } - } - } + if (otherAxisButtons != null) + { + for (int i = 0; i < otherAxisButtons.Length; i++) + { + if (otherAxisButtons[i].axisName == axisName && otherAxisButtons[i] != this) + { + m_PairedWith = otherAxisButtons[i]; + } + } + } + } - void OnDisable() - { - // The object is disabled so remove it from the cross platform input system - m_Axis.Remove(); - } + void OnDisable() + { + // The object is disabled so remove it from the cross platform input system + m_Axis.Remove(); + } + public void OnPointerDown(PointerEventData data) + { + if (m_PairedWith == null) + { + FindPairedButton(); + } + // update the axis and record that the button has been pressed this frame + m_Axis.Update( + Mathf.MoveTowards(m_Axis.GetValue, axisValue, responseSpeed * Time.deltaTime) + ); + } - public void OnPointerDown(PointerEventData data) - { - if (m_PairedWith == null) - { - FindPairedButton(); - } - // update the axis and record that the button has been pressed this frame - m_Axis.Update(Mathf.MoveTowards(m_Axis.GetValue, axisValue, responseSpeed * Time.deltaTime)); - } - - - public void OnPointerUp(PointerEventData data) - { - m_Axis.Update(Mathf.MoveTowards(m_Axis.GetValue, 0, responseSpeed * Time.deltaTime)); - } - } -} \ No newline at end of file + public void OnPointerUp(PointerEventData data) + { + m_Axis.Update(Mathf.MoveTowards(m_Axis.GetValue, 0, responseSpeed * Time.deltaTime)); + } + } +} diff --git a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/ButtonHandler.cs b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/ButtonHandler.cs index ca34acff3c..41908fc26f 100755 --- a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/ButtonHandler.cs +++ b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/ButtonHandler.cs @@ -5,46 +5,35 @@ namespace UnityStandardAssets.CrossPlatformInput { public class ButtonHandler : MonoBehaviour { - public string Name; - void OnEnable() - { - - } + void OnEnable() { } public void SetDownState() { CrossPlatformInputManager.SetButtonDown(Name); } - public void SetUpState() { CrossPlatformInputManager.SetButtonUp(Name); } - public void SetAxisPositiveState() { CrossPlatformInputManager.SetAxisPositive(Name); } - public void SetAxisNeutralState() { CrossPlatformInputManager.SetAxisZero(Name); } - public void SetAxisNegativeState() { CrossPlatformInputManager.SetAxisNegative(Name); } - public void Update() - { - - } + public void Update() { } } } diff --git a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/CrossPlatformInputManager.cs b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/CrossPlatformInputManager.cs index 7f2894413d..2e0516702d 100755 --- a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/CrossPlatformInputManager.cs +++ b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/CrossPlatformInputManager.cs @@ -4,315 +4,268 @@ namespace UnityStandardAssets.CrossPlatformInput { - public static class CrossPlatformInputManager - { - public enum ActiveInputMethod - { - Hardware, - Touch - } - - - private static VirtualInput activeInput; - - private static VirtualInput s_TouchInput; - private static VirtualInput s_HardwareInput; - - - static CrossPlatformInputManager() - { - s_TouchInput = new MobileInput(); - s_HardwareInput = new StandaloneInput(); + public static class CrossPlatformInputManager + { + public enum ActiveInputMethod + { + Hardware, + Touch + } + + private static VirtualInput activeInput; + + private static VirtualInput s_TouchInput; + private static VirtualInput s_HardwareInput; + + static CrossPlatformInputManager() + { + s_TouchInput = new MobileInput(); + s_HardwareInput = new StandaloneInput(); #if MOBILE_INPUT activeInput = s_TouchInput; #else - activeInput = s_HardwareInput; + activeInput = s_HardwareInput; #endif - } - - public static void SwitchActiveInputMethod(ActiveInputMethod activeInputMethod) - { - switch (activeInputMethod) - { - case ActiveInputMethod.Hardware: - activeInput = s_HardwareInput; - break; - - case ActiveInputMethod.Touch: - activeInput = s_TouchInput; - break; - } - } - - public static bool AxisExists(string name) - { - return activeInput.AxisExists(name); - } - - public static bool ButtonExists(string name) - { - return activeInput.ButtonExists(name); - } - - public static void RegisterVirtualAxis(VirtualAxis axis) - { - activeInput.RegisterVirtualAxis(axis); - } - - - public static void RegisterVirtualButton(VirtualButton button) - { - activeInput.RegisterVirtualButton(button); - } - - - public static void UnRegisterVirtualAxis(string name) - { - if (name == null) - { - throw new ArgumentNullException("name"); - } - activeInput.UnRegisterVirtualAxis(name); - } - - - public static void UnRegisterVirtualButton(string name) - { - activeInput.UnRegisterVirtualButton(name); - } - - - // returns a reference to a named virtual axis if it exists otherwise null - public static VirtualAxis VirtualAxisReference(string name) - { - return activeInput.VirtualAxisReference(name); - } - - - // returns the platform appropriate axis for the given name - public static float GetAxis(string name) - { - return GetAxis(name, false); - } - - - public static float GetAxisRaw(string name) - { - return GetAxis(name, true); - } - - - // private function handles both types of axis (raw and not raw) - private static float GetAxis(string name, bool raw) - { - return activeInput.GetAxis(name, raw); - } - - - // -- Button handling -- - public static bool GetButton(string name) - { - return activeInput.GetButton(name); - } - - - public static bool GetButtonDown(string name) - { - return activeInput.GetButtonDown(name); - } - - - public static bool GetButtonUp(string name) - { - return activeInput.GetButtonUp(name); - } - - - public static void SetButtonDown(string name) - { - activeInput.SetButtonDown(name); - } - - - public static void SetButtonUp(string name) - { - activeInput.SetButtonUp(name); - } - - - public static void SetAxisPositive(string name) - { - activeInput.SetAxisPositive(name); - } - - - public static void SetAxisNegative(string name) - { - activeInput.SetAxisNegative(name); - } - - - public static void SetAxisZero(string name) - { - activeInput.SetAxisZero(name); - } - - - public static void SetAxis(string name, float value) - { - activeInput.SetAxis(name, value); - } - - - public static Vector3 mousePosition - { - get { return activeInput.MousePosition(); } - } - - - public static void SetVirtualMousePositionX(float f) - { - activeInput.SetVirtualMousePositionX(f); - } - - - public static void SetVirtualMousePositionY(float f) - { - activeInput.SetVirtualMousePositionY(f); - } - - - public static void SetVirtualMousePositionZ(float f) - { - activeInput.SetVirtualMousePositionZ(f); - } - - - // virtual axis and button classes - applies to mobile input - // Can be mapped to touch joysticks, tilt, gyro, etc, depending on desired implementation. - // Could also be implemented by other input devices - kinect, electronic sensors, etc - public class VirtualAxis - { - public string name { get; private set; } - private float m_Value; - public bool matchWithInputManager { get; private set; } - - - public VirtualAxis(string name) - : this(name, true) - { - } - - - public VirtualAxis(string name, bool matchToInputSettings) - { - this.name = name; - matchWithInputManager = matchToInputSettings; - } - - - // removes an axes from the cross platform input system - public void Remove() - { - UnRegisterVirtualAxis(name); - } - - - // a controller gameobject (eg. a virtual thumbstick) should update this class - public void Update(float value) - { - m_Value = value; - } - - - public float GetValue - { - get { return m_Value; } - } - - - public float GetValueRaw - { - get { return m_Value; } - } - } - - // a controller gameobject (eg. a virtual GUI button) should call the - // 'pressed' function of this class. Other objects can then read the - // Get/Down/Up state of this button. - public class VirtualButton - { - public string name { get; private set; } - public bool matchWithInputManager { get; private set; } - - private int m_LastPressedFrame = -5; - private int m_ReleasedFrame = -5; - private bool m_Pressed; - - - public VirtualButton(string name) - : this(name, true) - { - } - - - public VirtualButton(string name, bool matchToInputSettings) - { - this.name = name; - matchWithInputManager = matchToInputSettings; - } - - - // A controller gameobject should call this function when the button is pressed down - public void Pressed() - { - if (m_Pressed) - { - return; - } - m_Pressed = true; - m_LastPressedFrame = Time.frameCount; - } - - - // A controller gameobject should call this function when the button is released - public void Released() - { - m_Pressed = false; - m_ReleasedFrame = Time.frameCount; - } - - - // the controller gameobject should call Remove when the button is destroyed or disabled - public void Remove() - { - UnRegisterVirtualButton(name); - } - - - // these are the states of the button which can be read via the cross platform input system - public bool GetButton - { - get { return m_Pressed; } - } - - - public bool GetButtonDown - { - get - { - return m_LastPressedFrame - Time.frameCount == -1; - } - } - - - public bool GetButtonUp - { - get - { - return (m_ReleasedFrame == Time.frameCount - 1); - } - } - } - } + } + + public static void SwitchActiveInputMethod(ActiveInputMethod activeInputMethod) + { + switch (activeInputMethod) + { + case ActiveInputMethod.Hardware: + activeInput = s_HardwareInput; + break; + + case ActiveInputMethod.Touch: + activeInput = s_TouchInput; + break; + } + } + + public static bool AxisExists(string name) + { + return activeInput.AxisExists(name); + } + + public static bool ButtonExists(string name) + { + return activeInput.ButtonExists(name); + } + + public static void RegisterVirtualAxis(VirtualAxis axis) + { + activeInput.RegisterVirtualAxis(axis); + } + + public static void RegisterVirtualButton(VirtualButton button) + { + activeInput.RegisterVirtualButton(button); + } + + public static void UnRegisterVirtualAxis(string name) + { + if (name == null) + { + throw new ArgumentNullException("name"); + } + activeInput.UnRegisterVirtualAxis(name); + } + + public static void UnRegisterVirtualButton(string name) + { + activeInput.UnRegisterVirtualButton(name); + } + + // returns a reference to a named virtual axis if it exists otherwise null + public static VirtualAxis VirtualAxisReference(string name) + { + return activeInput.VirtualAxisReference(name); + } + + // returns the platform appropriate axis for the given name + public static float GetAxis(string name) + { + return GetAxis(name, false); + } + + public static float GetAxisRaw(string name) + { + return GetAxis(name, true); + } + + // private function handles both types of axis (raw and not raw) + private static float GetAxis(string name, bool raw) + { + return activeInput.GetAxis(name, raw); + } + + // -- Button handling -- + public static bool GetButton(string name) + { + return activeInput.GetButton(name); + } + + public static bool GetButtonDown(string name) + { + return activeInput.GetButtonDown(name); + } + + public static bool GetButtonUp(string name) + { + return activeInput.GetButtonUp(name); + } + + public static void SetButtonDown(string name) + { + activeInput.SetButtonDown(name); + } + + public static void SetButtonUp(string name) + { + activeInput.SetButtonUp(name); + } + + public static void SetAxisPositive(string name) + { + activeInput.SetAxisPositive(name); + } + + public static void SetAxisNegative(string name) + { + activeInput.SetAxisNegative(name); + } + + public static void SetAxisZero(string name) + { + activeInput.SetAxisZero(name); + } + + public static void SetAxis(string name, float value) + { + activeInput.SetAxis(name, value); + } + + public static Vector3 mousePosition + { + get { return activeInput.MousePosition(); } + } + + public static void SetVirtualMousePositionX(float f) + { + activeInput.SetVirtualMousePositionX(f); + } + + public static void SetVirtualMousePositionY(float f) + { + activeInput.SetVirtualMousePositionY(f); + } + + public static void SetVirtualMousePositionZ(float f) + { + activeInput.SetVirtualMousePositionZ(f); + } + + // virtual axis and button classes - applies to mobile input + // Can be mapped to touch joysticks, tilt, gyro, etc, depending on desired implementation. + // Could also be implemented by other input devices - kinect, electronic sensors, etc + public class VirtualAxis + { + public string name { get; private set; } + private float m_Value; + public bool matchWithInputManager { get; private set; } + + public VirtualAxis(string name) + : this(name, true) { } + + public VirtualAxis(string name, bool matchToInputSettings) + { + this.name = name; + matchWithInputManager = matchToInputSettings; + } + + // removes an axes from the cross platform input system + public void Remove() + { + UnRegisterVirtualAxis(name); + } + + // a controller gameobject (eg. a virtual thumbstick) should update this class + public void Update(float value) + { + m_Value = value; + } + + public float GetValue + { + get { return m_Value; } + } + + public float GetValueRaw + { + get { return m_Value; } + } + } + + // a controller gameobject (eg. a virtual GUI button) should call the + // 'pressed' function of this class. Other objects can then read the + // Get/Down/Up state of this button. + public class VirtualButton + { + public string name { get; private set; } + public bool matchWithInputManager { get; private set; } + + private int m_LastPressedFrame = -5; + private int m_ReleasedFrame = -5; + private bool m_Pressed; + + public VirtualButton(string name) + : this(name, true) { } + + public VirtualButton(string name, bool matchToInputSettings) + { + this.name = name; + matchWithInputManager = matchToInputSettings; + } + + // A controller gameobject should call this function when the button is pressed down + public void Pressed() + { + if (m_Pressed) + { + return; + } + m_Pressed = true; + m_LastPressedFrame = Time.frameCount; + } + + // A controller gameobject should call this function when the button is released + public void Released() + { + m_Pressed = false; + m_ReleasedFrame = Time.frameCount; + } + + // the controller gameobject should call Remove when the button is destroyed or disabled + public void Remove() + { + UnRegisterVirtualButton(name); + } + + // these are the states of the button which can be read via the cross platform input system + public bool GetButton + { + get { return m_Pressed; } + } + + public bool GetButtonDown + { + get { return m_LastPressedFrame - Time.frameCount == -1; } + } + + public bool GetButtonUp + { + get { return (m_ReleasedFrame == Time.frameCount - 1); } + } + } + } } diff --git a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/InputAxisScrollbar.cs b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/InputAxisScrollbar.cs index b29832b935..c8a55c1071 100755 --- a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/InputAxisScrollbar.cs +++ b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/InputAxisScrollbar.cs @@ -7,11 +7,11 @@ public class InputAxisScrollbar : MonoBehaviour { public string axis; - void Update() { } + void Update() { } - public void HandleInput(float value) + public void HandleInput(float value) { - CrossPlatformInputManager.SetAxis(axis, (value*2f) - 1f); + CrossPlatformInputManager.SetAxis(axis, (value * 2f) - 1f); } } } diff --git a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/Joystick.cs b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/Joystick.cs index fad46a8964..816a871121 100755 --- a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/Joystick.cs +++ b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/Joystick.cs @@ -4,115 +4,118 @@ namespace UnityStandardAssets.CrossPlatformInput { - public class Joystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler - { - public enum AxisOption - { - // Options for which axes to use - Both, // Use both - OnlyHorizontal, // Only horizontal - OnlyVertical // Only vertical - } + public class Joystick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler + { + public enum AxisOption + { + // Options for which axes to use + Both, // Use both + OnlyHorizontal, // Only horizontal + OnlyVertical // Only vertical + } - public int MovementRange = 100; - public AxisOption axesToUse = AxisOption.Both; // The options for the axes that the still will use - public string horizontalAxisName = "Horizontal"; // The name given to the horizontal axis for the cross platform input - public string verticalAxisName = "Vertical"; // The name given to the vertical axis for the cross platform input + public int MovementRange = 100; + public AxisOption axesToUse = AxisOption.Both; // The options for the axes that the still will use + public string horizontalAxisName = "Horizontal"; // The name given to the horizontal axis for the cross platform input + public string verticalAxisName = "Vertical"; // The name given to the vertical axis for the cross platform input - Vector3 m_StartPos; - bool m_UseX; // Toggle for using the x axis - bool m_UseY; // Toggle for using the Y axis - CrossPlatformInputManager.VirtualAxis m_HorizontalVirtualAxis; // Reference to the joystick in the cross platform input - CrossPlatformInputManager.VirtualAxis m_VerticalVirtualAxis; // Reference to the joystick in the cross platform input + Vector3 m_StartPos; + bool m_UseX; // Toggle for using the x axis + bool m_UseY; // Toggle for using the Y axis + CrossPlatformInputManager.VirtualAxis m_HorizontalVirtualAxis; // Reference to the joystick in the cross platform input + CrossPlatformInputManager.VirtualAxis m_VerticalVirtualAxis; // Reference to the joystick in the cross platform input - void OnEnable() - { - CreateVirtualAxes(); - } + void OnEnable() + { + CreateVirtualAxes(); + } void Start() { m_StartPos = transform.position; } - void UpdateVirtualAxes(Vector3 value) - { - var delta = m_StartPos - value; - delta.y = -delta.y; - delta /= MovementRange; - if (m_UseX) - { - m_HorizontalVirtualAxis.Update(-delta.x); - } - - if (m_UseY) - { - m_VerticalVirtualAxis.Update(delta.y); - } - } - - void CreateVirtualAxes() - { - // set axes to use - m_UseX = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal); - m_UseY = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical); - - // create new axes based on axes to use - if (m_UseX) - { - m_HorizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(horizontalAxisName); - CrossPlatformInputManager.RegisterVirtualAxis(m_HorizontalVirtualAxis); - } - if (m_UseY) - { - m_VerticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(verticalAxisName); - CrossPlatformInputManager.RegisterVirtualAxis(m_VerticalVirtualAxis); - } - } - - - public void OnDrag(PointerEventData data) - { - Vector3 newPos = Vector3.zero; - - if (m_UseX) - { - int delta = (int)(data.position.x - m_StartPos.x); - delta = Mathf.Clamp(delta, - MovementRange, MovementRange); - newPos.x = delta; - } - - if (m_UseY) - { - int delta = (int)(data.position.y - m_StartPos.y); - delta = Mathf.Clamp(delta, -MovementRange, MovementRange); - newPos.y = delta; - } - transform.position = new Vector3(m_StartPos.x + newPos.x, m_StartPos.y + newPos.y, m_StartPos.z + newPos.z); - UpdateVirtualAxes(transform.position); - } + void UpdateVirtualAxes(Vector3 value) + { + var delta = m_StartPos - value; + delta.y = -delta.y; + delta /= MovementRange; + if (m_UseX) + { + m_HorizontalVirtualAxis.Update(-delta.x); + } + + if (m_UseY) + { + m_VerticalVirtualAxis.Update(delta.y); + } + } + void CreateVirtualAxes() + { + // set axes to use + m_UseX = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal); + m_UseY = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical); + + // create new axes based on axes to use + if (m_UseX) + { + m_HorizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis( + horizontalAxisName + ); + CrossPlatformInputManager.RegisterVirtualAxis(m_HorizontalVirtualAxis); + } + if (m_UseY) + { + m_VerticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(verticalAxisName); + CrossPlatformInputManager.RegisterVirtualAxis(m_VerticalVirtualAxis); + } + } - public void OnPointerUp(PointerEventData data) - { - transform.position = m_StartPos; - UpdateVirtualAxes(m_StartPos); - } + public void OnDrag(PointerEventData data) + { + Vector3 newPos = Vector3.zero; + + if (m_UseX) + { + int delta = (int)(data.position.x - m_StartPos.x); + delta = Mathf.Clamp(delta, -MovementRange, MovementRange); + newPos.x = delta; + } + + if (m_UseY) + { + int delta = (int)(data.position.y - m_StartPos.y); + delta = Mathf.Clamp(delta, -MovementRange, MovementRange); + newPos.y = delta; + } + transform.position = new Vector3( + m_StartPos.x + newPos.x, + m_StartPos.y + newPos.y, + m_StartPos.z + newPos.z + ); + UpdateVirtualAxes(transform.position); + } + public void OnPointerUp(PointerEventData data) + { + transform.position = m_StartPos; + UpdateVirtualAxes(m_StartPos); + } - public void OnPointerDown(PointerEventData data) { } + public void OnPointerDown(PointerEventData data) { } - void OnDisable() - { - // remove the joysticks from the cross platform input - if (m_UseX) - { - m_HorizontalVirtualAxis.Remove(); - } - if (m_UseY) - { - m_VerticalVirtualAxis.Remove(); - } - } - } -} \ No newline at end of file + void OnDisable() + { + // remove the joysticks from the cross platform input + if (m_UseX) + { + m_HorizontalVirtualAxis.Remove(); + } + if (m_UseY) + { + m_VerticalVirtualAxis.Remove(); + } + } + } +} diff --git a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/MobileControlRig.cs b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/MobileControlRig.cs index dbfb89b5ea..a5c2b2ac37 100755 --- a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/MobileControlRig.cs +++ b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/MobileControlRig.cs @@ -1,16 +1,15 @@ using System; +using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif -using UnityEngine; - namespace UnityStandardAssets.CrossPlatformInput { [ExecuteInEditMode] public class MobileControlRig : MonoBehaviour #if UNITY_EDITOR - , UnityEditor.Build.IActiveBuildTargetChanged + , UnityEditor.Build.IActiveBuildTargetChanged #endif { // this script enables or disables the child objects of a control rig @@ -21,17 +20,14 @@ public class MobileControlRig : MonoBehaviour #if !UNITY_EDITOR - void OnEnable() - { - CheckEnableControlRig(); - } + void OnEnable() + { + CheckEnableControlRig(); + } #else public int callbackOrder { - get - { - return 1; - } + get { return 1; } } #endif @@ -41,10 +37,11 @@ private void Start() if (Application.isPlaying) // if in the editor, need to check if we are playing, as start is also called just after exiting play #endif { - UnityEngine.EventSystems.EventSystem system = GameObject.FindObjectOfType(); + UnityEngine.EventSystems.EventSystem system = + GameObject.FindObjectOfType(); if (system == null) - {// the scene have no event system, spawn one + { // the scene have no event system, spawn one GameObject o = new GameObject("EventSystem"); o.AddComponent(); @@ -60,30 +57,26 @@ private void OnEnable() EditorApplication.update += Update; } - private void OnDisable() { EditorApplication.update -= Update; } - private void Update() { CheckEnableControlRig(); } #endif - private void CheckEnableControlRig() { #if MOBILE_INPUT - EnableControlRig(true); + EnableControlRig(true); #else EnableControlRig(false); #endif } - private void EnableControlRig(bool enabled) { foreach (Transform t in transform) @@ -99,4 +92,4 @@ public void OnActiveBuildTargetChanged(BuildTarget previousTarget, BuildTarget n } #endif } -} \ No newline at end of file +} diff --git a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/PlatformSpecific/MobileInput.cs b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/PlatformSpecific/MobileInput.cs index 580bda73bf..1a2ec8220b 100755 --- a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/PlatformSpecific/MobileInput.cs +++ b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/PlatformSpecific/MobileInput.cs @@ -8,17 +8,19 @@ public class MobileInput : VirtualInput private void AddButton(string name) { // we have not registered this button yet so add it, happens in the constructor - CrossPlatformInputManager.RegisterVirtualButton(new CrossPlatformInputManager.VirtualButton(name)); + CrossPlatformInputManager.RegisterVirtualButton( + new CrossPlatformInputManager.VirtualButton(name) + ); } - private void AddAxes(string name) { // we have not registered this button yet so add it, happens in the constructor - CrossPlatformInputManager.RegisterVirtualAxis(new CrossPlatformInputManager.VirtualAxis(name)); + CrossPlatformInputManager.RegisterVirtualAxis( + new CrossPlatformInputManager.VirtualAxis(name) + ); } - public override float GetAxis(string name, bool raw) { if (!m_VirtualAxes.ContainsKey(name)) @@ -28,7 +30,6 @@ public override float GetAxis(string name, bool raw) return m_VirtualAxes[name].GetValue; } - public override void SetButtonDown(string name) { if (!m_VirtualButtons.ContainsKey(name)) @@ -38,7 +39,6 @@ public override void SetButtonDown(string name) m_VirtualButtons[name].Pressed(); } - public override void SetButtonUp(string name) { if (!m_VirtualButtons.ContainsKey(name)) @@ -48,7 +48,6 @@ public override void SetButtonUp(string name) m_VirtualButtons[name].Released(); } - public override void SetAxisPositive(string name) { if (!m_VirtualAxes.ContainsKey(name)) @@ -58,7 +57,6 @@ public override void SetAxisPositive(string name) m_VirtualAxes[name].Update(1f); } - public override void SetAxisNegative(string name) { if (!m_VirtualAxes.ContainsKey(name)) @@ -68,7 +66,6 @@ public override void SetAxisNegative(string name) m_VirtualAxes[name].Update(-1f); } - public override void SetAxisZero(string name) { if (!m_VirtualAxes.ContainsKey(name)) @@ -78,7 +75,6 @@ public override void SetAxisZero(string name) m_VirtualAxes[name].Update(0f); } - public override void SetAxis(string name, float value) { if (!m_VirtualAxes.ContainsKey(name)) @@ -88,7 +84,6 @@ public override void SetAxis(string name, float value) m_VirtualAxes[name].Update(value); } - public override bool GetButtonDown(string name) { if (m_VirtualButtons.ContainsKey(name)) @@ -100,7 +95,6 @@ public override bool GetButtonDown(string name) return m_VirtualButtons[name].GetButtonDown; } - public override bool GetButtonUp(string name) { if (m_VirtualButtons.ContainsKey(name)) @@ -112,7 +106,6 @@ public override bool GetButtonUp(string name) return m_VirtualButtons[name].GetButtonUp; } - public override bool GetButton(string name) { if (m_VirtualButtons.ContainsKey(name)) @@ -124,7 +117,6 @@ public override bool GetButton(string name) return m_VirtualButtons[name].GetButton; } - public override Vector3 MousePosition() { return virtualMousePosition; diff --git a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/PlatformSpecific/StandaloneInput.cs b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/PlatformSpecific/StandaloneInput.cs index 9cc1a37827..25a68cc114 100755 --- a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/PlatformSpecific/StandaloneInput.cs +++ b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/PlatformSpecific/StandaloneInput.cs @@ -10,70 +10,66 @@ public override float GetAxis(string name, bool raw) return raw ? Input.GetAxisRaw(name) : Input.GetAxis(name); } - public override bool GetButton(string name) { return Input.GetButton(name); } - public override bool GetButtonDown(string name) { return Input.GetButtonDown(name); } - public override bool GetButtonUp(string name) { return Input.GetButtonUp(name); } - public override void SetButtonDown(string name) { throw new Exception( - " This is not possible to be called for standalone input. Please check your platform and code where this is called"); + " This is not possible to be called for standalone input. Please check your platform and code where this is called" + ); } - public override void SetButtonUp(string name) { throw new Exception( - " This is not possible to be called for standalone input. Please check your platform and code where this is called"); + " This is not possible to be called for standalone input. Please check your platform and code where this is called" + ); } - public override void SetAxisPositive(string name) { throw new Exception( - " This is not possible to be called for standalone input. Please check your platform and code where this is called"); + " This is not possible to be called for standalone input. Please check your platform and code where this is called" + ); } - public override void SetAxisNegative(string name) { throw new Exception( - " This is not possible to be called for standalone input. Please check your platform and code where this is called"); + " This is not possible to be called for standalone input. Please check your platform and code where this is called" + ); } - public override void SetAxisZero(string name) { throw new Exception( - " This is not possible to be called for standalone input. Please check your platform and code where this is called"); + " This is not possible to be called for standalone input. Please check your platform and code where this is called" + ); } - public override void SetAxis(string name, float value) { throw new Exception( - " This is not possible to be called for standalone input. Please check your platform and code where this is called"); + " This is not possible to be called for standalone input. Please check your platform and code where this is called" + ); } - public override Vector3 MousePosition() { return Input.mousePosition; } } -} \ No newline at end of file +} diff --git a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/TiltInput.cs b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/TiltInput.cs index 328e3b4a15..3ced32ba48 100755 --- a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/TiltInput.cs +++ b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/TiltInput.cs @@ -16,7 +16,6 @@ public enum AxisOptions SidewaysAxis, } - [Serializable] public class AxisMapping { @@ -28,21 +27,17 @@ public enum MappingType MousePositionZ }; - public MappingType type; public string axisName; } - public AxisMapping mapping; public AxisOptions tiltAroundAxis = AxisOptions.ForwardAxis; public float fullTiltAngle = 25; public float centreAngleOffset = 0; - private CrossPlatformInputManager.VirtualAxis m_SteerAxis; - private void OnEnable() { if (mapping.type == AxisMapping.MappingType.NamedAxis) @@ -52,7 +47,6 @@ private void OnEnable() } } - private void Update() { float angle = 0; @@ -61,35 +55,36 @@ private void Update() switch (tiltAroundAxis) { case AxisOptions.ForwardAxis: - angle = Mathf.Atan2(Input.acceleration.x, -Input.acceleration.y)*Mathf.Rad2Deg + - centreAngleOffset; + angle = + Mathf.Atan2(Input.acceleration.x, -Input.acceleration.y) * Mathf.Rad2Deg + + centreAngleOffset; break; case AxisOptions.SidewaysAxis: - angle = Mathf.Atan2(Input.acceleration.z, -Input.acceleration.y)*Mathf.Rad2Deg + - centreAngleOffset; + angle = + Mathf.Atan2(Input.acceleration.z, -Input.acceleration.y) * Mathf.Rad2Deg + + centreAngleOffset; break; } } - float axisValue = Mathf.InverseLerp(-fullTiltAngle, fullTiltAngle, angle)*2 - 1; + float axisValue = Mathf.InverseLerp(-fullTiltAngle, fullTiltAngle, angle) * 2 - 1; switch (mapping.type) { case AxisMapping.MappingType.NamedAxis: m_SteerAxis.Update(axisValue); break; case AxisMapping.MappingType.MousePositionX: - CrossPlatformInputManager.SetVirtualMousePositionX(axisValue*Screen.width); + CrossPlatformInputManager.SetVirtualMousePositionX(axisValue * Screen.width); break; case AxisMapping.MappingType.MousePositionY: - CrossPlatformInputManager.SetVirtualMousePositionY(axisValue*Screen.width); + CrossPlatformInputManager.SetVirtualMousePositionY(axisValue * Screen.width); break; case AxisMapping.MappingType.MousePositionZ: - CrossPlatformInputManager.SetVirtualMousePositionZ(axisValue*Screen.width); + CrossPlatformInputManager.SetVirtualMousePositionZ(axisValue * Screen.width); break; } } - private void OnDisable() { m_SteerAxis.Remove(); @@ -97,11 +92,10 @@ private void OnDisable() } } - namespace UnityStandardAssets.CrossPlatformInput.Inspector { #if UNITY_EDITOR - [CustomPropertyDrawer(typeof (TiltInput.AxisMapping))] + [CustomPropertyDrawer(typeof(TiltInput.AxisMapping))] public class TiltInputAxisStylePropertyDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) @@ -116,24 +110,28 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten var indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; - var props = new[] {"type", "axisName"}; - var widths = new[] {.4f, .6f}; + var props = new[] { "type", "axisName" }; + var widths = new[] { .4f, .6f }; if (property.FindPropertyRelative("type").enumValueIndex > 0) { // hide name if not a named axis - props = new[] {"type"}; - widths = new[] {1f}; + props = new[] { "type" }; + widths = new[] { 1f }; } const float lineHeight = 18; for (int n = 0; n < props.Length; ++n) { - float w = widths[n]*inspectorWidth; + float w = widths[n] * inspectorWidth; // Calculate rects Rect rect = new Rect(x, y, w, lineHeight); x += w; - EditorGUI.PropertyField(rect, property.FindPropertyRelative(props[n]), GUIContent.none); + EditorGUI.PropertyField( + rect, + property.FindPropertyRelative(props[n]), + GUIContent.none + ); } // Set indent back to what it was diff --git a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/TouchPad.cs b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/TouchPad.cs index 3c3361278e..15e9a29a11 100755 --- a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/TouchPad.cs +++ b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/TouchPad.cs @@ -5,56 +5,52 @@ namespace UnityStandardAssets.CrossPlatformInput { - [RequireComponent(typeof(Image))] - public class TouchPad : MonoBehaviour, IPointerDownHandler, IPointerUpHandler - { - // Options for which axes to use - public enum AxisOption - { - Both, // Use both - OnlyHorizontal, // Only horizontal - OnlyVertical // Only vertical - } - - - public enum ControlStyle - { - Absolute, // operates from teh center of the image - Relative, // operates from the center of the initial touch - Swipe, // swipe to touch touch no maintained center - } - - - public AxisOption axesToUse = AxisOption.Both; // The options for the axes that the still will use - public ControlStyle controlStyle = ControlStyle.Absolute; // control style to use - public string horizontalAxisName = "Horizontal"; // The name given to the horizontal axis for the cross platform input - public string verticalAxisName = "Vertical"; // The name given to the vertical axis for the cross platform input - public float Xsensitivity = 1f; - public float Ysensitivity = 1f; - - Vector3 m_StartPos; - Vector2 m_PreviousDelta; - Vector3 m_JoytickOutput; - bool m_UseX; // Toggle for using the x axis - bool m_UseY; // Toggle for using the Y axis - CrossPlatformInputManager.VirtualAxis m_HorizontalVirtualAxis; // Reference to the joystick in the cross platform input - CrossPlatformInputManager.VirtualAxis m_VerticalVirtualAxis; // Reference to the joystick in the cross platform input - bool m_Dragging; - int m_Id = -1; - Vector2 m_PreviousTouchPos; // swipe style control touch + [RequireComponent(typeof(Image))] + public class TouchPad : MonoBehaviour, IPointerDownHandler, IPointerUpHandler + { + // Options for which axes to use + public enum AxisOption + { + Both, // Use both + OnlyHorizontal, // Only horizontal + OnlyVertical // Only vertical + } + public enum ControlStyle + { + Absolute, // operates from teh center of the image + Relative, // operates from the center of the initial touch + Swipe, // swipe to touch touch no maintained center + } + public AxisOption axesToUse = AxisOption.Both; // The options for the axes that the still will use + public ControlStyle controlStyle = ControlStyle.Absolute; // control style to use + public string horizontalAxisName = "Horizontal"; // The name given to the horizontal axis for the cross platform input + public string verticalAxisName = "Vertical"; // The name given to the vertical axis for the cross platform input + public float Xsensitivity = 1f; + public float Ysensitivity = 1f; + + Vector3 m_StartPos; + Vector2 m_PreviousDelta; + Vector3 m_JoytickOutput; + bool m_UseX; // Toggle for using the x axis + bool m_UseY; // Toggle for using the Y axis + CrossPlatformInputManager.VirtualAxis m_HorizontalVirtualAxis; // Reference to the joystick in the cross platform input + CrossPlatformInputManager.VirtualAxis m_VerticalVirtualAxis; // Reference to the joystick in the cross platform input + bool m_Dragging; + int m_Id = -1; + Vector2 m_PreviousTouchPos; // swipe style control touch #if !UNITY_EDITOR - private Vector3 m_Center; - private Image m_Image; + private Vector3 m_Center; + private Image m_Image; #else - Vector3 m_PreviousMouse; + Vector3 m_PreviousMouse; #endif - void OnEnable() - { - CreateVirtualAxes(); - } + void OnEnable() + { + CreateVirtualAxes(); + } void Start() { @@ -64,93 +60,96 @@ void Start() #endif } - void CreateVirtualAxes() - { - // set axes to use - m_UseX = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal); - m_UseY = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical); - - // create new axes based on axes to use - if (m_UseX) - { - m_HorizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(horizontalAxisName); - CrossPlatformInputManager.RegisterVirtualAxis(m_HorizontalVirtualAxis); - } - if (m_UseY) - { - m_VerticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(verticalAxisName); - CrossPlatformInputManager.RegisterVirtualAxis(m_VerticalVirtualAxis); - } - } - - void UpdateVirtualAxes(Vector3 value) - { - value = value.normalized; - if (m_UseX) - { - m_HorizontalVirtualAxis.Update(value.x); - } - - if (m_UseY) - { - m_VerticalVirtualAxis.Update(value.y); - } - } - - - public void OnPointerDown(PointerEventData data) - { - m_Dragging = true; - m_Id = data.pointerId; + void CreateVirtualAxes() + { + // set axes to use + m_UseX = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyHorizontal); + m_UseY = (axesToUse == AxisOption.Both || axesToUse == AxisOption.OnlyVertical); + + // create new axes based on axes to use + if (m_UseX) + { + m_HorizontalVirtualAxis = new CrossPlatformInputManager.VirtualAxis( + horizontalAxisName + ); + CrossPlatformInputManager.RegisterVirtualAxis(m_HorizontalVirtualAxis); + } + if (m_UseY) + { + m_VerticalVirtualAxis = new CrossPlatformInputManager.VirtualAxis(verticalAxisName); + CrossPlatformInputManager.RegisterVirtualAxis(m_VerticalVirtualAxis); + } + } + + void UpdateVirtualAxes(Vector3 value) + { + value = value.normalized; + if (m_UseX) + { + m_HorizontalVirtualAxis.Update(value.x); + } + + if (m_UseY) + { + m_VerticalVirtualAxis.Update(value.y); + } + } + + public void OnPointerDown(PointerEventData data) + { + m_Dragging = true; + m_Id = data.pointerId; #if !UNITY_EDITOR - if (controlStyle != ControlStyle.Absolute ) - m_Center = data.position; + if (controlStyle != ControlStyle.Absolute) + m_Center = data.position; #endif - } - - void Update() - { - if (!m_Dragging) - { - return; - } - if (Input.touchCount >= m_Id + 1 && m_Id != -1) - { -#if !UNITY_EDITOR + } - if (controlStyle == ControlStyle.Swipe) + void Update() + { + if (!m_Dragging) { - m_Center = m_PreviousTouchPos; - m_PreviousTouchPos = Input.touches[m_Id].position; + return; } - Vector2 pointerDelta = new Vector2(Input.touches[m_Id].position.x - m_Center.x , Input.touches[m_Id].position.y - m_Center.y).normalized; - pointerDelta.x *= Xsensitivity; - pointerDelta.y *= Ysensitivity; + if (Input.touchCount >= m_Id + 1 && m_Id != -1) + { +#if !UNITY_EDITOR + + if (controlStyle == ControlStyle.Swipe) + { + m_Center = m_PreviousTouchPos; + m_PreviousTouchPos = Input.touches[m_Id].position; + } + Vector2 pointerDelta = new Vector2( + Input.touches[m_Id].position.x - m_Center.x, + Input.touches[m_Id].position.y - m_Center.y + ).normalized; + pointerDelta.x *= Xsensitivity; + pointerDelta.y *= Ysensitivity; #else - Vector2 pointerDelta; - pointerDelta.x = Input.mousePosition.x - m_PreviousMouse.x; - pointerDelta.y = Input.mousePosition.y - m_PreviousMouse.y; - m_PreviousMouse = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f); + Vector2 pointerDelta; + pointerDelta.x = Input.mousePosition.x - m_PreviousMouse.x; + pointerDelta.y = Input.mousePosition.y - m_PreviousMouse.y; + m_PreviousMouse = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f); #endif - UpdateVirtualAxes(new Vector3(pointerDelta.x, pointerDelta.y, 0)); - } - } - - - public void OnPointerUp(PointerEventData data) - { - m_Dragging = false; - m_Id = -1; - UpdateVirtualAxes(Vector3.zero); - } - - void OnDisable() - { - if (CrossPlatformInputManager.AxisExists(horizontalAxisName)) - CrossPlatformInputManager.UnRegisterVirtualAxis(horizontalAxisName); - - if (CrossPlatformInputManager.AxisExists(verticalAxisName)) - CrossPlatformInputManager.UnRegisterVirtualAxis(verticalAxisName); - } - } -} \ No newline at end of file + UpdateVirtualAxes(new Vector3(pointerDelta.x, pointerDelta.y, 0)); + } + } + + public void OnPointerUp(PointerEventData data) + { + m_Dragging = false; + m_Id = -1; + UpdateVirtualAxes(Vector3.zero); + } + + void OnDisable() + { + if (CrossPlatformInputManager.AxisExists(horizontalAxisName)) + CrossPlatformInputManager.UnRegisterVirtualAxis(horizontalAxisName); + + if (CrossPlatformInputManager.AxisExists(verticalAxisName)) + CrossPlatformInputManager.UnRegisterVirtualAxis(verticalAxisName); + } + } +} diff --git a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/VirtualInput.cs b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/VirtualInput.cs index 0b9f5adf32..d67f7b0b89 100755 --- a/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/VirtualInput.cs +++ b/unity/Assets/Standard Assets/CrossPlatformInput/Scripts/VirtualInput.cs @@ -2,22 +2,22 @@ using System.Collections.Generic; using UnityEngine; - namespace UnityStandardAssets.CrossPlatformInput { public abstract class VirtualInput { public Vector3 virtualMousePosition { get; private set; } - - + protected Dictionary m_VirtualAxes = new Dictionary(); - // Dictionary to store the name relating to the virtual axes + + // Dictionary to store the name relating to the virtual axes protected Dictionary m_VirtualButtons = new Dictionary(); protected List m_AlwaysUseVirtual = new List(); - // list of the axis and button names that have been flagged to always use a virtual axis or button - + + // list of the axis and button names that have been flagged to always use a virtual axis or button + public bool AxisExists(string name) { @@ -29,13 +29,14 @@ public bool ButtonExists(string name) return m_VirtualButtons.ContainsKey(name); } - public void RegisterVirtualAxis(CrossPlatformInputManager.VirtualAxis axis) { // check if we already have an axis with that name and log and error if we do if (m_VirtualAxes.ContainsKey(axis.name)) { - Debug.LogError("There is already a virtual axis named " + axis.name + " registered."); + Debug.LogError( + "There is already a virtual axis named " + axis.name + " registered." + ); } else { @@ -50,13 +51,14 @@ public void RegisterVirtualAxis(CrossPlatformInputManager.VirtualAxis axis) } } - public void RegisterVirtualButton(CrossPlatformInputManager.VirtualButton button) { // check if already have a buttin with that name and log an error if we do if (m_VirtualButtons.ContainsKey(button.name)) { - Debug.LogError("There is already a virtual button named " + button.name + " registered."); + Debug.LogError( + "There is already a virtual button named " + button.name + " registered." + ); } else { @@ -71,7 +73,6 @@ public void RegisterVirtualButton(CrossPlatformInputManager.VirtualButton button } } - public void UnRegisterVirtualAxis(string name) { // if we have an axis with that name then remove it from our dictionary of registered axes @@ -81,7 +82,6 @@ public void UnRegisterVirtualAxis(string name) } } - public void UnRegisterVirtualButton(string name) { // if we have a button with this name then remove it from our dictionary of registered buttons @@ -91,34 +91,29 @@ public void UnRegisterVirtualButton(string name) } } - // returns a reference to a named virtual axis if it exists otherwise null public CrossPlatformInputManager.VirtualAxis VirtualAxisReference(string name) { return m_VirtualAxes.ContainsKey(name) ? m_VirtualAxes[name] : null; } - public void SetVirtualMousePositionX(float f) { virtualMousePosition = new Vector3(f, virtualMousePosition.y, virtualMousePosition.z); } - public void SetVirtualMousePositionY(float f) { virtualMousePosition = new Vector3(virtualMousePosition.x, f, virtualMousePosition.z); } - public void SetVirtualMousePositionZ(float f) { virtualMousePosition = new Vector3(virtualMousePosition.x, virtualMousePosition.y, f); } - public abstract float GetAxis(string name, bool raw); - + public abstract bool GetButton(string name); public abstract bool GetButtonDown(string name); public abstract bool GetButtonUp(string name); diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Antialiasing.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Antialiasing.cs index 9d07a36dc7..60bfcb9379 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Antialiasing.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Antialiasing.cs @@ -15,7 +15,7 @@ public enum AAMode } [ExecuteInEditMode] - [RequireComponent(typeof (Camera))] + [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Other/Antialiasing")] public class Antialiasing : PostEffectsBase { @@ -46,7 +46,6 @@ public class Antialiasing : PostEffectsBase public Shader shaderFXAAIII; private Material materialFXAAIII; - public Material CurrentAAMaterial() { Material returnValue = null; @@ -82,7 +81,6 @@ public Material CurrentAAMaterial() return returnValue; } - public override bool CheckResources() { CheckSupport(false); @@ -104,7 +102,6 @@ public override bool CheckResources() return isSupported; } - public void OnRenderImage(RenderTexture source, RenderTexture destination) { if (CheckResources() == false) @@ -113,7 +110,7 @@ public void OnRenderImage(RenderTexture source, RenderTexture destination) return; } - // ---------------------------------------------------------------- + // ---------------------------------------------------------------- // FXAA antialiasing modes if (mode == AAMode.FXAA3Console && (materialFXAAIII != null)) @@ -140,14 +137,14 @@ public void OnRenderImage(RenderTexture source, RenderTexture destination) } else if (mode == AAMode.SSAA && ssaa != null) { - // ---------------------------------------------------------------- + // ---------------------------------------------------------------- // SSAA antialiasing Graphics.Blit(source, destination, ssaa); } else if (mode == AAMode.DLAA && dlaa != null) { - // ---------------------------------------------------------------- - // DLAA antialiasing + // ---------------------------------------------------------------- + // DLAA antialiasing source.anisoLevel = 0; RenderTexture interim = RenderTexture.GetTemporary(source.width, source.height); diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Bloom.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Bloom.cs index fa17d344c2..41af490234 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Bloom.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Bloom.cs @@ -4,8 +4,8 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Bloom and Glow/Bloom")] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Bloom and Glow/Bloom")] public class Bloom : PostEffectsBase { public enum LensFlareStyle @@ -56,15 +56,15 @@ public enum BloomQuality public int hollywoodFlareBlurIterations = 2; public float flareRotation = 0.0f; - public LensFlareStyle lensflareMode = (LensFlareStyle) 1; + public LensFlareStyle lensflareMode = (LensFlareStyle)1; public float hollyStretchWidth = 2.5f; public float lensflareIntensity = 0.0f; public float lensflareThreshold = 0.3f; public float lensFlareSaturation = 0.75f; - public Color flareColorA = new Color (0.4f, 0.4f, 0.8f, 0.75f); - public Color flareColorB = new Color (0.4f, 0.8f, 0.8f, 0.75f); - public Color flareColorC = new Color (0.8f, 0.4f, 0.8f, 0.75f); - public Color flareColorD = new Color (0.8f, 0.4f, 0.0f, 0.75f); + public Color flareColorA = new Color(0.4f, 0.4f, 0.8f, 0.75f); + public Color flareColorB = new Color(0.4f, 0.8f, 0.8f, 0.75f); + public Color flareColorC = new Color(0.8f, 0.4f, 0.8f, 0.75f); + public Color flareColorD = new Color(0.8f, 0.4f, 0.0f, 0.75f); public Texture2D lensFlareVignetteMask; public Shader lensFlareShader; @@ -79,26 +79,31 @@ public enum BloomQuality public Shader brightPassFilterShader; private Material brightPassFilterMaterial; - - public override bool CheckResources () + public override bool CheckResources() { - CheckSupport (false); - - screenBlend = CheckShaderAndCreateMaterial (screenBlendShader, screenBlend); - lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader,lensFlareMaterial); - blurAndFlaresMaterial = CheckShaderAndCreateMaterial (blurAndFlaresShader, blurAndFlaresMaterial); - brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial); + CheckSupport(false); + + screenBlend = CheckShaderAndCreateMaterial(screenBlendShader, screenBlend); + lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader, lensFlareMaterial); + blurAndFlaresMaterial = CheckShaderAndCreateMaterial( + blurAndFlaresShader, + blurAndFlaresMaterial + ); + brightPassFilterMaterial = CheckShaderAndCreateMaterial( + brightPassFilterShader, + brightPassFilterMaterial + ); if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - public void OnRenderImage (RenderTexture source, RenderTexture destination) + public void OnRenderImage(RenderTexture source, RenderTexture destination) { - if (CheckResources()==false) + if (CheckResources() == false) { - Graphics.Blit (source, destination); + Graphics.Blit(source, destination); return; } @@ -107,11 +112,14 @@ public void OnRenderImage (RenderTexture source, RenderTexture destination) doHdr = false; if (hdr == HDRBloomMode.Auto) #if UNITY_5_6_OR_NEWER - doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent().allowHDR; + doHdr = + source.format == RenderTextureFormat.ARGBHalf + && GetComponent().allowHDR; #else doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent().hdr; #endif - else { + else + { doHdr = hdr == HDRBloomMode.On; } @@ -121,70 +129,94 @@ public void OnRenderImage (RenderTexture source, RenderTexture destination) if (doHdr) realBlendMode = BloomScreenBlendMode.Add; - var rtFormat= (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default; - var rtW2= source.width/2; - var rtH2= source.height/2; - var rtW4= source.width/4; - var rtH4= source.height/4; + var rtFormat = (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default; + var rtW2 = source.width / 2; + var rtH2 = source.height / 2; + var rtW4 = source.width / 4; + var rtH4 = source.height / 4; float widthOverHeight = (1.0f * source.width) / (1.0f * source.height); float oneOverBaseSize = 1.0f / 512.0f; // downsample - RenderTexture quarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); - RenderTexture halfRezColorDown = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat); - if (quality > BloomQuality.Cheap) { - Graphics.Blit (source, halfRezColorDown, screenBlend, 2); - RenderTexture rtDown4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); - Graphics.Blit (halfRezColorDown, rtDown4, screenBlend, 2); - Graphics.Blit (rtDown4, quarterRezColor, screenBlend, 6); + RenderTexture quarterRezColor = RenderTexture.GetTemporary(rtW4, rtH4, 0, rtFormat); + RenderTexture halfRezColorDown = RenderTexture.GetTemporary(rtW2, rtH2, 0, rtFormat); + if (quality > BloomQuality.Cheap) + { + Graphics.Blit(source, halfRezColorDown, screenBlend, 2); + RenderTexture rtDown4 = RenderTexture.GetTemporary(rtW4, rtH4, 0, rtFormat); + Graphics.Blit(halfRezColorDown, rtDown4, screenBlend, 2); + Graphics.Blit(rtDown4, quarterRezColor, screenBlend, 6); RenderTexture.ReleaseTemporary(rtDown4); } - else { - Graphics.Blit (source, halfRezColorDown); - Graphics.Blit (halfRezColorDown, quarterRezColor, screenBlend, 6); + else + { + Graphics.Blit(source, halfRezColorDown); + Graphics.Blit(halfRezColorDown, quarterRezColor, screenBlend, 6); } - RenderTexture.ReleaseTemporary (halfRezColorDown); + RenderTexture.ReleaseTemporary(halfRezColorDown); // cut colors (thresholding) - RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); - BrightFilter (bloomThreshold * bloomThresholdColor, quarterRezColor, secondQuarterRezColor); + RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary( + rtW4, + rtH4, + 0, + rtFormat + ); + BrightFilter( + bloomThreshold * bloomThresholdColor, + quarterRezColor, + secondQuarterRezColor + ); // blurring - if (bloomBlurIterations < 1) bloomBlurIterations = 1; - else if (bloomBlurIterations > 10) bloomBlurIterations = 10; + if (bloomBlurIterations < 1) + bloomBlurIterations = 1; + else if (bloomBlurIterations > 10) + bloomBlurIterations = 10; for (int iter = 0; iter < bloomBlurIterations; iter++) - { + { float spreadForPass = (1.0f + (iter * 0.25f)) * sepBlurSpread; // vertical blur - RenderTexture blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f)); - Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4); + RenderTexture blur4 = RenderTexture.GetTemporary(rtW4, rtH4, 0, rtFormat); + blurAndFlaresMaterial.SetVector( + "_Offsets", + new Vector4(0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f) + ); + Graphics.Blit(secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4); RenderTexture.ReleaseTemporary(secondQuarterRezColor); secondQuarterRezColor = blur4; // horizontal blur - blur4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); - Graphics.Blit (secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4); - RenderTexture.ReleaseTemporary (secondQuarterRezColor); + blur4 = RenderTexture.GetTemporary(rtW4, rtH4, 0, rtFormat); + blurAndFlaresMaterial.SetVector( + "_Offsets", + new Vector4( + (spreadForPass / widthOverHeight) * oneOverBaseSize, + 0.0f, + 0.0f, + 0.0f + ) + ); + Graphics.Blit(secondQuarterRezColor, blur4, blurAndFlaresMaterial, 4); + RenderTexture.ReleaseTemporary(secondQuarterRezColor); secondQuarterRezColor = blur4; if (quality > BloomQuality.Cheap) - { + { if (iter == 0) { Graphics.SetRenderTarget(quarterRezColor); GL.Clear(false, true, Color.black); // Clear to avoid RT restore - Graphics.Blit (secondQuarterRezColor, quarterRezColor); + Graphics.Blit(secondQuarterRezColor, quarterRezColor); } else { quarterRezColor.MarkRestoreExpected(); // using max blending, RT restore expected - Graphics.Blit (secondQuarterRezColor, quarterRezColor, screenBlend, 10); + Graphics.Blit(secondQuarterRezColor, quarterRezColor, screenBlend, 10); } } } @@ -193,169 +225,224 @@ public void OnRenderImage (RenderTexture source, RenderTexture destination) { Graphics.SetRenderTarget(secondQuarterRezColor); GL.Clear(false, true, Color.black); // Clear to avoid RT restore - Graphics.Blit (quarterRezColor, secondQuarterRezColor, screenBlend, 6); + Graphics.Blit(quarterRezColor, secondQuarterRezColor, screenBlend, 6); } // lens flares: ghosting, anamorphic or both (ghosted anamorphic flares) if (lensflareIntensity > Mathf.Epsilon) - { - - RenderTexture rtFlares4 = RenderTexture.GetTemporary (rtW4, rtH4, 0, rtFormat); + { + RenderTexture rtFlares4 = RenderTexture.GetTemporary(rtW4, rtH4, 0, rtFormat); if (lensflareMode == 0) - { + { // ghosting only - BrightFilter (lensflareThreshold, secondQuarterRezColor, rtFlares4); + BrightFilter(lensflareThreshold, secondQuarterRezColor, rtFlares4); if (quality > BloomQuality.Cheap) - { + { // smooth a little - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (0.0f, (1.5f) / (1.0f * quarterRezColor.height), 0.0f, 0.0f)); + blurAndFlaresMaterial.SetVector( + "_Offsets", + new Vector4(0.0f, (1.5f) / (1.0f * quarterRezColor.height), 0.0f, 0.0f) + ); Graphics.SetRenderTarget(quarterRezColor); GL.Clear(false, true, Color.black); // Clear to avoid RT restore - Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4); + Graphics.Blit(rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4); - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 ((1.5f) / (1.0f * quarterRezColor.width), 0.0f, 0.0f, 0.0f)); + blurAndFlaresMaterial.SetVector( + "_Offsets", + new Vector4((1.5f) / (1.0f * quarterRezColor.width), 0.0f, 0.0f, 0.0f) + ); Graphics.SetRenderTarget(rtFlares4); GL.Clear(false, true, Color.black); // Clear to avoid RT restore - Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4); + Graphics.Blit(quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4); } // no ugly edges! - Vignette (0.975f, rtFlares4, rtFlares4); - BlendFlares (rtFlares4, secondQuarterRezColor); + Vignette(0.975f, rtFlares4, rtFlares4); + BlendFlares(rtFlares4, secondQuarterRezColor); } else - { - + { // Vignette (0.975ff, rtFlares4, rtFlares4); // DrawBorder(rtFlares4, screenBlend, 8); float flareXRot = 1.0f * Mathf.Cos(flareRotation); float flareyRot = 1.0f * Mathf.Sin(flareRotation); - float stretchWidth = (hollyStretchWidth * 1.0f / widthOverHeight) * oneOverBaseSize; - - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot, flareyRot, 0.0f, 0.0f)); - blurAndFlaresMaterial.SetVector ("_Threshhold", new Vector4 (lensflareThreshold, 1.0f, 0.0f, 0.0f)); - blurAndFlaresMaterial.SetVector ("_TintColor", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity); - blurAndFlaresMaterial.SetFloat ("_Saturation", lensFlareSaturation); + float stretchWidth = + (hollyStretchWidth * 1.0f / widthOverHeight) * oneOverBaseSize; + + blurAndFlaresMaterial.SetVector( + "_Offsets", + new Vector4(flareXRot, flareyRot, 0.0f, 0.0f) + ); + blurAndFlaresMaterial.SetVector( + "_Threshhold", + new Vector4(lensflareThreshold, 1.0f, 0.0f, 0.0f) + ); + blurAndFlaresMaterial.SetVector( + "_TintColor", + new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) + * flareColorA.a + * lensflareIntensity + ); + blurAndFlaresMaterial.SetFloat("_Saturation", lensFlareSaturation); // "pre and cut" quarterRezColor.DiscardContents(); - Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 2); + Graphics.Blit(rtFlares4, quarterRezColor, blurAndFlaresMaterial, 2); // "post" rtFlares4.DiscardContents(); - Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 3); + Graphics.Blit(quarterRezColor, rtFlares4, blurAndFlaresMaterial, 3); - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (flareXRot * stretchWidth, flareyRot * stretchWidth, 0.0f, 0.0f)); + blurAndFlaresMaterial.SetVector( + "_Offsets", + new Vector4(flareXRot * stretchWidth, flareyRot * stretchWidth, 0.0f, 0.0f) + ); // stretch 1st - blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth); + blurAndFlaresMaterial.SetFloat("_StretchWidth", hollyStretchWidth); quarterRezColor.DiscardContents(); - Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1); + Graphics.Blit(rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1); // stretch 2nd - blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 2.0f); + blurAndFlaresMaterial.SetFloat("_StretchWidth", hollyStretchWidth * 2.0f); rtFlares4.DiscardContents(); - Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 1); + Graphics.Blit(quarterRezColor, rtFlares4, blurAndFlaresMaterial, 1); // stretch 3rd - blurAndFlaresMaterial.SetFloat ("_StretchWidth", hollyStretchWidth * 4.0f); + blurAndFlaresMaterial.SetFloat("_StretchWidth", hollyStretchWidth * 4.0f); quarterRezColor.DiscardContents(); - Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1); + Graphics.Blit(rtFlares4, quarterRezColor, blurAndFlaresMaterial, 1); // additional blur passes for (int iter = 0; iter < hollywoodFlareBlurIterations; iter++) - { - stretchWidth = (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize; - - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f)); + { + stretchWidth = + (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize; + + blurAndFlaresMaterial.SetVector( + "_Offsets", + new Vector4( + stretchWidth * flareXRot, + stretchWidth * flareyRot, + 0.0f, + 0.0f + ) + ); rtFlares4.DiscardContents(); - Graphics.Blit (quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4); - - blurAndFlaresMaterial.SetVector ("_Offsets", new Vector4 (stretchWidth * flareXRot, stretchWidth * flareyRot, 0.0f, 0.0f)); + Graphics.Blit(quarterRezColor, rtFlares4, blurAndFlaresMaterial, 4); + + blurAndFlaresMaterial.SetVector( + "_Offsets", + new Vector4( + stretchWidth * flareXRot, + stretchWidth * flareyRot, + 0.0f, + 0.0f + ) + ); quarterRezColor.DiscardContents(); - Graphics.Blit (rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4); + Graphics.Blit(rtFlares4, quarterRezColor, blurAndFlaresMaterial, 4); } - if (lensflareMode == (LensFlareStyle) 1) + if (lensflareMode == (LensFlareStyle)1) // anamorphic lens flares - AddTo (1.0f, quarterRezColor, secondQuarterRezColor); + AddTo(1.0f, quarterRezColor, secondQuarterRezColor); else - { + { // "combined" lens flares - Vignette (1.0f, quarterRezColor, rtFlares4); - BlendFlares (rtFlares4, quarterRezColor); - AddTo (1.0f, quarterRezColor, secondQuarterRezColor); + Vignette(1.0f, quarterRezColor, rtFlares4); + BlendFlares(rtFlares4, quarterRezColor); + AddTo(1.0f, quarterRezColor, secondQuarterRezColor); } } - RenderTexture.ReleaseTemporary (rtFlares4); + RenderTexture.ReleaseTemporary(rtFlares4); } - int blendPass = (int) realBlendMode; + int blendPass = (int)realBlendMode; // if (Mathf.Abs(chromaticBloom) < Mathf.Epsilon) // blendPass += 4; - screenBlend.SetFloat ("_Intensity", bloomIntensity); - screenBlend.SetTexture ("_ColorBuffer", source); + screenBlend.SetFloat("_Intensity", bloomIntensity); + screenBlend.SetTexture("_ColorBuffer", source); if (quality > BloomQuality.Cheap) - { - RenderTexture halfRezColorUp = RenderTexture.GetTemporary (rtW2, rtH2, 0, rtFormat); - Graphics.Blit (secondQuarterRezColor, halfRezColorUp); - Graphics.Blit (halfRezColorUp, destination, screenBlend, blendPass); - RenderTexture.ReleaseTemporary (halfRezColorUp); + { + RenderTexture halfRezColorUp = RenderTexture.GetTemporary(rtW2, rtH2, 0, rtFormat); + Graphics.Blit(secondQuarterRezColor, halfRezColorUp); + Graphics.Blit(halfRezColorUp, destination, screenBlend, blendPass); + RenderTexture.ReleaseTemporary(halfRezColorUp); } else - Graphics.Blit (secondQuarterRezColor, destination, screenBlend, blendPass); + Graphics.Blit(secondQuarterRezColor, destination, screenBlend, blendPass); - RenderTexture.ReleaseTemporary (quarterRezColor); - RenderTexture.ReleaseTemporary (secondQuarterRezColor); + RenderTexture.ReleaseTemporary(quarterRezColor); + RenderTexture.ReleaseTemporary(secondQuarterRezColor); } - private void AddTo (float intensity_, RenderTexture from, RenderTexture to) + private void AddTo(float intensity_, RenderTexture from, RenderTexture to) { - screenBlend.SetFloat ("_Intensity", intensity_); + screenBlend.SetFloat("_Intensity", intensity_); to.MarkRestoreExpected(); // additive blending, RT restore expected - Graphics.Blit (from, to, screenBlend, 9); + Graphics.Blit(from, to, screenBlend, 9); } - private void BlendFlares (RenderTexture from, RenderTexture to) + private void BlendFlares(RenderTexture from, RenderTexture to) { - lensFlareMaterial.SetVector ("colorA", new Vector4 (flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity); - lensFlareMaterial.SetVector ("colorB", new Vector4 (flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity); - lensFlareMaterial.SetVector ("colorC", new Vector4 (flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity); - lensFlareMaterial.SetVector ("colorD", new Vector4 (flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity); + lensFlareMaterial.SetVector( + "colorA", + new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) + * lensflareIntensity + ); + lensFlareMaterial.SetVector( + "colorB", + new Vector4(flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) + * lensflareIntensity + ); + lensFlareMaterial.SetVector( + "colorC", + new Vector4(flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) + * lensflareIntensity + ); + lensFlareMaterial.SetVector( + "colorD", + new Vector4(flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) + * lensflareIntensity + ); to.MarkRestoreExpected(); // additive blending, RT restore expected - Graphics.Blit (from, to, lensFlareMaterial); + Graphics.Blit(from, to, lensFlareMaterial); } - private void BrightFilter (float thresh, RenderTexture from, RenderTexture to) + private void BrightFilter(float thresh, RenderTexture from, RenderTexture to) { - brightPassFilterMaterial.SetVector ("_Threshhold", new Vector4 (thresh, thresh, thresh, thresh)); - Graphics.Blit (from, to, brightPassFilterMaterial, 0); + brightPassFilterMaterial.SetVector( + "_Threshhold", + new Vector4(thresh, thresh, thresh, thresh) + ); + Graphics.Blit(from, to, brightPassFilterMaterial, 0); } - private void BrightFilter (Color threshColor, RenderTexture from, RenderTexture to) + private void BrightFilter(Color threshColor, RenderTexture from, RenderTexture to) { - brightPassFilterMaterial.SetVector ("_Threshhold", threshColor); - Graphics.Blit (from, to, brightPassFilterMaterial, 1); + brightPassFilterMaterial.SetVector("_Threshhold", threshColor); + Graphics.Blit(from, to, brightPassFilterMaterial, 1); } - private void Vignette (float amount, RenderTexture from, RenderTexture to) + private void Vignette(float amount, RenderTexture from, RenderTexture to) { if (lensFlareVignetteMask) { - screenBlend.SetTexture ("_ColorBuffer", lensFlareVignetteMask); + screenBlend.SetTexture("_ColorBuffer", lensFlareVignetteMask); to.MarkRestoreExpected(); // using blending, RT restore expected - Graphics.Blit (from == to ? null : from, to, screenBlend, from == to ? 7 : 3); + Graphics.Blit(from == to ? null : from, to, screenBlend, from == to ? 7 : 3); } else if (from != to) { - Graphics.SetRenderTarget (to); + Graphics.SetRenderTarget(to); GL.Clear(false, true, Color.black); // clear destination to avoid RT restore - Graphics.Blit (from, to); + Graphics.Blit(from, to); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/BloomAndFlares.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/BloomAndFlares.cs index 4cb19e4909..109bde0796 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/BloomAndFlares.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/BloomAndFlares.cs @@ -79,7 +79,6 @@ public class BloomAndFlares : PostEffectsBase public Shader brightPassFilterShader; private Material brightPassFilterMaterial; - public override bool CheckResources() { CheckSupport(false); @@ -87,10 +86,22 @@ public override bool CheckResources() screenBlend = CheckShaderAndCreateMaterial(screenBlendShader, screenBlend); lensFlareMaterial = CheckShaderAndCreateMaterial(lensFlareShader, lensFlareMaterial); vignetteMaterial = CheckShaderAndCreateMaterial(vignetteShader, vignetteMaterial); - separableBlurMaterial = CheckShaderAndCreateMaterial(separableBlurShader, separableBlurMaterial); - addBrightStuffBlendOneOneMaterial = CheckShaderAndCreateMaterial(addBrightStuffOneOneShader, addBrightStuffBlendOneOneMaterial); - hollywoodFlaresMaterial = CheckShaderAndCreateMaterial(hollywoodFlaresShader, hollywoodFlaresMaterial); - brightPassFilterMaterial = CheckShaderAndCreateMaterial(brightPassFilterShader, brightPassFilterMaterial); + separableBlurMaterial = CheckShaderAndCreateMaterial( + separableBlurShader, + separableBlurMaterial + ); + addBrightStuffBlendOneOneMaterial = CheckShaderAndCreateMaterial( + addBrightStuffOneOneShader, + addBrightStuffBlendOneOneMaterial + ); + hollywoodFlaresMaterial = CheckShaderAndCreateMaterial( + hollywoodFlaresShader, + hollywoodFlaresMaterial + ); + brightPassFilterMaterial = CheckShaderAndCreateMaterial( + brightPassFilterShader, + brightPassFilterMaterial + ); if (!isSupported) ReportAutoDisable(); @@ -110,7 +121,9 @@ void OnRenderImage(RenderTexture source, RenderTexture destination) doHdr = false; if (hdr == HDRBloomMode.Auto) #if UNITY_5_6_OR_NEWER - doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent().allowHDR; + doHdr = + source.format == RenderTextureFormat.ARGBHalf + && GetComponent().allowHDR; #else doHdr = source.format == RenderTextureFormat.ARGBHalf && GetComponent().hdr; #endif @@ -126,10 +139,30 @@ void OnRenderImage(RenderTexture source, RenderTexture destination) realBlendMode = BloomScreenBlendMode.Add; var rtFormat = (doHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.Default; - RenderTexture halfRezColor = RenderTexture.GetTemporary(source.width / 2, source.height / 2, 0, rtFormat); - RenderTexture quarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat); - RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat); - RenderTexture thirdQuarterRezColor = RenderTexture.GetTemporary(source.width / 4, source.height / 4, 0, rtFormat); + RenderTexture halfRezColor = RenderTexture.GetTemporary( + source.width / 2, + source.height / 2, + 0, + rtFormat + ); + RenderTexture quarterRezColor = RenderTexture.GetTemporary( + source.width / 4, + source.height / 4, + 0, + rtFormat + ); + RenderTexture secondQuarterRezColor = RenderTexture.GetTemporary( + source.width / 4, + source.height / 4, + 0, + rtFormat + ); + RenderTexture thirdQuarterRezColor = RenderTexture.GetTemporary( + source.width / 4, + source.height / 4, + 0, + rtFormat + ); float widthOverHeight = (1.0f * source.width) / (1.0f * source.height); float oneOverBaseSize = 1.0f / 512.0f; @@ -148,18 +181,30 @@ void OnRenderImage(RenderTexture source, RenderTexture destination) // blurring - if (bloomBlurIterations < 1) bloomBlurIterations = 1; + if (bloomBlurIterations < 1) + bloomBlurIterations = 1; for (int iter = 0; iter < bloomBlurIterations; iter++) { float spreadForPass = (1.0f + (iter * 0.5f)) * sepBlurSpread; - separableBlurMaterial.SetVector("offsets", new Vector4(0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f)); + separableBlurMaterial.SetVector( + "offsets", + new Vector4(0.0f, spreadForPass * oneOverBaseSize, 0.0f, 0.0f) + ); RenderTexture src = iter == 0 ? secondQuarterRezColor : quarterRezColor; Graphics.Blit(src, thirdQuarterRezColor, separableBlurMaterial); src.DiscardContents(); - separableBlurMaterial.SetVector("offsets", new Vector4((spreadForPass / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); + separableBlurMaterial.SetVector( + "offsets", + new Vector4( + (spreadForPass / widthOverHeight) * oneOverBaseSize, + 0.0f, + 0.0f, + 0.0f + ) + ); Graphics.Blit(thirdQuarterRezColor, quarterRezColor, separableBlurMaterial); thirdQuarterRezColor.DiscardContents(); } @@ -168,10 +213,8 @@ void OnRenderImage(RenderTexture source, RenderTexture destination) if (lensflares) { - if (lensflareMode == 0) { - BrightFilter(lensflareThreshold, 0.0f, quarterRezColor, thirdQuarterRezColor); quarterRezColor.DiscardContents(); @@ -190,46 +233,114 @@ void OnRenderImage(RenderTexture source, RenderTexture destination) BlendFlares(secondQuarterRezColor, quarterRezColor); secondQuarterRezColor.DiscardContents(); } - // (b) hollywood/anamorphic flares? else { - // thirdQuarter has the brightcut unblurred colors // quarterRezColor is the blurred, brightcut buffer that will end up as bloom - hollywoodFlaresMaterial.SetVector("_threshold", new Vector4(lensflareThreshold, 1.0f / (1.0f - lensflareThreshold), 0.0f, 0.0f)); - hollywoodFlaresMaterial.SetVector("tintColor", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * flareColorA.a * lensflareIntensity); - Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 2); + hollywoodFlaresMaterial.SetVector( + "_threshold", + new Vector4( + lensflareThreshold, + 1.0f / (1.0f - lensflareThreshold), + 0.0f, + 0.0f + ) + ); + hollywoodFlaresMaterial.SetVector( + "tintColor", + new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) + * flareColorA.a + * lensflareIntensity + ); + Graphics.Blit( + thirdQuarterRezColor, + secondQuarterRezColor, + hollywoodFlaresMaterial, + 2 + ); thirdQuarterRezColor.DiscardContents(); - Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 3); + Graphics.Blit( + secondQuarterRezColor, + thirdQuarterRezColor, + hollywoodFlaresMaterial, + 3 + ); secondQuarterRezColor.DiscardContents(); - hollywoodFlaresMaterial.SetVector("offsets", new Vector4((sepBlurSpread * 1.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); + hollywoodFlaresMaterial.SetVector( + "offsets", + new Vector4( + (sepBlurSpread * 1.0f / widthOverHeight) * oneOverBaseSize, + 0.0f, + 0.0f, + 0.0f + ) + ); hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth); - Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1); + Graphics.Blit( + thirdQuarterRezColor, + secondQuarterRezColor, + hollywoodFlaresMaterial, + 1 + ); thirdQuarterRezColor.DiscardContents(); hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 2.0f); - Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, hollywoodFlaresMaterial, 1); + Graphics.Blit( + secondQuarterRezColor, + thirdQuarterRezColor, + hollywoodFlaresMaterial, + 1 + ); secondQuarterRezColor.DiscardContents(); hollywoodFlaresMaterial.SetFloat("stretchWidth", hollyStretchWidth * 4.0f); - Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, hollywoodFlaresMaterial, 1); + Graphics.Blit( + thirdQuarterRezColor, + secondQuarterRezColor, + hollywoodFlaresMaterial, + 1 + ); thirdQuarterRezColor.DiscardContents(); if (lensflareMode == (LensflareStyle34)1) { for (int itera = 0; itera < hollywoodFlareBlurIterations; itera++) { - separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); - Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial); + separableBlurMaterial.SetVector( + "offsets", + new Vector4( + (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, + 0.0f, + 0.0f, + 0.0f + ) + ); + Graphics.Blit( + secondQuarterRezColor, + thirdQuarterRezColor, + separableBlurMaterial + ); secondQuarterRezColor.DiscardContents(); - separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); - Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial); + separableBlurMaterial.SetVector( + "offsets", + new Vector4( + (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, + 0.0f, + 0.0f, + 0.0f + ) + ); + Graphics.Blit( + thirdQuarterRezColor, + secondQuarterRezColor, + separableBlurMaterial + ); thirdQuarterRezColor.DiscardContents(); } @@ -238,17 +349,40 @@ void OnRenderImage(RenderTexture source, RenderTexture destination) } else { - // (c) combined for (int ix = 0; ix < hollywoodFlareBlurIterations; ix++) { - separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); - Graphics.Blit(secondQuarterRezColor, thirdQuarterRezColor, separableBlurMaterial); + separableBlurMaterial.SetVector( + "offsets", + new Vector4( + (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, + 0.0f, + 0.0f, + 0.0f + ) + ); + Graphics.Blit( + secondQuarterRezColor, + thirdQuarterRezColor, + separableBlurMaterial + ); secondQuarterRezColor.DiscardContents(); - separableBlurMaterial.SetVector("offsets", new Vector4((hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); - Graphics.Blit(thirdQuarterRezColor, secondQuarterRezColor, separableBlurMaterial); + separableBlurMaterial.SetVector( + "offsets", + new Vector4( + (hollyStretchWidth * 2.0f / widthOverHeight) * oneOverBaseSize, + 0.0f, + 0.0f, + 0.0f + ) + ); + Graphics.Blit( + thirdQuarterRezColor, + secondQuarterRezColor, + separableBlurMaterial + ); thirdQuarterRezColor.DiscardContents(); } @@ -283,19 +417,46 @@ private void AddTo(float intensity_, RenderTexture from, RenderTexture to) private void BlendFlares(RenderTexture from, RenderTexture to) { - lensFlareMaterial.SetVector("colorA", new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) * lensflareIntensity); - lensFlareMaterial.SetVector("colorB", new Vector4(flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) * lensflareIntensity); - lensFlareMaterial.SetVector("colorC", new Vector4(flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) * lensflareIntensity); - lensFlareMaterial.SetVector("colorD", new Vector4(flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) * lensflareIntensity); + lensFlareMaterial.SetVector( + "colorA", + new Vector4(flareColorA.r, flareColorA.g, flareColorA.b, flareColorA.a) + * lensflareIntensity + ); + lensFlareMaterial.SetVector( + "colorB", + new Vector4(flareColorB.r, flareColorB.g, flareColorB.b, flareColorB.a) + * lensflareIntensity + ); + lensFlareMaterial.SetVector( + "colorC", + new Vector4(flareColorC.r, flareColorC.g, flareColorC.b, flareColorC.a) + * lensflareIntensity + ); + lensFlareMaterial.SetVector( + "colorD", + new Vector4(flareColorD.r, flareColorD.g, flareColorD.b, flareColorD.a) + * lensflareIntensity + ); Graphics.Blit(from, to, lensFlareMaterial); } - private void BrightFilter(float thresh, float useAlphaAsMask, RenderTexture from, RenderTexture to) + private void BrightFilter( + float thresh, + float useAlphaAsMask, + RenderTexture from, + RenderTexture to + ) { if (doHdr) - brightPassFilterMaterial.SetVector("threshold", new Vector4(thresh, 1.0f, 0.0f, 0.0f)); + brightPassFilterMaterial.SetVector( + "threshold", + new Vector4(thresh, 1.0f, 0.0f, 0.0f) + ); else - brightPassFilterMaterial.SetVector("threshold", new Vector4(thresh, 1.0f / (1.0f - thresh), 0.0f, 0.0f)); + brightPassFilterMaterial.SetVector( + "threshold", + new Vector4(thresh, 1.0f / (1.0f - thresh), 0.0f, 0.0f) + ); brightPassFilterMaterial.SetFloat("useSrcAlphaAsMask", useAlphaAsMask); Graphics.Blit(from, to, brightPassFilterMaterial); } @@ -313,6 +474,5 @@ private void Vignette(float amount, RenderTexture from, RenderTexture to) Graphics.Blit(from, to, vignetteMaterial); } } - } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/BloomOptimized.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/BloomOptimized.cs index fdd9fa86e1..fa3474a197 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/BloomOptimized.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/BloomOptimized.cs @@ -4,25 +4,25 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Bloom and Glow/Bloom (Optimized)")] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Bloom and Glow/Bloom (Optimized)")] public class BloomOptimized : PostEffectsBase { - public enum Resolution - { + { Low = 0, High = 1, } public enum BlurType - { + { Standard = 0, Sgx = 1, } [Range(0.0f, 1.5f)] public float threshold = 0.25f; + [Range(0.0f, 2.5f)] public float intensity = 0.75f; @@ -30,80 +30,86 @@ public enum BlurType public float blurSize = 1.0f; Resolution resolution = Resolution.Low; + [Range(1, 4)] public int blurIterations = 1; - public BlurType blurType= BlurType.Standard; + public BlurType blurType = BlurType.Standard; public Shader fastBloomShader = null; private Material fastBloomMaterial = null; + public override bool CheckResources() + { + CheckSupport(false); - public override bool CheckResources () - { - CheckSupport (false); - - fastBloomMaterial = CheckShaderAndCreateMaterial (fastBloomShader, fastBloomMaterial); + fastBloomMaterial = CheckShaderAndCreateMaterial(fastBloomShader, fastBloomMaterial); if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - void OnDisable () - { + void OnDisable() + { if (fastBloomMaterial) - DestroyImmediate (fastBloomMaterial); + DestroyImmediate(fastBloomMaterial); } - void OnRenderImage (RenderTexture source, RenderTexture destination) - { + void OnRenderImage(RenderTexture source, RenderTexture destination) + { if (CheckResources() == false) - { - Graphics.Blit (source, destination); + { + Graphics.Blit(source, destination); return; } int divider = resolution == Resolution.Low ? 4 : 2; float widthMod = resolution == Resolution.Low ? 0.5f : 1.0f; - fastBloomMaterial.SetVector ("_Parameter", new Vector4 (blurSize * widthMod, 0.0f, threshold, intensity)); + fastBloomMaterial.SetVector( + "_Parameter", + new Vector4(blurSize * widthMod, 0.0f, threshold, intensity) + ); source.filterMode = FilterMode.Bilinear; - var rtW= source.width/divider; - var rtH= source.height/divider; + var rtW = source.width / divider; + var rtH = source.height / divider; // downsample - RenderTexture rt = RenderTexture.GetTemporary (rtW, rtH, 0, source.format); + RenderTexture rt = RenderTexture.GetTemporary(rtW, rtH, 0, source.format); rt.filterMode = FilterMode.Bilinear; - Graphics.Blit (source, rt, fastBloomMaterial, 1); + Graphics.Blit(source, rt, fastBloomMaterial, 1); - var passOffs= blurType == BlurType.Standard ? 0 : 2; + var passOffs = blurType == BlurType.Standard ? 0 : 2; - for(int i = 0; i < blurIterations; i++) - { - fastBloomMaterial.SetVector ("_Parameter", new Vector4 (blurSize * widthMod + (i*1.0f), 0.0f, threshold, intensity)); + for (int i = 0; i < blurIterations; i++) + { + fastBloomMaterial.SetVector( + "_Parameter", + new Vector4(blurSize * widthMod + (i * 1.0f), 0.0f, threshold, intensity) + ); // vertical blur - RenderTexture rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format); + RenderTexture rt2 = RenderTexture.GetTemporary(rtW, rtH, 0, source.format); rt2.filterMode = FilterMode.Bilinear; - Graphics.Blit (rt, rt2, fastBloomMaterial, 2 + passOffs); - RenderTexture.ReleaseTemporary (rt); + Graphics.Blit(rt, rt2, fastBloomMaterial, 2 + passOffs); + RenderTexture.ReleaseTemporary(rt); rt = rt2; // horizontal blur - rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format); + rt2 = RenderTexture.GetTemporary(rtW, rtH, 0, source.format); rt2.filterMode = FilterMode.Bilinear; - Graphics.Blit (rt, rt2, fastBloomMaterial, 3 + passOffs); - RenderTexture.ReleaseTemporary (rt); + Graphics.Blit(rt, rt2, fastBloomMaterial, 3 + passOffs); + RenderTexture.ReleaseTemporary(rt); rt = rt2; } - fastBloomMaterial.SetTexture ("_Bloom", rt); + fastBloomMaterial.SetTexture("_Bloom", rt); - Graphics.Blit (source, destination, fastBloomMaterial, 0); + Graphics.Blit(source, destination, fastBloomMaterial, 0); - RenderTexture.ReleaseTemporary (rt); + RenderTexture.ReleaseTemporary(rt); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Blur.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Blur.cs index 85b2dc4773..e9a1f235c0 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Blur.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Blur.cs @@ -8,16 +8,15 @@ namespace UnityStandardAssets.ImageEffects public class Blur : MonoBehaviour { /// Blur iterations - larger number means more blur. - [Range(0,10)] + [Range(0, 10)] public int iterations = 3; /// Blur spread for each iteration. Lower values /// give better looking blur, but require more iterations to /// get large blurs. Value is usually between 0.5 and 1.0. - [Range(0.0f,1.0f)] + [Range(0.0f, 1.0f)] public float blurSpread = 0.6f; - // -------------------------------------------------------- // The blur iteration shader. // Basically it just takes 4 texture samples and averages them. @@ -27,9 +26,12 @@ public class Blur : MonoBehaviour public Shader blurShader = null; static Material m_Material = null; - protected Material material { - get { - if (m_Material == null) { + protected Material material + { + get + { + if (m_Material == null) + { m_Material = new Material(blurShader); m_Material.hideFlags = HideFlags.DontSave; } @@ -37,9 +39,11 @@ protected Material material { } } - protected void OnDisable() { - if ( m_Material ) { - DestroyImmediate( m_Material ); + protected void OnDisable() + { + if (m_Material) + { + DestroyImmediate(m_Material); } } @@ -53,50 +57,58 @@ protected void Start() // return; // } // Disable if the shader can't run on the users graphics card - if (!blurShader || !material.shader.isSupported) { + if (!blurShader || !material.shader.isSupported) + { enabled = false; return; } } // Performs one blur iteration. - public void FourTapCone (RenderTexture source, RenderTexture dest, int iteration) + public void FourTapCone(RenderTexture source, RenderTexture dest, int iteration) { - float off = 0.5f + iteration*blurSpread; - Graphics.BlitMultiTap (source, dest, material, - new Vector2(-off, -off), - new Vector2(-off, off), - new Vector2( off, off), - new Vector2( off, -off) - ); + float off = 0.5f + iteration * blurSpread; + Graphics.BlitMultiTap( + source, + dest, + material, + new Vector2(-off, -off), + new Vector2(-off, off), + new Vector2(off, off), + new Vector2(off, -off) + ); } // Downsamples the texture to a quarter resolution. - private void DownSample4x (RenderTexture source, RenderTexture dest) + private void DownSample4x(RenderTexture source, RenderTexture dest) { float off = 1.0f; - Graphics.BlitMultiTap (source, dest, material, - new Vector2(-off, -off), - new Vector2(-off, off), - new Vector2( off, off), - new Vector2( off, -off) - ); + Graphics.BlitMultiTap( + source, + dest, + material, + new Vector2(-off, -off), + new Vector2(-off, off), + new Vector2(off, off), + new Vector2(off, -off) + ); } // Called by the camera to apply the image effect - void OnRenderImage (RenderTexture source, RenderTexture destination) { - int rtW = source.width/4; - int rtH = source.height/4; + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + int rtW = source.width / 4; + int rtH = source.height / 4; RenderTexture buffer = RenderTexture.GetTemporary(rtW, rtH, 0); // Copy source to the 4x4 smaller texture. - DownSample4x (source, buffer); + DownSample4x(source, buffer); // Blur the small texture - for(int i = 0; i < iterations; i++) + for (int i = 0; i < iterations; i++) { RenderTexture buffer2 = RenderTexture.GetTemporary(rtW, rtH, 0); - FourTapCone (buffer, buffer2, i); + FourTapCone(buffer, buffer2, i); RenderTexture.ReleaseTemporary(buffer); buffer = buffer2; } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/BlurOptimized.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/BlurOptimized.cs index ae2644b530..ed5a65e107 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/BlurOptimized.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/BlurOptimized.cs @@ -4,15 +4,15 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Blur/Blur (Optimized)")] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Blur/Blur (Optimized)")] public class BlurOptimized : PostEffectsBase { - [Range(0, 2)] public int downsample = 1; - public enum BlurType { + public enum BlurType + { StandardGauss = 0, SgxGauss = 1, } @@ -23,71 +23,86 @@ public enum BlurType { [Range(1, 4)] public int blurIterations = 2; - public BlurType blurType= BlurType.StandardGauss; + public BlurType blurType = BlurType.StandardGauss; public Shader blurShader = null; private Material blurMaterial = null; + public override bool CheckResources() + { + CheckSupport(false); - public override bool CheckResources () { - CheckSupport (false); - - blurMaterial = CheckShaderAndCreateMaterial (blurShader, blurMaterial); + blurMaterial = CheckShaderAndCreateMaterial(blurShader, blurMaterial); if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - public void OnDisable () { + public void OnDisable() + { if (blurMaterial) - DestroyImmediate (blurMaterial); + DestroyImmediate(blurMaterial); } - public void OnRenderImage (RenderTexture source, RenderTexture destination) { - if (CheckResources() == false) { - Graphics.Blit (source, destination); + public void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (CheckResources() == false) + { + Graphics.Blit(source, destination); return; } - float widthMod = 1.0f / (1.0f * (1<> downsample; int rtH = source.height >> downsample; // downsample - RenderTexture rt = RenderTexture.GetTemporary (rtW, rtH, 0, source.format); + RenderTexture rt = RenderTexture.GetTemporary(rtW, rtH, 0, source.format); rt.filterMode = FilterMode.Bilinear; - Graphics.Blit (source, rt, blurMaterial, 0); - - var passOffs= blurType == BlurType.StandardGauss ? 0 : 2; - - for(int i = 0; i < blurIterations; i++) { - float iterationOffs = (i*1.0f); - blurMaterial.SetVector ("_Parameter", new Vector4 (blurSize * widthMod + iterationOffs, -blurSize * widthMod - iterationOffs, 0.0f, 0.0f)); + Graphics.Blit(source, rt, blurMaterial, 0); + + var passOffs = blurType == BlurType.StandardGauss ? 0 : 2; + + for (int i = 0; i < blurIterations; i++) + { + float iterationOffs = (i * 1.0f); + blurMaterial.SetVector( + "_Parameter", + new Vector4( + blurSize * widthMod + iterationOffs, + -blurSize * widthMod - iterationOffs, + 0.0f, + 0.0f + ) + ); // vertical blur - RenderTexture rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format); + RenderTexture rt2 = RenderTexture.GetTemporary(rtW, rtH, 0, source.format); rt2.filterMode = FilterMode.Bilinear; - Graphics.Blit (rt, rt2, blurMaterial, 1 + passOffs); - RenderTexture.ReleaseTemporary (rt); + Graphics.Blit(rt, rt2, blurMaterial, 1 + passOffs); + RenderTexture.ReleaseTemporary(rt); rt = rt2; // horizontal blur - rt2 = RenderTexture.GetTemporary (rtW, rtH, 0, source.format); + rt2 = RenderTexture.GetTemporary(rtW, rtH, 0, source.format); rt2.filterMode = FilterMode.Bilinear; - Graphics.Blit (rt, rt2, blurMaterial, 2 + passOffs); - RenderTexture.ReleaseTemporary (rt); + Graphics.Blit(rt, rt2, blurMaterial, 2 + passOffs); + RenderTexture.ReleaseTemporary(rt); rt = rt2; } - Graphics.Blit (rt, destination); + Graphics.Blit(rt, destination); - RenderTexture.ReleaseTemporary (rt); + RenderTexture.ReleaseTemporary(rt); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/CameraMotionBlur.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/CameraMotionBlur.cs index 9757856f99..1de15a258b 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/CameraMotionBlur.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/CameraMotionBlur.cs @@ -4,34 +4,35 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Camera/Camera Motion Blur") ] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Camera/Camera Motion Blur")] public class CameraMotionBlur : PostEffectsBase { // make sure to match this to MAX_RADIUS in shader ('k' in paper) static float MAX_RADIUS = 10.0f; - public enum MotionBlurFilter { - CameraMotion = 0, // global screen blur based on cam motion - LocalBlur = 1, // cheap blur, no dilation or scattering - Reconstruction = 2, // advanced filter (simulates scattering) as in plausible motion blur paper - ReconstructionDX11 = 3, // advanced filter (simulates scattering) as in plausible motion blur paper - ReconstructionDisc = 4, // advanced filter using scaled poisson disc sampling + public enum MotionBlurFilter + { + CameraMotion = 0, // global screen blur based on cam motion + LocalBlur = 1, // cheap blur, no dilation or scattering + Reconstruction = 2, // advanced filter (simulates scattering) as in plausible motion blur paper + ReconstructionDX11 = 3, // advanced filter (simulates scattering) as in plausible motion blur paper + ReconstructionDisc = 4, // advanced filter using scaled poisson disc sampling } // settings public MotionBlurFilter filterType = MotionBlurFilter.Reconstruction; - public bool preview = false; // show how blur would look like in action ... - public Vector3 previewScale = Vector3.one; // ... given this movement vector + public bool preview = false; // show how blur would look like in action ... + public Vector3 previewScale = Vector3.one; // ... given this movement vector // params public float movementScale = 0.0f; public float rotationScale = 1.0f; - public float maxVelocity = 8.0f; // maximum velocity in pixels - public float minVelocity = 0.1f; // minimum velocity in pixels - public float velocityScale = 0.375f; // global velocity scale - public float softZDistance = 0.005f; // for z overlap check softness (reconstruction filter only) - public int velocityDownsample = 1; // low resolution velocity buffer? (optimization) + public float maxVelocity = 8.0f; // maximum velocity in pixels + public float minVelocity = 0.1f; // minimum velocity in pixels + public float velocityScale = 0.375f; // global velocity scale + public float softZDistance = 0.005f; // for z overlap check softness (reconstruction filter only) + public int velocityDownsample = 1; // low resolution velocity buffer? (optimization) public LayerMask excludeLayers = 0; private GameObject tmpCam = null; @@ -47,186 +48,229 @@ public enum MotionBlurFilter { public float jitter = 0.05f; // (internal) debug - public bool showVelocity = false; + public bool showVelocity = false; public float showVelocityScale = 1.0f; // camera transforms private Matrix4x4 currentViewProjMat; - private Matrix4x4[] currentStereoViewProjMat; - private Matrix4x4 prevViewProjMat; - private Matrix4x4[] prevStereoViewProjMat; - private int prevFrameCount; - private bool wasActive; + private Matrix4x4[] currentStereoViewProjMat; + private Matrix4x4 prevViewProjMat; + private Matrix4x4[] prevStereoViewProjMat; + private int prevFrameCount; + private bool wasActive; + // shortcuts to calculate global blur direction when using 'CameraMotion' private Vector3 prevFrameForward = Vector3.forward; private Vector3 prevFrameUp = Vector3.up; private Vector3 prevFramePos = Vector3.zero; private Camera _camera; - - private void CalculateViewProjection () { - Matrix4x4 viewMat = _camera.worldToCameraMatrix; - Matrix4x4 projMat = GL.GetGPUProjectionMatrix (_camera.projectionMatrix, true); + private void CalculateViewProjection() + { + Matrix4x4 viewMat = _camera.worldToCameraMatrix; + Matrix4x4 projMat = GL.GetGPUProjectionMatrix(_camera.projectionMatrix, true); currentViewProjMat = projMat * viewMat; - if(_camera.stereoEnabled) - { - for (int eye = 0; eye < 2; ++eye) - { - Matrix4x4 stereoViewMat = _camera.GetStereoViewMatrix(eye == 0 ? Camera.StereoscopicEye.Left : Camera.StereoscopicEye.Right); - Matrix4x4 stereoProjMat = _camera.GetStereoProjectionMatrix(eye == 0 ? Camera.StereoscopicEye.Left : Camera.StereoscopicEye.Right); - stereoProjMat = GL.GetGPUProjectionMatrix(stereoProjMat, true); - currentStereoViewProjMat[eye] = stereoProjMat * stereoViewMat; - } - } + if (_camera.stereoEnabled) + { + for (int eye = 0; eye < 2; ++eye) + { + Matrix4x4 stereoViewMat = _camera.GetStereoViewMatrix( + eye == 0 ? Camera.StereoscopicEye.Left : Camera.StereoscopicEye.Right + ); + Matrix4x4 stereoProjMat = _camera.GetStereoProjectionMatrix( + eye == 0 ? Camera.StereoscopicEye.Left : Camera.StereoscopicEye.Right + ); + stereoProjMat = GL.GetGPUProjectionMatrix(stereoProjMat, true); + currentStereoViewProjMat[eye] = stereoProjMat * stereoViewMat; + } + } } - - new void Start () { - CheckResources (); + new void Start() + { + CheckResources(); if (_camera == null) _camera = GetComponent(); wasActive = gameObject.activeInHierarchy; - currentStereoViewProjMat = new Matrix4x4[2]; - prevStereoViewProjMat = new Matrix4x4[2]; - CalculateViewProjection (); - Remember (); + currentStereoViewProjMat = new Matrix4x4[2]; + prevStereoViewProjMat = new Matrix4x4[2]; + CalculateViewProjection(); + Remember(); wasActive = false; // hack to fake position/rotation update and prevent bad blurs } - void OnEnable () { - + void OnEnable() + { if (_camera == null) _camera = GetComponent(); _camera.depthTextureMode |= DepthTextureMode.Depth; } - void OnDisable () { - if (null != motionBlurMaterial) { - DestroyImmediate (motionBlurMaterial); + void OnDisable() + { + if (null != motionBlurMaterial) + { + DestroyImmediate(motionBlurMaterial); motionBlurMaterial = null; } - if (null != dx11MotionBlurMaterial) { - DestroyImmediate (dx11MotionBlurMaterial); + if (null != dx11MotionBlurMaterial) + { + DestroyImmediate(dx11MotionBlurMaterial); dx11MotionBlurMaterial = null; } - if (null != tmpCam) { - DestroyImmediate (tmpCam); + if (null != tmpCam) + { + DestroyImmediate(tmpCam); tmpCam = null; } } + public override bool CheckResources() + { + CheckSupport(true, true); // depth & hdr needed + motionBlurMaterial = CheckShaderAndCreateMaterial(shader, motionBlurMaterial); - public override bool CheckResources () { - CheckSupport (true, true); // depth & hdr needed - motionBlurMaterial = CheckShaderAndCreateMaterial (shader, motionBlurMaterial); - - if (supportDX11 && filterType == MotionBlurFilter.ReconstructionDX11) { - dx11MotionBlurMaterial = CheckShaderAndCreateMaterial (dx11MotionBlurShader, dx11MotionBlurMaterial); + if (supportDX11 && filterType == MotionBlurFilter.ReconstructionDX11) + { + dx11MotionBlurMaterial = CheckShaderAndCreateMaterial( + dx11MotionBlurShader, + dx11MotionBlurMaterial + ); } if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - void OnRenderImage (RenderTexture source, RenderTexture destination) { - if (false == CheckResources ()) { - Graphics.Blit (source, destination); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (false == CheckResources()) + { + Graphics.Blit(source, destination); return; } if (filterType == MotionBlurFilter.CameraMotion) - StartFrame (); + StartFrame(); // use if possible new RG format ... fallback to half otherwise - var rtFormat= SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.RGHalf) ? RenderTextureFormat.RGHalf : RenderTextureFormat.ARGBHalf; + var rtFormat = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RGHalf) + ? RenderTextureFormat.RGHalf + : RenderTextureFormat.ARGBHalf; // get temp textures - RenderTexture velBuffer = RenderTexture.GetTemporary (divRoundUp (source.width, velocityDownsample), divRoundUp (source.height, velocityDownsample), 0, rtFormat); + RenderTexture velBuffer = RenderTexture.GetTemporary( + divRoundUp(source.width, velocityDownsample), + divRoundUp(source.height, velocityDownsample), + 0, + rtFormat + ); int tileWidth = 1; int tileHeight = 1; - maxVelocity = Mathf.Max (2.0f, maxVelocity); + maxVelocity = Mathf.Max(2.0f, maxVelocity); float _maxVelocity = maxVelocity; // calculate 'k' // note: 's' is hardcoded in shaders except for DX11 path // auto DX11 fallback! - bool fallbackFromDX11 = filterType == MotionBlurFilter.ReconstructionDX11 && dx11MotionBlurMaterial == null; - - if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11 || filterType == MotionBlurFilter.ReconstructionDisc) { - maxVelocity = Mathf.Min (maxVelocity, MAX_RADIUS); - tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity); - tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity); - _maxVelocity = velBuffer.width/tileWidth; + bool fallbackFromDX11 = + filterType == MotionBlurFilter.ReconstructionDX11 && dx11MotionBlurMaterial == null; + + if ( + filterType == MotionBlurFilter.Reconstruction + || fallbackFromDX11 + || filterType == MotionBlurFilter.ReconstructionDisc + ) + { + maxVelocity = Mathf.Min(maxVelocity, MAX_RADIUS); + tileWidth = divRoundUp(velBuffer.width, (int)maxVelocity); + tileHeight = divRoundUp(velBuffer.height, (int)maxVelocity); + _maxVelocity = velBuffer.width / tileWidth; } - else { - tileWidth = divRoundUp (velBuffer.width, (int) maxVelocity); - tileHeight = divRoundUp (velBuffer.height, (int) maxVelocity); - _maxVelocity = velBuffer.width/tileWidth; + else + { + tileWidth = divRoundUp(velBuffer.width, (int)maxVelocity); + tileHeight = divRoundUp(velBuffer.height, (int)maxVelocity); + _maxVelocity = velBuffer.width / tileWidth; } - RenderTexture tileMax = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat); - RenderTexture neighbourMax = RenderTexture.GetTemporary (tileWidth, tileHeight, 0, rtFormat); + RenderTexture tileMax = RenderTexture.GetTemporary(tileWidth, tileHeight, 0, rtFormat); + RenderTexture neighbourMax = RenderTexture.GetTemporary( + tileWidth, + tileHeight, + 0, + rtFormat + ); velBuffer.filterMode = FilterMode.Point; tileMax.filterMode = FilterMode.Point; neighbourMax.filterMode = FilterMode.Point; - if (noiseTexture) noiseTexture.filterMode = FilterMode.Point; + if (noiseTexture) + noiseTexture.filterMode = FilterMode.Point; source.wrapMode = TextureWrapMode.Clamp; velBuffer.wrapMode = TextureWrapMode.Clamp; neighbourMax.wrapMode = TextureWrapMode.Clamp; tileMax.wrapMode = TextureWrapMode.Clamp; // calc correct viewprj matrix - CalculateViewProjection (); + CalculateViewProjection(); // just started up? - if (gameObject.activeInHierarchy && !wasActive) { - Remember (); + if (gameObject.activeInHierarchy && !wasActive) + { + Remember(); } wasActive = gameObject.activeInHierarchy; // matrices - Matrix4x4 invViewPrj = Matrix4x4.Inverse (currentViewProjMat); - motionBlurMaterial.SetMatrix ("_InvViewProj", invViewPrj); - motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat); - motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj); - if(_camera.stereoEnabled) - { - Matrix4x4[] invStereoViewPrj = new Matrix4x4[2]; - invStereoViewPrj[0] = Matrix4x4.Inverse(currentStereoViewProjMat[0]); - invStereoViewPrj[1] = Matrix4x4.Inverse(currentStereoViewProjMat[1]); - - Matrix4x4 combined = prevStereoViewProjMat[0] * invStereoViewPrj[0]; - motionBlurMaterial.SetMatrix("_StereoToPrevViewProjCombined0", combined); - motionBlurMaterial.SetMatrix("_StereoToPrevViewProjCombined1", prevStereoViewProjMat[1] * invStereoViewPrj[1]); - } - - motionBlurMaterial.SetFloat ("_MaxVelocity", _maxVelocity); - motionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity); - motionBlurMaterial.SetFloat ("_MinVelocity", minVelocity); - motionBlurMaterial.SetFloat ("_VelocityScale", velocityScale); - motionBlurMaterial.SetFloat ("_Jitter", jitter); + Matrix4x4 invViewPrj = Matrix4x4.Inverse(currentViewProjMat); + motionBlurMaterial.SetMatrix("_InvViewProj", invViewPrj); + motionBlurMaterial.SetMatrix("_PrevViewProj", prevViewProjMat); + motionBlurMaterial.SetMatrix("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj); + if (_camera.stereoEnabled) + { + Matrix4x4[] invStereoViewPrj = new Matrix4x4[2]; + invStereoViewPrj[0] = Matrix4x4.Inverse(currentStereoViewProjMat[0]); + invStereoViewPrj[1] = Matrix4x4.Inverse(currentStereoViewProjMat[1]); + + Matrix4x4 combined = prevStereoViewProjMat[0] * invStereoViewPrj[0]; + motionBlurMaterial.SetMatrix("_StereoToPrevViewProjCombined0", combined); + motionBlurMaterial.SetMatrix( + "_StereoToPrevViewProjCombined1", + prevStereoViewProjMat[1] * invStereoViewPrj[1] + ); + } + + motionBlurMaterial.SetFloat("_MaxVelocity", _maxVelocity); + motionBlurMaterial.SetFloat("_MaxRadiusOrKInPaper", _maxVelocity); + motionBlurMaterial.SetFloat("_MinVelocity", minVelocity); + motionBlurMaterial.SetFloat("_VelocityScale", velocityScale); + motionBlurMaterial.SetFloat("_Jitter", jitter); // texture samplers - motionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture); - motionBlurMaterial.SetTexture ("_VelTex", velBuffer); - motionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax); - motionBlurMaterial.SetTexture ("_TileTexDebug", tileMax); + motionBlurMaterial.SetTexture("_NoiseTex", noiseTexture); + motionBlurMaterial.SetTexture("_VelTex", velBuffer); + motionBlurMaterial.SetTexture("_NeighbourMaxTex", neighbourMax); + motionBlurMaterial.SetTexture("_TileTexDebug", tileMax); - if (preview) { + if (preview) + { // generate an artificial 'previous' matrix to simulate blur look Matrix4x4 viewMat = _camera.worldToCameraMatrix; Matrix4x4 offset = Matrix4x4.identity; offset.SetTRS(previewScale * 0.3333f, Quaternion.identity, Vector3.one); // using only translation - Matrix4x4 projMat = GL.GetGPUProjectionMatrix (_camera.projectionMatrix, true); + Matrix4x4 projMat = GL.GetGPUProjectionMatrix(_camera.projectionMatrix, true); prevViewProjMat = projMat * offset * viewMat; - motionBlurMaterial.SetMatrix ("_PrevViewProj", prevViewProjMat); - motionBlurMaterial.SetMatrix ("_ToPrevViewProjCombined", prevViewProjMat * invViewPrj); + motionBlurMaterial.SetMatrix("_PrevViewProj", prevViewProjMat); + motionBlurMaterial.SetMatrix( + "_ToPrevViewProjCombined", + prevViewProjMat * invViewPrj + ); } if (filterType == MotionBlurFilter.CameraMotion) @@ -234,149 +278,197 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) { // build blur vector to be used in shader to create a global blur direction Vector4 blurVector = Vector4.zero; - float lookUpDown = Vector3.Dot (transform.up, Vector3.up); - Vector3 distanceVector = prevFramePos-transform.position; + float lookUpDown = Vector3.Dot(transform.up, Vector3.up); + Vector3 distanceVector = prevFramePos - transform.position; float distMag = distanceVector.magnitude; float farHeur = 1.0f; // pitch (vertical) - farHeur = (Vector3.Angle (transform.up, prevFrameUp) / _camera.fieldOfView) * (source.width * 0.75f); - blurVector.x = rotationScale * farHeur;// Mathf.Clamp01((1.0ff-Vector3.Dot(transform.up, prevFrameUp))); + farHeur = + (Vector3.Angle(transform.up, prevFrameUp) / _camera.fieldOfView) + * (source.width * 0.75f); + blurVector.x = rotationScale * farHeur; // Mathf.Clamp01((1.0ff-Vector3.Dot(transform.up, prevFrameUp))); // yaw #1 (horizontal, faded by pitch) - farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f); - blurVector.y = rotationScale * lookUpDown * farHeur;// Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward))); + farHeur = + (Vector3.Angle(transform.forward, prevFrameForward) / _camera.fieldOfView) + * (source.width * 0.75f); + blurVector.y = rotationScale * lookUpDown * farHeur; // Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward))); // yaw #2 (when looking down, faded by 1-pitch) - farHeur = (Vector3.Angle (transform.forward, prevFrameForward) / _camera.fieldOfView) * (source.width * 0.75f); - blurVector.z = rotationScale * (1.0f- lookUpDown) * farHeur;// Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward))); + farHeur = + (Vector3.Angle(transform.forward, prevFrameForward) / _camera.fieldOfView) + * (source.width * 0.75f); + blurVector.z = rotationScale * (1.0f - lookUpDown) * farHeur; // Mathf.Clamp01((1.0ff-Vector3.Dot(transform.forward, prevFrameForward))); - if (distMag > Mathf.Epsilon && movementScale > Mathf.Epsilon) { + if (distMag > Mathf.Epsilon && movementScale > Mathf.Epsilon) + { // forward (probably most important) - blurVector.w = movementScale * (Vector3.Dot (transform.forward, distanceVector) ) * (source.width * 0.5f); + blurVector.w = + movementScale + * (Vector3.Dot(transform.forward, distanceVector)) + * (source.width * 0.5f); // jump (maybe scale down further) - blurVector.x += movementScale * (Vector3.Dot (transform.up, distanceVector) ) * (source.width * 0.5f); + blurVector.x += + movementScale + * (Vector3.Dot(transform.up, distanceVector)) + * (source.width * 0.5f); // strafe (maybe scale down further) - blurVector.y += movementScale * (Vector3.Dot (transform.right, distanceVector) ) * (source.width * 0.5f); + blurVector.y += + movementScale + * (Vector3.Dot(transform.right, distanceVector)) + * (source.width * 0.5f); } if (preview) // crude approximation - motionBlurMaterial.SetVector ("_BlurDirectionPacked", new Vector4 (previewScale.y, previewScale.x, 0.0f, previewScale.z) * 0.5f * _camera.fieldOfView); + motionBlurMaterial.SetVector( + "_BlurDirectionPacked", + new Vector4(previewScale.y, previewScale.x, 0.0f, previewScale.z) + * 0.5f + * _camera.fieldOfView + ); else - motionBlurMaterial.SetVector ("_BlurDirectionPacked", blurVector); + motionBlurMaterial.SetVector("_BlurDirectionPacked", blurVector); } - else { + else + { // generate velocity buffer - Graphics.Blit (source, velBuffer, motionBlurMaterial, 0); + Graphics.Blit(source, velBuffer, motionBlurMaterial, 0); // patch up velocity buffer: // exclude certain layers (e.g. skinned objects as we cant really support that atm) Camera cam = null; - if (excludeLayers.value != 0)// || dynamicLayers.value) - cam = GetTmpCam (); - - if (cam && excludeLayers.value != 0 && replacementClear && replacementClear.isSupported) { + if (excludeLayers.value != 0) // || dynamicLayers.value) + cam = GetTmpCam(); + + if ( + cam + && excludeLayers.value != 0 + && replacementClear + && replacementClear.isSupported + ) + { cam.targetTexture = velBuffer; cam.cullingMask = excludeLayers; - cam.RenderWithShader (replacementClear, ""); + cam.RenderWithShader(replacementClear, ""); } } - if (!preview && Time.frameCount != prevFrameCount) { + if (!preview && Time.frameCount != prevFrameCount) + { // remember current transformation data for next frame prevFrameCount = Time.frameCount; - Remember (); + Remember(); } source.filterMode = FilterMode.Bilinear; // debug vel buffer: - if (showVelocity) { + if (showVelocity) + { // generate tile max and neighbour max // Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2); // Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3); - motionBlurMaterial.SetFloat ("_DisplayVelocityScale", showVelocityScale); - Graphics.Blit (velBuffer, destination, motionBlurMaterial, 1); + motionBlurMaterial.SetFloat("_DisplayVelocityScale", showVelocityScale); + Graphics.Blit(velBuffer, destination, motionBlurMaterial, 1); } - else { - if (filterType == MotionBlurFilter.ReconstructionDX11 && !fallbackFromDX11) { + else + { + if (filterType == MotionBlurFilter.ReconstructionDX11 && !fallbackFromDX11) + { // need to reset some parameters for dx11 shader - dx11MotionBlurMaterial.SetFloat ("_MinVelocity", minVelocity); - dx11MotionBlurMaterial.SetFloat ("_VelocityScale", velocityScale); - dx11MotionBlurMaterial.SetFloat ("_Jitter", jitter); + dx11MotionBlurMaterial.SetFloat("_MinVelocity", minVelocity); + dx11MotionBlurMaterial.SetFloat("_VelocityScale", velocityScale); + dx11MotionBlurMaterial.SetFloat("_Jitter", jitter); // texture samplers - dx11MotionBlurMaterial.SetTexture ("_NoiseTex", noiseTexture); - dx11MotionBlurMaterial.SetTexture ("_VelTex", velBuffer); - dx11MotionBlurMaterial.SetTexture ("_NeighbourMaxTex", neighbourMax); + dx11MotionBlurMaterial.SetTexture("_NoiseTex", noiseTexture); + dx11MotionBlurMaterial.SetTexture("_VelTex", velBuffer); + dx11MotionBlurMaterial.SetTexture("_NeighbourMaxTex", neighbourMax); - dx11MotionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) ); - dx11MotionBlurMaterial.SetFloat ("_MaxRadiusOrKInPaper", _maxVelocity); + dx11MotionBlurMaterial.SetFloat( + "_SoftZDistance", + Mathf.Max(0.00025f, softZDistance) + ); + dx11MotionBlurMaterial.SetFloat("_MaxRadiusOrKInPaper", _maxVelocity); // generate tile max and neighbour max - Graphics.Blit (velBuffer, tileMax, dx11MotionBlurMaterial, 0); - Graphics.Blit (tileMax, neighbourMax, dx11MotionBlurMaterial, 1); + Graphics.Blit(velBuffer, tileMax, dx11MotionBlurMaterial, 0); + Graphics.Blit(tileMax, neighbourMax, dx11MotionBlurMaterial, 1); // final blur - Graphics.Blit (source, destination, dx11MotionBlurMaterial, 2); + Graphics.Blit(source, destination, dx11MotionBlurMaterial, 2); } - else if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11) { + else if (filterType == MotionBlurFilter.Reconstruction || fallbackFromDX11) + { // 'reconstructing' properly integrated color - motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) ); + motionBlurMaterial.SetFloat( + "_SoftZDistance", + Mathf.Max(0.00025f, softZDistance) + ); // generate tile max and neighbour max - Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2); - Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3); + Graphics.Blit(velBuffer, tileMax, motionBlurMaterial, 2); + Graphics.Blit(tileMax, neighbourMax, motionBlurMaterial, 3); // final blur - Graphics.Blit (source, destination, motionBlurMaterial, 4); + Graphics.Blit(source, destination, motionBlurMaterial, 4); } - else if (filterType == MotionBlurFilter.CameraMotion) { + else if (filterType == MotionBlurFilter.CameraMotion) + { // orange box style motion blur - Graphics.Blit (source, destination, motionBlurMaterial, 6); + Graphics.Blit(source, destination, motionBlurMaterial, 6); } - else if (filterType == MotionBlurFilter.ReconstructionDisc) { + else if (filterType == MotionBlurFilter.ReconstructionDisc) + { // dof style motion blur defocuing and ellipse around the princical blur direction // 'reconstructing' properly integrated color - motionBlurMaterial.SetFloat ("_SoftZDistance", Mathf.Max(0.00025f, softZDistance) ); + motionBlurMaterial.SetFloat( + "_SoftZDistance", + Mathf.Max(0.00025f, softZDistance) + ); // generate tile max and neighbour max - Graphics.Blit (velBuffer, tileMax, motionBlurMaterial, 2); - Graphics.Blit (tileMax, neighbourMax, motionBlurMaterial, 3); + Graphics.Blit(velBuffer, tileMax, motionBlurMaterial, 2); + Graphics.Blit(tileMax, neighbourMax, motionBlurMaterial, 3); - Graphics.Blit (source, destination, motionBlurMaterial, 7); + Graphics.Blit(source, destination, motionBlurMaterial, 7); } - else { + else + { // simple & fast blur (low quality): just blurring along velocity - Graphics.Blit (source, destination, motionBlurMaterial, 5); + Graphics.Blit(source, destination, motionBlurMaterial, 5); } } // cleanup - RenderTexture.ReleaseTemporary (velBuffer); - RenderTexture.ReleaseTemporary (tileMax); - RenderTexture.ReleaseTemporary (neighbourMax); + RenderTexture.ReleaseTemporary(velBuffer); + RenderTexture.ReleaseTemporary(tileMax); + RenderTexture.ReleaseTemporary(neighbourMax); } - void Remember () { + void Remember() + { prevViewProjMat = currentViewProjMat; - prevFrameForward = transform.forward; + prevFrameForward = transform.forward; prevFrameUp = transform.up; prevFramePos = transform.position; - prevStereoViewProjMat[0] = currentStereoViewProjMat[0]; - prevStereoViewProjMat[1] = currentStereoViewProjMat[1]; - } + prevStereoViewProjMat[0] = currentStereoViewProjMat[0]; + prevStereoViewProjMat[1] = currentStereoViewProjMat[1]; + } - Camera GetTmpCam () { - if (tmpCam == null) { + Camera GetTmpCam() + { + if (tmpCam == null) + { string name = "_" + _camera.name + "_MotionBlurTmpCam"; - GameObject go = GameObject.Find (name); + GameObject go = GameObject.Find(name); if (null == go) // couldn't find, recreate - tmpCam = new GameObject (name, typeof (Camera)); + tmpCam = new GameObject(name, typeof(Camera)); else tmpCam = go; } @@ -394,13 +486,14 @@ Camera GetTmpCam () { return tmpCam.GetComponent(); } - void StartFrame () { + void StartFrame() + { // take only x% of positional changes into account (camera motion) // TODO: possibly do the same for rotational part prevFramePos = Vector3.Slerp(prevFramePos, transform.position, 0.75f); } - static int divRoundUp (int x, int d) + static int divRoundUp(int x, int d) { return (x + d - 1) / d; } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ColorCorrectionCurves.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ColorCorrectionCurves.cs index dd4e9d648c..960ea4e452 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ColorCorrectionCurves.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ColorCorrectionCurves.cs @@ -4,25 +4,46 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [AddComponentMenu ("Image Effects/Color Adjustments/Color Correction (Curves, Saturation)")] + [AddComponentMenu("Image Effects/Color Adjustments/Color Correction (Curves, Saturation)")] public class ColorCorrectionCurves : PostEffectsBase - { + { public enum ColorCorrectionMode - { + { Simple = 0, Advanced = 1 } - public AnimationCurve redChannel = new AnimationCurve(new Keyframe(0f,0f), new Keyframe(1f,1f)); - public AnimationCurve greenChannel = new AnimationCurve(new Keyframe(0f,0f), new Keyframe(1f,1f)); - public AnimationCurve blueChannel = new AnimationCurve(new Keyframe(0f,0f), new Keyframe(1f,1f)); - - public bool useDepthCorrection = false; - - public AnimationCurve zCurve = new AnimationCurve(new Keyframe(0f,0f), new Keyframe(1f,1f)); - public AnimationCurve depthRedChannel = new AnimationCurve(new Keyframe(0f,0f), new Keyframe(1f,1f)); - public AnimationCurve depthGreenChannel = new AnimationCurve(new Keyframe(0f,0f), new Keyframe(1f,1f)); - public AnimationCurve depthBlueChannel = new AnimationCurve(new Keyframe(0f,0f), new Keyframe(1f,1f)); + public AnimationCurve redChannel = new AnimationCurve( + new Keyframe(0f, 0f), + new Keyframe(1f, 1f) + ); + public AnimationCurve greenChannel = new AnimationCurve( + new Keyframe(0f, 0f), + new Keyframe(1f, 1f) + ); + public AnimationCurve blueChannel = new AnimationCurve( + new Keyframe(0f, 0f), + new Keyframe(1f, 1f) + ); + + public bool useDepthCorrection = false; + + public AnimationCurve zCurve = new AnimationCurve( + new Keyframe(0f, 0f), + new Keyframe(1f, 1f) + ); + public AnimationCurve depthRedChannel = new AnimationCurve( + new Keyframe(0f, 0f), + new Keyframe(1f, 1f) + ); + public AnimationCurve depthGreenChannel = new AnimationCurve( + new Keyframe(0f, 0f), + new Keyframe(1f, 1f) + ); + public AnimationCurve depthBlueChannel = new AnimationCurve( + new Keyframe(0f, 0f), + new Keyframe(1f, 1f) + ); private Material ccMaterial; private Material ccDepthMaterial; @@ -34,45 +55,52 @@ public enum ColorCorrectionMode public float saturation = 1.0f; - public bool selectiveCc = false; + public bool selectiveCc = false; public Color selectiveFromColor = Color.white; public Color selectiveToColor = Color.white; public ColorCorrectionMode mode; - public bool updateTextures = true; + public bool updateTextures = true; public Shader colorCorrectionCurvesShader = null; public Shader simpleColorCorrectionCurvesShader = null; public Shader colorCorrectionSelectiveShader = null; - private bool updateTexturesOnStartup = true; - + private bool updateTexturesOnStartup = true; - new void Start () - { - base.Start (); + new void Start() + { + base.Start(); updateTexturesOnStartup = true; } - void Awake () { } - - - public override bool CheckResources () - { - CheckSupport (mode == ColorCorrectionMode.Advanced); - - ccMaterial = CheckShaderAndCreateMaterial (simpleColorCorrectionCurvesShader, ccMaterial); - ccDepthMaterial = CheckShaderAndCreateMaterial (colorCorrectionCurvesShader, ccDepthMaterial); - selectiveCcMaterial = CheckShaderAndCreateMaterial (colorCorrectionSelectiveShader, selectiveCcMaterial); + void Awake() { } + + public override bool CheckResources() + { + CheckSupport(mode == ColorCorrectionMode.Advanced); + + ccMaterial = CheckShaderAndCreateMaterial( + simpleColorCorrectionCurvesShader, + ccMaterial + ); + ccDepthMaterial = CheckShaderAndCreateMaterial( + colorCorrectionCurvesShader, + ccDepthMaterial + ); + selectiveCcMaterial = CheckShaderAndCreateMaterial( + colorCorrectionSelectiveShader, + selectiveCcMaterial + ); if (!rgbChannelTex) - rgbChannelTex = new Texture2D (256, 4, TextureFormat.ARGB32, false, true); + rgbChannelTex = new Texture2D(256, 4, TextureFormat.ARGB32, false, true); if (!rgbDepthChannelTex) - rgbDepthChannelTex = new Texture2D (256, 4, TextureFormat.ARGB32, false, true); + rgbDepthChannelTex = new Texture2D(256, 4, TextureFormat.ARGB32, false, true); if (!zCurveTex) - zCurveTex = new Texture2D (256, 1, TextureFormat.ARGB32, false, true); + zCurveTex = new Texture2D(256, 1, TextureFormat.ARGB32, false, true); rgbChannelTex.hideFlags = HideFlags.DontSave; rgbDepthChannelTex.hideFlags = HideFlags.DontSave; @@ -83,61 +111,85 @@ public override bool CheckResources () zCurveTex.wrapMode = TextureWrapMode.Clamp; if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - public void UpdateParameters () - { + public void UpdateParameters() + { CheckResources(); // textures might not be created if we're tweaking UI while disabled if (redChannel != null && greenChannel != null && blueChannel != null) - { + { for (float i = 0.0f; i <= 1.0f; i += 1.0f / 255.0f) - { - float rCh = Mathf.Clamp (redChannel.Evaluate(i), 0.0f, 1.0f); - float gCh = Mathf.Clamp (greenChannel.Evaluate(i), 0.0f, 1.0f); - float bCh = Mathf.Clamp (blueChannel.Evaluate(i), 0.0f, 1.0f); - - rgbChannelTex.SetPixel ((int) Mathf.Floor(i*255.0f), 0, new Color(rCh,rCh,rCh) ); - rgbChannelTex.SetPixel ((int) Mathf.Floor(i*255.0f), 1, new Color(gCh,gCh,gCh) ); - rgbChannelTex.SetPixel ((int) Mathf.Floor(i*255.0f), 2, new Color(bCh,bCh,bCh) ); - - float zC = Mathf.Clamp (zCurve.Evaluate(i), 0.0f,1.0f); - - zCurveTex.SetPixel ((int) Mathf.Floor(i*255.0f), 0, new Color(zC,zC,zC) ); - - rCh = Mathf.Clamp (depthRedChannel.Evaluate(i), 0.0f,1.0f); - gCh = Mathf.Clamp (depthGreenChannel.Evaluate(i), 0.0f,1.0f); - bCh = Mathf.Clamp (depthBlueChannel.Evaluate(i), 0.0f,1.0f); - - rgbDepthChannelTex.SetPixel ((int) Mathf.Floor(i*255.0f), 0, new Color(rCh,rCh,rCh) ); - rgbDepthChannelTex.SetPixel ((int) Mathf.Floor(i*255.0f), 1, new Color(gCh,gCh,gCh) ); - rgbDepthChannelTex.SetPixel ((int) Mathf.Floor(i*255.0f), 2, new Color(bCh,bCh,bCh) ); + { + float rCh = Mathf.Clamp(redChannel.Evaluate(i), 0.0f, 1.0f); + float gCh = Mathf.Clamp(greenChannel.Evaluate(i), 0.0f, 1.0f); + float bCh = Mathf.Clamp(blueChannel.Evaluate(i), 0.0f, 1.0f); + + rgbChannelTex.SetPixel( + (int)Mathf.Floor(i * 255.0f), + 0, + new Color(rCh, rCh, rCh) + ); + rgbChannelTex.SetPixel( + (int)Mathf.Floor(i * 255.0f), + 1, + new Color(gCh, gCh, gCh) + ); + rgbChannelTex.SetPixel( + (int)Mathf.Floor(i * 255.0f), + 2, + new Color(bCh, bCh, bCh) + ); + + float zC = Mathf.Clamp(zCurve.Evaluate(i), 0.0f, 1.0f); + + zCurveTex.SetPixel((int)Mathf.Floor(i * 255.0f), 0, new Color(zC, zC, zC)); + + rCh = Mathf.Clamp(depthRedChannel.Evaluate(i), 0.0f, 1.0f); + gCh = Mathf.Clamp(depthGreenChannel.Evaluate(i), 0.0f, 1.0f); + bCh = Mathf.Clamp(depthBlueChannel.Evaluate(i), 0.0f, 1.0f); + + rgbDepthChannelTex.SetPixel( + (int)Mathf.Floor(i * 255.0f), + 0, + new Color(rCh, rCh, rCh) + ); + rgbDepthChannelTex.SetPixel( + (int)Mathf.Floor(i * 255.0f), + 1, + new Color(gCh, gCh, gCh) + ); + rgbDepthChannelTex.SetPixel( + (int)Mathf.Floor(i * 255.0f), + 2, + new Color(bCh, bCh, bCh) + ); } - rgbChannelTex.Apply (); - rgbDepthChannelTex.Apply (); - zCurveTex.Apply (); + rgbChannelTex.Apply(); + rgbDepthChannelTex.Apply(); + zCurveTex.Apply(); } } - void UpdateTextures () - { - UpdateParameters (); + void UpdateTextures() + { + UpdateParameters(); } - void OnRenderImage (RenderTexture source, RenderTexture destination) - { - if (CheckResources()==false) - { - Graphics.Blit (source, destination); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (CheckResources() == false) + { + Graphics.Blit(source, destination); return; } if (updateTexturesOnStartup) - { - UpdateParameters (); + { + UpdateParameters(); updateTexturesOnStartup = false; } @@ -147,34 +199,34 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) RenderTexture renderTarget2Use = destination; if (selectiveCc) - { - renderTarget2Use = RenderTexture.GetTemporary (source.width, source.height); + { + renderTarget2Use = RenderTexture.GetTemporary(source.width, source.height); } if (useDepthCorrection) - { - ccDepthMaterial.SetTexture ("_RgbTex", rgbChannelTex); - ccDepthMaterial.SetTexture ("_ZCurve", zCurveTex); - ccDepthMaterial.SetTexture ("_RgbDepthTex", rgbDepthChannelTex); - ccDepthMaterial.SetFloat ("_Saturation", saturation); + { + ccDepthMaterial.SetTexture("_RgbTex", rgbChannelTex); + ccDepthMaterial.SetTexture("_ZCurve", zCurveTex); + ccDepthMaterial.SetTexture("_RgbDepthTex", rgbDepthChannelTex); + ccDepthMaterial.SetFloat("_Saturation", saturation); - Graphics.Blit (source, renderTarget2Use, ccDepthMaterial); + Graphics.Blit(source, renderTarget2Use, ccDepthMaterial); } else - { - ccMaterial.SetTexture ("_RgbTex", rgbChannelTex); - ccMaterial.SetFloat ("_Saturation", saturation); + { + ccMaterial.SetTexture("_RgbTex", rgbChannelTex); + ccMaterial.SetFloat("_Saturation", saturation); - Graphics.Blit (source, renderTarget2Use, ccMaterial); + Graphics.Blit(source, renderTarget2Use, ccMaterial); } if (selectiveCc) - { - selectiveCcMaterial.SetColor ("selColor", selectiveFromColor); - selectiveCcMaterial.SetColor ("targetColor", selectiveToColor); - Graphics.Blit (renderTarget2Use, destination, selectiveCcMaterial); + { + selectiveCcMaterial.SetColor("selColor", selectiveFromColor); + selectiveCcMaterial.SetColor("targetColor", selectiveToColor); + Graphics.Blit(renderTarget2Use, destination, selectiveCcMaterial); - RenderTexture.ReleaseTemporary (renderTarget2Use); + RenderTexture.ReleaseTemporary(renderTarget2Use); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ColorCorrectionLookup.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ColorCorrectionLookup.cs index f122aea0a7..05e7649c0a 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ColorCorrectionLookup.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ColorCorrectionLookup.cs @@ -4,7 +4,7 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [AddComponentMenu ("Image Effects/Color Adjustments/Color Correction (3D Lookup Texture)")] + [AddComponentMenu("Image Effects/Color Adjustments/Color Correction (3D Lookup Texture)")] public class ColorCorrectionLookup : PostEffectsBase { public Shader shader; @@ -14,71 +14,90 @@ public class ColorCorrectionLookup : PostEffectsBase public Texture3D converted3DLut = null; public string basedOnTempTex = ""; + public override bool CheckResources() + { + CheckSupport(false); - public override bool CheckResources () { - CheckSupport (false); - - material = CheckShaderAndCreateMaterial (shader, material); + material = CheckShaderAndCreateMaterial(shader, material); if (!isSupported || !SystemInfo.supports3DTextures) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - void OnDisable () { - if (material) { - DestroyImmediate (material); + void OnDisable() + { + if (material) + { + DestroyImmediate(material); material = null; } } - void OnDestroy () { + void OnDestroy() + { if (converted3DLut) - DestroyImmediate (converted3DLut); + DestroyImmediate(converted3DLut); converted3DLut = null; } - public void SetIdentityLut () { + public void SetIdentityLut() + { int dim = 16; - var newC = new Color[dim*dim*dim]; + var newC = new Color[dim * dim * dim]; float oneOverDim = 1.0f / (1.0f * dim - 1.0f); - for(int i = 0; i < dim; i++) { - for(int j = 0; j < dim; j++) { - for(int k = 0; k < dim; k++) { - newC[i + (j*dim) + (k*dim*dim)] = new Color((i*1.0f)*oneOverDim, (j*1.0f)*oneOverDim, (k*1.0f)*oneOverDim, 1.0f); + for (int i = 0; i < dim; i++) + { + for (int j = 0; j < dim; j++) + { + for (int k = 0; k < dim; k++) + { + newC[i + (j * dim) + (k * dim * dim)] = new Color( + (i * 1.0f) * oneOverDim, + (j * 1.0f) * oneOverDim, + (k * 1.0f) * oneOverDim, + 1.0f + ); } } } if (converted3DLut) - DestroyImmediate (converted3DLut); - converted3DLut = new Texture3D (dim, dim, dim, TextureFormat.ARGB32, false); - converted3DLut.SetPixels (newC); - converted3DLut.Apply (); + DestroyImmediate(converted3DLut); + converted3DLut = new Texture3D(dim, dim, dim, TextureFormat.ARGB32, false); + converted3DLut.SetPixels(newC); + converted3DLut.Apply(); basedOnTempTex = ""; } - public bool ValidDimensions ( Texture2D tex2d) { - if (!tex2d) return false; + public bool ValidDimensions(Texture2D tex2d) + { + if (!tex2d) + return false; int h = tex2d.height; - if (h != Mathf.FloorToInt(Mathf.Sqrt(tex2d.width))) { + if (h != Mathf.FloorToInt(Mathf.Sqrt(tex2d.width))) + { return false; } return true; } - public void Convert ( Texture2D temp2DTex, string path) { - + public void Convert(Texture2D temp2DTex, string path) + { // conversion fun: the given 2D texture needs to be of the format // w * h, wheras h is the 'depth' (or 3d dimension 'dim') and w = dim * dim - if (temp2DTex) { + if (temp2DTex) + { int dim = temp2DTex.width * temp2DTex.height; dim = temp2DTex.height; - if (!ValidDimensions(temp2DTex)) { - Debug.LogWarning ("The given 2D texture " + temp2DTex.name + " cannot be used as a 3D LUT."); + if (!ValidDimensions(temp2DTex)) + { + Debug.LogWarning( + "The given 2D texture " + temp2DTex.name + " cannot be used as a 3D LUT." + ); basedOnTempTex = ""; return; } @@ -86,45 +105,59 @@ public void Convert ( Texture2D temp2DTex, string path) { var c = temp2DTex.GetPixels(); var newC = new Color[c.Length]; - for(int i = 0; i < dim; i++) { - for(int j = 0; j < dim; j++) { - for(int k = 0; k < dim; k++) { - int j_ = dim-j-1; - newC[i + (j*dim) + (k*dim*dim)] = c[k*dim+i+j_*dim*dim]; + for (int i = 0; i < dim; i++) + { + for (int j = 0; j < dim; j++) + { + for (int k = 0; k < dim; k++) + { + int j_ = dim - j - 1; + newC[i + (j * dim) + (k * dim * dim)] = c[k * dim + i + j_ * dim * dim]; } } } if (converted3DLut) - DestroyImmediate (converted3DLut); - converted3DLut = new Texture3D (dim, dim, dim, TextureFormat.ARGB32, false); - converted3DLut.SetPixels (newC); - converted3DLut.Apply (); + DestroyImmediate(converted3DLut); + converted3DLut = new Texture3D(dim, dim, dim, TextureFormat.ARGB32, false); + converted3DLut.SetPixels(newC); + converted3DLut.Apply(); basedOnTempTex = path; } - else { + else + { // error, something went terribly wrong - Debug.LogError ("Couldn't color correct with 3D LUT texture. Image Effect will be disabled."); + Debug.LogError( + "Couldn't color correct with 3D LUT texture. Image Effect will be disabled." + ); } } - void OnRenderImage (RenderTexture source, RenderTexture destination) { - if (CheckResources () == false || !SystemInfo.supports3DTextures) { - Graphics.Blit (source, destination); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (CheckResources() == false || !SystemInfo.supports3DTextures) + { + Graphics.Blit(source, destination); return; } - if (converted3DLut == null) { - SetIdentityLut (); + if (converted3DLut == null) + { + SetIdentityLut(); } int lutSize = converted3DLut.width; converted3DLut.wrapMode = TextureWrapMode.Clamp; - material.SetFloat("_Scale", (lutSize - 1) / (1.0f*lutSize)); + material.SetFloat("_Scale", (lutSize - 1) / (1.0f * lutSize)); material.SetFloat("_Offset", 1.0f / (2.0f * lutSize)); material.SetTexture("_ClutTex", converted3DLut); - Graphics.Blit (source, destination, material, QualitySettings.activeColorSpace == ColorSpace.Linear ? 1 : 0); + Graphics.Blit( + source, + destination, + material, + QualitySettings.activeColorSpace == ColorSpace.Linear ? 1 : 0 + ); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ColorCorrectionRamp.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ColorCorrectionRamp.cs index 662f59ffcc..5bdc5f0a14 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ColorCorrectionRamp.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ColorCorrectionRamp.cs @@ -5,13 +5,15 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [AddComponentMenu("Image Effects/Color Adjustments/Color Correction (Ramp)")] - public class ColorCorrectionRamp : ImageEffectBase { - public Texture textureRamp; + public class ColorCorrectionRamp : ImageEffectBase + { + public Texture textureRamp; // Called by camera to apply image effect - void OnRenderImage (RenderTexture source, RenderTexture destination) { - material.SetTexture ("_RampTex", textureRamp); - Graphics.Blit (source, destination, material); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + material.SetTexture("_RampTex", textureRamp); + Graphics.Blit(source, destination, material); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ContrastEnhance.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ContrastEnhance.cs index 489c56184b..8b1b7a68fe 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ContrastEnhance.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ContrastEnhance.cs @@ -7,74 +7,86 @@ namespace UnityStandardAssets.ImageEffects [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Color Adjustments/Contrast Enhance (Unsharp Mask)")] public class ContrastEnhance : PostEffectsBase - { + { [Range(0.0f, 1.0f)] public float intensity = 0.5f; - [Range(0.0f,0.999f)] + + [Range(0.0f, 0.999f)] public float threshold = 0.0f; private Material separableBlurMaterial; private Material contrastCompositeMaterial; - [Range(0.0f,1.0f)] + [Range(0.0f, 1.0f)] public float blurSpread = 1.0f; public Shader separableBlurShader = null; public Shader contrastCompositeShader = null; + public override bool CheckResources() + { + CheckSupport(false); - public override bool CheckResources () - { - CheckSupport (false); - - contrastCompositeMaterial = CheckShaderAndCreateMaterial (contrastCompositeShader, contrastCompositeMaterial); - separableBlurMaterial = CheckShaderAndCreateMaterial (separableBlurShader, separableBlurMaterial); + contrastCompositeMaterial = CheckShaderAndCreateMaterial( + contrastCompositeShader, + contrastCompositeMaterial + ); + separableBlurMaterial = CheckShaderAndCreateMaterial( + separableBlurShader, + separableBlurMaterial + ); if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - void OnRenderImage (RenderTexture source, RenderTexture destination) - { - if (CheckResources()==false) - { - Graphics.Blit (source, destination); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (CheckResources() == false) + { + Graphics.Blit(source, destination); return; } int rtW = source.width; int rtH = source.height; - RenderTexture color2 = RenderTexture.GetTemporary (rtW/2, rtH/2, 0); + RenderTexture color2 = RenderTexture.GetTemporary(rtW / 2, rtH / 2, 0); // downsample - Graphics.Blit (source, color2); - RenderTexture color4a = RenderTexture.GetTemporary (rtW/4, rtH/4, 0); - Graphics.Blit (color2, color4a); - RenderTexture.ReleaseTemporary (color2); + Graphics.Blit(source, color2); + RenderTexture color4a = RenderTexture.GetTemporary(rtW / 4, rtH / 4, 0); + Graphics.Blit(color2, color4a); + RenderTexture.ReleaseTemporary(color2); // blur - separableBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, (blurSpread * 1.0f) / color4a.height, 0.0f, 0.0f)); - RenderTexture color4b = RenderTexture.GetTemporary (rtW/4, rtH/4, 0); - Graphics.Blit (color4a, color4b, separableBlurMaterial); - RenderTexture.ReleaseTemporary (color4a); - - separableBlurMaterial.SetVector ("offsets", new Vector4 ((blurSpread * 1.0f) / color4a.width, 0.0f, 0.0f, 0.0f)); - color4a = RenderTexture.GetTemporary (rtW/4, rtH/4, 0); - Graphics.Blit (color4b, color4a, separableBlurMaterial); - RenderTexture.ReleaseTemporary (color4b); + separableBlurMaterial.SetVector( + "offsets", + new Vector4(0.0f, (blurSpread * 1.0f) / color4a.height, 0.0f, 0.0f) + ); + RenderTexture color4b = RenderTexture.GetTemporary(rtW / 4, rtH / 4, 0); + Graphics.Blit(color4a, color4b, separableBlurMaterial); + RenderTexture.ReleaseTemporary(color4a); + + separableBlurMaterial.SetVector( + "offsets", + new Vector4((blurSpread * 1.0f) / color4a.width, 0.0f, 0.0f, 0.0f) + ); + color4a = RenderTexture.GetTemporary(rtW / 4, rtH / 4, 0); + Graphics.Blit(color4b, color4a, separableBlurMaterial); + RenderTexture.ReleaseTemporary(color4b); // composite - contrastCompositeMaterial.SetTexture ("_MainTexBlurred", color4a); - contrastCompositeMaterial.SetFloat ("intensity", intensity); - contrastCompositeMaterial.SetFloat ("threshold", threshold); - Graphics.Blit (source, destination, contrastCompositeMaterial); + contrastCompositeMaterial.SetTexture("_MainTexBlurred", color4a); + contrastCompositeMaterial.SetFloat("intensity", intensity); + contrastCompositeMaterial.SetFloat("threshold", threshold); + Graphics.Blit(source, destination, contrastCompositeMaterial); - RenderTexture.ReleaseTemporary (color4a); + RenderTexture.ReleaseTemporary(color4a); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ContrastStretch.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ContrastStretch.cs index a408674e3d..b6494ab91e 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ContrastStretch.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ContrastStretch.cs @@ -18,26 +18,27 @@ public class ContrastStretch : MonoBehaviour /// limitMinimum=1, limitMaximum=0 is always stretching colors to full range. /// The limit on the minimum luminance (0...1) - we won't go above this. - [Range(0.0f,1.0f)] + [Range(0.0f, 1.0f)] public float limitMinimum = 0.2f; /// The limit on the maximum luminance (0...1) - we won't go below this. [Range(0.0f, 1.0f)] public float limitMaximum = 0.6f; - // To maintain adaptation levels over time, we need two 1x1 render textures // and ping-pong between them. private RenderTexture[] adaptRenderTex = new RenderTexture[2]; private int curAdaptIndex = 0; - // Computes scene luminance (grayscale) image - public Shader shaderLum; + public Shader shaderLum; private Material m_materialLum; - protected Material materialLum { - get { - if ( m_materialLum == null ) { + protected Material materialLum + { + get + { + if (m_materialLum == null) + { m_materialLum = new Material(shaderLum); m_materialLum.hideFlags = HideFlags.HideAndDontSave; } @@ -48,11 +49,14 @@ protected Material materialLum { // Reduces size of the image by 2x2, while computing maximum/minimum values. // By repeatedly applying this shader, we reduce the initial luminance image // to 1x1 image with minimum/maximum luminances found. - public Shader shaderReduce; + public Shader shaderReduce; private Material m_materialReduce; - protected Material materialReduce { - get { - if ( m_materialReduce == null ) { + protected Material materialReduce + { + get + { + if (m_materialReduce == null) + { m_materialReduce = new Material(shaderReduce); m_materialReduce.hideFlags = HideFlags.HideAndDontSave; } @@ -62,11 +66,14 @@ protected Material materialReduce { // Adaptation shader - gradually "adapts" minimum/maximum luminances, // based on currently adapted 1x1 image and the actual 1x1 image of the current scene. - public Shader shaderAdapt; + public Shader shaderAdapt; private Material m_materialAdapt; - protected Material materialAdapt { - get { - if ( m_materialAdapt == null ) { + protected Material materialAdapt + { + get + { + if (m_materialAdapt == null) + { m_materialAdapt = new Material(shaderAdapt); m_materialAdapt.hideFlags = HideFlags.HideAndDontSave; } @@ -76,11 +83,14 @@ protected Material materialAdapt { // Final pass - stretches the color values of the original scene, based on currently // adpated minimum/maximum values. - public Shader shaderApply; + public Shader shaderApply; private Material m_materialApply; - protected Material materialApply { - get { - if ( m_materialApply == null ) { + protected Material materialApply + { + get + { + if (m_materialApply == null) + { m_materialApply = new Material(shaderApply); m_materialApply.hideFlags = HideFlags.HideAndDontSave; } @@ -96,7 +106,13 @@ void Start() // return; // } - if (!shaderAdapt.isSupported || !shaderApply.isSupported || !shaderLum.isSupported || !shaderReduce.isSupported) { + if ( + !shaderAdapt.isSupported + || !shaderApply.isSupported + || !shaderLum.isSupported + || !shaderReduce.isSupported + ) + { enabled = false; return; } @@ -104,9 +120,10 @@ void Start() void OnEnable() { - for( int i = 0; i < 2; ++i ) + for (int i = 0; i < 2; ++i) { - if ( !adaptRenderTex[i] ) { + if (!adaptRenderTex[i]) + { adaptRenderTex[i] = new RenderTexture(1, 1, 0); adaptRenderTex[i].hideFlags = HideFlags.HideAndDontSave; } @@ -115,86 +132,88 @@ void OnEnable() void OnDisable() { - for( int i = 0; i < 2; ++i ) + for (int i = 0; i < 2; ++i) { - DestroyImmediate( adaptRenderTex[i] ); + DestroyImmediate(adaptRenderTex[i]); adaptRenderTex[i] = null; } - if ( m_materialLum ) - DestroyImmediate( m_materialLum ); - if ( m_materialReduce ) - DestroyImmediate( m_materialReduce ); - if ( m_materialAdapt ) - DestroyImmediate( m_materialAdapt ); - if ( m_materialApply ) - DestroyImmediate( m_materialApply ); + if (m_materialLum) + DestroyImmediate(m_materialLum); + if (m_materialReduce) + DestroyImmediate(m_materialReduce); + if (m_materialAdapt) + DestroyImmediate(m_materialAdapt); + if (m_materialApply) + DestroyImmediate(m_materialApply); } - /// Apply the filter - void OnRenderImage (RenderTexture source, RenderTexture destination) + void OnRenderImage(RenderTexture source, RenderTexture destination) { // Blit to smaller RT and convert to luminance on the way const int TEMP_RATIO = 1; // 4x4 smaller - RenderTexture rtTempSrc = RenderTexture.GetTemporary(source.width/TEMP_RATIO, source.height/TEMP_RATIO); - Graphics.Blit (source, rtTempSrc, materialLum); + RenderTexture rtTempSrc = RenderTexture.GetTemporary( + source.width / TEMP_RATIO, + source.height / TEMP_RATIO + ); + Graphics.Blit(source, rtTempSrc, materialLum); // Repeatedly reduce this image in size, computing min/max luminance values // In the end we'll have 1x1 image with min/max luminances found. const int FINAL_SIZE = 1; // const int FINAL_SIZE = 1; - while( rtTempSrc.width > FINAL_SIZE || rtTempSrc.height > FINAL_SIZE ) + while (rtTempSrc.width > FINAL_SIZE || rtTempSrc.height > FINAL_SIZE) { const int REDUCE_RATIO = 2; // our shader does 2x2 reduction int destW = rtTempSrc.width / REDUCE_RATIO; - if ( destW < FINAL_SIZE ) destW = FINAL_SIZE; + if (destW < FINAL_SIZE) + destW = FINAL_SIZE; int destH = rtTempSrc.height / REDUCE_RATIO; - if ( destH < FINAL_SIZE ) destH = FINAL_SIZE; - RenderTexture rtTempDst = RenderTexture.GetTemporary(destW,destH); - Graphics.Blit (rtTempSrc, rtTempDst, materialReduce); + if (destH < FINAL_SIZE) + destH = FINAL_SIZE; + RenderTexture rtTempDst = RenderTexture.GetTemporary(destW, destH); + Graphics.Blit(rtTempSrc, rtTempDst, materialReduce); // Release old src temporary, and make new temporary the source - RenderTexture.ReleaseTemporary( rtTempSrc ); + RenderTexture.ReleaseTemporary(rtTempSrc); rtTempSrc = rtTempDst; } // Update viewer's adaptation level - CalculateAdaptation( rtTempSrc ); + CalculateAdaptation(rtTempSrc); // Apply contrast strech to the original scene, using currently adapted parameters - materialApply.SetTexture("_AdaptTex", adaptRenderTex[curAdaptIndex] ); - Graphics.Blit (source, destination, materialApply); + materialApply.SetTexture("_AdaptTex", adaptRenderTex[curAdaptIndex]); + Graphics.Blit(source, destination, materialApply); - RenderTexture.ReleaseTemporary( rtTempSrc ); + RenderTexture.ReleaseTemporary(rtTempSrc); } - /// Helper function to do gradual adaptation to min/max luminances - private void CalculateAdaptation( Texture curTexture ) + private void CalculateAdaptation(Texture curTexture) { int prevAdaptIndex = curAdaptIndex; - curAdaptIndex = (curAdaptIndex+1) % 2; + curAdaptIndex = (curAdaptIndex + 1) % 2; // Adaptation speed is expressed in percents/frame, based on 30FPS. // Calculate the adaptation lerp, based on current FPS. - float adaptLerp = 1.0f - Mathf.Pow( 1.0f - adaptationSpeed, 30.0f * Time.deltaTime ); + float adaptLerp = 1.0f - Mathf.Pow(1.0f - adaptationSpeed, 30.0f * Time.deltaTime); const float kMinAdaptLerp = 0.01f; - adaptLerp = Mathf.Clamp( adaptLerp, kMinAdaptLerp, 1 ); - - materialAdapt.SetTexture("_CurTex", curTexture ); - materialAdapt.SetVector("_AdaptParams", new Vector4( - adaptLerp, - limitMinimum, - limitMaximum, - 0.0f - )); + adaptLerp = Mathf.Clamp(adaptLerp, kMinAdaptLerp, 1); + + materialAdapt.SetTexture("_CurTex", curTexture); + materialAdapt.SetVector( + "_AdaptParams", + new Vector4(adaptLerp, limitMinimum, limitMaximum, 0.0f) + ); // clear destination RT so its contents don't need to be restored Graphics.SetRenderTarget(adaptRenderTex[curAdaptIndex]); GL.Clear(false, true, Color.black); - Graphics.Blit ( + Graphics.Blit( adaptRenderTex[prevAdaptIndex], adaptRenderTex[curAdaptIndex], - materialAdapt); + materialAdapt + ); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/CreaseShading.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/CreaseShading.cs index 9b147e0ea0..c18b0ba6b0 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/CreaseShading.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/CreaseShading.cs @@ -4,10 +4,10 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Edge Detection/Crease Shading")] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Edge Detection/Crease Shading")] public class CreaseShading : PostEffectsBase - { + { public float intensity = 0.5f; public int softness = 1; public float spread = 1.0f; @@ -21,25 +21,27 @@ public class CreaseShading : PostEffectsBase public Shader creaseApplyShader = null; private Material creaseApplyMaterial = null; + public override bool CheckResources() + { + CheckSupport(true); - public override bool CheckResources () - { - CheckSupport (true); - - blurMaterial = CheckShaderAndCreateMaterial (blurShader, blurMaterial); - depthFetchMaterial = CheckShaderAndCreateMaterial (depthFetchShader, depthFetchMaterial); - creaseApplyMaterial = CheckShaderAndCreateMaterial (creaseApplyShader, creaseApplyMaterial); + blurMaterial = CheckShaderAndCreateMaterial(blurShader, blurMaterial); + depthFetchMaterial = CheckShaderAndCreateMaterial(depthFetchShader, depthFetchMaterial); + creaseApplyMaterial = CheckShaderAndCreateMaterial( + creaseApplyShader, + creaseApplyMaterial + ); if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - void OnRenderImage (RenderTexture source, RenderTexture destination) - { - if (CheckResources()==false) - { - Graphics.Blit (source, destination); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (CheckResources() == false) + { + Graphics.Blit(source, destination); return; } @@ -49,34 +51,40 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) float widthOverHeight = (1.0f * rtW) / (1.0f * rtH); float oneOverBaseSize = 1.0f / 512.0f; - RenderTexture hrTex = RenderTexture.GetTemporary (rtW, rtH, 0); - RenderTexture lrTex1 = RenderTexture.GetTemporary (rtW/2, rtH/2, 0); - - Graphics.Blit (source,hrTex, depthFetchMaterial); - Graphics.Blit (hrTex, lrTex1); - - for(int i = 0; i < softness; i++) - { - RenderTexture lrTex2 = RenderTexture.GetTemporary (rtW/2, rtH/2, 0); - blurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f)); - Graphics.Blit (lrTex1, lrTex2, blurMaterial); - RenderTexture.ReleaseTemporary (lrTex1); + RenderTexture hrTex = RenderTexture.GetTemporary(rtW, rtH, 0); + RenderTexture lrTex1 = RenderTexture.GetTemporary(rtW / 2, rtH / 2, 0); + + Graphics.Blit(source, hrTex, depthFetchMaterial); + Graphics.Blit(hrTex, lrTex1); + + for (int i = 0; i < softness; i++) + { + RenderTexture lrTex2 = RenderTexture.GetTemporary(rtW / 2, rtH / 2, 0); + blurMaterial.SetVector( + "offsets", + new Vector4(0.0f, spread * oneOverBaseSize, 0.0f, 0.0f) + ); + Graphics.Blit(lrTex1, lrTex2, blurMaterial); + RenderTexture.ReleaseTemporary(lrTex1); lrTex1 = lrTex2; - lrTex2 = RenderTexture.GetTemporary (rtW/2, rtH/2, 0); - blurMaterial.SetVector ("offsets", new Vector4 (spread * oneOverBaseSize / widthOverHeight, 0.0f, 0.0f, 0.0f)); - Graphics.Blit (lrTex1, lrTex2, blurMaterial); - RenderTexture.ReleaseTemporary (lrTex1); + lrTex2 = RenderTexture.GetTemporary(rtW / 2, rtH / 2, 0); + blurMaterial.SetVector( + "offsets", + new Vector4(spread * oneOverBaseSize / widthOverHeight, 0.0f, 0.0f, 0.0f) + ); + Graphics.Blit(lrTex1, lrTex2, blurMaterial); + RenderTexture.ReleaseTemporary(lrTex1); lrTex1 = lrTex2; } - creaseApplyMaterial.SetTexture ("_HrDepthTex", hrTex); - creaseApplyMaterial.SetTexture ("_LrDepthTex", lrTex1); - creaseApplyMaterial.SetFloat ("intensity", intensity); - Graphics.Blit (source,destination, creaseApplyMaterial); + creaseApplyMaterial.SetTexture("_HrDepthTex", hrTex); + creaseApplyMaterial.SetTexture("_LrDepthTex", lrTex1); + creaseApplyMaterial.SetFloat("intensity", intensity); + Graphics.Blit(source, destination, creaseApplyMaterial); - RenderTexture.ReleaseTemporary (hrTex); - RenderTexture.ReleaseTemporary (lrTex1); + RenderTexture.ReleaseTemporary(hrTex); + RenderTexture.ReleaseTemporary(lrTex1); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/DepthOfField.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/DepthOfField.cs index 77b2de2483..c380d0da0e 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/DepthOfField.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/DepthOfField.cs @@ -4,24 +4,26 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Camera/Depth of Field (Lens Blur, Scatter, DX11)") ] - public class DepthOfField : PostEffectsBase { - - public bool visualizeFocus = false; + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Camera/Depth of Field (Lens Blur, Scatter, DX11)")] + public class DepthOfField : PostEffectsBase + { + public bool visualizeFocus = false; public float focalLength = 10.0f; public float focalSize = 0.05f; public float aperture = 0.5f; public Transform focalTransform = null; public float maxBlurSize = 2.0f; - public bool highResolution = false; + public bool highResolution = false; - public enum BlurType { + public enum BlurType + { DiscBlur = 0, DX11 = 1, } - public enum BlurSampleCount { + public enum BlurSampleCount + { Low = 0, Medium = 1, High = 2, @@ -30,7 +32,7 @@ public enum BlurSampleCount { public BlurType blurType = BlurType.DiscBlur; public BlurSampleCount blurSampleCount = BlurSampleCount.High; - public bool nearBlur = false; + public bool nearBlur = false; public float foregroundOverlap = 1.0f; public Shader dofHdrShader; @@ -52,115 +54,156 @@ public enum BlurSampleCount { private Camera cachedCamera; - public override bool CheckResources () { - CheckSupport (true); // only requires depth, not HDR + public override bool CheckResources() + { + CheckSupport(true); // only requires depth, not HDR - dofHdrMaterial = CheckShaderAndCreateMaterial (dofHdrShader, dofHdrMaterial); - if (supportDX11 && blurType == BlurType.DX11) { - dx11bokehMaterial = CheckShaderAndCreateMaterial(dx11BokehShader, dx11bokehMaterial); - CreateComputeResources (); + dofHdrMaterial = CheckShaderAndCreateMaterial(dofHdrShader, dofHdrMaterial); + if (supportDX11 && blurType == BlurType.DX11) + { + dx11bokehMaterial = CheckShaderAndCreateMaterial( + dx11BokehShader, + dx11bokehMaterial + ); + CreateComputeResources(); } if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - void OnEnable () { + void OnEnable() + { cachedCamera = GetComponent(); cachedCamera.depthTextureMode |= DepthTextureMode.Depth; } - void OnDisable () { - ReleaseComputeResources (); + void OnDisable() + { + ReleaseComputeResources(); - if (dofHdrMaterial) DestroyImmediate(dofHdrMaterial); + if (dofHdrMaterial) + DestroyImmediate(dofHdrMaterial); dofHdrMaterial = null; - if (dx11bokehMaterial) DestroyImmediate(dx11bokehMaterial); + if (dx11bokehMaterial) + DestroyImmediate(dx11bokehMaterial); dx11bokehMaterial = null; } - void ReleaseComputeResources () { - if (cbDrawArgs != null) cbDrawArgs.Release(); + void ReleaseComputeResources() + { + if (cbDrawArgs != null) + cbDrawArgs.Release(); cbDrawArgs = null; - if (cbPoints != null) cbPoints.Release(); + if (cbPoints != null) + cbPoints.Release(); cbPoints = null; } - void CreateComputeResources () { + void CreateComputeResources() + { if (cbDrawArgs == null) { - cbDrawArgs = new ComputeBuffer (1, 16, ComputeBufferType.IndirectArguments); - var args= new int[4]; - args[0] = 0; args[1] = 1; args[2] = 0; args[3] = 0; - cbDrawArgs.SetData (args); + cbDrawArgs = new ComputeBuffer(1, 16, ComputeBufferType.IndirectArguments); + var args = new int[4]; + args[0] = 0; + args[1] = 1; + args[2] = 0; + args[3] = 0; + cbDrawArgs.SetData(args); } if (cbPoints == null) { - cbPoints = new ComputeBuffer (90000, 12+16, ComputeBufferType.Append); + cbPoints = new ComputeBuffer(90000, 12 + 16, ComputeBufferType.Append); } } - float FocalDistance01 ( float worldDist) { - return cachedCamera.WorldToViewportPoint((worldDist-cachedCamera.nearClipPlane) * cachedCamera.transform.forward + cachedCamera.transform.position).z / (cachedCamera.farClipPlane-cachedCamera.nearClipPlane); + float FocalDistance01(float worldDist) + { + return cachedCamera + .WorldToViewportPoint( + (worldDist - cachedCamera.nearClipPlane) * cachedCamera.transform.forward + + cachedCamera.transform.position + ) + .z / (cachedCamera.farClipPlane - cachedCamera.nearClipPlane); } - private void WriteCoc ( RenderTexture fromTo, bool fgDilate) { + private void WriteCoc(RenderTexture fromTo, bool fgDilate) + { dofHdrMaterial.SetTexture("_FgOverlap", null); - if (nearBlur && fgDilate) { - - int rtW = fromTo.width/2; - int rtH = fromTo.height/2; + if (nearBlur && fgDilate) + { + int rtW = fromTo.width / 2; + int rtH = fromTo.height / 2; // capture fg coc - RenderTexture temp2 = RenderTexture.GetTemporary (rtW, rtH, 0, fromTo.format); - Graphics.Blit (fromTo, temp2, dofHdrMaterial, 4); + RenderTexture temp2 = RenderTexture.GetTemporary(rtW, rtH, 0, fromTo.format); + Graphics.Blit(fromTo, temp2, dofHdrMaterial, 4); // special blur float fgAdjustment = internalBlurWidth * foregroundOverlap; - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, fgAdjustment , 0.0f, fgAdjustment)); - RenderTexture temp1 = RenderTexture.GetTemporary (rtW, rtH, 0, fromTo.format); - Graphics.Blit (temp2, temp1, dofHdrMaterial, 2); + dofHdrMaterial.SetVector( + "_Offsets", + new Vector4(0.0f, fgAdjustment, 0.0f, fgAdjustment) + ); + RenderTexture temp1 = RenderTexture.GetTemporary(rtW, rtH, 0, fromTo.format); + Graphics.Blit(temp2, temp1, dofHdrMaterial, 2); RenderTexture.ReleaseTemporary(temp2); - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (fgAdjustment, 0.0f, 0.0f, fgAdjustment)); - temp2 = RenderTexture.GetTemporary (rtW, rtH, 0, fromTo.format); - Graphics.Blit (temp1, temp2, dofHdrMaterial, 2); + dofHdrMaterial.SetVector( + "_Offsets", + new Vector4(fgAdjustment, 0.0f, 0.0f, fgAdjustment) + ); + temp2 = RenderTexture.GetTemporary(rtW, rtH, 0, fromTo.format); + Graphics.Blit(temp1, temp2, dofHdrMaterial, 2); RenderTexture.ReleaseTemporary(temp1); // "merge up" with background COC dofHdrMaterial.SetTexture("_FgOverlap", temp2); fromTo.MarkRestoreExpected(); // only touching alpha channel, RT restore expected - Graphics.Blit (fromTo, fromTo, dofHdrMaterial, 13); + Graphics.Blit(fromTo, fromTo, dofHdrMaterial, 13); RenderTexture.ReleaseTemporary(temp2); } - else { + else + { // capture full coc in alpha channel (fromTo is not read, but bound to detect screen flip) - fromTo.MarkRestoreExpected(); // only touching alpha channel, RT restore expected - Graphics.Blit (fromTo, fromTo, dofHdrMaterial, 0); + fromTo.MarkRestoreExpected(); // only touching alpha channel, RT restore expected + Graphics.Blit(fromTo, fromTo, dofHdrMaterial, 0); } } - void OnRenderImage (RenderTexture source, RenderTexture destination) { - if (!CheckResources ()) { - Graphics.Blit (source, destination); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (!CheckResources()) + { + Graphics.Blit(source, destination); return; } // clamp & prepare values so they make sense - if (aperture < 0.0f) aperture = 0.0f; - if (maxBlurSize < 0.1f) maxBlurSize = 0.1f; + if (aperture < 0.0f) + aperture = 0.0f; + if (maxBlurSize < 0.1f) + maxBlurSize = 0.1f; focalSize = Mathf.Clamp(focalSize, 0.0f, 2.0f); internalBlurWidth = Mathf.Max(maxBlurSize, 0.0f); // focal & coc calculations - focalDistance01 = (focalTransform) ? (cachedCamera.WorldToViewportPoint (focalTransform.position)).z / (cachedCamera.farClipPlane) : FocalDistance01 (focalLength); - dofHdrMaterial.SetVector("_CurveParams", new Vector4(1.0f, focalSize, (1.0f / (1.0f - aperture) - 1.0f), focalDistance01)); + focalDistance01 = + (focalTransform) + ? (cachedCamera.WorldToViewportPoint(focalTransform.position)).z + / (cachedCamera.farClipPlane) + : FocalDistance01(focalLength); + dofHdrMaterial.SetVector( + "_CurveParams", + new Vector4(1.0f, focalSize, (1.0f / (1.0f - aperture) - 1.0f), focalDistance01) + ); // possible render texture helpers @@ -172,19 +215,17 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) { if (visualizeFocus) { - // // 2. // visualize coc // // - WriteCoc (source, true); - Graphics.Blit (source, destination, dofHdrMaterial, 16); + WriteCoc(source, true); + Graphics.Blit(source, destination, dofHdrMaterial, 16); } else if ((blurType == BlurType.DX11) && dx11bokehMaterial) { - // // 1. // optimized dx11 bokeh scatter @@ -192,158 +233,266 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) { // - if (highResolution) { - + if (highResolution) + { internalBlurWidth = internalBlurWidth < 0.1f ? 0.1f : internalBlurWidth; fgBlurDist = internalBlurWidth * foregroundOverlap; - rtLow = RenderTexture.GetTemporary (source.width, source.height, 0, source.format); + rtLow = RenderTexture.GetTemporary( + source.width, + source.height, + 0, + source.format + ); - var dest2= RenderTexture.GetTemporary (source.width, source.height, 0, source.format); + var dest2 = RenderTexture.GetTemporary( + source.width, + source.height, + 0, + source.format + ); // capture COC - WriteCoc (source, false); + WriteCoc(source, false); // blur a bit so we can do a frequency check - rtSuperLow1 = RenderTexture.GetTemporary(source.width>>1, source.height>>1, 0, source.format); - rtSuperLow2 = RenderTexture.GetTemporary(source.width>>1, source.height>>1, 0, source.format); + rtSuperLow1 = RenderTexture.GetTemporary( + source.width >> 1, + source.height >> 1, + 0, + source.format + ); + rtSuperLow2 = RenderTexture.GetTemporary( + source.width >> 1, + source.height >> 1, + 0, + source.format + ); Graphics.Blit(source, rtSuperLow1, dofHdrMaterial, 15); - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, 1.5f , 0.0f, 1.5f)); - Graphics.Blit (rtSuperLow1, rtSuperLow2, dofHdrMaterial, 19); - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (1.5f, 0.0f, 0.0f, 1.5f)); - Graphics.Blit (rtSuperLow2, rtSuperLow1, dofHdrMaterial, 19); + dofHdrMaterial.SetVector("_Offsets", new Vector4(0.0f, 1.5f, 0.0f, 1.5f)); + Graphics.Blit(rtSuperLow1, rtSuperLow2, dofHdrMaterial, 19); + dofHdrMaterial.SetVector("_Offsets", new Vector4(1.5f, 0.0f, 0.0f, 1.5f)); + Graphics.Blit(rtSuperLow2, rtSuperLow1, dofHdrMaterial, 19); // capture fg coc if (nearBlur) - Graphics.Blit (source, rtSuperLow2, dofHdrMaterial, 4); - - dx11bokehMaterial.SetTexture ("_BlurredColor", rtSuperLow1); - dx11bokehMaterial.SetFloat ("_SpawnHeuristic", dx11SpawnHeuristic); - dx11bokehMaterial.SetVector ("_BokehParams", new Vector4(dx11BokehScale, dx11BokehIntensity, Mathf.Clamp(dx11BokehThreshold, 0.005f, 4.0f), internalBlurWidth)); - dx11bokehMaterial.SetTexture ("_FgCocMask", nearBlur ? rtSuperLow2 : null); + Graphics.Blit(source, rtSuperLow2, dofHdrMaterial, 4); + + dx11bokehMaterial.SetTexture("_BlurredColor", rtSuperLow1); + dx11bokehMaterial.SetFloat("_SpawnHeuristic", dx11SpawnHeuristic); + dx11bokehMaterial.SetVector( + "_BokehParams", + new Vector4( + dx11BokehScale, + dx11BokehIntensity, + Mathf.Clamp(dx11BokehThreshold, 0.005f, 4.0f), + internalBlurWidth + ) + ); + dx11bokehMaterial.SetTexture("_FgCocMask", nearBlur ? rtSuperLow2 : null); // collect bokeh candidates and replace with a darker pixel - Graphics.SetRandomWriteTarget (1, cbPoints); - Graphics.Blit (source, rtLow, dx11bokehMaterial, 0); - Graphics.ClearRandomWriteTargets (); + Graphics.SetRandomWriteTarget(1, cbPoints); + Graphics.Blit(source, rtLow, dx11bokehMaterial, 0); + Graphics.ClearRandomWriteTargets(); // fg coc blur happens here (after collect!) - if (nearBlur) { - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, fgBlurDist , 0.0f, fgBlurDist)); - Graphics.Blit (rtSuperLow2, rtSuperLow1, dofHdrMaterial, 2); - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (fgBlurDist, 0.0f, 0.0f, fgBlurDist)); - Graphics.Blit (rtSuperLow1, rtSuperLow2, dofHdrMaterial, 2); + if (nearBlur) + { + dofHdrMaterial.SetVector( + "_Offsets", + new Vector4(0.0f, fgBlurDist, 0.0f, fgBlurDist) + ); + Graphics.Blit(rtSuperLow2, rtSuperLow1, dofHdrMaterial, 2); + dofHdrMaterial.SetVector( + "_Offsets", + new Vector4(fgBlurDist, 0.0f, 0.0f, fgBlurDist) + ); + Graphics.Blit(rtSuperLow1, rtSuperLow2, dofHdrMaterial, 2); // merge fg coc with bg coc - Graphics.Blit (rtSuperLow2, rtLow, dofHdrMaterial, 3); + Graphics.Blit(rtSuperLow2, rtLow, dofHdrMaterial, 3); } // NEW: LAY OUT ALPHA on destination target so we get nicer outlines for the high rez version - Graphics.Blit (rtLow, dest2, dofHdrMaterial, 20); + Graphics.Blit(rtLow, dest2, dofHdrMaterial, 20); // box blur (easier to merge with bokeh buffer) - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (internalBlurWidth, 0.0f , 0.0f, internalBlurWidth)); - Graphics.Blit (rtLow, source, dofHdrMaterial, 5); - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, internalBlurWidth, 0.0f, internalBlurWidth)); - Graphics.Blit (source, dest2, dofHdrMaterial, 21); + dofHdrMaterial.SetVector( + "_Offsets", + new Vector4(internalBlurWidth, 0.0f, 0.0f, internalBlurWidth) + ); + Graphics.Blit(rtLow, source, dofHdrMaterial, 5); + dofHdrMaterial.SetVector( + "_Offsets", + new Vector4(0.0f, internalBlurWidth, 0.0f, internalBlurWidth) + ); + Graphics.Blit(source, dest2, dofHdrMaterial, 21); // apply bokeh candidates - Graphics.SetRenderTarget (dest2); - ComputeBuffer.CopyCount (cbPoints, cbDrawArgs, 0); - dx11bokehMaterial.SetBuffer ("pointBuffer", cbPoints); - dx11bokehMaterial.SetTexture ("_MainTex", dx11BokehTexture); - dx11bokehMaterial.SetVector ("_Screen", new Vector3(1.0f/(1.0f*source.width), 1.0f/(1.0f*source.height), internalBlurWidth)); - dx11bokehMaterial.SetPass (2); - - Graphics.DrawProceduralIndirectNow (MeshTopology.Points, cbDrawArgs, 0); - - Graphics.Blit (dest2, destination); // hackaround for DX11 high resolution flipfun (OPTIMIZEME) + Graphics.SetRenderTarget(dest2); + ComputeBuffer.CopyCount(cbPoints, cbDrawArgs, 0); + dx11bokehMaterial.SetBuffer("pointBuffer", cbPoints); + dx11bokehMaterial.SetTexture("_MainTex", dx11BokehTexture); + dx11bokehMaterial.SetVector( + "_Screen", + new Vector3( + 1.0f / (1.0f * source.width), + 1.0f / (1.0f * source.height), + internalBlurWidth + ) + ); + dx11bokehMaterial.SetPass(2); + + Graphics.DrawProceduralIndirectNow(MeshTopology.Points, cbDrawArgs, 0); + + Graphics.Blit(dest2, destination); // hackaround for DX11 high resolution flipfun (OPTIMIZEME) RenderTexture.ReleaseTemporary(dest2); RenderTexture.ReleaseTemporary(rtSuperLow1); RenderTexture.ReleaseTemporary(rtSuperLow2); } - else { - rtLow = RenderTexture.GetTemporary (source.width>>1, source.height>>1, 0, source.format); - rtLow2 = RenderTexture.GetTemporary (source.width>>1, source.height>>1, 0, source.format); + else + { + rtLow = RenderTexture.GetTemporary( + source.width >> 1, + source.height >> 1, + 0, + source.format + ); + rtLow2 = RenderTexture.GetTemporary( + source.width >> 1, + source.height >> 1, + 0, + source.format + ); fgBlurDist = internalBlurWidth * foregroundOverlap; // capture COC & color in low resolution - WriteCoc (source, false); + WriteCoc(source, false); source.filterMode = FilterMode.Bilinear; - Graphics.Blit (source, rtLow, dofHdrMaterial, 6); + Graphics.Blit(source, rtLow, dofHdrMaterial, 6); // blur a bit so we can do a frequency check - rtSuperLow1 = RenderTexture.GetTemporary(rtLow.width>>1, rtLow.height>>1, 0, rtLow.format); - rtSuperLow2 = RenderTexture.GetTemporary(rtLow.width>>1, rtLow.height>>1, 0, rtLow.format); + rtSuperLow1 = RenderTexture.GetTemporary( + rtLow.width >> 1, + rtLow.height >> 1, + 0, + rtLow.format + ); + rtSuperLow2 = RenderTexture.GetTemporary( + rtLow.width >> 1, + rtLow.height >> 1, + 0, + rtLow.format + ); Graphics.Blit(rtLow, rtSuperLow1, dofHdrMaterial, 15); - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, 1.5f , 0.0f, 1.5f)); - Graphics.Blit (rtSuperLow1, rtSuperLow2, dofHdrMaterial, 19); - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (1.5f, 0.0f, 0.0f, 1.5f)); - Graphics.Blit (rtSuperLow2, rtSuperLow1, dofHdrMaterial, 19); + dofHdrMaterial.SetVector("_Offsets", new Vector4(0.0f, 1.5f, 0.0f, 1.5f)); + Graphics.Blit(rtSuperLow1, rtSuperLow2, dofHdrMaterial, 19); + dofHdrMaterial.SetVector("_Offsets", new Vector4(1.5f, 0.0f, 0.0f, 1.5f)); + Graphics.Blit(rtSuperLow2, rtSuperLow1, dofHdrMaterial, 19); RenderTexture rtLow3 = null; - if (nearBlur) { + if (nearBlur) + { // capture fg coc - rtLow3 = RenderTexture.GetTemporary (source.width>>1, source.height>>1, 0, source.format); - Graphics.Blit (source, rtLow3, dofHdrMaterial, 4); + rtLow3 = RenderTexture.GetTemporary( + source.width >> 1, + source.height >> 1, + 0, + source.format + ); + Graphics.Blit(source, rtLow3, dofHdrMaterial, 4); } - dx11bokehMaterial.SetTexture ("_BlurredColor", rtSuperLow1); - dx11bokehMaterial.SetFloat ("_SpawnHeuristic", dx11SpawnHeuristic); - dx11bokehMaterial.SetVector ("_BokehParams", new Vector4(dx11BokehScale, dx11BokehIntensity, Mathf.Clamp(dx11BokehThreshold, 0.005f, 4.0f), internalBlurWidth)); - dx11bokehMaterial.SetTexture ("_FgCocMask", rtLow3); + dx11bokehMaterial.SetTexture("_BlurredColor", rtSuperLow1); + dx11bokehMaterial.SetFloat("_SpawnHeuristic", dx11SpawnHeuristic); + dx11bokehMaterial.SetVector( + "_BokehParams", + new Vector4( + dx11BokehScale, + dx11BokehIntensity, + Mathf.Clamp(dx11BokehThreshold, 0.005f, 4.0f), + internalBlurWidth + ) + ); + dx11bokehMaterial.SetTexture("_FgCocMask", rtLow3); // collect bokeh candidates and replace with a darker pixel - Graphics.SetRandomWriteTarget (1, cbPoints); - Graphics.Blit (rtLow, rtLow2, dx11bokehMaterial, 0); - Graphics.ClearRandomWriteTargets (); + Graphics.SetRandomWriteTarget(1, cbPoints); + Graphics.Blit(rtLow, rtLow2, dx11bokehMaterial, 0); + Graphics.ClearRandomWriteTargets(); RenderTexture.ReleaseTemporary(rtSuperLow1); RenderTexture.ReleaseTemporary(rtSuperLow2); // fg coc blur happens here (after collect!) - if (nearBlur) { - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, fgBlurDist , 0.0f, fgBlurDist)); - Graphics.Blit (rtLow3, rtLow, dofHdrMaterial, 2); - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (fgBlurDist, 0.0f, 0.0f, fgBlurDist)); - Graphics.Blit (rtLow, rtLow3, dofHdrMaterial, 2); + if (nearBlur) + { + dofHdrMaterial.SetVector( + "_Offsets", + new Vector4(0.0f, fgBlurDist, 0.0f, fgBlurDist) + ); + Graphics.Blit(rtLow3, rtLow, dofHdrMaterial, 2); + dofHdrMaterial.SetVector( + "_Offsets", + new Vector4(fgBlurDist, 0.0f, 0.0f, fgBlurDist) + ); + Graphics.Blit(rtLow, rtLow3, dofHdrMaterial, 2); // merge fg coc with bg coc - Graphics.Blit (rtLow3, rtLow2, dofHdrMaterial, 3); + Graphics.Blit(rtLow3, rtLow2, dofHdrMaterial, 3); } // box blur (easier to merge with bokeh buffer) - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (internalBlurWidth, 0.0f , 0.0f, internalBlurWidth)); - Graphics.Blit (rtLow2, rtLow, dofHdrMaterial, 5); - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, internalBlurWidth, 0.0f, internalBlurWidth)); - Graphics.Blit (rtLow, rtLow2, dofHdrMaterial, 5); + dofHdrMaterial.SetVector( + "_Offsets", + new Vector4(internalBlurWidth, 0.0f, 0.0f, internalBlurWidth) + ); + Graphics.Blit(rtLow2, rtLow, dofHdrMaterial, 5); + dofHdrMaterial.SetVector( + "_Offsets", + new Vector4(0.0f, internalBlurWidth, 0.0f, internalBlurWidth) + ); + Graphics.Blit(rtLow, rtLow2, dofHdrMaterial, 5); // apply bokeh candidates - Graphics.SetRenderTarget (rtLow2); - ComputeBuffer.CopyCount (cbPoints, cbDrawArgs, 0); - dx11bokehMaterial.SetBuffer ("pointBuffer", cbPoints); - dx11bokehMaterial.SetTexture ("_MainTex", dx11BokehTexture); - dx11bokehMaterial.SetVector ("_Screen", new Vector3(1.0f/(1.0f*rtLow2.width), 1.0f/(1.0f*rtLow2.height), internalBlurWidth)); - dx11bokehMaterial.SetPass (1); - Graphics.DrawProceduralIndirectNow (MeshTopology.Points, cbDrawArgs, 0); + Graphics.SetRenderTarget(rtLow2); + ComputeBuffer.CopyCount(cbPoints, cbDrawArgs, 0); + dx11bokehMaterial.SetBuffer("pointBuffer", cbPoints); + dx11bokehMaterial.SetTexture("_MainTex", dx11BokehTexture); + dx11bokehMaterial.SetVector( + "_Screen", + new Vector3( + 1.0f / (1.0f * rtLow2.width), + 1.0f / (1.0f * rtLow2.height), + internalBlurWidth + ) + ); + dx11bokehMaterial.SetPass(1); + Graphics.DrawProceduralIndirectNow(MeshTopology.Points, cbDrawArgs, 0); // upsample & combine - dofHdrMaterial.SetTexture ("_LowRez", rtLow2); - dofHdrMaterial.SetTexture ("_FgOverlap", rtLow3); - dofHdrMaterial.SetVector ("_Offsets", ((1.0f*source.width)/(1.0f*rtLow2.width)) * internalBlurWidth * Vector4.one); - Graphics.Blit (source, destination, dofHdrMaterial, 9); - - if (rtLow3) RenderTexture.ReleaseTemporary(rtLow3); + dofHdrMaterial.SetTexture("_LowRez", rtLow2); + dofHdrMaterial.SetTexture("_FgOverlap", rtLow3); + dofHdrMaterial.SetVector( + "_Offsets", + ((1.0f * source.width) / (1.0f * rtLow2.width)) + * internalBlurWidth + * Vector4.one + ); + Graphics.Blit(source, destination, dofHdrMaterial, 9); + + if (rtLow3) + RenderTexture.ReleaseTemporary(rtLow3); } } else { - // // 2. // poisson disc style blur in low resolution @@ -352,36 +501,73 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) { source.filterMode = FilterMode.Bilinear; - if (highResolution) internalBlurWidth *= 2.0f; - - WriteCoc (source, true); - - rtLow = RenderTexture.GetTemporary (source.width >> 1, source.height >> 1, 0, source.format); - rtLow2 = RenderTexture.GetTemporary (source.width >> 1, source.height >> 1, 0, source.format); - - int blurPass = (blurSampleCount == BlurSampleCount.High || blurSampleCount == BlurSampleCount.Medium) ? 17 : 11; - - if (highResolution) { - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, internalBlurWidth, 0.025f, internalBlurWidth)); - Graphics.Blit (source, destination, dofHdrMaterial, blurPass); + if (highResolution) + internalBlurWidth *= 2.0f; + + WriteCoc(source, true); + + rtLow = RenderTexture.GetTemporary( + source.width >> 1, + source.height >> 1, + 0, + source.format + ); + rtLow2 = RenderTexture.GetTemporary( + source.width >> 1, + source.height >> 1, + 0, + source.format + ); + + int blurPass = + ( + blurSampleCount == BlurSampleCount.High + || blurSampleCount == BlurSampleCount.Medium + ) + ? 17 + : 11; + + if (highResolution) + { + dofHdrMaterial.SetVector( + "_Offsets", + new Vector4(0.0f, internalBlurWidth, 0.025f, internalBlurWidth) + ); + Graphics.Blit(source, destination, dofHdrMaterial, blurPass); } - else { - dofHdrMaterial.SetVector ("_Offsets", new Vector4 (0.0f, internalBlurWidth, 0.1f, internalBlurWidth)); + else + { + dofHdrMaterial.SetVector( + "_Offsets", + new Vector4(0.0f, internalBlurWidth, 0.1f, internalBlurWidth) + ); // blur - Graphics.Blit (source, rtLow, dofHdrMaterial, 6); - Graphics.Blit (rtLow, rtLow2, dofHdrMaterial, blurPass); + Graphics.Blit(source, rtLow, dofHdrMaterial, 6); + Graphics.Blit(rtLow, rtLow2, dofHdrMaterial, blurPass); // cheaper blur in high resolution, upsample and combine dofHdrMaterial.SetTexture("_LowRez", rtLow2); dofHdrMaterial.SetTexture("_FgOverlap", null); - dofHdrMaterial.SetVector ("_Offsets", Vector4.one * ((1.0f*source.width)/(1.0f*rtLow2.width)) * internalBlurWidth); - Graphics.Blit (source, destination, dofHdrMaterial, blurSampleCount == BlurSampleCount.High ? 18 : 12); + dofHdrMaterial.SetVector( + "_Offsets", + Vector4.one + * ((1.0f * source.width) / (1.0f * rtLow2.width)) + * internalBlurWidth + ); + Graphics.Blit( + source, + destination, + dofHdrMaterial, + blurSampleCount == BlurSampleCount.High ? 18 : 12 + ); } } - if (rtLow) RenderTexture.ReleaseTemporary(rtLow); - if (rtLow2) RenderTexture.ReleaseTemporary(rtLow2); + if (rtLow) + RenderTexture.ReleaseTemporary(rtLow); + if (rtLow2) + RenderTexture.ReleaseTemporary(rtLow2); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/DepthOfFieldDeprecated.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/DepthOfFieldDeprecated.cs index 915bfba378..fc18a813be 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/DepthOfFieldDeprecated.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/DepthOfFieldDeprecated.cs @@ -4,8 +4,8 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Camera/Depth of Field (deprecated)") ] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Camera/Depth of Field (deprecated)")] public class DepthOfFieldDeprecated : PostEffectsBase { public enum Dof34QualitySetting @@ -35,12 +35,12 @@ public enum BokehDestination BackgroundAndForeground = 0x3, } - static private int SMOOTH_DOWNSAMPLE_PASS = 6; - static private float BOKEH_EXTRA_BLUR = 2.0f; + private static int SMOOTH_DOWNSAMPLE_PASS = 6; + private static float BOKEH_EXTRA_BLUR = 2.0f; public Dof34QualitySetting quality = Dof34QualitySetting.OnlyBackground; - public DofResolution resolution = DofResolution.Low; - public bool simpleTweakMode = true; + public DofResolution resolution = DofResolution.Low; + public bool simpleTweakMode = true; public float focalPoint = 1.0f; public float smoothness = 0.5f; @@ -67,14 +67,14 @@ public enum BokehDestination public Shader dofShader; private Material dofMaterial = null; - public bool visualize = false; + public bool visualize = false; public BokehDestination bokehDestination = BokehDestination.Background; private float widthOverHeight = 1.25f; private float oneOverBaseSize = 1.0f / 512.0f; - public bool bokeh = false; - public bool bokehSupport = true; + public bool bokeh = false; + public bool bokehSupport = true; public Shader bokehShader; public Texture2D bokehTexture; public float bokehScale = 2.4f; @@ -86,45 +86,55 @@ public enum BokehDestination private Camera _camera; - void CreateMaterials () { - dofBlurMaterial = CheckShaderAndCreateMaterial (dofBlurShader, dofBlurMaterial); - dofMaterial = CheckShaderAndCreateMaterial (dofShader,dofMaterial); + void CreateMaterials() + { + dofBlurMaterial = CheckShaderAndCreateMaterial(dofBlurShader, dofBlurMaterial); + dofMaterial = CheckShaderAndCreateMaterial(dofShader, dofMaterial); bokehSupport = bokehShader.isSupported; if (bokeh && bokehSupport && bokehShader) - bokehMaterial = CheckShaderAndCreateMaterial (bokehShader, bokehMaterial); + bokehMaterial = CheckShaderAndCreateMaterial(bokehShader, bokehMaterial); } + public override bool CheckResources() + { + CheckSupport(true); - public override bool CheckResources () { - CheckSupport (true); - - dofBlurMaterial = CheckShaderAndCreateMaterial (dofBlurShader, dofBlurMaterial); - dofMaterial = CheckShaderAndCreateMaterial (dofShader,dofMaterial); + dofBlurMaterial = CheckShaderAndCreateMaterial(dofBlurShader, dofBlurMaterial); + dofMaterial = CheckShaderAndCreateMaterial(dofShader, dofMaterial); bokehSupport = bokehShader.isSupported; if (bokeh && bokehSupport && bokehShader) - bokehMaterial = CheckShaderAndCreateMaterial (bokehShader, bokehMaterial); + bokehMaterial = CheckShaderAndCreateMaterial(bokehShader, bokehMaterial); if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - void OnDisable () { - Quads.Cleanup (); + void OnDisable() + { + Quads.Cleanup(); } - void OnEnable () { + void OnEnable() + { _camera = GetComponent(); _camera.depthTextureMode |= DepthTextureMode.Depth; } - float FocalDistance01 ( float worldDist) { - return _camera.WorldToViewportPoint((worldDist-_camera.nearClipPlane) * _camera.transform.forward + _camera.transform.position).z / (_camera.farClipPlane-_camera.nearClipPlane); + float FocalDistance01(float worldDist) + { + return _camera + .WorldToViewportPoint( + (worldDist - _camera.nearClipPlane) * _camera.transform.forward + + _camera.transform.position + ) + .z / (_camera.farClipPlane - _camera.nearClipPlane); } - int GetDividerBasedOnQuality () { + int GetDividerBasedOnQuality() + { int divider = 1; if (resolution == DofResolution.Medium) divider = 2; @@ -133,7 +143,8 @@ int GetDividerBasedOnQuality () { return divider; } - int GetLowResolutionDividerBasedOnQuality ( int baseDivider) { + int GetLowResolutionDividerBasedOnQuality(int baseDivider) + { int lowTexDivider = baseDivider; if (resolution == DofResolution.High) lowTexDivider *= 2; @@ -149,9 +160,11 @@ int GetLowResolutionDividerBasedOnQuality ( int baseDivider) { private RenderTexture bokehSource = null; private RenderTexture bokehSource2 = null; - void OnRenderImage (RenderTexture source, RenderTexture destination) { - if (CheckResources()==false) { - Graphics.Blit (source, destination); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (CheckResources() == false) + { + Graphics.Blit(source, destination); return; } @@ -163,203 +176,339 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) { bokeh = bokeh && bokehSupport; float bokehBlurAmplifier = bokeh ? BOKEH_EXTRA_BLUR : 1.0f; - bool blurForeground = quality > Dof34QualitySetting.OnlyBackground; - float focal01Size = focalSize / (_camera.farClipPlane - _camera.nearClipPlane);; + bool blurForeground = quality > Dof34QualitySetting.OnlyBackground; + float focal01Size = focalSize / (_camera.farClipPlane - _camera.nearClipPlane); + ; - if (simpleTweakMode) { - focalDistance01 = objectFocus ? (_camera.WorldToViewportPoint (objectFocus.position)).z / (_camera.farClipPlane) : FocalDistance01 (focalPoint); + if (simpleTweakMode) + { + focalDistance01 = objectFocus + ? (_camera.WorldToViewportPoint(objectFocus.position)).z + / (_camera.farClipPlane) + : FocalDistance01(focalPoint); focalStartCurve = focalDistance01 * smoothness; focalEndCurve = focalStartCurve; - blurForeground = blurForeground && (focalPoint > (_camera.nearClipPlane + Mathf.Epsilon)); + blurForeground = + blurForeground && (focalPoint > (_camera.nearClipPlane + Mathf.Epsilon)); } - else { - if (objectFocus) { - var vpPoint= _camera.WorldToViewportPoint (objectFocus.position); + else + { + if (objectFocus) + { + var vpPoint = _camera.WorldToViewportPoint(objectFocus.position); vpPoint.z = (vpPoint.z) / (_camera.farClipPlane); focalDistance01 = vpPoint.z; } else - focalDistance01 = FocalDistance01 (focalZDistance); + focalDistance01 = FocalDistance01(focalZDistance); focalStartCurve = focalZStartCurve; focalEndCurve = focalZEndCurve; - blurForeground = blurForeground && (focalPoint > (_camera.nearClipPlane + Mathf.Epsilon)); + blurForeground = + blurForeground && (focalPoint > (_camera.nearClipPlane + Mathf.Epsilon)); } widthOverHeight = (1.0f * source.width) / (1.0f * source.height); oneOverBaseSize = 1.0f / 512.0f; - dofMaterial.SetFloat ("_ForegroundBlurExtrude", foregroundBlurExtrude); - dofMaterial.SetVector ("_CurveParams", new Vector4 (simpleTweakMode ? 1.0f / focalStartCurve : focalStartCurve, simpleTweakMode ? 1.0f / focalEndCurve : focalEndCurve, focal01Size * 0.5f, focalDistance01)); - dofMaterial.SetVector ("_InvRenderTargetSize", new Vector4 (1.0f / (1.0f * source.width), 1.0f / (1.0f * source.height),0.0f,0.0f)); - - int divider = GetDividerBasedOnQuality (); - int lowTexDivider = GetLowResolutionDividerBasedOnQuality (divider); - - AllocateTextures (blurForeground, source, divider, lowTexDivider); + dofMaterial.SetFloat("_ForegroundBlurExtrude", foregroundBlurExtrude); + dofMaterial.SetVector( + "_CurveParams", + new Vector4( + simpleTweakMode ? 1.0f / focalStartCurve : focalStartCurve, + simpleTweakMode ? 1.0f / focalEndCurve : focalEndCurve, + focal01Size * 0.5f, + focalDistance01 + ) + ); + dofMaterial.SetVector( + "_InvRenderTargetSize", + new Vector4(1.0f / (1.0f * source.width), 1.0f / (1.0f * source.height), 0.0f, 0.0f) + ); + + int divider = GetDividerBasedOnQuality(); + int lowTexDivider = GetLowResolutionDividerBasedOnQuality(divider); + + AllocateTextures(blurForeground, source, divider, lowTexDivider); // WRITE COC to alpha channel // source is only being bound to detect y texcoord flip - Graphics.Blit (source, source, dofMaterial, 3); + Graphics.Blit(source, source, dofMaterial, 3); // better DOWNSAMPLE (could actually be weighted for higher quality) - Downsample (source, mediumRezWorkTexture); + Downsample(source, mediumRezWorkTexture); // BLUR A LITTLE first, which has two purposes // 1.) reduce jitter, noise, aliasing // 2.) produce the little-blur buffer used in composition later - Blur (mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 4, maxBlurSpread); + Blur(mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 4, maxBlurSpread); if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0)) { - dofMaterial.SetVector ("_Threshhold", new Vector4(bokehThresholdContrast, bokehThresholdLuminance, 0.95f, 0.0f)); + dofMaterial.SetVector( + "_Threshhold", + new Vector4(bokehThresholdContrast, bokehThresholdLuminance, 0.95f, 0.0f) + ); // add and mark the parts that should end up as bokeh shapes - Graphics.Blit (mediumRezWorkTexture, bokehSource2, dofMaterial, 11); + Graphics.Blit(mediumRezWorkTexture, bokehSource2, dofMaterial, 11); // remove those parts (maybe even a little tittle bittle more) from the regurlarly blurred buffer // Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture, dofMaterial, 10); - Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture);//, dofMaterial, 10); + Graphics.Blit(mediumRezWorkTexture, lowRezWorkTexture); //, dofMaterial, 10); // maybe you want to reblur the small blur ... but not really needed. // Blur (mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 4, maxBlurSpread); // bigger BLUR - Blur (lowRezWorkTexture, lowRezWorkTexture, bluriness, 0, maxBlurSpread * bokehBlurAmplifier); + Blur( + lowRezWorkTexture, + lowRezWorkTexture, + bluriness, + 0, + maxBlurSpread * bokehBlurAmplifier + ); } - else { + else + { // bigger BLUR - Downsample (mediumRezWorkTexture, lowRezWorkTexture); - Blur (lowRezWorkTexture, lowRezWorkTexture, bluriness, 0, maxBlurSpread); + Downsample(mediumRezWorkTexture, lowRezWorkTexture); + Blur(lowRezWorkTexture, lowRezWorkTexture, bluriness, 0, maxBlurSpread); } - dofBlurMaterial.SetTexture ("_TapLow", lowRezWorkTexture); - dofBlurMaterial.SetTexture ("_TapMedium", mediumRezWorkTexture); - Graphics.Blit (null, finalDefocus, dofBlurMaterial, 3); + dofBlurMaterial.SetTexture("_TapLow", lowRezWorkTexture); + dofBlurMaterial.SetTexture("_TapMedium", mediumRezWorkTexture); + Graphics.Blit(null, finalDefocus, dofBlurMaterial, 3); // we are only adding bokeh now if the background is the only part we have to deal with if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0)) - AddBokeh (bokehSource2, bokehSource, finalDefocus); + AddBokeh(bokehSource2, bokehSource, finalDefocus); - dofMaterial.SetTexture ("_TapLowBackground", finalDefocus); - dofMaterial.SetTexture ("_TapMedium", mediumRezWorkTexture); // needed for debugging/visualization + dofMaterial.SetTexture("_TapLowBackground", finalDefocus); + dofMaterial.SetTexture("_TapMedium", mediumRezWorkTexture); // needed for debugging/visualization // FINAL DEFOCUS (background) - Graphics.Blit (source, blurForeground ? foregroundTexture : destination, dofMaterial, visualize ? 2 : 0); + Graphics.Blit( + source, + blurForeground ? foregroundTexture : destination, + dofMaterial, + visualize ? 2 : 0 + ); // FINAL DEFOCUS (foreground) - if (blurForeground) { + if (blurForeground) + { // WRITE COC to alpha channel - Graphics.Blit (foregroundTexture, source, dofMaterial, 5); + Graphics.Blit(foregroundTexture, source, dofMaterial, 5); // DOWNSAMPLE (unweighted) - Downsample (source, mediumRezWorkTexture); + Downsample(source, mediumRezWorkTexture); // BLUR A LITTLE first, which has two purposes // 1.) reduce jitter, noise, aliasing // 2.) produce the little-blur buffer used in composition later - BlurFg (mediumRezWorkTexture, mediumRezWorkTexture, DofBlurriness.Low, 2, maxBlurSpread); + BlurFg( + mediumRezWorkTexture, + mediumRezWorkTexture, + DofBlurriness.Low, + 2, + maxBlurSpread + ); if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0)) { - dofMaterial.SetVector ("_Threshhold", new Vector4(bokehThresholdContrast * 0.5f, bokehThresholdLuminance, 0.0f, 0.0f)); + dofMaterial.SetVector( + "_Threshhold", + new Vector4( + bokehThresholdContrast * 0.5f, + bokehThresholdLuminance, + 0.0f, + 0.0f + ) + ); // add and mark the parts that should end up as bokeh shapes - Graphics.Blit (mediumRezWorkTexture, bokehSource2, dofMaterial, 11); + Graphics.Blit(mediumRezWorkTexture, bokehSource2, dofMaterial, 11); // remove the parts (maybe even a little tittle bittle more) that will end up in bokeh space // Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture, dofMaterial, 10); - Graphics.Blit (mediumRezWorkTexture, lowRezWorkTexture);//, dofMaterial, 10); + Graphics.Blit(mediumRezWorkTexture, lowRezWorkTexture); //, dofMaterial, 10); // big BLUR - BlurFg (lowRezWorkTexture, lowRezWorkTexture, bluriness, 1, maxBlurSpread * bokehBlurAmplifier); + BlurFg( + lowRezWorkTexture, + lowRezWorkTexture, + bluriness, + 1, + maxBlurSpread * bokehBlurAmplifier + ); } - else { + else + { // big BLUR - BlurFg (mediumRezWorkTexture, lowRezWorkTexture, bluriness, 1, maxBlurSpread); + BlurFg(mediumRezWorkTexture, lowRezWorkTexture, bluriness, 1, maxBlurSpread); } // simple upsample once - Graphics.Blit (lowRezWorkTexture, finalDefocus); + Graphics.Blit(lowRezWorkTexture, finalDefocus); - dofMaterial.SetTexture ("_TapLowForeground", finalDefocus); - Graphics.Blit (source, destination, dofMaterial, visualize ? 1 : 4); + dofMaterial.SetTexture("_TapLowForeground", finalDefocus); + Graphics.Blit(source, destination, dofMaterial, visualize ? 1 : 4); if ((bokeh) && ((BokehDestination.Foreground & bokehDestination) != 0)) - AddBokeh (bokehSource2, bokehSource, destination); + AddBokeh(bokehSource2, bokehSource, destination); } - ReleaseTextures (); + ReleaseTextures(); } - void Blur ( RenderTexture from, RenderTexture to, DofBlurriness iterations, int blurPass, float spread) { - RenderTexture tmp = RenderTexture.GetTemporary (to.width, to.height); - if ((int)iterations > 1) { - BlurHex (from, to, blurPass, spread, tmp); - if ((int)iterations > 2) { - dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f)); - Graphics.Blit (to, tmp, dofBlurMaterial, blurPass); - dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); - Graphics.Blit (tmp, to, dofBlurMaterial, blurPass); + void Blur( + RenderTexture from, + RenderTexture to, + DofBlurriness iterations, + int blurPass, + float spread + ) + { + RenderTexture tmp = RenderTexture.GetTemporary(to.width, to.height); + if ((int)iterations > 1) + { + BlurHex(from, to, blurPass, spread, tmp); + if ((int)iterations > 2) + { + dofBlurMaterial.SetVector( + "offsets", + new Vector4(0.0f, spread * oneOverBaseSize, 0.0f, 0.0f) + ); + Graphics.Blit(to, tmp, dofBlurMaterial, blurPass); + dofBlurMaterial.SetVector( + "offsets", + new Vector4(spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f) + ); + Graphics.Blit(tmp, to, dofBlurMaterial, blurPass); } } - else { - dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f)); - Graphics.Blit (from, tmp, dofBlurMaterial, blurPass); - dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); - Graphics.Blit (tmp, to, dofBlurMaterial, blurPass); + else + { + dofBlurMaterial.SetVector( + "offsets", + new Vector4(0.0f, spread * oneOverBaseSize, 0.0f, 0.0f) + ); + Graphics.Blit(from, tmp, dofBlurMaterial, blurPass); + dofBlurMaterial.SetVector( + "offsets", + new Vector4(spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f) + ); + Graphics.Blit(tmp, to, dofBlurMaterial, blurPass); } - RenderTexture.ReleaseTemporary (tmp); + RenderTexture.ReleaseTemporary(tmp); } - void BlurFg ( RenderTexture from, RenderTexture to, DofBlurriness iterations, int blurPass, float spread) { + void BlurFg( + RenderTexture from, + RenderTexture to, + DofBlurriness iterations, + int blurPass, + float spread + ) + { // we want a nice, big coc, hence we need to tap once from this (higher resolution) texture - dofBlurMaterial.SetTexture ("_TapHigh", from); - - RenderTexture tmp = RenderTexture.GetTemporary (to.width, to.height); - if ((int)iterations > 1) { - BlurHex (from, to, blurPass, spread, tmp); - if ((int)iterations > 2) { - dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f)); - Graphics.Blit (to, tmp, dofBlurMaterial, blurPass); - dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); - Graphics.Blit (tmp, to, dofBlurMaterial, blurPass); + dofBlurMaterial.SetTexture("_TapHigh", from); + + RenderTexture tmp = RenderTexture.GetTemporary(to.width, to.height); + if ((int)iterations > 1) + { + BlurHex(from, to, blurPass, spread, tmp); + if ((int)iterations > 2) + { + dofBlurMaterial.SetVector( + "offsets", + new Vector4(0.0f, spread * oneOverBaseSize, 0.0f, 0.0f) + ); + Graphics.Blit(to, tmp, dofBlurMaterial, blurPass); + dofBlurMaterial.SetVector( + "offsets", + new Vector4(spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f) + ); + Graphics.Blit(tmp, to, dofBlurMaterial, blurPass); } } - else { - dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f)); - Graphics.Blit (from, tmp, dofBlurMaterial, blurPass); - dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); - Graphics.Blit (tmp, to, dofBlurMaterial, blurPass); + else + { + dofBlurMaterial.SetVector( + "offsets", + new Vector4(0.0f, spread * oneOverBaseSize, 0.0f, 0.0f) + ); + Graphics.Blit(from, tmp, dofBlurMaterial, blurPass); + dofBlurMaterial.SetVector( + "offsets", + new Vector4(spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f) + ); + Graphics.Blit(tmp, to, dofBlurMaterial, blurPass); } - RenderTexture.ReleaseTemporary (tmp); + RenderTexture.ReleaseTemporary(tmp); } - void BlurHex ( RenderTexture from, RenderTexture to, int blurPass, float spread, RenderTexture tmp) { - dofBlurMaterial.SetVector ("offsets", new Vector4 (0.0f, spread * oneOverBaseSize, 0.0f, 0.0f)); - Graphics.Blit (from, tmp, dofBlurMaterial, blurPass); - dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f)); - Graphics.Blit (tmp, to, dofBlurMaterial, blurPass); - dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, spread * oneOverBaseSize, 0.0f, 0.0f)); - Graphics.Blit (to, tmp, dofBlurMaterial, blurPass); - dofBlurMaterial.SetVector ("offsets", new Vector4 (spread / widthOverHeight * oneOverBaseSize, -spread * oneOverBaseSize, 0.0f, 0.0f)); - Graphics.Blit (tmp, to, dofBlurMaterial, blurPass); + void BlurHex( + RenderTexture from, + RenderTexture to, + int blurPass, + float spread, + RenderTexture tmp + ) + { + dofBlurMaterial.SetVector( + "offsets", + new Vector4(0.0f, spread * oneOverBaseSize, 0.0f, 0.0f) + ); + Graphics.Blit(from, tmp, dofBlurMaterial, blurPass); + dofBlurMaterial.SetVector( + "offsets", + new Vector4(spread / widthOverHeight * oneOverBaseSize, 0.0f, 0.0f, 0.0f) + ); + Graphics.Blit(tmp, to, dofBlurMaterial, blurPass); + dofBlurMaterial.SetVector( + "offsets", + new Vector4( + spread / widthOverHeight * oneOverBaseSize, + spread * oneOverBaseSize, + 0.0f, + 0.0f + ) + ); + Graphics.Blit(to, tmp, dofBlurMaterial, blurPass); + dofBlurMaterial.SetVector( + "offsets", + new Vector4( + spread / widthOverHeight * oneOverBaseSize, + -spread * oneOverBaseSize, + 0.0f, + 0.0f + ) + ); + Graphics.Blit(tmp, to, dofBlurMaterial, blurPass); } - void Downsample ( RenderTexture from, RenderTexture to) { - dofMaterial.SetVector ("_InvRenderTargetSize", new Vector4 (1.0f / (1.0f * to.width), 1.0f / (1.0f * to.height), 0.0f, 0.0f)); - Graphics.Blit (from, to, dofMaterial, SMOOTH_DOWNSAMPLE_PASS); + void Downsample(RenderTexture from, RenderTexture to) + { + dofMaterial.SetVector( + "_InvRenderTargetSize", + new Vector4(1.0f / (1.0f * to.width), 1.0f / (1.0f * to.height), 0.0f, 0.0f) + ); + Graphics.Blit(from, to, dofMaterial, SMOOTH_DOWNSAMPLE_PASS); } - void AddBokeh ( RenderTexture bokehInfo, RenderTexture tempTex, RenderTexture finalTarget) { - if (bokehMaterial) { - var meshes = Quads.GetMeshes (tempTex.width, tempTex.height); // quads: exchanging more triangles with less overdraw + void AddBokeh(RenderTexture bokehInfo, RenderTexture tempTex, RenderTexture finalTarget) + { + if (bokehMaterial) + { + var meshes = Quads.GetMeshes(tempTex.width, tempTex.height); // quads: exchanging more triangles with less overdraw RenderTexture.active = tempTex; - GL.Clear (false, true, new Color (0.0f, 0.0f, 0.0f, 0.0f)); + GL.Clear(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f)); - GL.PushMatrix (); - GL.LoadIdentity (); + GL.PushMatrix(); + GL.LoadIdentity(); // point filter mode is important, otherwise we get bokeh shape & size artefacts bokehInfo.filterMode = FilterMode.Point; @@ -368,50 +517,86 @@ void AddBokeh ( RenderTexture bokehInfo, RenderTexture tempTex, RenderTexture fi float sc = 2.0f / (1.0f * bokehInfo.width); sc += bokehScale * maxBlurSpread * BOKEH_EXTRA_BLUR * oneOverBaseSize; - bokehMaterial.SetTexture ("_Source", bokehInfo); - bokehMaterial.SetTexture ("_MainTex", bokehTexture); - bokehMaterial.SetVector ("_ArScale",new Vector4 (sc, sc * arW, 0.5f, 0.5f * arW)); - bokehMaterial.SetFloat ("_Intensity", bokehIntensity); - bokehMaterial.SetPass (0); + bokehMaterial.SetTexture("_Source", bokehInfo); + bokehMaterial.SetTexture("_MainTex", bokehTexture); + bokehMaterial.SetVector("_ArScale", new Vector4(sc, sc * arW, 0.5f, 0.5f * arW)); + bokehMaterial.SetFloat("_Intensity", bokehIntensity); + bokehMaterial.SetPass(0); - foreach(Mesh m in meshes) - if (m) Graphics.DrawMeshNow (m, Matrix4x4.identity); + foreach (Mesh m in meshes) + if (m) + Graphics.DrawMeshNow(m, Matrix4x4.identity); - GL.PopMatrix (); + GL.PopMatrix(); - Graphics.Blit (tempTex, finalTarget, dofMaterial, 8); + Graphics.Blit(tempTex, finalTarget, dofMaterial, 8); // important to set back as we sample from this later on bokehInfo.filterMode = FilterMode.Bilinear; } } - - void ReleaseTextures () { - if (foregroundTexture) RenderTexture.ReleaseTemporary (foregroundTexture); - if (finalDefocus) RenderTexture.ReleaseTemporary (finalDefocus); - if (mediumRezWorkTexture) RenderTexture.ReleaseTemporary (mediumRezWorkTexture); - if (lowRezWorkTexture) RenderTexture.ReleaseTemporary (lowRezWorkTexture); - if (bokehSource) RenderTexture.ReleaseTemporary (bokehSource); - if (bokehSource2) RenderTexture.ReleaseTemporary (bokehSource2); + void ReleaseTextures() + { + if (foregroundTexture) + RenderTexture.ReleaseTemporary(foregroundTexture); + if (finalDefocus) + RenderTexture.ReleaseTemporary(finalDefocus); + if (mediumRezWorkTexture) + RenderTexture.ReleaseTemporary(mediumRezWorkTexture); + if (lowRezWorkTexture) + RenderTexture.ReleaseTemporary(lowRezWorkTexture); + if (bokehSource) + RenderTexture.ReleaseTemporary(bokehSource); + if (bokehSource2) + RenderTexture.ReleaseTemporary(bokehSource2); } - void AllocateTextures ( bool blurForeground, RenderTexture source, int divider, int lowTexDivider) { + void AllocateTextures( + bool blurForeground, + RenderTexture source, + int divider, + int lowTexDivider + ) + { foregroundTexture = null; if (blurForeground) - foregroundTexture = RenderTexture.GetTemporary (source.width, source.height, 0); - mediumRezWorkTexture = RenderTexture.GetTemporary (source.width / divider, source.height / divider, 0); - finalDefocus = RenderTexture.GetTemporary (source.width / divider, source.height / divider, 0); - lowRezWorkTexture = RenderTexture.GetTemporary (source.width / lowTexDivider, source.height / lowTexDivider, 0); + foregroundTexture = RenderTexture.GetTemporary(source.width, source.height, 0); + mediumRezWorkTexture = RenderTexture.GetTemporary( + source.width / divider, + source.height / divider, + 0 + ); + finalDefocus = RenderTexture.GetTemporary( + source.width / divider, + source.height / divider, + 0 + ); + lowRezWorkTexture = RenderTexture.GetTemporary( + source.width / lowTexDivider, + source.height / lowTexDivider, + 0 + ); bokehSource = null; bokehSource2 = null; - if (bokeh) { - bokehSource = RenderTexture.GetTemporary (source.width / (lowTexDivider * bokehDownsample), source.height / (lowTexDivider * bokehDownsample), 0, RenderTextureFormat.ARGBHalf); - bokehSource2 = RenderTexture.GetTemporary (source.width / (lowTexDivider * bokehDownsample), source.height / (lowTexDivider * bokehDownsample), 0, RenderTextureFormat.ARGBHalf); + if (bokeh) + { + bokehSource = RenderTexture.GetTemporary( + source.width / (lowTexDivider * bokehDownsample), + source.height / (lowTexDivider * bokehDownsample), + 0, + RenderTextureFormat.ARGBHalf + ); + bokehSource2 = RenderTexture.GetTemporary( + source.width / (lowTexDivider * bokehDownsample), + source.height / (lowTexDivider * bokehDownsample), + 0, + RenderTextureFormat.ARGBHalf + ); bokehSource.filterMode = FilterMode.Bilinear; bokehSource2.filterMode = FilterMode.Bilinear; RenderTexture.active = bokehSource2; - GL.Clear (false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f)); + GL.Clear(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f)); } // to make sure: always use bilinear filter setting diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/EdgeDetection.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/EdgeDetection.cs index ec0ac18511..74b27194a7 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/EdgeDetection.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/EdgeDetection.cs @@ -4,8 +4,8 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof (Camera))] - [AddComponentMenu ("Image Effects/Edge Detection/Edge Detection")] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Edge Detection/Edge Detection")] public class EdgeDetection : PostEffectsBase { public enum EdgeDetectMode @@ -17,7 +17,6 @@ public enum EdgeDetectMode TriangleLuminance = 4, } - public EdgeDetectMode mode = EdgeDetectMode.SobelDepthThin; public float sensitivityDepth = 1.0f; public float sensitivityNormals = 1.0f; @@ -31,59 +30,63 @@ public enum EdgeDetectMode private Material edgeDetectMaterial = null; private EdgeDetectMode oldMode = EdgeDetectMode.SobelDepthThin; + public override bool CheckResources() + { + CheckSupport(true); - public override bool CheckResources () - { - CheckSupport (true); - - edgeDetectMaterial = CheckShaderAndCreateMaterial (edgeDetectShader,edgeDetectMaterial); + edgeDetectMaterial = CheckShaderAndCreateMaterial(edgeDetectShader, edgeDetectMaterial); if (mode != oldMode) - SetCameraFlag (); + SetCameraFlag(); oldMode = mode; if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - - new void Start () - { - oldMode = mode; + new void Start() + { + oldMode = mode; } - void SetCameraFlag () - { + void SetCameraFlag() + { if (mode == EdgeDetectMode.SobelDepth || mode == EdgeDetectMode.SobelDepthThin) GetComponent().depthTextureMode |= DepthTextureMode.Depth; - else if (mode == EdgeDetectMode.TriangleDepthNormals || mode == EdgeDetectMode.RobertsCrossDepthNormals) + else if ( + mode == EdgeDetectMode.TriangleDepthNormals + || mode == EdgeDetectMode.RobertsCrossDepthNormals + ) GetComponent().depthTextureMode |= DepthTextureMode.DepthNormals; } - void OnEnable () - { + void OnEnable() + { SetCameraFlag(); } [ImageEffectOpaque] - void OnRenderImage (RenderTexture source, RenderTexture destination) - { - if (CheckResources () == false) - { - Graphics.Blit (source, destination); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (CheckResources() == false) + { + Graphics.Blit(source, destination); return; } - Vector2 sensitivity = new Vector2 (sensitivityDepth, sensitivityNormals); - edgeDetectMaterial.SetVector ("_Sensitivity", new Vector4 (sensitivity.x, sensitivity.y, 1.0f, sensitivity.y)); - edgeDetectMaterial.SetFloat ("_BgFade", edgesOnly); - edgeDetectMaterial.SetFloat ("_SampleDistance", sampleDist); - edgeDetectMaterial.SetVector ("_BgColor", edgesOnlyBgColor); - edgeDetectMaterial.SetFloat ("_Exponent", edgeExp); - edgeDetectMaterial.SetFloat ("_Threshold", lumThreshold); - - Graphics.Blit (source, destination, edgeDetectMaterial, (int) mode); + Vector2 sensitivity = new Vector2(sensitivityDepth, sensitivityNormals); + edgeDetectMaterial.SetVector( + "_Sensitivity", + new Vector4(sensitivity.x, sensitivity.y, 1.0f, sensitivity.y) + ); + edgeDetectMaterial.SetFloat("_BgFade", edgesOnly); + edgeDetectMaterial.SetFloat("_SampleDistance", sampleDist); + edgeDetectMaterial.SetVector("_BgColor", edgesOnlyBgColor); + edgeDetectMaterial.SetFloat("_Exponent", edgeExp); + edgeDetectMaterial.SetFloat("_Threshold", lumThreshold); + + Graphics.Blit(source, destination, edgeDetectMaterial, (int)mode); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Fisheye.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Fisheye.cs index b95b48005c..d32d6b18b6 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Fisheye.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Fisheye.cs @@ -4,34 +4,34 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Displacement/Fisheye")] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Displacement/Fisheye")] public class Fisheye : PostEffectsBase - { + { [Range(0.0f, 1.5f)] public float strengthX = 0.05f; + [Range(0.0f, 1.5f)] public float strengthY = 0.05f; public Shader fishEyeShader = null; private Material fisheyeMaterial = null; - - public override bool CheckResources () - { - CheckSupport (false); - fisheyeMaterial = CheckShaderAndCreateMaterial(fishEyeShader,fisheyeMaterial); + public override bool CheckResources() + { + CheckSupport(false); + fisheyeMaterial = CheckShaderAndCreateMaterial(fishEyeShader, fisheyeMaterial); if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - void OnRenderImage (RenderTexture source, RenderTexture destination) - { - if (CheckResources()==false) - { - Graphics.Blit (source, destination); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (CheckResources() == false) + { + Graphics.Blit(source, destination); return; } @@ -39,8 +39,16 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) float ar = (source.width * 1.0f) / (source.height * 1.0f); - fisheyeMaterial.SetVector ("intensity", new Vector4 (strengthX * ar * oneOverBaseSize, strengthY * oneOverBaseSize, strengthX * ar * oneOverBaseSize, strengthY * oneOverBaseSize)); - Graphics.Blit (source, destination, fisheyeMaterial); + fisheyeMaterial.SetVector( + "intensity", + new Vector4( + strengthX * ar * oneOverBaseSize, + strengthY * oneOverBaseSize, + strengthX * ar * oneOverBaseSize, + strengthY * oneOverBaseSize + ) + ); + Graphics.Blit(source, destination, fisheyeMaterial); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/GlobalFog.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/GlobalFog.cs index 3a71b64cd8..2839aad8a3 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/GlobalFog.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/GlobalFog.cs @@ -4,37 +4,42 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Rendering/Global Fog")] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Rendering/Global Fog")] public class GlobalFog : PostEffectsBase - { - [Tooltip("Apply distance-based fog?")] - public bool distanceFog = true; - [Tooltip("Exclude far plane pixels from distance-based fog? (Skybox or clear color)")] - public bool excludeFarPixels = true; - [Tooltip("Distance fog is based on radial distance from camera when checked")] - public bool useRadialDistance = false; - [Tooltip("Apply height-based fog?")] - public bool heightFog = true; - [Tooltip("Fog top Y coordinate")] + { + [Tooltip("Apply distance-based fog?")] + public bool distanceFog = true; + + [Tooltip("Exclude far plane pixels from distance-based fog? (Skybox or clear color)")] + public bool excludeFarPixels = true; + + [Tooltip("Distance fog is based on radial distance from camera when checked")] + public bool useRadialDistance = false; + + [Tooltip("Apply height-based fog?")] + public bool heightFog = true; + + [Tooltip("Fog top Y coordinate")] public float height = 1.0f; - [Range(0.001f,10.0f)] + + [Range(0.001f, 10.0f)] public float heightDensity = 2.0f; - [Tooltip("Push fog away from the camera by this amount")] + + [Tooltip("Push fog away from the camera by this amount")] public float startDistance = 0.0f; public Shader fogShader = null; private Material fogMaterial = null; + public override bool CheckResources() + { + CheckSupport(true); - public override bool CheckResources () - { - CheckSupport (true); - - fogMaterial = CheckShaderAndCreateMaterial (fogShader, fogMaterial); + fogMaterial = CheckShaderAndCreateMaterial(fogShader, fogMaterial); if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } @@ -51,7 +56,12 @@ void OnRenderImage(RenderTexture source, RenderTexture destination) Transform camtr = cam.transform; Vector3[] frustumCorners = new Vector3[4]; - cam.CalculateFrustumCorners(new Rect(0, 0, 1, 1), cam.farClipPlane, cam.stereoActiveEye, frustumCorners); + cam.CalculateFrustumCorners( + new Rect(0, 0, 1, 1), + cam.farClipPlane, + cam.stereoActiveEye, + frustumCorners + ); var bottomLeft = camtr.TransformVector(frustumCorners[0]); var topLeft = camtr.TransformVector(frustumCorners[1]); var topRight = camtr.TransformVector(frustumCorners[2]); @@ -69,8 +79,14 @@ void OnRenderImage(RenderTexture source, RenderTexture destination) float excludeDepth = (excludeFarPixels ? 1.0f : 2.0f); fogMaterial.SetMatrix("_FrustumCornersWS", frustumCornersArray); fogMaterial.SetVector("_CameraWS", camPos); - fogMaterial.SetVector("_HeightParams", new Vector4(height, FdotC, paramK, heightDensity * 0.5f)); - fogMaterial.SetVector("_DistanceParams", new Vector4(-Mathf.Max(startDistance, 0.0f), excludeDepth, 0, 0)); + fogMaterial.SetVector( + "_HeightParams", + new Vector4(height, FdotC, paramK, heightDensity * 0.5f) + ); + fogMaterial.SetVector( + "_DistanceParams", + new Vector4(-Mathf.Max(startDistance, 0.0f), excludeDepth, 0, 0) + ); var sceneMode = RenderSettings.fogMode; var sceneDensity = RenderSettings.fogDensity; @@ -85,7 +101,10 @@ void OnRenderImage(RenderTexture source, RenderTexture destination) sceneParams.z = linear ? -invDiff : 0.0f; sceneParams.w = linear ? sceneEnd * invDiff : 0.0f; fogMaterial.SetVector("_SceneFogParams", sceneParams); - fogMaterial.SetVector("_SceneFogMode", new Vector4((int)sceneMode, useRadialDistance ? 1 : 0, 0, 0)); + fogMaterial.SetVector( + "_SceneFogMode", + new Vector4((int)sceneMode, useRadialDistance ? 1 : 0, 0, 0) + ); int pass = 0; if (distanceFog && heightFog) diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Grayscale.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Grayscale.cs index 0208fcbe1d..0c7fc92065 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Grayscale.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Grayscale.cs @@ -5,17 +5,19 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] [AddComponentMenu("Image Effects/Color Adjustments/Grayscale")] - public class Grayscale : ImageEffectBase { - public Texture textureRamp; + public class Grayscale : ImageEffectBase + { + public Texture textureRamp; - [Range(-1.0f,1.0f)] - public float rampOffset; + [Range(-1.0f, 1.0f)] + public float rampOffset; // Called by camera to apply image effect - void OnRenderImage (RenderTexture source, RenderTexture destination) { + void OnRenderImage(RenderTexture source, RenderTexture destination) + { material.SetTexture("_RampTex", textureRamp); material.SetFloat("_RampOffset", rampOffset); - Graphics.Blit (source, destination, material); + Graphics.Blit(source, destination, material); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ImageEffectBase.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ImageEffectBase.cs index 8a41185f20..389c5be362 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ImageEffectBase.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ImageEffectBase.cs @@ -3,7 +3,7 @@ namespace UnityStandardAssets.ImageEffects { - [RequireComponent(typeof (Camera))] + [RequireComponent(typeof(Camera))] [AddComponentMenu("")] public class ImageEffectBase : MonoBehaviour { @@ -13,7 +13,6 @@ public class ImageEffectBase : MonoBehaviour private Material m_Material; - protected virtual void Start() { // Disable if we don't support image effects @@ -29,7 +28,6 @@ protected virtual void Start() enabled = false; } - protected Material material { get @@ -43,7 +41,6 @@ protected Material material } } - protected virtual void OnDisable() { if (m_Material) diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ImageEffects.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ImageEffects.cs index aa056e1c1e..1cd7da5414 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ImageEffects.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ImageEffects.cs @@ -7,7 +7,14 @@ namespace UnityStandardAssets.ImageEffects [AddComponentMenu("")] public class ImageEffects { - public static void RenderDistortion(Material material, RenderTexture source, RenderTexture destination, float angle, Vector2 center, Vector2 radius) + public static void RenderDistortion( + Material material, + RenderTexture source, + RenderTexture destination, + float angle, + Vector2 center, + Vector2 radius + ) { bool invertY = source.texelSize.y < 0.0f; if (invertY) @@ -16,25 +23,34 @@ public static void RenderDistortion(Material material, RenderTexture source, Ren angle = -angle; } - Matrix4x4 rotationMatrix = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, angle), Vector3.one); + Matrix4x4 rotationMatrix = Matrix4x4.TRS( + Vector3.zero, + Quaternion.Euler(0, 0, angle), + Vector3.one + ); material.SetMatrix("_RotationMatrix", rotationMatrix); - material.SetVector("_CenterRadius", new Vector4(center.x, center.y, radius.x, radius.y)); - material.SetFloat("_Angle", angle*Mathf.Deg2Rad); + material.SetVector( + "_CenterRadius", + new Vector4(center.x, center.y, radius.x, radius.y) + ); + material.SetFloat("_Angle", angle * Mathf.Deg2Rad); Graphics.Blit(source, destination, material); } - [Obsolete("Use Graphics.Blit(source,dest) instead")] public static void Blit(RenderTexture source, RenderTexture dest) { Graphics.Blit(source, dest); } - [Obsolete("Use Graphics.Blit(source, destination, material) instead")] - public static void BlitWithMaterial(Material material, RenderTexture source, RenderTexture dest) + public static void BlitWithMaterial( + Material material, + RenderTexture source, + RenderTexture dest + ) { Graphics.Blit(source, dest, material); } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/MotionBlur.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/MotionBlur.cs index 7a95ab8099..bdbf1a8caf 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/MotionBlur.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/MotionBlur.cs @@ -19,53 +19,61 @@ public class MotionBlur : ImageEffectBase private RenderTexture accumTexture; - override protected void Start() + protected override void Start() { base.Start(); } - override protected void OnDisable() + protected override void OnDisable() { base.OnDisable(); DestroyImmediate(accumTexture); } // Called by camera to apply image effect - void OnRenderImage (RenderTexture source, RenderTexture destination) + void OnRenderImage(RenderTexture source, RenderTexture destination) { // Create the accumulation texture - if (accumTexture == null || accumTexture.width != source.width || accumTexture.height != source.height) + if ( + accumTexture == null + || accumTexture.width != source.width + || accumTexture.height != source.height + ) { DestroyImmediate(accumTexture); accumTexture = new RenderTexture(source.width, source.height, 0); accumTexture.hideFlags = HideFlags.HideAndDontSave; - Graphics.Blit( source, accumTexture ); + Graphics.Blit(source, accumTexture); } // If Extra Blur is selected, downscale the texture to 4x4 smaller resolution. if (extraBlur) { - RenderTexture blurbuffer = RenderTexture.GetTemporary(source.width/4, source.height/4, 0); + RenderTexture blurbuffer = RenderTexture.GetTemporary( + source.width / 4, + source.height / 4, + 0 + ); accumTexture.MarkRestoreExpected(); Graphics.Blit(accumTexture, blurbuffer); - Graphics.Blit(blurbuffer,accumTexture); + Graphics.Blit(blurbuffer, accumTexture); RenderTexture.ReleaseTemporary(blurbuffer); } // Clamp the motion blur variable, so it can never leave permanent trails in the image - blurAmount = Mathf.Clamp( blurAmount, 0.0f, 0.92f ); + blurAmount = Mathf.Clamp(blurAmount, 0.0f, 0.92f); // Setup the texture and floating point values in the shader material.SetTexture("_MainTex", accumTexture); - material.SetFloat("_AccumOrig", 1.0F-blurAmount); + material.SetFloat("_AccumOrig", 1.0F - blurAmount); // We are accumulating motion over frames without clear/discard // by design, so silence any performance warnings from Unity accumTexture.MarkRestoreExpected(); // Render the image using the motion blur shader - Graphics.Blit (source, accumTexture, material); - Graphics.Blit (accumTexture, destination); + Graphics.Blit(source, accumTexture, material); + Graphics.Blit(accumTexture, destination); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/NoiseAndGrain.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/NoiseAndGrain.cs index 8082ada29a..84c7d3f324 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/NoiseAndGrain.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/NoiseAndGrain.cs @@ -5,11 +5,10 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Noise/Noise And Grain (Filmic)")] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Noise/Noise And Grain (Filmic)")] public class NoiseAndGrain : PostEffectsBase - { - + { public float intensityMultiplier = 0.25f; public float generalIntensity = 0.5f; @@ -17,9 +16,9 @@ public class NoiseAndGrain : PostEffectsBase public float whiteIntensity = 1.0f; public float midGrey = 0.2f; - public bool dx11Grain = false; + public bool dx11Grain = false; public float softness = 0.0f; - public bool monochrome = false; + public bool monochrome = false; public Vector3 intensities = new Vector3(1.0f, 1.0f, 1.0f); public Vector3 tiling = new Vector3(64.0f, 64.0f, 64.0f); @@ -37,33 +36,39 @@ public class NoiseAndGrain : PostEffectsBase private static float TILE_AMOUNT = 64.0f; + public override bool CheckResources() + { + CheckSupport(false); - public override bool CheckResources () - { - CheckSupport (false); - - noiseMaterial = CheckShaderAndCreateMaterial (noiseShader, noiseMaterial); + noiseMaterial = CheckShaderAndCreateMaterial(noiseShader, noiseMaterial); if (dx11Grain && supportDX11) - { + { #if UNITY_EDITOR dx11NoiseShader = Shader.Find("Hidden/NoiseAndGrainDX11"); #endif - dx11NoiseMaterial = CheckShaderAndCreateMaterial (dx11NoiseShader, dx11NoiseMaterial); + dx11NoiseMaterial = CheckShaderAndCreateMaterial( + dx11NoiseShader, + dx11NoiseMaterial + ); } if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - void OnRenderImage (RenderTexture source, RenderTexture destination) - { - if (CheckResources()==false || (null==noiseTexture)) - { - Graphics.Blit (source, destination); - if (null==noiseTexture) { - Debug.LogWarning("Noise & Grain effect failing as noise texture is not assigned. please assign.", transform); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (CheckResources() == false || (null == noiseTexture)) + { + Graphics.Blit(source, destination); + if (null == noiseTexture) + { + Debug.LogWarning( + "Noise & Grain effect failing as noise texture is not assigned. please assign.", + transform + ); } return; } @@ -71,111 +76,160 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) softness = Mathf.Clamp(softness, 0.0f, 0.99f); if (dx11Grain && supportDX11) - { + { // We have a fancy, procedural noise pattern in this version, so no texture needed dx11NoiseMaterial.SetFloat("_DX11NoiseTime", Time.frameCount); - dx11NoiseMaterial.SetTexture ("_NoiseTex", noiseTexture); - dx11NoiseMaterial.SetVector ("_NoisePerChannel", monochrome ? Vector3.one : intensities); - dx11NoiseMaterial.SetVector ("_MidGrey", new Vector3(midGrey, 1.0f/(1.0f-midGrey), -1.0f/midGrey)); - dx11NoiseMaterial.SetVector ("_NoiseAmount", new Vector3(generalIntensity, blackIntensity, whiteIntensity) * intensityMultiplier); + dx11NoiseMaterial.SetTexture("_NoiseTex", noiseTexture); + dx11NoiseMaterial.SetVector( + "_NoisePerChannel", + monochrome ? Vector3.one : intensities + ); + dx11NoiseMaterial.SetVector( + "_MidGrey", + new Vector3(midGrey, 1.0f / (1.0f - midGrey), -1.0f / midGrey) + ); + dx11NoiseMaterial.SetVector( + "_NoiseAmount", + new Vector3(generalIntensity, blackIntensity, whiteIntensity) + * intensityMultiplier + ); if (softness > Mathf.Epsilon) { - RenderTexture rt = RenderTexture.GetTemporary((int) (source.width * (1.0f-softness)), (int) (source.height * (1.0f-softness))); - DrawNoiseQuadGrid (source, rt, dx11NoiseMaterial, noiseTexture, monochrome ? 3 : 2); + RenderTexture rt = RenderTexture.GetTemporary( + (int)(source.width * (1.0f - softness)), + (int)(source.height * (1.0f - softness)) + ); + DrawNoiseQuadGrid( + source, + rt, + dx11NoiseMaterial, + noiseTexture, + monochrome ? 3 : 2 + ); dx11NoiseMaterial.SetTexture("_NoiseTex", rt); Graphics.Blit(source, destination, dx11NoiseMaterial, 4); RenderTexture.ReleaseTemporary(rt); } else - DrawNoiseQuadGrid (source, destination, dx11NoiseMaterial, noiseTexture, (monochrome ? 1 : 0)); + DrawNoiseQuadGrid( + source, + destination, + dx11NoiseMaterial, + noiseTexture, + (monochrome ? 1 : 0) + ); } else - { + { // normal noise (DX9 style) - if (noiseTexture) { + if (noiseTexture) + { noiseTexture.wrapMode = TextureWrapMode.Repeat; noiseTexture.filterMode = filterMode; } - noiseMaterial.SetTexture ("_NoiseTex", noiseTexture); - noiseMaterial.SetVector ("_NoisePerChannel", monochrome ? Vector3.one : intensities); - noiseMaterial.SetVector ("_NoiseTilingPerChannel", monochrome ? Vector3.one * monochromeTiling : tiling); - noiseMaterial.SetVector ("_MidGrey", new Vector3(midGrey, 1.0f/(1.0f-midGrey), -1.0f/midGrey)); - noiseMaterial.SetVector ("_NoiseAmount", new Vector3(generalIntensity, blackIntensity, whiteIntensity) * intensityMultiplier); + noiseMaterial.SetTexture("_NoiseTex", noiseTexture); + noiseMaterial.SetVector("_NoisePerChannel", monochrome ? Vector3.one : intensities); + noiseMaterial.SetVector( + "_NoiseTilingPerChannel", + monochrome ? Vector3.one * monochromeTiling : tiling + ); + noiseMaterial.SetVector( + "_MidGrey", + new Vector3(midGrey, 1.0f / (1.0f - midGrey), -1.0f / midGrey) + ); + noiseMaterial.SetVector( + "_NoiseAmount", + new Vector3(generalIntensity, blackIntensity, whiteIntensity) + * intensityMultiplier + ); if (softness > Mathf.Epsilon) { - RenderTexture rt2 = RenderTexture.GetTemporary((int) (source.width * (1.0f-softness)), (int) (source.height * (1.0f-softness))); - DrawNoiseQuadGrid (source, rt2, noiseMaterial, noiseTexture, 2); + RenderTexture rt2 = RenderTexture.GetTemporary( + (int)(source.width * (1.0f - softness)), + (int)(source.height * (1.0f - softness)) + ); + DrawNoiseQuadGrid(source, rt2, noiseMaterial, noiseTexture, 2); noiseMaterial.SetTexture("_NoiseTex", rt2); Graphics.Blit(source, destination, noiseMaterial, 1); RenderTexture.ReleaseTemporary(rt2); } else - DrawNoiseQuadGrid (source, destination, noiseMaterial, noiseTexture, 0); + DrawNoiseQuadGrid(source, destination, noiseMaterial, noiseTexture, 0); } } - static void DrawNoiseQuadGrid (RenderTexture source, RenderTexture dest, Material fxMaterial, Texture2D noise, int passNr) - { + static void DrawNoiseQuadGrid( + RenderTexture source, + RenderTexture dest, + Material fxMaterial, + Texture2D noise, + int passNr + ) + { RenderTexture.active = dest; float noiseSize = (noise.width * 1.0f); float subDs = (1.0f * source.width) / TILE_AMOUNT; - fxMaterial.SetTexture ("_MainTex", source); + fxMaterial.SetTexture("_MainTex", source); - GL.PushMatrix (); - GL.LoadOrtho (); + GL.PushMatrix(); + GL.LoadOrtho(); float aspectCorrection = (1.0f * source.width) / (1.0f * source.height); float stepSizeX = 1.0f / subDs; float stepSizeY = stepSizeX * aspectCorrection; float texTile = noiseSize / (noise.width * 1.0f); - fxMaterial.SetPass (passNr); + fxMaterial.SetPass(passNr); - GL.Begin (GL.QUADS); + GL.Begin(GL.QUADS); for (float x1 = 0.0f; x1 < 1.0f; x1 += stepSizeX) - { + { for (float y1 = 0.0f; y1 < 1.0f; y1 += stepSizeY) - { - float tcXStart = Random.Range (0.0f, 1.0f); - float tcYStart = Random.Range (0.0f, 1.0f); + { + float tcXStart = Random.Range(0.0f, 1.0f); + float tcYStart = Random.Range(0.0f, 1.0f); // Vector3 v3 = Random.insideUnitSphere; // Color c = new Color(v3.x, v3.y, v3.z); - tcXStart = Mathf.Floor(tcXStart*noiseSize) / noiseSize; - tcYStart = Mathf.Floor(tcYStart*noiseSize) / noiseSize; + tcXStart = Mathf.Floor(tcXStart * noiseSize) / noiseSize; + tcYStart = Mathf.Floor(tcYStart * noiseSize) / noiseSize; float texTileMod = 1.0f / noiseSize; - GL.MultiTexCoord2 (0, tcXStart, tcYStart); - GL.MultiTexCoord2 (1, 0.0f, 0.0f); + GL.MultiTexCoord2(0, tcXStart, tcYStart); + GL.MultiTexCoord2(1, 0.0f, 0.0f); // GL.Color( c ); - GL.Vertex3 (x1, y1, 0.1f); - GL.MultiTexCoord2 (0, tcXStart + texTile * texTileMod, tcYStart); - GL.MultiTexCoord2 (1, 1.0f, 0.0f); + GL.Vertex3(x1, y1, 0.1f); + GL.MultiTexCoord2(0, tcXStart + texTile * texTileMod, tcYStart); + GL.MultiTexCoord2(1, 1.0f, 0.0f); // GL.Color( c ); - GL.Vertex3 (x1 + stepSizeX, y1, 0.1f); - GL.MultiTexCoord2 (0, tcXStart + texTile * texTileMod, tcYStart + texTile * texTileMod); - GL.MultiTexCoord2 (1, 1.0f, 1.0f); + GL.Vertex3(x1 + stepSizeX, y1, 0.1f); + GL.MultiTexCoord2( + 0, + tcXStart + texTile * texTileMod, + tcYStart + texTile * texTileMod + ); + GL.MultiTexCoord2(1, 1.0f, 1.0f); // GL.Color( c ); - GL.Vertex3 (x1 + stepSizeX, y1 + stepSizeY, 0.1f); - GL.MultiTexCoord2 (0, tcXStart, tcYStart + texTile * texTileMod); - GL.MultiTexCoord2 (1, 0.0f, 1.0f); + GL.Vertex3(x1 + stepSizeX, y1 + stepSizeY, 0.1f); + GL.MultiTexCoord2(0, tcXStart, tcYStart + texTile * texTileMod); + GL.MultiTexCoord2(1, 0.0f, 1.0f); // GL.Color( c ); - GL.Vertex3 (x1, y1 + stepSizeY, 0.1f); + GL.Vertex3(x1, y1 + stepSizeY, 0.1f); } } - GL.End (); - GL.PopMatrix (); + GL.End(); + GL.PopMatrix(); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/NoiseAndScratches.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/NoiseAndScratches.cs index 2347d97c33..0bdeee0a7e 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/NoiseAndScratches.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/NoiseAndScratches.cs @@ -5,7 +5,7 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] + [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Noise/Noise and Scratches")] public class NoiseAndScratches : MonoBehaviour { @@ -16,8 +16,9 @@ public class NoiseAndScratches : MonoBehaviour private bool rgbFallback = false; // Noise grain takes random intensity from Min to Max. - [Range(0.0f,5.0f)] + [Range(0.0f, 5.0f)] public float grainIntensityMin = 0.1f; + [Range(0.0f, 5.0f)] public float grainIntensityMax = 0.2f; @@ -28,27 +29,30 @@ public class NoiseAndScratches : MonoBehaviour // Scratches take random intensity from Min to Max. [Range(0.0f, 5.0f)] public float scratchIntensityMin = 0.05f; + [Range(0.0f, 5.0f)] public float scratchIntensityMax = 0.25f; /// Scratches jump to another locations at this times per second. [Range(1.0f, 30.0f)] public float scratchFPS = 10.0f; + /// While scratches are in the same location, they jitter a bit. [Range(0.0f, 1.0f)] public float scratchJitter = 0.01f; public Texture grainTexture; public Texture scratchTexture; - public Shader shaderRGB; - public Shader shaderYUV; + public Shader shaderRGB; + public Shader shaderYUV; private Material m_MaterialRGB; private Material m_MaterialYUV; private float scratchTimeLeft = 0.0f; - private float scratchX, scratchY; + private float scratchX, + scratchY; - protected void Start () + protected void Start() { // Disable if we don't support image effects // if (!SystemInfo.supportsImageEffects) { @@ -56,58 +60,63 @@ protected void Start () // return; // } - if ( shaderRGB == null || shaderYUV == null ) + if (shaderRGB == null || shaderYUV == null) { - Debug.Log( "Noise shaders are not set up! Disabling noise effect." ); + Debug.Log("Noise shaders are not set up! Disabling noise effect."); enabled = false; } else { - if ( !shaderRGB.isSupported ) // disable effect if RGB shader is not supported + if (!shaderRGB.isSupported) // disable effect if RGB shader is not supported enabled = false; - else if ( !shaderYUV.isSupported ) // fallback to RGB if YUV is not supported + else if (!shaderYUV.isSupported) // fallback to RGB if YUV is not supported rgbFallback = true; } } - protected Material material { - get { - if ( m_MaterialRGB == null ) { - m_MaterialRGB = new Material( shaderRGB ); + protected Material material + { + get + { + if (m_MaterialRGB == null) + { + m_MaterialRGB = new Material(shaderRGB); m_MaterialRGB.hideFlags = HideFlags.HideAndDontSave; } - if ( m_MaterialYUV == null && !rgbFallback ) { - m_MaterialYUV = new Material( shaderYUV ); + if (m_MaterialYUV == null && !rgbFallback) + { + m_MaterialYUV = new Material(shaderYUV); m_MaterialYUV.hideFlags = HideFlags.HideAndDontSave; } return (!rgbFallback && !monochrome) ? m_MaterialYUV : m_MaterialRGB; } } - protected void OnDisable() { - if ( m_MaterialRGB ) - DestroyImmediate( m_MaterialRGB ); - if ( m_MaterialYUV ) - DestroyImmediate( m_MaterialYUV ); + protected void OnDisable() + { + if (m_MaterialRGB) + DestroyImmediate(m_MaterialRGB); + if (m_MaterialYUV) + DestroyImmediate(m_MaterialYUV); } private void SanitizeParameters() { - grainIntensityMin = Mathf.Clamp( grainIntensityMin, 0.0f, 5.0f ); - grainIntensityMax = Mathf.Clamp( grainIntensityMax, 0.0f, 5.0f ); - scratchIntensityMin = Mathf.Clamp( scratchIntensityMin, 0.0f, 5.0f ); - scratchIntensityMax = Mathf.Clamp( scratchIntensityMax, 0.0f, 5.0f ); - scratchFPS = Mathf.Clamp( scratchFPS, 1, 30 ); - scratchJitter = Mathf.Clamp( scratchJitter, 0.0f, 1.0f ); - grainSize = Mathf.Clamp( grainSize, 0.1f, 50.0f ); + grainIntensityMin = Mathf.Clamp(grainIntensityMin, 0.0f, 5.0f); + grainIntensityMax = Mathf.Clamp(grainIntensityMax, 0.0f, 5.0f); + scratchIntensityMin = Mathf.Clamp(scratchIntensityMin, 0.0f, 5.0f); + scratchIntensityMax = Mathf.Clamp(scratchIntensityMax, 0.0f, 5.0f); + scratchFPS = Mathf.Clamp(scratchFPS, 1, 30); + scratchJitter = Mathf.Clamp(scratchJitter, 0.0f, 1.0f); + grainSize = Mathf.Clamp(grainSize, 0.1f, 50.0f); } // Called by the camera to apply the image effect - void OnRenderImage (RenderTexture source, RenderTexture destination) + void OnRenderImage(RenderTexture source, RenderTexture destination) { SanitizeParameters(); - if ( scratchTimeLeft <= 0.0f ) + if (scratchTimeLeft <= 0.0f) { scratchTimeLeft = Random.value * 2 / scratchFPS; // we have sanitized it earlier, won't be zero scratchX = Random.value; @@ -120,23 +129,34 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) mat.SetTexture("_GrainTex", grainTexture); mat.SetTexture("_ScratchTex", scratchTexture); float grainScale = 1.0f / grainSize; // we have sanitized it earlier, won't be zero - mat.SetVector("_GrainOffsetScale", new Vector4( - Random.value, - Random.value, - (float)Screen.width / (float)grainTexture.width * grainScale, - (float)Screen.height / (float)grainTexture.height * grainScale - )); - mat.SetVector("_ScratchOffsetScale", new Vector4( - scratchX + Random.value*scratchJitter, - scratchY + Random.value*scratchJitter, - (float)Screen.width / (float) scratchTexture.width, - (float)Screen.height / (float) scratchTexture.height - )); - mat.SetVector("_Intensity", new Vector4( - Random.Range(grainIntensityMin, grainIntensityMax), - Random.Range(scratchIntensityMin, scratchIntensityMax), - 0, 0 )); - Graphics.Blit (source, destination, mat); + mat.SetVector( + "_GrainOffsetScale", + new Vector4( + Random.value, + Random.value, + (float)Screen.width / (float)grainTexture.width * grainScale, + (float)Screen.height / (float)grainTexture.height * grainScale + ) + ); + mat.SetVector( + "_ScratchOffsetScale", + new Vector4( + scratchX + Random.value * scratchJitter, + scratchY + Random.value * scratchJitter, + (float)Screen.width / (float)scratchTexture.width, + (float)Screen.height / (float)scratchTexture.height + ) + ); + mat.SetVector( + "_Intensity", + new Vector4( + Random.Range(grainIntensityMin, grainIntensityMax), + Random.Range(scratchIntensityMin, scratchIntensityMax), + 0, + 0 + ) + ); + Graphics.Blit(source, destination, mat); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/PostEffectsBase.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/PostEffectsBase.cs index 6762ee9f0b..c13ceb3f54 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/PostEffectsBase.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/PostEffectsBase.cs @@ -5,20 +5,20 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] + [RequireComponent(typeof(Camera))] public class PostEffectsBase : MonoBehaviour - { - protected bool supportHDRTextures = true; - protected bool supportDX11 = false; - protected bool isSupported = true; + { + protected bool supportHDRTextures = true; + protected bool supportDX11 = false; + protected bool isSupported = true; - private List createdMaterials = new List (); + private List createdMaterials = new List(); - protected Material CheckShaderAndCreateMaterial ( Shader s, Material m2Create) - { + protected Material CheckShaderAndCreateMaterial(Shader s, Material m2Create) + { if (!s) - { - Debug.Log("Missing shader in " + ToString ()); + { + Debug.Log("Missing shader in " + ToString()); enabled = false; return null; } @@ -27,25 +27,30 @@ protected Material CheckShaderAndCreateMaterial ( Shader s, Material m2Create) return m2Create; if (!s.isSupported) - { - NotSupported (); - Debug.Log("The shader " + s.ToString() + " on effect "+ToString()+" is not supported on this platform!"); + { + NotSupported(); + Debug.Log( + "The shader " + + s.ToString() + + " on effect " + + ToString() + + " is not supported on this platform!" + ); return null; } - m2Create = new Material (s); - createdMaterials.Add (m2Create); + m2Create = new Material(s); + createdMaterials.Add(m2Create); m2Create.hideFlags = HideFlags.DontSave; return m2Create; - } - + } - protected Material CreateMaterial (Shader s, Material m2Create) - { + protected Material CreateMaterial(Shader s, Material m2Create) + { if (!s) - { - Debug.Log ("Missing shader in " + ToString ()); + { + Debug.Log("Missing shader in " + ToString()); return null; } @@ -53,74 +58,74 @@ protected Material CreateMaterial (Shader s, Material m2Create) return m2Create; if (!s.isSupported) - { + { return null; } - m2Create = new Material (s); - createdMaterials.Add (m2Create); + m2Create = new Material(s); + createdMaterials.Add(m2Create); m2Create.hideFlags = HideFlags.DontSave; - + return m2Create; - } + } - void OnEnable () - { + void OnEnable() + { isSupported = true; } - void OnDestroy () + void OnDestroy() { - RemoveCreatedMaterials (); + RemoveCreatedMaterials(); } - private void RemoveCreatedMaterials () + private void RemoveCreatedMaterials() { while (createdMaterials.Count > 0) { Material mat = createdMaterials[0]; - createdMaterials.RemoveAt (0); + createdMaterials.RemoveAt(0); #if UNITY_EDITOR - DestroyImmediate (mat); + DestroyImmediate(mat); #else Destroy(mat); #endif } } - protected bool CheckSupport () - { - return CheckSupport (false); + protected bool CheckSupport() + { + return CheckSupport(false); } - - public virtual bool CheckResources () - { - Debug.LogWarning ("CheckResources () for " + ToString() + " should be overwritten."); + public virtual bool CheckResources() + { + Debug.LogWarning("CheckResources () for " + ToString() + " should be overwritten."); return isSupported; } - - protected void Start () - { - CheckResources (); + protected void Start() + { + CheckResources(); } - protected bool CheckSupport (bool needDepth) - { + protected bool CheckSupport(bool needDepth) + { isSupported = true; - supportHDRTextures = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf); + supportHDRTextures = SystemInfo.SupportsRenderTextureFormat( + RenderTextureFormat.ARGBHalf + ); supportDX11 = SystemInfo.graphicsShaderLevel >= 50 && SystemInfo.supportsComputeShaders; // if (!SystemInfo.supportsImageEffects) - // { + // { // NotSupported (); // return false; // } - if (needDepth && !SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.Depth)) - { - NotSupported (); + if (needDepth && !SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.Depth)) + { + NotSupported(); return false; } @@ -130,65 +135,71 @@ protected bool CheckSupport (bool needDepth) return true; } - protected bool CheckSupport (bool needDepth, bool needHdr) - { + protected bool CheckSupport(bool needDepth, bool needHdr) + { if (!CheckSupport(needDepth)) return false; if (needHdr && !supportHDRTextures) - { - NotSupported (); + { + NotSupported(); return false; } return true; } - - public bool Dx11Support () - { + public bool Dx11Support() + { return supportDX11; } - - protected void ReportAutoDisable () - { - Debug.LogWarning ("The image effect " + ToString() + " has been disabled as it's not supported on the current platform."); + protected void ReportAutoDisable() + { + Debug.LogWarning( + "The image effect " + + ToString() + + " has been disabled as it's not supported on the current platform." + ); } // deprecated but needed for old effects to survive upgrading - bool CheckShader (Shader s) - { - Debug.Log("The shader " + s.ToString () + " on effect "+ ToString () + " is not part of the Unity 3.2+ effects suite anymore. For best performance and quality, please ensure you are using the latest Standard Assets Image Effects (Pro only) package."); + bool CheckShader(Shader s) + { + Debug.Log( + "The shader " + + s.ToString() + + " on effect " + + ToString() + + " is not part of the Unity 3.2+ effects suite anymore. For best performance and quality, please ensure you are using the latest Standard Assets Image Effects (Pro only) package." + ); if (!s.isSupported) - { - NotSupported (); + { + NotSupported(); return false; } else - { + { return false; } } - - protected void NotSupported () - { + protected void NotSupported() + { enabled = false; isSupported = false; return; } - - protected void DrawBorder (RenderTexture dest, Material material) - { + protected void DrawBorder(RenderTexture dest, Material material) + { float x1; float x2; float y1; float y2; RenderTexture.active = dest; - bool invertY = true; // source.texelSize.y < 0.0ff; + bool invertY = true; // source.texelSize.y < 0.0ff; // Set up the simple Matrix GL.PushMatrix(); GL.LoadOrtho(); @@ -197,60 +208,79 @@ protected void DrawBorder (RenderTexture dest, Material material) { material.SetPass(i); - float y1_; float y2_; + float y1_; + float y2_; if (invertY) { - y1_ = 1.0f; y2_ = 0.0f; + y1_ = 1.0f; + y2_ = 0.0f; } else { - y1_ = 0.0f; y2_ = 1.0f; + y1_ = 0.0f; + y2_ = 1.0f; } // left x1 = 0.0f; - x2 = 0.0f + 1.0f/(dest.width*1.0f); + x2 = 0.0f + 1.0f / (dest.width * 1.0f); y1 = 0.0f; y2 = 1.0f; GL.Begin(GL.QUADS); - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); + GL.TexCoord2(0.0f, y1_); + GL.Vertex3(x1, y1, 0.1f); + GL.TexCoord2(1.0f, y1_); + GL.Vertex3(x2, y1, 0.1f); + GL.TexCoord2(1.0f, y2_); + GL.Vertex3(x2, y2, 0.1f); + GL.TexCoord2(0.0f, y2_); + GL.Vertex3(x1, y2, 0.1f); // right - x1 = 1.0f - 1.0f/(dest.width*1.0f); + x1 = 1.0f - 1.0f / (dest.width * 1.0f); x2 = 1.0f; y1 = 0.0f; y2 = 1.0f; - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); + GL.TexCoord2(0.0f, y1_); + GL.Vertex3(x1, y1, 0.1f); + GL.TexCoord2(1.0f, y1_); + GL.Vertex3(x2, y1, 0.1f); + GL.TexCoord2(1.0f, y2_); + GL.Vertex3(x2, y2, 0.1f); + GL.TexCoord2(0.0f, y2_); + GL.Vertex3(x1, y2, 0.1f); // top x1 = 0.0f; x2 = 1.0f; y1 = 0.0f; - y2 = 0.0f + 1.0f/(dest.height*1.0f); + y2 = 0.0f + 1.0f / (dest.height * 1.0f); - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); + GL.TexCoord2(0.0f, y1_); + GL.Vertex3(x1, y1, 0.1f); + GL.TexCoord2(1.0f, y1_); + GL.Vertex3(x2, y1, 0.1f); + GL.TexCoord2(1.0f, y2_); + GL.Vertex3(x2, y2, 0.1f); + GL.TexCoord2(0.0f, y2_); + GL.Vertex3(x1, y2, 0.1f); // bottom x1 = 0.0f; x2 = 1.0f; - y1 = 1.0f - 1.0f/(dest.height*1.0f); + y1 = 1.0f - 1.0f / (dest.height * 1.0f); y2 = 1.0f; - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); + GL.TexCoord2(0.0f, y1_); + GL.Vertex3(x1, y1, 0.1f); + GL.TexCoord2(1.0f, y1_); + GL.Vertex3(x2, y1, 0.1f); + GL.TexCoord2(1.0f, y2_); + GL.Vertex3(x2, y2, 0.1f); + GL.TexCoord2(0.0f, y2_); + GL.Vertex3(x1, y2, 0.1f); GL.End(); } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/PostEffectsHelper.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/PostEffectsHelper.cs index a935c16dbe..c0a2dc4338 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/PostEffectsHelper.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/PostEffectsHelper.cs @@ -4,25 +4,27 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] + [RequireComponent(typeof(Camera))] class PostEffectsHelper : MonoBehaviour { - void OnRenderImage (RenderTexture source, RenderTexture destination) + void OnRenderImage(RenderTexture source, RenderTexture destination) { Debug.Log("OnRenderImage in Helper called ..."); } - static void DrawLowLevelPlaneAlignedWithCamera ( - float dist , - RenderTexture source, RenderTexture dest , - Material material , - Camera cameraForProjectionMatrix ) + static void DrawLowLevelPlaneAlignedWithCamera( + float dist, + RenderTexture source, + RenderTexture dest, + Material material, + Camera cameraForProjectionMatrix + ) { // Make the destination texture the target for all rendering RenderTexture.active = dest; // Assign the source texture to a property from a shader material.SetTexture("_MainTex", source); - bool invertY = true; // source.texelSize.y < 0.0f; + bool invertY = true; // source.texelSize.y < 0.0f; // Set up the simple Matrix GL.PushMatrix(); GL.LoadIdentity(); @@ -32,10 +34,10 @@ static void DrawLowLevelPlaneAlignedWithCamera ( float cotangent = Mathf.Cos(fovYHalfRad) / Mathf.Sin(fovYHalfRad); float asp = cameraForProjectionMatrix.aspect; - float x1 = asp/-cotangent; - float x2 = asp/cotangent; - float y1 = 1.0f/-cotangent; - float y2 = 1.0f/cotangent; + float x1 = asp / -cotangent; + float x2 = asp / cotangent; + float y1 = 1.0f / -cotangent; + float y2 = 1.0f / cotangent; float sc = 1.0f; // magic constant (for now) @@ -51,36 +53,41 @@ static void DrawLowLevelPlaneAlignedWithCamera ( material.SetPass(i); GL.Begin(GL.QUADS); - float y1_; float y2_; + float y1_; + float y2_; if (invertY) { - y1_ = 1.0f; y2_ = 0.0f; + y1_ = 1.0f; + y2_ = 0.0f; } else { - y1_ = 0.0f; y2_ = 1.0f; + y1_ = 0.0f; + y2_ = 1.0f; } - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, z1); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, z1); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, z1); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, z1); + GL.TexCoord2(0.0f, y1_); + GL.Vertex3(x1, y1, z1); + GL.TexCoord2(1.0f, y1_); + GL.Vertex3(x2, y1, z1); + GL.TexCoord2(1.0f, y2_); + GL.Vertex3(x2, y2, z1); + GL.TexCoord2(0.0f, y2_); + GL.Vertex3(x1, y2, z1); GL.End(); } GL.PopMatrix(); } - static void DrawBorder ( - RenderTexture dest , - Material material ) - { + static void DrawBorder(RenderTexture dest, Material material) + { float x1; float x2; float y1; float y2; RenderTexture.active = dest; - bool invertY = true; // source.texelSize.y < 0.0ff; + bool invertY = true; // source.texelSize.y < 0.0ff; // Set up the simple Matrix GL.PushMatrix(); GL.LoadOrtho(); @@ -89,60 +96,79 @@ static void DrawBorder ( { material.SetPass(i); - float y1_; float y2_; + float y1_; + float y2_; if (invertY) { - y1_ = 1.0f; y2_ = 0.0f; + y1_ = 1.0f; + y2_ = 0.0f; } else { - y1_ = 0.0f; y2_ = 1.0f; + y1_ = 0.0f; + y2_ = 1.0f; } // left x1 = 0.0f; - x2 = 0.0f + 1.0f/(dest.width*1.0f); + x2 = 0.0f + 1.0f / (dest.width * 1.0f); y1 = 0.0f; y2 = 1.0f; GL.Begin(GL.QUADS); - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); + GL.TexCoord2(0.0f, y1_); + GL.Vertex3(x1, y1, 0.1f); + GL.TexCoord2(1.0f, y1_); + GL.Vertex3(x2, y1, 0.1f); + GL.TexCoord2(1.0f, y2_); + GL.Vertex3(x2, y2, 0.1f); + GL.TexCoord2(0.0f, y2_); + GL.Vertex3(x1, y2, 0.1f); // right - x1 = 1.0f - 1.0f/(dest.width*1.0f); + x1 = 1.0f - 1.0f / (dest.width * 1.0f); x2 = 1.0f; y1 = 0.0f; y2 = 1.0f; - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); + GL.TexCoord2(0.0f, y1_); + GL.Vertex3(x1, y1, 0.1f); + GL.TexCoord2(1.0f, y1_); + GL.Vertex3(x2, y1, 0.1f); + GL.TexCoord2(1.0f, y2_); + GL.Vertex3(x2, y2, 0.1f); + GL.TexCoord2(0.0f, y2_); + GL.Vertex3(x1, y2, 0.1f); // top x1 = 0.0f; x2 = 1.0f; y1 = 0.0f; - y2 = 0.0f + 1.0f/(dest.height*1.0f); + y2 = 0.0f + 1.0f / (dest.height * 1.0f); - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); + GL.TexCoord2(0.0f, y1_); + GL.Vertex3(x1, y1, 0.1f); + GL.TexCoord2(1.0f, y1_); + GL.Vertex3(x2, y1, 0.1f); + GL.TexCoord2(1.0f, y2_); + GL.Vertex3(x2, y2, 0.1f); + GL.TexCoord2(0.0f, y2_); + GL.Vertex3(x1, y2, 0.1f); // bottom x1 = 0.0f; x2 = 1.0f; - y1 = 1.0f - 1.0f/(dest.height*1.0f); + y1 = 1.0f - 1.0f / (dest.height * 1.0f); y2 = 1.0f; - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); + GL.TexCoord2(0.0f, y1_); + GL.Vertex3(x1, y1, 0.1f); + GL.TexCoord2(1.0f, y1_); + GL.Vertex3(x2, y1, 0.1f); + GL.TexCoord2(1.0f, y2_); + GL.Vertex3(x2, y2, 0.1f); + GL.TexCoord2(0.0f, y2_); + GL.Vertex3(x1, y2, 0.1f); GL.End(); } @@ -150,13 +176,21 @@ static void DrawBorder ( GL.PopMatrix(); } - static void DrawLowLevelQuad ( float x1, float x2, float y1, float y2, RenderTexture source, RenderTexture dest, Material material ) - { + static void DrawLowLevelQuad( + float x1, + float x2, + float y1, + float y2, + RenderTexture source, + RenderTexture dest, + Material material + ) + { // Make the destination texture the target for all rendering RenderTexture.active = dest; // Assign the source texture to a property from a shader material.SetTexture("_MainTex", source); - bool invertY = true; // source.texelSize.y < 0.0f; + bool invertY = true; // source.texelSize.y < 0.0f; // Set up the simple Matrix GL.PushMatrix(); GL.LoadOrtho(); @@ -166,19 +200,26 @@ static void DrawLowLevelQuad ( float x1, float x2, float y1, float y2, RenderTe material.SetPass(i); GL.Begin(GL.QUADS); - float y1_; float y2_; + float y1_; + float y2_; if (invertY) { - y1_ = 1.0f; y2_ = 0.0f; + y1_ = 1.0f; + y2_ = 0.0f; } else { - y1_ = 0.0f; y2_ = 1.0f; + y1_ = 0.0f; + y2_ = 1.0f; } - GL.TexCoord2(0.0f, y1_); GL.Vertex3(x1, y1, 0.1f); - GL.TexCoord2(1.0f, y1_); GL.Vertex3(x2, y1, 0.1f); - GL.TexCoord2(1.0f, y2_); GL.Vertex3(x2, y2, 0.1f); - GL.TexCoord2(0.0f, y2_); GL.Vertex3(x1, y2, 0.1f); + GL.TexCoord2(0.0f, y1_); + GL.Vertex3(x1, y1, 0.1f); + GL.TexCoord2(1.0f, y1_); + GL.Vertex3(x2, y1, 0.1f); + GL.TexCoord2(1.0f, y2_); + GL.Vertex3(x2, y2, 0.1f); + GL.TexCoord2(0.0f, y2_); + GL.Vertex3(x1, y2, 0.1f); GL.End(); } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Quads.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Quads.cs index e48a19d495..d155b9b0be 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Quads.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Quads.cs @@ -11,7 +11,7 @@ class Quads static Mesh[] meshes; static int currentQuads = 0; - static bool HasMeshes () + static bool HasMeshes() { if (meshes == null) return false; @@ -21,8 +21,7 @@ static bool HasMeshes () return true; } - - public static void Cleanup () + public static void Cleanup() { if (meshes == null) return; @@ -31,17 +30,17 @@ public static void Cleanup () { if (null != meshes[i]) { - Object.DestroyImmediate (meshes[i]); + Object.DestroyImmediate(meshes[i]); meshes[i] = null; } } meshes = null; } - - public static Mesh[] GetMeshes ( int totalWidth, int totalHeight) + public static Mesh[] GetMeshes(int totalWidth, int totalHeight) { - if (HasMeshes () && (currentQuads == (totalWidth * totalHeight))) { + if (HasMeshes() && (currentQuads == (totalWidth * totalHeight))) + { return meshes; } @@ -49,26 +48,26 @@ public static Mesh[] GetMeshes ( int totalWidth, int totalHeight) int totalQuads = totalWidth * totalHeight; currentQuads = totalQuads; - int meshCount = Mathf.CeilToInt ((1.0f * totalQuads) / (1.0f * maxQuads)); + int meshCount = Mathf.CeilToInt((1.0f * totalQuads) / (1.0f * maxQuads)); - meshes = new Mesh [meshCount]; + meshes = new Mesh[meshCount]; int i = 0; int index = 0; for (i = 0; i < totalQuads; i += maxQuads) { - int quads = Mathf.FloorToInt (Mathf.Clamp ((totalQuads-i), 0, maxQuads)); + int quads = Mathf.FloorToInt(Mathf.Clamp((totalQuads - i), 0, maxQuads)); - meshes[index] = GetMesh (quads, i, totalWidth, totalHeight); + meshes[index] = GetMesh(quads, i, totalWidth, totalHeight); index++; } return meshes; } - static Mesh GetMesh (int triCount, int triOffset, int totalWidth, int totalHeight) + static Mesh GetMesh(int triCount, int triOffset, int totalWidth, int totalHeight) { - var mesh = new Mesh (); + var mesh = new Mesh(); mesh.hideFlags = HideFlags.DontSave; var verts = new Vector3[triCount * 4]; @@ -83,25 +82,25 @@ static Mesh GetMesh (int triCount, int triOffset, int totalWidth, int totalHeigh int vertexWithOffset = triOffset + i; - float x = Mathf.Floor (vertexWithOffset % totalWidth) / totalWidth; - float y = Mathf.Floor (vertexWithOffset / totalWidth) / totalHeight; + float x = Mathf.Floor(vertexWithOffset % totalWidth) / totalWidth; + float y = Mathf.Floor(vertexWithOffset / totalWidth) / totalHeight; - Vector3 position = new Vector3 (x * 2 - 1, y * 2 - 1, 1.0f); + Vector3 position = new Vector3(x * 2 - 1, y * 2 - 1, 1.0f); verts[i4 + 0] = position; verts[i4 + 1] = position; verts[i4 + 2] = position; verts[i4 + 3] = position; - uvs[i4 + 0] = new Vector2 (0.0f, 0.0f); - uvs[i4 + 1] = new Vector2 (1.0f, 0.0f); - uvs[i4 + 2] = new Vector2 (0.0f, 1.0f); - uvs[i4 + 3] = new Vector2 (1.0f, 1.0f); + uvs[i4 + 0] = new Vector2(0.0f, 0.0f); + uvs[i4 + 1] = new Vector2(1.0f, 0.0f); + uvs[i4 + 2] = new Vector2(0.0f, 1.0f); + uvs[i4 + 3] = new Vector2(1.0f, 1.0f); - uvs2[i4 + 0] = new Vector2 (x, y); - uvs2[i4 + 1] = new Vector2 (x, y); - uvs2[i4 + 2] = new Vector2 (x, y); - uvs2[i4 + 3] = new Vector2 (x, y); + uvs2[i4 + 0] = new Vector2(x, y); + uvs2[i4 + 1] = new Vector2(x, y); + uvs2[i4 + 2] = new Vector2(x, y); + uvs2[i4 + 3] = new Vector2(x, y); tris[i6 + 0] = i4 + 0; tris[i6 + 1] = i4 + 1; @@ -110,7 +109,6 @@ static Mesh GetMesh (int triCount, int triOffset, int totalWidth, int totalHeigh tris[i6 + 3] = i4 + 1; tris[i6 + 4] = i4 + 2; tris[i6 + 5] = i4 + 3; - } mesh.vertices = verts; @@ -120,6 +118,5 @@ static Mesh GetMesh (int triCount, int triOffset, int totalWidth, int totalHeigh return mesh; } - } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ScreenOverlay.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ScreenOverlay.cs index f0cd0757dd..afb88cba8a 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ScreenOverlay.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ScreenOverlay.cs @@ -4,12 +4,12 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Other/Screen Overlay")] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Other/Screen Overlay")] public class ScreenOverlay : PostEffectsBase - { - public enum OverlayBlendMode - { + { + public enum OverlayBlendMode + { Additive = 0, ScreenBlend = 1, Multiply = 2, @@ -24,46 +24,48 @@ public enum OverlayBlendMode public Shader overlayShader = null; private Material overlayMaterial = null; + public override bool CheckResources() + { + CheckSupport(false); - public override bool CheckResources () - { - CheckSupport (false); + overlayMaterial = CheckShaderAndCreateMaterial(overlayShader, overlayMaterial); - overlayMaterial = CheckShaderAndCreateMaterial (overlayShader, overlayMaterial); - - if (!isSupported) - ReportAutoDisable (); + if (!isSupported) + ReportAutoDisable(); return isSupported; } - void OnRenderImage (RenderTexture source, RenderTexture destination) - { + void OnRenderImage(RenderTexture source, RenderTexture destination) + { if (CheckResources() == false) - { - Graphics.Blit (source, destination); + { + Graphics.Blit(source, destination); return; } - Vector4 UV_Transform = new Vector4(1, 0, 0, 1); + Vector4 UV_Transform = new Vector4(1, 0, 0, 1); - #if UNITY_WP8 - // WP8 has no OS support for rotating screen with device orientation, - // so we do those transformations ourselves. - if (Screen.orientation == ScreenOrientation.LandscapeLeft) { - UV_Transform = new Vector4(0, -1, 1, 0); - } - if (Screen.orientation == ScreenOrientation.LandscapeRight) { - UV_Transform = new Vector4(0, 1, -1, 0); - } - if (Screen.orientation == ScreenOrientation.PortraitUpsideDown) { - UV_Transform = new Vector4(-1, 0, 0, -1); - } - #endif +#if UNITY_WP8 + // WP8 has no OS support for rotating screen with device orientation, + // so we do those transformations ourselves. + if (Screen.orientation == ScreenOrientation.LandscapeLeft) + { + UV_Transform = new Vector4(0, -1, 1, 0); + } + if (Screen.orientation == ScreenOrientation.LandscapeRight) + { + UV_Transform = new Vector4(0, 1, -1, 0); + } + if (Screen.orientation == ScreenOrientation.PortraitUpsideDown) + { + UV_Transform = new Vector4(-1, 0, 0, -1); + } +#endif overlayMaterial.SetVector("_UV_Transform", UV_Transform); - overlayMaterial.SetFloat ("_Intensity", intensity); - overlayMaterial.SetTexture ("_Overlay", texture); - Graphics.Blit (source, destination, overlayMaterial, (int) blendMode); + overlayMaterial.SetFloat("_Intensity", intensity); + overlayMaterial.SetTexture("_Overlay", texture); + Graphics.Blit(source, destination, overlayMaterial, (int)blendMode); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ScreenSpaceAmbientObscurance.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ScreenSpaceAmbientObscurance.cs index b876fef731..24bfd03c96 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ScreenSpaceAmbientObscurance.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ScreenSpaceAmbientObscurance.cs @@ -3,121 +3,135 @@ namespace UnityStandardAssets.ImageEffects { - [ ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Rendering/Screen Space Ambient Obscurance")] - class ScreenSpaceAmbientObscurance : PostEffectsBase { - [Range (0,3)] + [ExecuteInEditMode] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Rendering/Screen Space Ambient Obscurance")] + class ScreenSpaceAmbientObscurance : PostEffectsBase + { + [Range(0, 3)] public float intensity = 0.5f; - [Range (0.1f,3)] + + [Range(0.1f, 3)] public float radius = 0.2f; - [Range (0,3)] + + [Range(0, 3)] public int blurIterations = 1; - [Range (0,5)] + + [Range(0, 5)] public float blurFilterDistance = 1.25f; - [Range (0,1)] + + [Range(0, 1)] public int downsample = 0; public Texture2D rand = null; - public Shader aoShader= null; + public Shader aoShader = null; private Material aoMaterial = null; - public override bool CheckResources () { - CheckSupport (true); + public override bool CheckResources() + { + CheckSupport(true); - aoMaterial = CheckShaderAndCreateMaterial (aoShader, aoMaterial); + aoMaterial = CheckShaderAndCreateMaterial(aoShader, aoMaterial); if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - void OnDisable () { + void OnDisable() + { if (aoMaterial) - DestroyImmediate (aoMaterial); + DestroyImmediate(aoMaterial); aoMaterial = null; } [ImageEffectOpaque] - void OnRenderImage (RenderTexture source, RenderTexture destination) { - if (CheckResources () == false) { - Graphics.Blit (source, destination); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (CheckResources() == false) + { + Graphics.Blit(source, destination); return; } - Camera camera = GetComponent(); + Camera camera = GetComponent(); Matrix4x4 P = camera.projectionMatrix; - var invP= P.inverse; - Vector4 projInfo = new Vector4 - ((-2.0f / P[0,0]), - (-2.0f / P[1,1]), - ((1.0f - P[0,2]) / P[0,0]), - ((1.0f + P[1,2]) / P[1,1])); - - if (camera.stereoEnabled) - { - Matrix4x4 P0 = camera.GetStereoProjectionMatrix(Camera.StereoscopicEye.Left); - Matrix4x4 P1 = camera.GetStereoProjectionMatrix(Camera.StereoscopicEye.Right); - - Vector4 projInfo0 = new Vector4 - ((-2.0f / (P0[0, 0])), - (-2.0f / (P0[1, 1])), - ((1.0f - P0[0, 2]) / P0[0, 0]), - ((1.0f + P0[1, 2]) / P0[1, 1])); - - Vector4 projInfo1 = new Vector4 - ((-2.0f / (P1[0, 0])), - (-2.0f / (P1[1, 1])), - ((1.0f - P1[0, 2]) / P1[0, 0]), - ((1.0f + P1[1, 2]) / P1[1, 1])); - - aoMaterial.SetVector("_ProjInfoLeft", projInfo0); // used for unprojection - aoMaterial.SetVector("_ProjInfoRight", projInfo1); // used for unprojection - } - - aoMaterial.SetVector ("_ProjInfo", projInfo); // used for unprojection - aoMaterial.SetMatrix ("_ProjectionInv", invP); // only used for reference - aoMaterial.SetTexture ("_Rand", rand); // not needed for DX11 :) - aoMaterial.SetFloat ("_Radius", radius); - aoMaterial.SetFloat ("_Radius2", radius*radius); - aoMaterial.SetFloat ("_Intensity", intensity); - aoMaterial.SetFloat ("_BlurFilterDistance", blurFilterDistance); + var invP = P.inverse; + Vector4 projInfo = new Vector4( + (-2.0f / P[0, 0]), + (-2.0f / P[1, 1]), + ((1.0f - P[0, 2]) / P[0, 0]), + ((1.0f + P[1, 2]) / P[1, 1]) + ); + + if (camera.stereoEnabled) + { + Matrix4x4 P0 = camera.GetStereoProjectionMatrix(Camera.StereoscopicEye.Left); + Matrix4x4 P1 = camera.GetStereoProjectionMatrix(Camera.StereoscopicEye.Right); + + Vector4 projInfo0 = new Vector4( + (-2.0f / (P0[0, 0])), + (-2.0f / (P0[1, 1])), + ((1.0f - P0[0, 2]) / P0[0, 0]), + ((1.0f + P0[1, 2]) / P0[1, 1]) + ); + + Vector4 projInfo1 = new Vector4( + (-2.0f / (P1[0, 0])), + (-2.0f / (P1[1, 1])), + ((1.0f - P1[0, 2]) / P1[0, 0]), + ((1.0f + P1[1, 2]) / P1[1, 1]) + ); + + aoMaterial.SetVector("_ProjInfoLeft", projInfo0); // used for unprojection + aoMaterial.SetVector("_ProjInfoRight", projInfo1); // used for unprojection + } + + aoMaterial.SetVector("_ProjInfo", projInfo); // used for unprojection + aoMaterial.SetMatrix("_ProjectionInv", invP); // only used for reference + aoMaterial.SetTexture("_Rand", rand); // not needed for DX11 :) + aoMaterial.SetFloat("_Radius", radius); + aoMaterial.SetFloat("_Radius2", radius * radius); + aoMaterial.SetFloat("_Intensity", intensity); + aoMaterial.SetFloat("_BlurFilterDistance", blurFilterDistance); int rtW = source.width; int rtH = source.height; - RenderTexture tmpRt = RenderTexture.GetTemporary (rtW>>downsample, rtH>>downsample); + RenderTexture tmpRt = RenderTexture.GetTemporary(rtW >> downsample, rtH >> downsample); RenderTexture tmpRt2; - Graphics.Blit (source, tmpRt, aoMaterial, 0); + Graphics.Blit(source, tmpRt, aoMaterial, 0); - if (downsample > 0) { - tmpRt2 = RenderTexture.GetTemporary (rtW, rtH); + if (downsample > 0) + { + tmpRt2 = RenderTexture.GetTemporary(rtW, rtH); Graphics.Blit(tmpRt, tmpRt2, aoMaterial, 4); - RenderTexture.ReleaseTemporary (tmpRt); + RenderTexture.ReleaseTemporary(tmpRt); tmpRt = tmpRt2; // @NOTE: it's probably worth a shot to blur in low resolution // instead with a bilat-upsample afterwards ... } - for (int i = 0; i < blurIterations; i++) { - aoMaterial.SetVector("_Axis", new Vector2(1.0f,0.0f)); - tmpRt2 = RenderTexture.GetTemporary (rtW, rtH); - Graphics.Blit (tmpRt, tmpRt2, aoMaterial, 1); - RenderTexture.ReleaseTemporary (tmpRt); - - aoMaterial.SetVector("_Axis", new Vector2(0.0f,1.0f)); - tmpRt = RenderTexture.GetTemporary (rtW, rtH); - Graphics.Blit (tmpRt2, tmpRt, aoMaterial, 1); - RenderTexture.ReleaseTemporary (tmpRt2); + for (int i = 0; i < blurIterations; i++) + { + aoMaterial.SetVector("_Axis", new Vector2(1.0f, 0.0f)); + tmpRt2 = RenderTexture.GetTemporary(rtW, rtH); + Graphics.Blit(tmpRt, tmpRt2, aoMaterial, 1); + RenderTexture.ReleaseTemporary(tmpRt); + + aoMaterial.SetVector("_Axis", new Vector2(0.0f, 1.0f)); + tmpRt = RenderTexture.GetTemporary(rtW, rtH); + Graphics.Blit(tmpRt2, tmpRt, aoMaterial, 1); + RenderTexture.ReleaseTemporary(tmpRt2); } - aoMaterial.SetTexture ("_AOTex", tmpRt); - Graphics.Blit (source, destination, aoMaterial, 2); + aoMaterial.SetTexture("_AOTex", tmpRt); + Graphics.Blit(source, destination, aoMaterial, 2); - RenderTexture.ReleaseTemporary (tmpRt); + RenderTexture.ReleaseTemporary(tmpRt); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ScreenSpaceAmbientOcclusion.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ScreenSpaceAmbientOcclusion.cs index 0b9aa797b5..579a64662c 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ScreenSpaceAmbientOcclusion.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/ScreenSpaceAmbientOcclusion.cs @@ -4,12 +4,12 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] + [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Rendering/Screen Space Ambient Occlusion")] public class ScreenSpaceAmbientOcclusion : MonoBehaviour { public enum SSAOSamples - { + { Low = 0, Medium = 1, High = 2, @@ -18,14 +18,19 @@ public enum SSAOSamples [Range(0.05f, 1.0f)] public float m_Radius = 0.4f; public SSAOSamples m_SampleCount = SSAOSamples.Medium; + [Range(0.5f, 4.0f)] public float m_OcclusionIntensity = 1.5f; + [Range(0, 4)] public int m_Blur = 2; - [Range(1,6)] + + [Range(1, 6)] public int m_Downsampling = 2; + [Range(0.2f, 2.0f)] public float m_OcclusionAttenuation = 1.0f; + [Range(0.00001f, 0.5f)] public float m_MinZ = 0.01f; @@ -36,27 +41,27 @@ public enum SSAOSamples private bool m_Supported; - private static Material CreateMaterial (Shader shader) + private static Material CreateMaterial(Shader shader) { if (!shader) return null; - Material m = new Material (shader); + Material m = new Material(shader); m.hideFlags = HideFlags.HideAndDontSave; return m; } - private static void DestroyMaterial (Material mat) + + private static void DestroyMaterial(Material mat) { if (mat) { - DestroyImmediate (mat); + DestroyImmediate(mat); mat = null; } } - void OnDisable() { - DestroyMaterial (m_SSAOMaterial); + DestroyMaterial(m_SSAOMaterial); } void Start() @@ -68,7 +73,7 @@ void Start() // return; // } - CreateMaterials (); + CreateMaterials(); if (!m_SSAOMaterial || m_SSAOMaterial.passCount != 5) { m_Supported = false; @@ -81,125 +86,142 @@ void Start() m_Supported = true; } - void OnEnable () { + void OnEnable() + { GetComponent().depthTextureMode |= DepthTextureMode.DepthNormals; } - private void CreateMaterials () + private void CreateMaterials() { if (!m_SSAOMaterial && m_SSAOShader.isSupported) { - m_SSAOMaterial = CreateMaterial (m_SSAOShader); - m_SSAOMaterial.SetTexture ("_RandomTexture", m_RandomTexture); + m_SSAOMaterial = CreateMaterial(m_SSAOShader); + m_SSAOMaterial.SetTexture("_RandomTexture", m_RandomTexture); } } [ImageEffectOpaque] - void OnRenderImage (RenderTexture source, RenderTexture destination) + void OnRenderImage(RenderTexture source, RenderTexture destination) { - if (!m_Supported || !m_SSAOShader.isSupported) { + if (!m_Supported || !m_SSAOShader.isSupported) + { enabled = false; return; } - CreateMaterials (); + CreateMaterials(); - m_Downsampling = Mathf.Clamp (m_Downsampling, 1, 6); - m_Radius = Mathf.Clamp (m_Radius, 0.05f, 1.0f); - m_MinZ = Mathf.Clamp (m_MinZ, 0.00001f, 0.5f); - m_OcclusionIntensity = Mathf.Clamp (m_OcclusionIntensity, 0.5f, 4.0f); - m_OcclusionAttenuation = Mathf.Clamp (m_OcclusionAttenuation, 0.2f, 2.0f); - m_Blur = Mathf.Clamp (m_Blur, 0, 4); + m_Downsampling = Mathf.Clamp(m_Downsampling, 1, 6); + m_Radius = Mathf.Clamp(m_Radius, 0.05f, 1.0f); + m_MinZ = Mathf.Clamp(m_MinZ, 0.00001f, 0.5f); + m_OcclusionIntensity = Mathf.Clamp(m_OcclusionIntensity, 0.5f, 4.0f); + m_OcclusionAttenuation = Mathf.Clamp(m_OcclusionAttenuation, 0.2f, 2.0f); + m_Blur = Mathf.Clamp(m_Blur, 0, 4); // Render SSAO term into a smaller texture - RenderTexture rtAO = RenderTexture.GetTemporary (source.width / m_Downsampling, source.height / m_Downsampling, 0); + RenderTexture rtAO = RenderTexture.GetTemporary( + source.width / m_Downsampling, + source.height / m_Downsampling, + 0 + ); float fovY = GetComponent().fieldOfView; float far = GetComponent().farClipPlane; - float y = Mathf.Tan (fovY * Mathf.Deg2Rad * 0.5f) * far; + float y = Mathf.Tan(fovY * Mathf.Deg2Rad * 0.5f) * far; float x = y * GetComponent().aspect; - m_SSAOMaterial.SetVector ("_FarCorner", new Vector3(x,y,far)); - int noiseWidth, noiseHeight; - if (m_RandomTexture) { + m_SSAOMaterial.SetVector("_FarCorner", new Vector3(x, y, far)); + int noiseWidth, + noiseHeight; + if (m_RandomTexture) + { noiseWidth = m_RandomTexture.width; noiseHeight = m_RandomTexture.height; - } else { - noiseWidth = 1; noiseHeight = 1; } - m_SSAOMaterial.SetVector ("_NoiseScale", new Vector3 ((float)rtAO.width / noiseWidth, (float)rtAO.height / noiseHeight, 0.0f)); - m_SSAOMaterial.SetVector ("_Params", new Vector4( - m_Radius, - m_MinZ, - 1.0f / m_OcclusionAttenuation, - m_OcclusionIntensity)); + else + { + noiseWidth = 1; + noiseHeight = 1; + } + m_SSAOMaterial.SetVector( + "_NoiseScale", + new Vector3((float)rtAO.width / noiseWidth, (float)rtAO.height / noiseHeight, 0.0f) + ); + m_SSAOMaterial.SetVector( + "_Params", + new Vector4(m_Radius, m_MinZ, 1.0f / m_OcclusionAttenuation, m_OcclusionIntensity) + ); bool doBlur = m_Blur > 0; - Graphics.Blit (doBlur ? null : source, rtAO, m_SSAOMaterial, (int)m_SampleCount); + Graphics.Blit(doBlur ? null : source, rtAO, m_SSAOMaterial, (int)m_SampleCount); if (doBlur) { // Blur SSAO horizontally - RenderTexture rtBlurX = RenderTexture.GetTemporary (source.width, source.height, 0); - m_SSAOMaterial.SetVector ("_TexelOffsetScale", - new Vector4 ((float)m_Blur / source.width, 0,0,0)); - m_SSAOMaterial.SetTexture ("_SSAO", rtAO); - Graphics.Blit (null, rtBlurX, m_SSAOMaterial, 3); - RenderTexture.ReleaseTemporary (rtAO); // original rtAO not needed anymore + RenderTexture rtBlurX = RenderTexture.GetTemporary(source.width, source.height, 0); + m_SSAOMaterial.SetVector( + "_TexelOffsetScale", + new Vector4((float)m_Blur / source.width, 0, 0, 0) + ); + m_SSAOMaterial.SetTexture("_SSAO", rtAO); + Graphics.Blit(null, rtBlurX, m_SSAOMaterial, 3); + RenderTexture.ReleaseTemporary(rtAO); // original rtAO not needed anymore // Blur SSAO vertically - RenderTexture rtBlurY = RenderTexture.GetTemporary (source.width, source.height, 0); - m_SSAOMaterial.SetVector ("_TexelOffsetScale", - new Vector4 (0, (float)m_Blur/source.height, 0,0)); - m_SSAOMaterial.SetTexture ("_SSAO", rtBlurX); - Graphics.Blit (source, rtBlurY, m_SSAOMaterial, 3); - RenderTexture.ReleaseTemporary (rtBlurX); // blurX RT not needed anymore + RenderTexture rtBlurY = RenderTexture.GetTemporary(source.width, source.height, 0); + m_SSAOMaterial.SetVector( + "_TexelOffsetScale", + new Vector4(0, (float)m_Blur / source.height, 0, 0) + ); + m_SSAOMaterial.SetTexture("_SSAO", rtBlurX); + Graphics.Blit(source, rtBlurY, m_SSAOMaterial, 3); + RenderTexture.ReleaseTemporary(rtBlurX); // blurX RT not needed anymore rtAO = rtBlurY; // AO is the blurred one now } // Modulate scene rendering with SSAO - m_SSAOMaterial.SetTexture ("_SSAO", rtAO); - Graphics.Blit (source, destination, m_SSAOMaterial, 4); + m_SSAOMaterial.SetTexture("_SSAO", rtAO); + Graphics.Blit(source, destination, m_SSAOMaterial, 4); - RenderTexture.ReleaseTemporary (rtAO); + RenderTexture.ReleaseTemporary(rtAO); } /* - private void CreateRandomTable (int count, float minLength) - { - Random.seed = 1337; - Vector3[] samples = new Vector3[count]; - // initial samples - for (int i = 0; i < count; ++i) - samples[i] = Random.onUnitSphere; - // energy minimization: push samples away from others - int iterations = 100; - while (iterations-- > 0) { - for (int i = 0; i < count; ++i) { - Vector3 vec = samples[i]; - Vector3 res = Vector3.zero; - // minimize with other samples - for (int j = 0; j < count; ++j) { - Vector3 force = vec - samples[j]; - float fac = Vector3.Dot (force, force); - if (fac > 0.00001f) - res += force * (1.0f / fac); - } - samples[i] = (samples[i] + res * 0.5f).normalized; - } - } - // now scale samples between minLength and 1.0 - for (int i = 0; i < count; ++i) { - samples[i] = samples[i] * Random.Range (minLength, 1.0f); - } - - string table = string.Format ("#define SAMPLE_COUNT {0}\n", count); - table += "const float3 RAND_SAMPLES[SAMPLE_COUNT] = {\n"; - for (int i = 0; i < count; ++i) { - Vector3 v = samples[i]; - table += string.Format("\tfloat3({0},{1},{2}),\n", v.x, v.y, v.z); - } - table += "};\n"; - Debug.Log (table); - } - */ + private void CreateRandomTable (int count, float minLength) + { + Random.seed = 1337; + Vector3[] samples = new Vector3[count]; + // initial samples + for (int i = 0; i < count; ++i) + samples[i] = Random.onUnitSphere; + // energy minimization: push samples away from others + int iterations = 100; + while (iterations-- > 0) { + for (int i = 0; i < count; ++i) { + Vector3 vec = samples[i]; + Vector3 res = Vector3.zero; + // minimize with other samples + for (int j = 0; j < count; ++j) { + Vector3 force = vec - samples[j]; + float fac = Vector3.Dot (force, force); + if (fac > 0.00001f) + res += force * (1.0f / fac); + } + samples[i] = (samples[i] + res * 0.5f).normalized; + } + } + // now scale samples between minLength and 1.0 + for (int i = 0; i < count; ++i) { + samples[i] = samples[i] * Random.Range (minLength, 1.0f); + } + + string table = string.Format ("#define SAMPLE_COUNT {0}\n", count); + table += "const float3 RAND_SAMPLES[SAMPLE_COUNT] = {\n"; + for (int i = 0; i < count; ++i) { + Vector3 v = samples[i]; + table += string.Format("\tfloat3({0},{1},{2}),\n", v.x, v.y, v.z); + } + table += "};\n"; + Debug.Log (table); + } + */ } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/SepiaTone.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/SepiaTone.cs index fa4edcd8c1..73ec1c1d65 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/SepiaTone.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/SepiaTone.cs @@ -6,11 +6,11 @@ namespace UnityStandardAssets.ImageEffects [ExecuteInEditMode] [AddComponentMenu("Image Effects/Color Adjustments/Sepia Tone")] public class SepiaTone : ImageEffectBase - { + { // Called by camera to apply image effect - void OnRenderImage (RenderTexture source, RenderTexture destination) - { - Graphics.Blit (source, destination, material); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + Graphics.Blit(source, destination, material); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/SunShafts.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/SunShafts.cs index 53f21e774c..7541ac530d 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/SunShafts.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/SunShafts.cs @@ -4,8 +4,8 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Rendering/Sun Shafts")] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Rendering/Sun Shafts")] public class SunShafts : PostEffectsBase { public enum SunShaftsResolution @@ -21,20 +21,19 @@ public enum ShaftsScreenBlendMode Add = 1, } - public SunShaftsResolution resolution = SunShaftsResolution.Normal; public ShaftsScreenBlendMode screenBlendMode = ShaftsScreenBlendMode.Screen; public Transform sunTransform; public int radialBlurIterations = 2; public Color sunColor = Color.white; - public Color sunThreshold = new Color(0.87f,0.74f,0.65f); + public Color sunThreshold = new Color(0.87f, 0.74f, 0.65f); public float sunShaftBlurRadius = 2.5f; public float sunShaftIntensity = 1.15f; public float maxRadius = 0.75f; - public bool useDepthTexture = true; + public bool useDepthTexture = true; public Shader sunShaftsShader; private Material sunShaftsMaterial; @@ -42,21 +41,26 @@ public enum ShaftsScreenBlendMode public Shader simpleClearShader; private Material simpleClearMaterial; + public override bool CheckResources() + { + CheckSupport(useDepthTexture); - public override bool CheckResources () { - CheckSupport (useDepthTexture); - - sunShaftsMaterial = CheckShaderAndCreateMaterial (sunShaftsShader, sunShaftsMaterial); - simpleClearMaterial = CheckShaderAndCreateMaterial (simpleClearShader, simpleClearMaterial); + sunShaftsMaterial = CheckShaderAndCreateMaterial(sunShaftsShader, sunShaftsMaterial); + simpleClearMaterial = CheckShaderAndCreateMaterial( + simpleClearShader, + simpleClearMaterial + ); if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - void OnRenderImage (RenderTexture source, RenderTexture destination) { - if (CheckResources()==false) { - Graphics.Blit (source, destination); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (CheckResources() == false) + { + Graphics.Blit(source, destination); return; } @@ -72,7 +76,7 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) { Vector3 v = Vector3.one * 0.5f; if (sunTransform) - v = GetComponent().WorldToViewportPoint (sunTransform.position); + v = GetComponent().WorldToViewportPoint(sunTransform.position); else v = new Vector3(0.5f, 0.5f, 0.0f); @@ -80,72 +84,95 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) { int rtH = source.height / divider; RenderTexture lrColorB; - RenderTexture lrDepthBuffer = RenderTexture.GetTemporary (rtW, rtH, 0); + RenderTexture lrDepthBuffer = RenderTexture.GetTemporary(rtW, rtH, 0); // mask out everything except the skybox // we have 2 methods, one of which requires depth buffer support, the other one is just comparing images - sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (1.0f, 1.0f, 0.0f, 0.0f) * sunShaftBlurRadius ); - sunShaftsMaterial.SetVector ("_SunPosition", new Vector4 (v.x, v.y, v.z, maxRadius)); - sunShaftsMaterial.SetVector ("_SunThreshold", sunThreshold); + sunShaftsMaterial.SetVector( + "_BlurRadius4", + new Vector4(1.0f, 1.0f, 0.0f, 0.0f) * sunShaftBlurRadius + ); + sunShaftsMaterial.SetVector("_SunPosition", new Vector4(v.x, v.y, v.z, maxRadius)); + sunShaftsMaterial.SetVector("_SunThreshold", sunThreshold); - if (!useDepthTexture) { + if (!useDepthTexture) + { #if UNITY_5_6_OR_NEWER - var format = GetComponent().allowHDR ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default; + var format = GetComponent().allowHDR + ? RenderTextureFormat.DefaultHDR + : RenderTextureFormat.Default; #else - var format = GetComponent().hdr ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default; + var format = GetComponent().hdr + ? RenderTextureFormat.DefaultHDR + : RenderTextureFormat.Default; #endif - RenderTexture tmpBuffer = RenderTexture.GetTemporary (source.width, source.height, 0, format); + RenderTexture tmpBuffer = RenderTexture.GetTemporary( + source.width, + source.height, + 0, + format + ); RenderTexture.active = tmpBuffer; - GL.ClearWithSkybox (false, GetComponent()); + GL.ClearWithSkybox(false, GetComponent()); - sunShaftsMaterial.SetTexture ("_Skybox", tmpBuffer); - Graphics.Blit (source, lrDepthBuffer, sunShaftsMaterial, 3); - RenderTexture.ReleaseTemporary (tmpBuffer); + sunShaftsMaterial.SetTexture("_Skybox", tmpBuffer); + Graphics.Blit(source, lrDepthBuffer, sunShaftsMaterial, 3); + RenderTexture.ReleaseTemporary(tmpBuffer); } - else { - Graphics.Blit (source, lrDepthBuffer, sunShaftsMaterial, 2); + else + { + Graphics.Blit(source, lrDepthBuffer, sunShaftsMaterial, 2); } // paint a small black small border to get rid of clamping problems - DrawBorder (lrDepthBuffer, simpleClearMaterial); + DrawBorder(lrDepthBuffer, simpleClearMaterial); // radial blur: - radialBlurIterations = Mathf.Clamp (radialBlurIterations, 1, 4); + radialBlurIterations = Mathf.Clamp(radialBlurIterations, 1, 4); float ofs = sunShaftBlurRadius * (1.0f / 768.0f); - sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f)); - sunShaftsMaterial.SetVector ("_SunPosition", new Vector4 (v.x, v.y, v.z, maxRadius)); + sunShaftsMaterial.SetVector("_BlurRadius4", new Vector4(ofs, ofs, 0.0f, 0.0f)); + sunShaftsMaterial.SetVector("_SunPosition", new Vector4(v.x, v.y, v.z, maxRadius)); - for (int it2 = 0; it2 < radialBlurIterations; it2++ ) { + for (int it2 = 0; it2 < radialBlurIterations; it2++) + { // each iteration takes 2 * 6 samples // we update _BlurRadius each time to cheaply get a very smooth look - lrColorB = RenderTexture.GetTemporary (rtW, rtH, 0); - Graphics.Blit (lrDepthBuffer, lrColorB, sunShaftsMaterial, 1); - RenderTexture.ReleaseTemporary (lrDepthBuffer); + lrColorB = RenderTexture.GetTemporary(rtW, rtH, 0); + Graphics.Blit(lrDepthBuffer, lrColorB, sunShaftsMaterial, 1); + RenderTexture.ReleaseTemporary(lrDepthBuffer); ofs = sunShaftBlurRadius * (((it2 * 2.0f + 1.0f) * 6.0f)) / 768.0f; - sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f) ); + sunShaftsMaterial.SetVector("_BlurRadius4", new Vector4(ofs, ofs, 0.0f, 0.0f)); - lrDepthBuffer = RenderTexture.GetTemporary (rtW, rtH, 0); - Graphics.Blit (lrColorB, lrDepthBuffer, sunShaftsMaterial, 1); - RenderTexture.ReleaseTemporary (lrColorB); + lrDepthBuffer = RenderTexture.GetTemporary(rtW, rtH, 0); + Graphics.Blit(lrColorB, lrDepthBuffer, sunShaftsMaterial, 1); + RenderTexture.ReleaseTemporary(lrColorB); ofs = sunShaftBlurRadius * (((it2 * 2.0f + 2.0f) * 6.0f)) / 768.0f; - sunShaftsMaterial.SetVector ("_BlurRadius4", new Vector4 (ofs, ofs, 0.0f, 0.0f) ); + sunShaftsMaterial.SetVector("_BlurRadius4", new Vector4(ofs, ofs, 0.0f, 0.0f)); } // put together: if (v.z >= 0.0f) - sunShaftsMaterial.SetVector ("_SunColor", new Vector4 (sunColor.r, sunColor.g, sunColor.b, sunColor.a) * sunShaftIntensity); + sunShaftsMaterial.SetVector( + "_SunColor", + new Vector4(sunColor.r, sunColor.g, sunColor.b, sunColor.a) * sunShaftIntensity + ); else - sunShaftsMaterial.SetVector ("_SunColor", Vector4.zero); // no backprojection ! - sunShaftsMaterial.SetTexture ("_ColorBuffer", lrDepthBuffer); - Graphics.Blit (source, destination, sunShaftsMaterial, (screenBlendMode == ShaftsScreenBlendMode.Screen) ? 0 : 4); - - RenderTexture.ReleaseTemporary (lrDepthBuffer); + sunShaftsMaterial.SetVector("_SunColor", Vector4.zero); // no backprojection ! + sunShaftsMaterial.SetTexture("_ColorBuffer", lrDepthBuffer); + Graphics.Blit( + source, + destination, + sunShaftsMaterial, + (screenBlendMode == ShaftsScreenBlendMode.Screen) ? 0 : 4 + ); + + RenderTexture.ReleaseTemporary(lrDepthBuffer); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/TiltShift.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/TiltShift.cs index e2045442c2..4dda902b50 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/TiltShift.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/TiltShift.cs @@ -3,18 +3,20 @@ namespace UnityStandardAssets.ImageEffects { - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Camera/Tilt Shift (Lens Blur)")] - class TiltShift : PostEffectsBase { + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Camera/Tilt Shift (Lens Blur)")] + class TiltShift : PostEffectsBase + { public enum TiltShiftMode { TiltShiftMode, IrisMode, } + public enum TiltShiftQuality { Preview, - Low, + Low, Normal, High, } @@ -34,20 +36,22 @@ public enum TiltShiftQuality public Shader tiltShiftShader = null; private Material tiltShiftMaterial = null; + public override bool CheckResources() + { + CheckSupport(false); - public override bool CheckResources () { - CheckSupport (false); - - tiltShiftMaterial = CheckShaderAndCreateMaterial (tiltShiftShader, tiltShiftMaterial); + tiltShiftMaterial = CheckShaderAndCreateMaterial(tiltShiftShader, tiltShiftMaterial); if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - void OnRenderImage (RenderTexture source, RenderTexture destination) { - if (CheckResources() == false) { - Graphics.Blit (source, destination); + void OnRenderImage(RenderTexture source, RenderTexture destination) + { + if (CheckResources() == false) + { + Graphics.Blit(source, destination); return; } @@ -56,21 +60,34 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) { source.filterMode = FilterMode.Bilinear; RenderTexture rt = destination; - if (downsample > 0f) { - rt = RenderTexture.GetTemporary (source.width>>downsample, source.height>>downsample, 0, source.format); + if (downsample > 0f) + { + rt = RenderTexture.GetTemporary( + source.width >> downsample, + source.height >> downsample, + 0, + source.format + ); rt.filterMode = FilterMode.Bilinear; } - int basePassNr = (int) quality; basePassNr *= 2; - Graphics.Blit (source, rt, tiltShiftMaterial, mode == TiltShiftMode.TiltShiftMode ? basePassNr : basePassNr + 1); - - if (downsample > 0) { - tiltShiftMaterial.SetTexture ("_Blurred", rt); - Graphics.Blit (source, destination, tiltShiftMaterial, 8); + int basePassNr = (int)quality; + basePassNr *= 2; + Graphics.Blit( + source, + rt, + tiltShiftMaterial, + mode == TiltShiftMode.TiltShiftMode ? basePassNr : basePassNr + 1 + ); + + if (downsample > 0) + { + tiltShiftMaterial.SetTexture("_Blurred", rt); + Graphics.Blit(source, destination, tiltShiftMaterial, 8); } if (rt != destination) - RenderTexture.ReleaseTemporary (rt); + RenderTexture.ReleaseTemporary(rt); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Tonemapping.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Tonemapping.cs index dec8e88f20..0dac359615 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Tonemapping.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Tonemapping.cs @@ -4,7 +4,7 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent(typeof (Camera))] + [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Color Adjustments/Tonemapping")] public class Tonemapping : PostEffectsBase { @@ -52,7 +52,6 @@ public enum AdaptiveTexSize private RenderTexture rt = null; private RenderTextureFormat rtFormat = RenderTextureFormat.ARGBHalf; - public override bool CheckResources() { CheckSupport(false, true); @@ -71,7 +70,6 @@ public override bool CheckResources() return isSupported; } - public float UpdateCurve() { float range = 1.0f; @@ -81,17 +79,16 @@ public float UpdateCurve() { if (remapCurve.length > 0) range = remapCurve[remapCurve.length - 1].time; - for (float i = 0.0f; i <= 1.0f; i += 1.0f/255.0f) + for (float i = 0.0f; i <= 1.0f; i += 1.0f / 255.0f) { - float c = remapCurve.Evaluate(i*1.0f*range); - curveTex.SetPixel((int) Mathf.Floor(i*255.0f), 0, new Color(c, c, c)); + float c = remapCurve.Evaluate(i * 1.0f * range); + curveTex.SetPixel((int)Mathf.Floor(i * 255.0f), 0, new Color(c, c, c)); } curveTex.Apply(); } - return 1.0f/range; + return 1.0f / range; } - private void OnDisable() { if (rt) @@ -111,20 +108,20 @@ private void OnDisable() } } - private bool CreateInternalRenderTexture() { if (rt) { return false; } - rtFormat = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RGHalf) ? RenderTextureFormat.RGHalf : RenderTextureFormat.ARGBHalf; + rtFormat = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RGHalf) + ? RenderTextureFormat.RGHalf + : RenderTextureFormat.ARGBHalf; rt = new RenderTexture(1, 1, 0, rtFormat); rt.hideFlags = HideFlags.DontSave; return true; } - // attribute indicates that the image filter chain will continue in LDR [ImageEffectTransformsToLDR] private void OnRenderImage(RenderTexture source, RenderTexture destination) @@ -181,7 +178,7 @@ private void OnRenderImage(RenderTexture source, RenderTexture destination) if (type == TonemapperType.OptimizedHejiDawson) { - tonemapMaterial.SetFloat("_ExposureAdjustment", 0.5f*exposureAdjustment); + tonemapMaterial.SetFloat("_ExposureAdjustment", 0.5f * exposureAdjustment); Graphics.Blit(source, destination, tonemapMaterial, 7); return; } @@ -195,16 +192,26 @@ private void OnRenderImage(RenderTexture source, RenderTexture destination) bool freshlyBrewedInternalRt = CreateInternalRenderTexture(); // this retrieves rtFormat, so should happen before rt allocations - RenderTexture rtSquared = RenderTexture.GetTemporary((int) adaptiveTextureSize, (int) adaptiveTextureSize, 0, rtFormat); + RenderTexture rtSquared = RenderTexture.GetTemporary( + (int)adaptiveTextureSize, + (int)adaptiveTextureSize, + 0, + rtFormat + ); Graphics.Blit(source, rtSquared); - int downsample = (int) Mathf.Log(rtSquared.width*1.0f, 2); + int downsample = (int)Mathf.Log(rtSquared.width * 1.0f, 2); int div = 2; var rts = new RenderTexture[downsample]; for (int i = 0; i < downsample; i++) { - rts[i] = RenderTexture.GetTemporary(rtSquared.width/div, rtSquared.width/div, 0, rtFormat); + rts[i] = RenderTexture.GetTemporary( + rtSquared.width / div, + rtSquared.width / div, + 0, + rtFormat + ); div *= 2; } @@ -235,18 +242,20 @@ private void OnRenderImage(RenderTexture source, RenderTexture destination) tonemapMaterial.SetFloat("_AdaptionSpeed", adaptionSpeed); rt.MarkRestoreExpected(); // keeping luminance values between frames, RT restore expected - #if UNITY_EDITOR if (Application.isPlaying && !freshlyBrewedInternalRt) Graphics.Blit(lumRt, rt, tonemapMaterial, 2); else Graphics.Blit(lumRt, rt, tonemapMaterial, 3); #else - Graphics.Blit (lumRt, rt, tonemapMaterial, freshlyBrewedInternalRt ? 3 : 2); + Graphics.Blit(lumRt, rt, tonemapMaterial, freshlyBrewedInternalRt ? 3 : 2); #endif middleGrey = middleGrey < 0.001f ? 0.001f : middleGrey; - tonemapMaterial.SetVector("_HdrParams", new Vector4(middleGrey, middleGrey, middleGrey, white*white)); + tonemapMaterial.SetVector( + "_HdrParams", + new Vector4(middleGrey, middleGrey, middleGrey, white * white) + ); tonemapMaterial.SetTexture("_SmallTex", rt); if (type == TonemapperType.AdaptiveReinhard) { diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Twirl.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Twirl.cs index 2ca750266b..7703a046a1 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Twirl.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Twirl.cs @@ -7,16 +7,16 @@ namespace UnityStandardAssets.ImageEffects [AddComponentMenu("Image Effects/Displacement/Twirl")] public class Twirl : ImageEffectBase { - public Vector2 radius = new Vector2(0.3F,0.3F); - [Range(0.0f,360.0f)] - public float angle = 50; - public Vector2 center = new Vector2 (0.5F, 0.5F); + public Vector2 radius = new Vector2(0.3F, 0.3F); + [Range(0.0f, 360.0f)] + public float angle = 50; + public Vector2 center = new Vector2(0.5F, 0.5F); // Called by camera to apply image effect - void OnRenderImage (RenderTexture source, RenderTexture destination) + void OnRenderImage(RenderTexture source, RenderTexture destination) { - ImageEffects.RenderDistortion (material, source, destination, angle, center, radius); + ImageEffects.RenderDistortion(material, source, destination, angle, center, radius); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/VignetteAndChromaticAberration.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/VignetteAndChromaticAberration.cs index 85053a2a76..d35e889862 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/VignetteAndChromaticAberration.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/VignetteAndChromaticAberration.cs @@ -4,8 +4,8 @@ namespace UnityStandardAssets.ImageEffects { [ExecuteInEditMode] - [RequireComponent (typeof(Camera))] - [AddComponentMenu ("Image Effects/Camera/Vignette and Chromatic Aberration")] + [RequireComponent(typeof(Camera))] + [AddComponentMenu("Image Effects/Camera/Vignette and Chromatic Aberration")] public class VignetteAndChromaticAberration : PostEffectsBase { public enum AberrationMode @@ -14,51 +14,53 @@ public enum AberrationMode Advanced = 1, } - public AberrationMode mode = AberrationMode.Simple; - public float intensity = 0.036f; // intensity == 0 disables pre pass (optimization) + public float intensity = 0.036f; // intensity == 0 disables pre pass (optimization) public float chromaticAberration = 0.2f; public float axialAberration = 0.5f; - public float blur = 0.0f; // blur == 0 disables blur pass (optimization) + public float blur = 0.0f; // blur == 0 disables blur pass (optimization) public float blurSpread = 0.75f; public float luminanceDependency = 0.25f; public float blurDistance = 2.5f; public Shader vignetteShader; public Shader separableBlurShader; public Shader chromAberrationShader; - - + private Material m_VignetteMaterial; private Material m_SeparableBlurMaterial; private Material m_ChromAberrationMaterial; - - public override bool CheckResources () + public override bool CheckResources() { - CheckSupport (false); - - m_VignetteMaterial = CheckShaderAndCreateMaterial (vignetteShader, m_VignetteMaterial); - m_SeparableBlurMaterial = CheckShaderAndCreateMaterial (separableBlurShader, m_SeparableBlurMaterial); - m_ChromAberrationMaterial = CheckShaderAndCreateMaterial (chromAberrationShader, m_ChromAberrationMaterial); + CheckSupport(false); + + m_VignetteMaterial = CheckShaderAndCreateMaterial(vignetteShader, m_VignetteMaterial); + m_SeparableBlurMaterial = CheckShaderAndCreateMaterial( + separableBlurShader, + m_SeparableBlurMaterial + ); + m_ChromAberrationMaterial = CheckShaderAndCreateMaterial( + chromAberrationShader, + m_ChromAberrationMaterial + ); if (!isSupported) - ReportAutoDisable (); + ReportAutoDisable(); return isSupported; } - - void OnRenderImage (RenderTexture source, RenderTexture destination) + void OnRenderImage(RenderTexture source, RenderTexture destination) { - if ( CheckResources () == false) + if (CheckResources() == false) { - Graphics.Blit (source, destination); + Graphics.Blit(source, destination); return; } int rtW = source.width; int rtH = source.height; - bool doPrepass = (Mathf.Abs(blur)>0.0f || Mathf.Abs(intensity)>0.0f); + bool doPrepass = (Mathf.Abs(blur) > 0.0f || Mathf.Abs(intensity) > 0.0f); float widthOverHeight = (1.0f * rtW) / (1.0f * rtH); const float oneOverBaseSize = 1.0f / 512.0f; @@ -68,47 +70,76 @@ void OnRenderImage (RenderTexture source, RenderTexture destination) if (doPrepass) { - color = RenderTexture.GetTemporary (rtW, rtH, 0, source.format); + color = RenderTexture.GetTemporary(rtW, rtH, 0, source.format); // Blur corners - if (Mathf.Abs (blur)>0.0f) + if (Mathf.Abs(blur) > 0.0f) { - color2A = RenderTexture.GetTemporary (rtW / 2, rtH / 2, 0, source.format); - - Graphics.Blit (source, color2A, m_ChromAberrationMaterial, 0); - - for(int i = 0; i < 2; i++) - { // maybe make iteration count tweakable - m_SeparableBlurMaterial.SetVector ("offsets",new Vector4 (0.0f, blurSpread * oneOverBaseSize, 0.0f, 0.0f)); - RenderTexture color2B = RenderTexture.GetTemporary (rtW / 2, rtH / 2, 0, source.format); - Graphics.Blit (color2A, color2B, m_SeparableBlurMaterial); - RenderTexture.ReleaseTemporary (color2A); - - m_SeparableBlurMaterial.SetVector ("offsets",new Vector4 (blurSpread * oneOverBaseSize / widthOverHeight, 0.0f, 0.0f, 0.0f)); - color2A = RenderTexture.GetTemporary (rtW / 2, rtH / 2, 0, source.format); - Graphics.Blit (color2B, color2A, m_SeparableBlurMaterial); - RenderTexture.ReleaseTemporary (color2B); + color2A = RenderTexture.GetTemporary(rtW / 2, rtH / 2, 0, source.format); + + Graphics.Blit(source, color2A, m_ChromAberrationMaterial, 0); + + for (int i = 0; i < 2; i++) + { // maybe make iteration count tweakable + m_SeparableBlurMaterial.SetVector( + "offsets", + new Vector4(0.0f, blurSpread * oneOverBaseSize, 0.0f, 0.0f) + ); + RenderTexture color2B = RenderTexture.GetTemporary( + rtW / 2, + rtH / 2, + 0, + source.format + ); + Graphics.Blit(color2A, color2B, m_SeparableBlurMaterial); + RenderTexture.ReleaseTemporary(color2A); + + m_SeparableBlurMaterial.SetVector( + "offsets", + new Vector4( + blurSpread * oneOverBaseSize / widthOverHeight, + 0.0f, + 0.0f, + 0.0f + ) + ); + color2A = RenderTexture.GetTemporary(rtW / 2, rtH / 2, 0, source.format); + Graphics.Blit(color2B, color2A, m_SeparableBlurMaterial); + RenderTexture.ReleaseTemporary(color2B); } } - m_VignetteMaterial.SetFloat("_Intensity", (1.0f / (1.0f - intensity) - 1.0f)); // intensity for vignette - m_VignetteMaterial.SetFloat("_Blur", (1.0f / (1.0f - blur)) - 1.0f); // blur intensity - m_VignetteMaterial.SetTexture ("_VignetteTex", color2A); // blurred texture + m_VignetteMaterial.SetFloat("_Intensity", (1.0f / (1.0f - intensity) - 1.0f)); // intensity for vignette + m_VignetteMaterial.SetFloat("_Blur", (1.0f / (1.0f - blur)) - 1.0f); // blur intensity + m_VignetteMaterial.SetTexture("_VignetteTex", color2A); // blurred texture - Graphics.Blit (source, color, m_VignetteMaterial, 0); // prepass blit: darken & blur corners + Graphics.Blit(source, color, m_VignetteMaterial, 0); // prepass blit: darken & blur corners } - m_ChromAberrationMaterial.SetFloat ("_ChromaticAberration", chromaticAberration); - m_ChromAberrationMaterial.SetFloat ("_AxialAberration", axialAberration); - m_ChromAberrationMaterial.SetVector ("_BlurDistance", new Vector2 (-blurDistance, blurDistance)); - m_ChromAberrationMaterial.SetFloat ("_Luminance", 1.0f/Mathf.Max(Mathf.Epsilon, luminanceDependency)); + m_ChromAberrationMaterial.SetFloat("_ChromaticAberration", chromaticAberration); + m_ChromAberrationMaterial.SetFloat("_AxialAberration", axialAberration); + m_ChromAberrationMaterial.SetVector( + "_BlurDistance", + new Vector2(-blurDistance, blurDistance) + ); + m_ChromAberrationMaterial.SetFloat( + "_Luminance", + 1.0f / Mathf.Max(Mathf.Epsilon, luminanceDependency) + ); - if (doPrepass) color.wrapMode = TextureWrapMode.Clamp; - else source.wrapMode = TextureWrapMode.Clamp; - Graphics.Blit (doPrepass ? color : source, destination, m_ChromAberrationMaterial, mode == AberrationMode.Advanced ? 2 : 1); - - RenderTexture.ReleaseTemporary (color); - RenderTexture.ReleaseTemporary (color2A); + if (doPrepass) + color.wrapMode = TextureWrapMode.Clamp; + else + source.wrapMode = TextureWrapMode.Clamp; + Graphics.Blit( + doPrepass ? color : source, + destination, + m_ChromAberrationMaterial, + mode == AberrationMode.Advanced ? 2 : 1 + ); + + RenderTexture.ReleaseTemporary(color); + RenderTexture.ReleaseTemporary(color2A); } } } diff --git a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Vortex.cs b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Vortex.cs index e011615ada..7449fe5dae 100644 --- a/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Vortex.cs +++ b/unity/Assets/Standard Assets/Effects/ImageEffects/Scripts/Vortex.cs @@ -7,14 +7,14 @@ namespace UnityStandardAssets.ImageEffects [AddComponentMenu("Image Effects/Displacement/Vortex")] public class Vortex : ImageEffectBase { - public Vector2 radius = new Vector2(0.4F,0.4F); + public Vector2 radius = new Vector2(0.4F, 0.4F); public float angle = 50; public Vector2 center = new Vector2(0.5F, 0.5F); - + // Called by camera to apply image effect - void OnRenderImage (RenderTexture source, RenderTexture destination) + void OnRenderImage(RenderTexture source, RenderTexture destination) { - ImageEffects.RenderDistortion (material, source, destination, angle, center, radius); + ImageEffects.RenderDistortion(material, source, destination, angle, center, radius); } } } diff --git a/unity/Assets/Standard Assets/Utility/ActivateTrigger.cs b/unity/Assets/Standard Assets/Utility/ActivateTrigger.cs index f1d5a4589f..d7e9af22b0 100755 --- a/unity/Assets/Standard Assets/Utility/ActivateTrigger.cs +++ b/unity/Assets/Standard Assets/Utility/ActivateTrigger.cs @@ -10,21 +10,20 @@ public class ActivateTrigger : MonoBehaviour // a trigger collider is entered. public enum Mode { - Trigger = 0, // Just broadcast the action on to the target - Replace = 1, // replace target with source - Activate = 2, // Activate the target GameObject - Enable = 3, // Enable a component - Animate = 4, // Start animation on target - Deactivate = 5 // Decativate target GameObject + Trigger = 0, // Just broadcast the action on to the target + Replace = 1, // replace target with source + Activate = 2, // Activate the target GameObject + Enable = 3, // Enable a component + Animate = 4, // Start animation on target + Deactivate = 5 // Decativate target GameObject } - public Mode action = Mode.Activate; // The action to accomplish - public Object target; // The game object to affect. If none, the trigger work on this game object + public Mode action = Mode.Activate; // The action to accomplish + public Object target; // The game object to affect. If none, the trigger work on this game object public GameObject source; public int triggerCount = 1; public bool repeatTrigger = false; - private void DoActivateTrigger() { triggerCount--; @@ -52,8 +51,11 @@ private void DoActivateTrigger() { if (targetGameObject != null) { - Instantiate(source, targetGameObject.transform.position, - targetGameObject.transform.rotation); + Instantiate( + source, + targetGameObject.transform.position, + targetGameObject.transform.rotation + ); Destroy(targetGameObject); } } @@ -86,7 +88,6 @@ private void DoActivateTrigger() } } - private void OnTriggerEnter(Collider other) { DoActivateTrigger(); diff --git a/unity/Assets/Standard Assets/Utility/AlphaButtonClickMask.cs b/unity/Assets/Standard Assets/Utility/AlphaButtonClickMask.cs index a344bcee3d..5fb927cd7f 100755 --- a/unity/Assets/Standard Assets/Utility/AlphaButtonClickMask.cs +++ b/unity/Assets/Standard Assets/Utility/AlphaButtonClickMask.cs @@ -1,8 +1,8 @@ -using UnityEngine; +using System.Collections; +using UnityEngine; using UnityEngine.UI; -using System.Collections; -public class AlphaButtonClickMask : MonoBehaviour, ICanvasRaycastFilter +public class AlphaButtonClickMask : MonoBehaviour, ICanvasRaycastFilter { protected Image _image; @@ -39,12 +39,21 @@ public void Start() public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera) { Vector2 localPoint; - RectTransformUtility.ScreenPointToLocalPointInRectangle(_image.rectTransform, sp, eventCamera, out localPoint); + RectTransformUtility.ScreenPointToLocalPointInRectangle( + _image.rectTransform, + sp, + eventCamera, + out localPoint + ); - Vector2 normalizedLocal = new Vector2(1.0f + localPoint.x / _image.rectTransform.rect.width, 1.0f + localPoint.y / _image.rectTransform.rect.height); + Vector2 normalizedLocal = new Vector2( + 1.0f + localPoint.x / _image.rectTransform.rect.width, + 1.0f + localPoint.y / _image.rectTransform.rect.height + ); Vector2 uv = new Vector2( - _image.sprite.rect.x + normalizedLocal.x * _image.sprite.rect.width, - _image.sprite.rect.y + normalizedLocal.y * _image.sprite.rect.height ); + _image.sprite.rect.x + normalizedLocal.x * _image.sprite.rect.width, + _image.sprite.rect.y + normalizedLocal.y * _image.sprite.rect.height + ); uv.x /= _image.sprite.texture.width; uv.y /= _image.sprite.texture.height; @@ -52,6 +61,6 @@ public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera) // uv are inversed, as 0,0 or the rect transform seem to be upper right, then going negativ toward lower left... Color c = _image.sprite.texture.GetPixelBilinear(uv.x, uv.y); - return c.a> 0.1f; + return c.a > 0.1f; } } diff --git a/unity/Assets/Standard Assets/Utility/AutoMobileShaderSwitch.cs b/unity/Assets/Standard Assets/Utility/AutoMobileShaderSwitch.cs index 349eadd81c..dd5c743cc8 100755 --- a/unity/Assets/Standard Assets/Utility/AutoMobileShaderSwitch.cs +++ b/unity/Assets/Standard Assets/Utility/AutoMobileShaderSwitch.cs @@ -9,63 +9,80 @@ namespace UnityStandardAssets.Utility { public class AutoMobileShaderSwitch : MonoBehaviour { - [SerializeField] private ReplacementList m_ReplacementList; + [SerializeField] + private ReplacementList m_ReplacementList; // Use this for initialization private void OnEnable() { #if UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8 || UNITY_TIZEN || UNITY_STV - var renderers = FindObjectsOfType(); - Debug.Log (renderers.Length+" renderers"); - var oldMaterials = new List(); - var newMaterials = new List(); - - int materialsReplaced = 0; - int materialInstancesReplaced = 0; - - foreach(ReplacementDefinition replacementDef in m_ReplacementList.items) - { - foreach(var r in renderers) - { - Material[] modifiedMaterials = null; - for(int n=0; n(); + Debug.Log(renderers.Length + " renderers"); + var oldMaterials = new List(); + var newMaterials = new List(); + + int materialsReplaced = 0; + int materialInstancesReplaced = 0; + + foreach (ReplacementDefinition replacementDef in m_ReplacementList.items) + { + foreach (var r in renderers) + { + Material[] modifiedMaterials = null; + for (int n = 0; n < r.sharedMaterials.Length; ++n) + { + var material = r.sharedMaterials[n]; + if (material.shader == replacementDef.original) + { + if (modifiedMaterials == null) + { + modifiedMaterials = r.materials; + } + if (!oldMaterials.Contains(material)) + { + oldMaterials.Add(material); + Material newMaterial = (Material)Instantiate(material); + newMaterial.shader = replacementDef.replacement; + newMaterials.Add(newMaterial); + ++materialsReplaced; + } + Debug.Log( + "replacing " + + r.gameObject.name + + " renderer " + + n + + " with " + + newMaterials[oldMaterials.IndexOf(material)].name + ); + modifiedMaterials[n] = newMaterials[oldMaterials.IndexOf(material)]; + ++materialInstancesReplaced; + } + } + if (modifiedMaterials != null) + { + r.materials = modifiedMaterials; + } + } + } + Debug.Log(materialInstancesReplaced + " material instances replaced"); + Debug.Log(materialsReplaced + " materials replaced"); + for (int n = 0; n < oldMaterials.Count; ++n) + { + Debug.Log( + oldMaterials[n].name + + " (" + + oldMaterials[n].shader.name + + ")" + + " replaced with " + + newMaterials[n].name + + " (" + + newMaterials[n].shader.name + + ")" + ); + } #endif } - [Serializable] public class ReplacementDefinition { @@ -84,7 +101,7 @@ public class ReplacementList namespace UnityStandardAssets.Utility.Inspector { #if UNITY_EDITOR - [CustomPropertyDrawer(typeof (AutoMobileShaderSwitch.ReplacementList))] + [CustomPropertyDrawer(typeof(AutoMobileShaderSwitch.ReplacementList))] public class ReplacementListDrawer : PropertyDrawer { const float k_LineHeight = 18; @@ -103,9 +120,9 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten EditorGUI.indentLevel = 0; var items = property.FindPropertyRelative("items"); - var titles = new string[] {"Original", "Replacement", ""}; - var props = new string[] {"original", "replacement", "-"}; - var widths = new float[] {.45f, .45f, .1f}; + var titles = new string[] { "Original", "Replacement", "" }; + var props = new string[] { "original", "replacement", "-" }; + var widths = new float[] { .45f, .45f, .1f }; const float lineHeight = 18; bool changedLength = false; if (items.arraySize > 0) @@ -117,7 +134,7 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten float rowX = x; for (int n = 0; n < props.Length; ++n) { - float w = widths[n]*inspectorWidth; + float w = widths[n] * inspectorWidth; // Calculate rects Rect rect = new Rect(rowX, y, w, lineHeight); @@ -173,8 +190,12 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten } // add button - var addButtonRect = new Rect((x + position.width) - widths[widths.Length - 1]*inspectorWidth, y, - widths[widths.Length - 1]*inspectorWidth, lineHeight); + var addButtonRect = new Rect( + (x + position.width) - widths[widths.Length - 1] * inspectorWidth, + y, + widths[widths.Length - 1] * inspectorWidth, + lineHeight + ); if (GUI.Button(addButtonRect, "+")) { items.InsertArrayElementAtIndex(items.arraySize); @@ -187,12 +208,11 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten EditorGUI.EndProperty(); } - public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { SerializedProperty items = property.FindPropertyRelative("items"); float lineAndSpace = k_LineHeight + k_Spacing; - return 40 + (items.arraySize*lineAndSpace) + lineAndSpace; + return 40 + (items.arraySize * lineAndSpace) + lineAndSpace; } } #endif diff --git a/unity/Assets/Standard Assets/Utility/AutoMoveAndRotate.cs b/unity/Assets/Standard Assets/Utility/AutoMoveAndRotate.cs index a6aea7909d..0d54386c1d 100755 --- a/unity/Assets/Standard Assets/Utility/AutoMoveAndRotate.cs +++ b/unity/Assets/Standard Assets/Utility/AutoMoveAndRotate.cs @@ -10,13 +10,11 @@ public class AutoMoveAndRotate : MonoBehaviour public bool ignoreTimescale; private float m_LastRealTime; - private void Start() { m_LastRealTime = Time.realtimeSinceStartup; } - // Update is called once per frame private void Update() { @@ -26,11 +24,10 @@ private void Update() deltaTime = (Time.realtimeSinceStartup - m_LastRealTime); m_LastRealTime = Time.realtimeSinceStartup; } - transform.Translate(moveUnitsPerSecond.value*deltaTime, moveUnitsPerSecond.space); - transform.Rotate(rotateDegreesPerSecond.value*deltaTime, moveUnitsPerSecond.space); + transform.Translate(moveUnitsPerSecond.value * deltaTime, moveUnitsPerSecond.space); + transform.Rotate(rotateDegreesPerSecond.value * deltaTime, moveUnitsPerSecond.space); } - [Serializable] public class Vector3andSpace { diff --git a/unity/Assets/Standard Assets/Utility/CameraRefocus.cs b/unity/Assets/Standard Assets/Utility/CameraRefocus.cs index 8f58b35456..066fc2f82e 100755 --- a/unity/Assets/Standard Assets/Utility/CameraRefocus.cs +++ b/unity/Assets/Standard Assets/Utility/CameraRefocus.cs @@ -12,7 +12,6 @@ public class CameraRefocus private Vector3 m_OrigCameraPos; private bool m_Refocus; - public CameraRefocus(Camera camera, Transform parent, Vector3 origCameraPos) { m_OrigCameraPos = origCameraPos; @@ -20,24 +19,27 @@ public CameraRefocus(Camera camera, Transform parent, Vector3 origCameraPos) Parent = parent; } - public void ChangeCamera(Camera camera) { Camera = camera; } - public void ChangeParent(Transform parent) { Parent = parent; } - public void GetFocusPoint() { RaycastHit hitInfo; - if (Physics.Raycast(Parent.transform.position + m_OrigCameraPos, Parent.transform.forward, out hitInfo, - 100f)) + if ( + Physics.Raycast( + Parent.transform.position + m_OrigCameraPos, + Parent.transform.forward, + out hitInfo, + 100f + ) + ) { Lookatpoint = hitInfo.point; m_Refocus = true; @@ -46,7 +48,6 @@ public void GetFocusPoint() m_Refocus = false; } - public void SetFocusPoint() { if (m_Refocus) diff --git a/unity/Assets/Standard Assets/Utility/CurveControlledBob.cs b/unity/Assets/Standard Assets/Utility/CurveControlledBob.cs index 3e0e505fc9..3f00cfb2ff 100755 --- a/unity/Assets/Standard Assets/Utility/CurveControlledBob.cs +++ b/unity/Assets/Standard Assets/Utility/CurveControlledBob.cs @@ -1,7 +1,6 @@ using System; using UnityEngine; - namespace UnityStandardAssets.Utility { [Serializable] @@ -9,9 +8,13 @@ public class CurveControlledBob { public float HorizontalBobRange = 0.33f; public float VerticalBobRange = 0.33f; - public AnimationCurve Bobcurve = new AnimationCurve(new Keyframe(0f, 0f), new Keyframe(0.5f, 1f), - new Keyframe(1f, 0f), new Keyframe(1.5f, -1f), - new Keyframe(2f, 0f)); // sin curve for head bob + public AnimationCurve Bobcurve = new AnimationCurve( + new Keyframe(0f, 0f), + new Keyframe(0.5f, 1f), + new Keyframe(1f, 0f), + new Keyframe(1.5f, -1f), + new Keyframe(2f, 0f) + ); // sin curve for head bob public float VerticaltoHorizontalRatio = 1f; private float m_CyclePositionX; @@ -20,7 +23,6 @@ public class CurveControlledBob private Vector3 m_OriginalCameraPosition; private float m_Time; - public void Setup(Camera camera, float bobBaseInterval) { m_BobBaseInterval = bobBaseInterval; @@ -30,14 +32,18 @@ public void Setup(Camera camera, float bobBaseInterval) m_Time = Bobcurve[Bobcurve.length - 1].time; } - public Vector3 DoHeadBob(float speed) { - float xPos = m_OriginalCameraPosition.x + (Bobcurve.Evaluate(m_CyclePositionX)*HorizontalBobRange); - float yPos = m_OriginalCameraPosition.y + (Bobcurve.Evaluate(m_CyclePositionY)*VerticalBobRange); - - m_CyclePositionX += (speed*Time.deltaTime)/m_BobBaseInterval; - m_CyclePositionY += ((speed*Time.deltaTime)/m_BobBaseInterval)*VerticaltoHorizontalRatio; + float xPos = + m_OriginalCameraPosition.x + + (Bobcurve.Evaluate(m_CyclePositionX) * HorizontalBobRange); + float yPos = + m_OriginalCameraPosition.y + + (Bobcurve.Evaluate(m_CyclePositionY) * VerticalBobRange); + + m_CyclePositionX += (speed * Time.deltaTime) / m_BobBaseInterval; + m_CyclePositionY += + ((speed * Time.deltaTime) / m_BobBaseInterval) * VerticaltoHorizontalRatio; if (m_CyclePositionX > m_Time) { diff --git a/unity/Assets/Standard Assets/Utility/DragRigidbody.cs b/unity/Assets/Standard Assets/Utility/DragRigidbody.cs index 69aff293c4..525a889257 100755 --- a/unity/Assets/Standard Assets/Utility/DragRigidbody.cs +++ b/unity/Assets/Standard Assets/Utility/DragRigidbody.cs @@ -15,7 +15,6 @@ public class DragRigidbody : MonoBehaviour private SpringJoint m_SpringJoint; - private void Update() { // Make sure the user pressed the mouse down @@ -29,9 +28,14 @@ private void Update() // We need to actually hit an object RaycastHit hit = new RaycastHit(); if ( - !Physics.Raycast(mainCamera.ScreenPointToRay(Input.mousePosition).origin, - mainCamera.ScreenPointToRay(Input.mousePosition).direction, out hit, 100, - Physics.DefaultRaycastLayers)) + !Physics.Raycast( + mainCamera.ScreenPointToRay(Input.mousePosition).origin, + mainCamera.ScreenPointToRay(Input.mousePosition).direction, + out hit, + 100, + Physics.DefaultRaycastLayers + ) + ) { return; } @@ -60,7 +64,6 @@ private void Update() StartCoroutine("DragObject", hit.distance); } - private IEnumerator DragObject(float distance) { var oldDrag = m_SpringJoint.connectedBody.drag; @@ -82,7 +85,6 @@ private IEnumerator DragObject(float distance) } } - private Camera FindCamera() { if (GetComponent()) diff --git a/unity/Assets/Standard Assets/Utility/DynamicShadowSettings.cs b/unity/Assets/Standard Assets/Utility/DynamicShadowSettings.cs index 0ac577b0a1..98a5cb1090 100755 --- a/unity/Assets/Standard Assets/Utility/DynamicShadowSettings.cs +++ b/unity/Assets/Standard Assets/Utility/DynamicShadowSettings.cs @@ -18,13 +18,11 @@ public class DynamicShadowSettings : MonoBehaviour private float m_ChangeSpeed; private float m_OriginalStrength = 1; - private void Start() { m_OriginalStrength = sunLight.shadowStrength; } - // Update is called once per frame private void Update() { @@ -38,13 +36,18 @@ private void Update() if (Mathf.Abs(height - m_SmoothHeight) > 1) { - m_SmoothHeight = Mathf.SmoothDamp(m_SmoothHeight, height, ref m_ChangeSpeed, adaptTime); + m_SmoothHeight = Mathf.SmoothDamp( + m_SmoothHeight, + height, + ref m_ChangeSpeed, + adaptTime + ); } float i = Mathf.InverseLerp(minHeight, maxHeight, m_SmoothHeight); QualitySettings.shadowDistance = Mathf.Lerp(minShadowDistance, maxShadowDistance, i); - sunLight.shadowBias = Mathf.Lerp(minShadowBias, maxShadowBias, 1 - ((1 - i)*(1 - i))); + sunLight.shadowBias = Mathf.Lerp(minShadowBias, maxShadowBias, 1 - ((1 - i) * (1 - i))); sunLight.shadowStrength = Mathf.Lerp(m_OriginalStrength, 0, i); } } diff --git a/unity/Assets/Standard Assets/Utility/EventSystemChecker.cs b/unity/Assets/Standard Assets/Utility/EventSystemChecker.cs index e10c8cb1dc..e416b55520 100755 --- a/unity/Assets/Standard Assets/Utility/EventSystemChecker.cs +++ b/unity/Assets/Standard Assets/Utility/EventSystemChecker.cs @@ -7,15 +7,15 @@ public class EventSystemChecker : MonoBehaviour { // public GameObject eventSystem; - // Use this for initialization - void Awake () - { - if(!FindObjectOfType()) + // Use this for initialization + void Awake() + { + if (!FindObjectOfType()) { - // Instantiate(eventSystem); + // Instantiate(eventSystem); GameObject obj = new GameObject("EventSystem"); obj.AddComponent(); obj.AddComponent().forceModuleActive = true; } - } + } } diff --git a/unity/Assets/Standard Assets/Utility/FOVKick.cs b/unity/Assets/Standard Assets/Utility/FOVKick.cs index e1e545307d..639e03c644 100755 --- a/unity/Assets/Standard Assets/Utility/FOVKick.cs +++ b/unity/Assets/Standard Assets/Utility/FOVKick.cs @@ -7,13 +7,14 @@ namespace UnityStandardAssets.Utility [Serializable] public class FOVKick { - public Camera Camera; // optional camera setup, if null the main camera will be used - [HideInInspector] public float originalFov; // the original fov - public float FOVIncrease = 3f; // the amount the field of view increases when going into a run - public float TimeToIncrease = 1f; // the amount of time the field of view will increase over - public float TimeToDecrease = 1f; // the amount of time the field of view will take to return to its original size - public AnimationCurve IncreaseCurve; + public Camera Camera; // optional camera setup, if null the main camera will be used + [HideInInspector] + public float originalFov; // the original fov + public float FOVIncrease = 3f; // the amount the field of view increases when going into a run + public float TimeToIncrease = 1f; // the amount of time the field of view will increase over + public float TimeToDecrease = 1f; // the amount of time the field of view will take to return to its original size + public AnimationCurve IncreaseCurve; public void Setup(Camera camera) { @@ -23,46 +24,47 @@ public void Setup(Camera camera) originalFov = camera.fieldOfView; } - private void CheckStatus(Camera camera) { if (camera == null) { - throw new Exception("FOVKick camera is null, please supply the camera to the constructor"); + throw new Exception( + "FOVKick camera is null, please supply the camera to the constructor" + ); } if (IncreaseCurve == null) { throw new Exception( - "FOVKick Increase curve is null, please define the curve for the field of view kicks"); + "FOVKick Increase curve is null, please define the curve for the field of view kicks" + ); } } - public void ChangeCamera(Camera camera) { Camera = camera; } - public IEnumerator FOVKickUp() { - float t = Mathf.Abs((Camera.fieldOfView - originalFov)/FOVIncrease); + float t = Mathf.Abs((Camera.fieldOfView - originalFov) / FOVIncrease); while (t < TimeToIncrease) { - Camera.fieldOfView = originalFov + (IncreaseCurve.Evaluate(t/TimeToIncrease)*FOVIncrease); + Camera.fieldOfView = + originalFov + (IncreaseCurve.Evaluate(t / TimeToIncrease) * FOVIncrease); t += Time.deltaTime; yield return new WaitForEndOfFrame(); } } - public IEnumerator FOVKickDown() { - float t = Mathf.Abs((Camera.fieldOfView - originalFov)/FOVIncrease); + float t = Mathf.Abs((Camera.fieldOfView - originalFov) / FOVIncrease); while (t > 0) { - Camera.fieldOfView = originalFov + (IncreaseCurve.Evaluate(t/TimeToDecrease)*FOVIncrease); + Camera.fieldOfView = + originalFov + (IncreaseCurve.Evaluate(t / TimeToDecrease) * FOVIncrease); t -= Time.deltaTime; yield return new WaitForEndOfFrame(); } diff --git a/unity/Assets/Standard Assets/Utility/FPSCounter.cs b/unity/Assets/Standard Assets/Utility/FPSCounter.cs index fc03cbfb44..0179a87c79 100755 --- a/unity/Assets/Standard Assets/Utility/FPSCounter.cs +++ b/unity/Assets/Standard Assets/Utility/FPSCounter.cs @@ -4,7 +4,7 @@ namespace UnityStandardAssets.Utility { - [RequireComponent(typeof (Text))] + [RequireComponent(typeof(Text))] public class FPSCounter : MonoBehaviour { const float fpsMeasurePeriod = 0.5f; @@ -14,21 +14,19 @@ public class FPSCounter : MonoBehaviour const string display = "{0} FPS"; private Text m_Text; - private void Start() { m_FpsNextPeriod = Time.realtimeSinceStartup + fpsMeasurePeriod; m_Text = GetComponent(); } - private void Update() { // measure average frames per second m_FpsAccumulator++; if (Time.realtimeSinceStartup > m_FpsNextPeriod) { - m_CurrentFps = (int) (m_FpsAccumulator/fpsMeasurePeriod); + m_CurrentFps = (int)(m_FpsAccumulator / fpsMeasurePeriod); m_FpsAccumulator = 0; m_FpsNextPeriod += fpsMeasurePeriod; m_Text.text = string.Format(display, m_CurrentFps); diff --git a/unity/Assets/Standard Assets/Utility/FollowTarget.cs b/unity/Assets/Standard Assets/Utility/FollowTarget.cs index d0c0ebbe22..1511abe38c 100755 --- a/unity/Assets/Standard Assets/Utility/FollowTarget.cs +++ b/unity/Assets/Standard Assets/Utility/FollowTarget.cs @@ -1,7 +1,6 @@ using System; using UnityEngine; - namespace UnityStandardAssets.Utility { public class FollowTarget : MonoBehaviour @@ -9,7 +8,6 @@ public class FollowTarget : MonoBehaviour public Transform target; public Vector3 offset = new Vector3(0f, 7.5f, 0f); - private void LateUpdate() { transform.position = target.position + offset; diff --git a/unity/Assets/Standard Assets/Utility/LerpControlledBob.cs b/unity/Assets/Standard Assets/Utility/LerpControlledBob.cs index aa8128eedc..dde547f427 100755 --- a/unity/Assets/Standard Assets/Utility/LerpControlledBob.cs +++ b/unity/Assets/Standard Assets/Utility/LerpControlledBob.cs @@ -12,21 +12,19 @@ public class LerpControlledBob private float m_Offset = 0f; - // provides the offset that can be used public float Offset() { return m_Offset; } - public IEnumerator DoBobCycle() { // make the camera move down slightly float t = 0f; while (t < BobDuration) { - m_Offset = Mathf.Lerp(0f, BobAmount, t/BobDuration); + m_Offset = Mathf.Lerp(0f, BobAmount, t / BobDuration); t += Time.deltaTime; yield return new WaitForFixedUpdate(); } @@ -35,7 +33,7 @@ public IEnumerator DoBobCycle() t = 0f; while (t < BobDuration) { - m_Offset = Mathf.Lerp(BobAmount, 0f, t/BobDuration); + m_Offset = Mathf.Lerp(BobAmount, 0f, t / BobDuration); t += Time.deltaTime; yield return new WaitForFixedUpdate(); } diff --git a/unity/Assets/Standard Assets/Utility/ObjectResetter.cs b/unity/Assets/Standard Assets/Utility/ObjectResetter.cs index 875b8ba896..123125b90a 100755 --- a/unity/Assets/Standard Assets/Utility/ObjectResetter.cs +++ b/unity/Assets/Standard Assets/Utility/ObjectResetter.cs @@ -23,13 +23,11 @@ private void Start() Rigidbody = GetComponent(); } - public void DelayedReset(float delay) { StartCoroutine(ResetCoroutine(delay)); } - public IEnumerator ResetCoroutine(float delay) { yield return new WaitForSeconds(delay); diff --git a/unity/Assets/Standard Assets/Utility/SimpleMouseRotator.cs b/unity/Assets/Standard Assets/Utility/SimpleMouseRotator.cs index 82e8a9875e..96a6821c05 100755 --- a/unity/Assets/Standard Assets/Utility/SimpleMouseRotator.cs +++ b/unity/Assets/Standard Assets/Utility/SimpleMouseRotator.cs @@ -21,20 +21,17 @@ public class SimpleMouseRotator : MonoBehaviour public bool autoZeroVerticalOnMobile = true; public bool autoZeroHorizontalOnMobile = false; public bool relative = true; - - + private Vector3 m_TargetAngles; private Vector3 m_FollowAngles; private Vector3 m_FollowVelocity; private Quaternion m_OriginalRotation; - private void Start() { m_OriginalRotation = transform.localRotation; } - private void Update() { // we make initial calculations from the original local rotation @@ -71,27 +68,49 @@ private void Update() } #if MOBILE_INPUT - // on mobile, sometimes we want input mapped directly to tilt value, - // so it springs back automatically when the look input is released. - if (autoZeroHorizontalOnMobile) { - m_TargetAngles.y = Mathf.Lerp (-rotationRange.y * 0.5f, rotationRange.y * 0.5f, inputH * .5f + .5f); - } else { - m_TargetAngles.y += inputH * rotationSpeed; - } - if (autoZeroVerticalOnMobile) { - m_TargetAngles.x = Mathf.Lerp (-rotationRange.x * 0.5f, rotationRange.x * 0.5f, inputV * .5f + .5f); - } else { - m_TargetAngles.x += inputV * rotationSpeed; - } + // on mobile, sometimes we want input mapped directly to tilt value, + // so it springs back automatically when the look input is released. + if (autoZeroHorizontalOnMobile) + { + m_TargetAngles.y = Mathf.Lerp( + -rotationRange.y * 0.5f, + rotationRange.y * 0.5f, + inputH * .5f + .5f + ); + } + else + { + m_TargetAngles.y += inputH * rotationSpeed; + } + if (autoZeroVerticalOnMobile) + { + m_TargetAngles.x = Mathf.Lerp( + -rotationRange.x * 0.5f, + rotationRange.x * 0.5f, + inputV * .5f + .5f + ); + } + else + { + m_TargetAngles.x += inputV * rotationSpeed; + } #else // with mouse input, we have direct control with no springback required. - m_TargetAngles.y += inputH*rotationSpeed; - m_TargetAngles.x += inputV*rotationSpeed; + m_TargetAngles.y += inputH * rotationSpeed; + m_TargetAngles.x += inputV * rotationSpeed; #endif // clamp values to allowed range - m_TargetAngles.y = Mathf.Clamp(m_TargetAngles.y, -rotationRange.y*0.5f, rotationRange.y*0.5f); - m_TargetAngles.x = Mathf.Clamp(m_TargetAngles.x, -rotationRange.x*0.5f, rotationRange.x*0.5f); + m_TargetAngles.y = Mathf.Clamp( + m_TargetAngles.y, + -rotationRange.y * 0.5f, + rotationRange.y * 0.5f + ); + m_TargetAngles.x = Mathf.Clamp( + m_TargetAngles.x, + -rotationRange.x * 0.5f, + rotationRange.x * 0.5f + ); } else { @@ -99,15 +118,29 @@ private void Update() inputV = Input.mousePosition.y; // set values to allowed range - m_TargetAngles.y = Mathf.Lerp(-rotationRange.y*0.5f, rotationRange.y*0.5f, inputH/Screen.width); - m_TargetAngles.x = Mathf.Lerp(-rotationRange.x*0.5f, rotationRange.x*0.5f, inputV/Screen.height); + m_TargetAngles.y = Mathf.Lerp( + -rotationRange.y * 0.5f, + rotationRange.y * 0.5f, + inputH / Screen.width + ); + m_TargetAngles.x = Mathf.Lerp( + -rotationRange.x * 0.5f, + rotationRange.x * 0.5f, + inputV / Screen.height + ); } // smoothly interpolate current values to target angles - m_FollowAngles = Vector3.SmoothDamp(m_FollowAngles, m_TargetAngles, ref m_FollowVelocity, dampingTime); + m_FollowAngles = Vector3.SmoothDamp( + m_FollowAngles, + m_TargetAngles, + ref m_FollowVelocity, + dampingTime + ); // update the actual gameobject's rotation - transform.localRotation = m_OriginalRotation*Quaternion.Euler(-m_FollowAngles.x, m_FollowAngles.y, 0); + transform.localRotation = + m_OriginalRotation * Quaternion.Euler(-m_FollowAngles.x, m_FollowAngles.y, 0); } } } diff --git a/unity/Assets/Standard Assets/Utility/SmoothFollow.cs b/unity/Assets/Standard Assets/Utility/SmoothFollow.cs index cbe8278856..7dac259511 100755 --- a/unity/Assets/Standard Assets/Utility/SmoothFollow.cs +++ b/unity/Assets/Standard Assets/Utility/SmoothFollow.cs @@ -2,60 +2,70 @@ namespace UnityStandardAssets.Utility { - public class SmoothFollow : MonoBehaviour - { - - // The target we are following - [SerializeField] - private Transform target = null; - // The distance in the x-z plane to the target - [SerializeField] - private float distance = 10.0f; - // the height we want the camera to be above the target - [SerializeField] - private float height = 5.0f; - - [SerializeField] - private float rotationDamping = 0.0f; - [SerializeField] - private float heightDamping = 0.0f; - - // Use this for initialization - void Start() { } - - // Update is called once per frame - void LateUpdate() - { - // Early out if we don't have a target - if (!target) - return; - - // Calculate the current rotation angles - var wantedRotationAngle = target.eulerAngles.y; - var wantedHeight = target.position.y + height; - - var currentRotationAngle = transform.eulerAngles.y; - var currentHeight = transform.position.y; - - // Damp the rotation around the y-axis - currentRotationAngle = Mathf.LerpAngle(currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime); - - // Damp the height - currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime); - - // Convert the angle into a rotation - var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0); - - // Set the position of the camera on the x-z plane to: - // distance meters behind the target - transform.position = target.position; - transform.position -= currentRotation * Vector3.forward * distance; - - // Set the height of the camera - transform.position = new Vector3(transform.position.x ,currentHeight , transform.position.z); - - // Always look at the target - transform.LookAt(target); - } - } -} \ No newline at end of file + public class SmoothFollow : MonoBehaviour + { + // The target we are following + [SerializeField] + private Transform target = null; + + // The distance in the x-z plane to the target + [SerializeField] + private float distance = 10.0f; + + // the height we want the camera to be above the target + [SerializeField] + private float height = 5.0f; + + [SerializeField] + private float rotationDamping = 0.0f; + + [SerializeField] + private float heightDamping = 0.0f; + + // Use this for initialization + void Start() { } + + // Update is called once per frame + void LateUpdate() + { + // Early out if we don't have a target + if (!target) + return; + + // Calculate the current rotation angles + var wantedRotationAngle = target.eulerAngles.y; + var wantedHeight = target.position.y + height; + + var currentRotationAngle = transform.eulerAngles.y; + var currentHeight = transform.position.y; + + // Damp the rotation around the y-axis + currentRotationAngle = Mathf.LerpAngle( + currentRotationAngle, + wantedRotationAngle, + rotationDamping * Time.deltaTime + ); + + // Damp the height + currentHeight = Mathf.Lerp(currentHeight, wantedHeight, heightDamping * Time.deltaTime); + + // Convert the angle into a rotation + var currentRotation = Quaternion.Euler(0, currentRotationAngle, 0); + + // Set the position of the camera on the x-z plane to: + // distance meters behind the target + transform.position = target.position; + transform.position -= currentRotation * Vector3.forward * distance; + + // Set the height of the camera + transform.position = new Vector3( + transform.position.x, + currentHeight, + transform.position.z + ); + + // Always look at the target + transform.LookAt(target); + } + } +} diff --git a/unity/Assets/Standard Assets/Utility/TimedObjectActivator.cs b/unity/Assets/Standard Assets/Utility/TimedObjectActivator.cs index d7469d0ad3..bf970c4cde 100755 --- a/unity/Assets/Standard Assets/Utility/TimedObjectActivator.cs +++ b/unity/Assets/Standard Assets/Utility/TimedObjectActivator.cs @@ -19,7 +19,6 @@ public enum Action Call, } - [Serializable] public class Entry { @@ -28,17 +27,14 @@ public class Entry public float delay; } - [Serializable] public class Entries { public Entry[] entries; } - - + public Entries entries = new Entries(); - private void Awake() { foreach (Entry entry in entries.entries) @@ -62,41 +58,37 @@ private void Awake() } } - private IEnumerator Activate(Entry entry) { yield return new WaitForSeconds(entry.delay); entry.target.SetActive(true); } - private IEnumerator Deactivate(Entry entry) { yield return new WaitForSeconds(entry.delay); entry.target.SetActive(false); } - private IEnumerator ReloadLevel(Entry entry) { yield return new WaitForSeconds(entry.delay); UnityEngine.SceneManagement.SceneManager.LoadScene( - UnityEngine.SceneManagement.SceneManager.GetSceneAt(0).name); + UnityEngine.SceneManagement.SceneManager.GetSceneAt(0).name + ); } } } - namespace UnityStandardAssets.Utility.Inspector { #if UNITY_EDITOR - [CustomPropertyDrawer(typeof (TimedObjectActivator.Entries))] + [CustomPropertyDrawer(typeof(TimedObjectActivator.Entries))] public class EntriesDrawer : PropertyDrawer { private const float k_LineHeight = 18; private const float k_Spacing = 4; - public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); @@ -116,10 +108,10 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten if (entries.arraySize > 0) { - float actionWidth = .25f*width; - float targetWidth = .6f*width; - float delayWidth = .1f*width; - float buttonWidth = .05f*width; + float actionWidth = .25f * width; + float targetWidth = .6f * width; + float delayWidth = .1f * width; + float buttonWidth = .05f * width; for (int i = 0; i < entries.arraySize; ++i) { @@ -144,19 +136,37 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten // Draw fields - passs GUIContent.none to each so they are drawn without labels - if (entry.FindPropertyRelative("action").enumValueIndex != - (int) TimedObjectActivator.Action.ReloadLevel) + if ( + entry.FindPropertyRelative("action").enumValueIndex + != (int)TimedObjectActivator.Action.ReloadLevel + ) { - EditorGUI.PropertyField(actionRect, entry.FindPropertyRelative("action"), GUIContent.none); - EditorGUI.PropertyField(targetRect, entry.FindPropertyRelative("target"), GUIContent.none); + EditorGUI.PropertyField( + actionRect, + entry.FindPropertyRelative("action"), + GUIContent.none + ); + EditorGUI.PropertyField( + targetRect, + entry.FindPropertyRelative("target"), + GUIContent.none + ); } else { actionRect.width = actionRect.width + targetRect.width; - EditorGUI.PropertyField(actionRect, entry.FindPropertyRelative("action"), GUIContent.none); + EditorGUI.PropertyField( + actionRect, + entry.FindPropertyRelative("action"), + GUIContent.none + ); } - EditorGUI.PropertyField(delayRect, entry.FindPropertyRelative("delay"), GUIContent.none); + EditorGUI.PropertyField( + delayRect, + entry.FindPropertyRelative("delay"), + GUIContent.none + ); if (GUI.Button(buttonRect, "-")) { entries.DeleteArrayElementAtIndex(i); @@ -164,7 +174,7 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten } } } - + // add & sort buttons y += k_LineHeight + k_Spacing; @@ -186,7 +196,10 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten var e1 = entries.GetArrayElementAtIndex(i); var e2 = entries.GetArrayElementAtIndex(i + 1); - if (e1.FindPropertyRelative("delay").floatValue > e2.FindPropertyRelative("delay").floatValue) + if ( + e1.FindPropertyRelative("delay").floatValue + > e2.FindPropertyRelative("delay").floatValue + ) { entries.MoveArrayElement(i + 1, i); changed = true; @@ -196,7 +209,6 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten } } - // Set indent back to what it was EditorGUI.indentLevel = indent; // @@ -205,12 +217,11 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten EditorGUI.EndProperty(); } - public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { SerializedProperty entries = property.FindPropertyRelative("entries"); float lineAndSpace = k_LineHeight + k_Spacing; - return 40 + (entries.arraySize*lineAndSpace) + lineAndSpace; + return 40 + (entries.arraySize * lineAndSpace) + lineAndSpace; } } #endif diff --git a/unity/Assets/Standard Assets/Utility/TimedObjectDestructor.cs b/unity/Assets/Standard Assets/Utility/TimedObjectDestructor.cs index ea6d653ae6..aba9edcfa5 100755 --- a/unity/Assets/Standard Assets/Utility/TimedObjectDestructor.cs +++ b/unity/Assets/Standard Assets/Utility/TimedObjectDestructor.cs @@ -5,16 +5,17 @@ namespace UnityStandardAssets.Utility { public class TimedObjectDestructor : MonoBehaviour { - [SerializeField] private float m_TimeOut = 1.0f; - [SerializeField] private bool m_DetachChildren = false; + [SerializeField] + private float m_TimeOut = 1.0f; + [SerializeField] + private bool m_DetachChildren = false; private void Awake() { Invoke("DestroyNow", m_TimeOut); } - private void DestroyNow() { if (m_DetachChildren) diff --git a/unity/Assets/Standard Assets/Utility/WaypointCircuit.cs b/unity/Assets/Standard Assets/Utility/WaypointCircuit.cs index 8e1088c263..050abc68f7 100755 --- a/unity/Assets/Standard Assets/Utility/WaypointCircuit.cs +++ b/unity/Assets/Standard Assets/Utility/WaypointCircuit.cs @@ -11,7 +11,9 @@ namespace UnityStandardAssets.Utility public class WaypointCircuit : MonoBehaviour { public WaypointList waypointList = new WaypointList(); - [SerializeField] private bool smoothRoute = true; + + [SerializeField] + private bool smoothRoute = true; private int numPoints; private Vector3[] points; private float[] distances; @@ -46,7 +48,6 @@ private void Awake() numPoints = Waypoints.Length; } - public RoutePoint GetRoutePoint(float dist) { // position and direction @@ -56,7 +57,6 @@ public RoutePoint GetRoutePoint(float dist) return new RoutePoint(p1, delta.normalized); } - public Vector3 GetRoutePosition(float dist) { int point = 0; @@ -73,9 +73,8 @@ public Vector3 GetRoutePosition(float dist) ++point; } - // get nearest two points, ensuring points wrap-around start & end of circuit - p1n = ((point - 1) + numPoints)%numPoints; + p1n = ((point - 1) + numPoints) % numPoints; p2n = point; // found point numbers, now find interpolation value between the two middle points @@ -89,13 +88,13 @@ public Vector3 GetRoutePosition(float dist) // get indices for the surrounding 2 points, because // four points are required by the catmull-rom function - p0n = ((point - 2) + numPoints)%numPoints; - p3n = (point + 1)%numPoints; + p0n = ((point - 2) + numPoints) % numPoints; + p3n = (point + 1) % numPoints; // 2nd point may have been the 'last' point - a dupe of the first, // (to give a value of max track distance instead of zero) // but now it must be wrapped back to zero if that was the case. - p2n = p2n%numPoints; + p2n = p2n % numPoints; P0 = points[p0n]; P1 = points[p1n]; @@ -108,24 +107,26 @@ public Vector3 GetRoutePosition(float dist) { // simple linear lerp between the two points: - p1n = ((point - 1) + numPoints)%numPoints; + p1n = ((point - 1) + numPoints) % numPoints; p2n = point; return Vector3.Lerp(points[p1n], points[p2n], i); } } - private Vector3 CatmullRom(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float i) { // comments are no use here... it's the catmull-rom equation. // Un-magic this, lord vector! - return 0.5f* - ((2*p1) + (-p0 + p2)*i + (2*p0 - 5*p1 + 4*p2 - p3)*i*i + - (-p0 + 3*p1 - 3*p2 + p3)*i*i*i); + return 0.5f + * ( + (2 * p1) + + (-p0 + p2) * i + + (2 * p0 - 5 * p1 + 4 * p2 - p3) * i * i + + (-p0 + 3 * p1 - 3 * p2 + p3) * i * i * i + ); } - private void CachePositionsAndDistances() { // transfer the position of each point and distances between points to arrays for @@ -136,32 +137,29 @@ private void CachePositionsAndDistances() float accumulateDistance = 0; for (int i = 0; i < points.Length; ++i) { - var t1 = Waypoints[(i)%Waypoints.Length]; - var t2 = Waypoints[(i + 1)%Waypoints.Length]; + var t1 = Waypoints[(i) % Waypoints.Length]; + var t2 = Waypoints[(i + 1) % Waypoints.Length]; if (t1 != null && t2 != null) { Vector3 p1 = t1.position; Vector3 p2 = t2.position; - points[i] = Waypoints[i%Waypoints.Length].position; + points[i] = Waypoints[i % Waypoints.Length].position; distances[i] = accumulateDistance; accumulateDistance += (p1 - p2).magnitude; } } } - private void OnDrawGizmos() { DrawGizmos(false); } - private void OnDrawGizmosSelected() { DrawGizmos(true); } - private void DrawGizmos(bool selected) { waypointList.circuit = this; @@ -176,7 +174,11 @@ private void DrawGizmos(bool selected) Vector3 prev = Waypoints[0].position; if (smoothRoute) { - for (float dist = 0; dist < Length; dist += Length/editorVisualisationSubsteps) + for ( + float dist = 0; + dist < Length; + dist += Length / editorVisualisationSubsteps + ) { Vector3 next = GetRoutePosition(dist + 1); Gizmos.DrawLine(prev, next); @@ -188,7 +190,7 @@ private void DrawGizmos(bool selected) { for (int n = 0; n < Waypoints.Length; ++n) { - Vector3 next = Waypoints[(n + 1)%Waypoints.Length].position; + Vector3 next = Waypoints[(n + 1) % Waypoints.Length].position; Gizmos.DrawLine(prev, next); prev = next; } @@ -196,7 +198,6 @@ private void DrawGizmos(bool selected) } } - [Serializable] public class WaypointList { @@ -209,7 +210,6 @@ public struct RoutePoint public Vector3 position; public Vector3 direction; - public RoutePoint(Vector3 position, Vector3 direction) { this.position = position; @@ -222,13 +222,12 @@ public RoutePoint(Vector3 position, Vector3 direction) namespace UnityStandardAssets.Utility.Inspector { #if UNITY_EDITOR - [CustomPropertyDrawer(typeof (WaypointCircuit.WaypointList))] + [CustomPropertyDrawer(typeof(WaypointCircuit.WaypointList))] public class WaypointListDrawer : PropertyDrawer { private float lineHeight = 18; private float spacing = 4; - public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EditorGUI.BeginProperty(position, label, property); @@ -245,9 +244,9 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten EditorGUI.indentLevel = 0; var items = property.FindPropertyRelative("items"); - var titles = new string[] {"Transform", "", "", ""}; - var props = new string[] {"transform", "^", "v", "-"}; - var widths = new float[] {.7f, .1f, .1f, .1f}; + var titles = new string[] { "Transform", "", "", "" }; + var props = new string[] { "transform", "^", "v", "-" }; + var widths = new float[] { .7f, .1f, .1f, .1f }; float lineHeight = 18; bool changedLength = false; if (items.arraySize > 0) @@ -259,7 +258,7 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten float rowX = x; for (int n = 0; n < props.Length; ++n) { - float w = widths[n]*inspectorWidth; + float w = widths[n] * inspectorWidth; // Calculate rects Rect rect = new Rect(rowX, y, w, lineHeight); @@ -273,7 +272,12 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten { if (n == 0) { - EditorGUI.ObjectField(rect, item.objectReferenceValue, typeof (Transform), true); + EditorGUI.ObjectField( + rect, + item.objectReferenceValue, + typeof(Transform), + true + ); } else { @@ -314,8 +318,12 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten else { // add button - var addButtonRect = new Rect((x + position.width) - widths[widths.Length - 1]*inspectorWidth, y, - widths[widths.Length - 1]*inspectorWidth, lineHeight); + var addButtonRect = new Rect( + (x + position.width) - widths[widths.Length - 1] * inspectorWidth, + y, + widths[widths.Length - 1] * inspectorWidth, + lineHeight + ); if (GUI.Button(addButtonRect, "+")) { items.InsertArrayElementAtIndex(items.arraySize); @@ -328,7 +336,9 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten var addAllButtonRect = new Rect(x, y, inspectorWidth, lineHeight); if (GUI.Button(addAllButtonRect, "Assign using all child objects")) { - var circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit; + var circuit = + property.FindPropertyRelative("circuit").objectReferenceValue + as WaypointCircuit; var children = new Transform[circuit.transform.childCount]; int n = 0; foreach (Transform child in circuit.transform) @@ -348,7 +358,9 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten var renameButtonRect = new Rect(x, y, inspectorWidth, lineHeight); if (GUI.Button(renameButtonRect, "Auto Rename numerically from this order")) { - var circuit = property.FindPropertyRelative("circuit").objectReferenceValue as WaypointCircuit; + var circuit = + property.FindPropertyRelative("circuit").objectReferenceValue + as WaypointCircuit; int n = 0; foreach (Transform child in circuit.waypointList.items) { @@ -362,21 +374,19 @@ public override void OnGUI(Rect position, SerializedProperty property, GUIConten EditorGUI.EndProperty(); } - public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { SerializedProperty items = property.FindPropertyRelative("items"); float lineAndSpace = lineHeight + spacing; - return 40 + (items.arraySize*lineAndSpace) + lineAndSpace; + return 40 + (items.arraySize * lineAndSpace) + lineAndSpace; } - // comparer for check distances in ray cast hits public class TransformNameComparer : IComparer { public int Compare(object x, object y) { - return ((Transform) x).name.CompareTo(((Transform) y).name); + return ((Transform)x).name.CompareTo(((Transform)y).name); } } } diff --git a/unity/Assets/Standard Assets/Utility/WaypointProgressTracker.cs b/unity/Assets/Standard Assets/Utility/WaypointProgressTracker.cs index c9db01306c..1d5fa7f266 100755 --- a/unity/Assets/Standard Assets/Utility/WaypointProgressTracker.cs +++ b/unity/Assets/Standard Assets/Utility/WaypointProgressTracker.cs @@ -11,24 +11,37 @@ public class WaypointProgressTracker : MonoBehaviour // This script manages the amount to look ahead along the route, // and keeps track of progress and laps. - [SerializeField] private WaypointCircuit circuit = null; // A reference to the waypoint-based route we should follow + [SerializeField] + private WaypointCircuit circuit = null; // A reference to the waypoint-based route we should follow + + [SerializeField] + private float lookAheadForTargetOffset = 5; - [SerializeField] private float lookAheadForTargetOffset = 5; // The offset ahead along the route that the we will aim for - [SerializeField] private float lookAheadForTargetFactor = .1f; + [SerializeField] + private float lookAheadForTargetFactor = .1f; + // A multiplier adding distance ahead along the route to aim for, based on current speed - [SerializeField] private float lookAheadForSpeedOffset = 10; + [SerializeField] + private float lookAheadForSpeedOffset = 10; + // The offset ahead only the route for speed adjustments (applied as the rotation of the waypoint target transform) - [SerializeField] private float lookAheadForSpeedFactor = .2f; + [SerializeField] + private float lookAheadForSpeedFactor = .2f; + // A multiplier adding distance ahead along the route for speed adjustments - [SerializeField] private ProgressStyle progressStyle = ProgressStyle.SmoothAlongRoute; + [SerializeField] + private ProgressStyle progressStyle = ProgressStyle.SmoothAlongRoute; + // whether to update the position smoothly along the route (good for curved paths) or just when we reach each waypoint. - [SerializeField] private float pointToPointThreshold = 4; + [SerializeField] + private float pointToPointThreshold = 4; + // proximity to waypoint which must be reached to switch target to next waypoint : only used in PointToPoint mode. public enum ProgressStyle @@ -66,7 +79,6 @@ private void Start() Reset(); } - // reset the object to sensible values public void Reset() { @@ -79,7 +91,6 @@ public void Reset() } } - private void Update() { if (progressStyle == ProgressStyle.SmoothAlongRoute) @@ -89,24 +100,35 @@ private void Update() // we use lerp as a simple way of smoothing out the speed over time. if (Time.deltaTime > 0) { - speed = Mathf.Lerp(speed, (lastPosition - transform.position).magnitude/Time.deltaTime, - Time.deltaTime); + speed = Mathf.Lerp( + speed, + (lastPosition - transform.position).magnitude / Time.deltaTime, + Time.deltaTime + ); } - target.position = - circuit.GetRoutePoint(progressDistance + lookAheadForTargetOffset + lookAheadForTargetFactor*speed) - .position; - target.rotation = - Quaternion.LookRotation( - circuit.GetRoutePoint(progressDistance + lookAheadForSpeedOffset + lookAheadForSpeedFactor*speed) - .direction); - + target.position = circuit + .GetRoutePoint( + progressDistance + + lookAheadForTargetOffset + + lookAheadForTargetFactor * speed + ) + .position; + target.rotation = Quaternion.LookRotation( + circuit + .GetRoutePoint( + progressDistance + + lookAheadForSpeedOffset + + lookAheadForSpeedFactor * speed + ) + .direction + ); // get our current progress along the route progressPoint = circuit.GetRoutePoint(progressDistance); Vector3 progressDelta = progressPoint.position - transform.position; if (Vector3.Dot(progressDelta, progressPoint.direction) < 0) { - progressDistance += progressDelta.magnitude*0.5f; + progressDistance += progressDelta.magnitude * 0.5f; } lastPosition = transform.position; @@ -118,10 +140,9 @@ private void Update() Vector3 targetDelta = target.position - transform.position; if (targetDelta.magnitude < pointToPointThreshold) { - progressNum = (progressNum + 1)%circuit.Waypoints.Length; + progressNum = (progressNum + 1) % circuit.Waypoints.Length; } - target.position = circuit.Waypoints[progressNum].position; target.rotation = circuit.Waypoints[progressNum].rotation; @@ -136,7 +157,6 @@ private void Update() } } - private void OnDrawGizmos() { if (Application.isPlaying) diff --git a/unity/Assets/UnitTests/Procedural/Assets/TestProceduralAssetCache.cs b/unity/Assets/UnitTests/Procedural/Assets/TestProceduralAssetCache.cs index edbb568484..2de10b14f5 100644 --- a/unity/Assets/UnitTests/Procedural/Assets/TestProceduralAssetCache.cs +++ b/unity/Assets/UnitTests/Procedural/Assets/TestProceduralAssetCache.cs @@ -1,28 +1,24 @@ +using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using NUnit.Framework; -using System; +using Thor.Procedural; +using Thor.Procedural.Data; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -using Thor.Procedural; -using Thor.Procedural.Data; -using System.Linq; + // using Priority_Queue; -namespace Tests { +namespace Tests +{ public class TestProceduralAssetCache { [UnityTest] - public IEnumerator TestBinaryValuedPriority() { - - var preloadedContent = new List() { - "1", - "2", - "3", - "4", - "5" - }; + public IEnumerator TestBinaryValuedPriority() + { + var preloadedContent = new List() { "1", "2", "3", "4", "5" }; int minPrioVal = 0; int maxPrioVal = 1; @@ -36,23 +32,17 @@ public IEnumerator TestBinaryValuedPriority() { cache.addAsset("6", "6", procedural: true); cache.addAsset("7", "7", procedural: true); cache.addAsset("8", "8", procedural: true); - + Assert.AreEqual(cache.Count(), 8); - cache.touch(new List { - "6", - "8" - }); + cache.touch(new List { "6", "8" }); - Assert.AreEqual(cache.priorityMinValue, minPrioVal+1); - Assert.AreEqual(cache.priorityMaxValue, maxPrioVal+1); + Assert.AreEqual(cache.priorityMinValue, minPrioVal + 1); + Assert.AreEqual(cache.priorityMaxValue, maxPrioVal + 1); cache.removeLRU(limit: 2); - var shouldRemain = preloadedContent.Concat(new List{ - "6", - "8" - }); + var shouldRemain = preloadedContent.Concat(new List { "6", "8" }); Debug.Log($"keys: {string.Join(", ", cache.Keys())}"); Assert.IsTrue(cache.Keys().All(k => shouldRemain.Contains(k))); @@ -61,15 +51,9 @@ public IEnumerator TestBinaryValuedPriority() { } [UnityTest] - public IEnumerator TestMultiValuedPriority() { - - var preloadedContent = new List() { - "1", - "2", - "3", - "4", - "5" - }; + public IEnumerator TestMultiValuedPriority() + { + var preloadedContent = new List() { "1", "2", "3", "4", "5" }; int minPrioVal = 0; int maxPrioVal = 10; @@ -83,31 +67,20 @@ public IEnumerator TestMultiValuedPriority() { cache.addAsset("6", "6", procedural: true); cache.addAsset("7", "7", procedural: true); cache.addAsset("8", "8", procedural: true); - + Assert.AreEqual(cache.Count(), 8); - cache.touch(new List { - "6", - "8" - }); + cache.touch(new List { "6", "8" }); - cache.touch(new List { - "6", - }); + cache.touch(new List { "6", }); - cache.touch(new List { - "6", - }); + cache.touch(new List { "6", }); - cache.touch(new List { - "8", - }); + cache.touch(new List { "8", }); cache.removeLRU(limit: 1); - var shouldRemain = preloadedContent.Concat(new List{ - "8" - }); + var shouldRemain = preloadedContent.Concat(new List { "8" }); Debug.Log($"keys: {string.Join(", ", cache.Keys())}"); Assert.IsTrue(cache.Keys().All(k => shouldRemain.Contains(k))); @@ -116,15 +89,9 @@ public IEnumerator TestMultiValuedPriority() { } [UnityTest] - public IEnumerator TestDontDeleteHighestPrio() { - - var preloadedContent = new List() { - "1", - "2", - "3", - "4", - "5" - }; + public IEnumerator TestDontDeleteHighestPrio() + { + var preloadedContent = new List() { "1", "2", "3", "4", "5" }; int minPrioVal = 0; int maxPrioVal = 10; @@ -139,37 +106,20 @@ public IEnumerator TestDontDeleteHighestPrio() { cache.addAsset("7", "7", procedural: true); cache.addAsset("8", "8", procedural: true); cache.addAsset("9", "9", procedural: true); - + Assert.AreEqual(cache.Count(), 9); - cache.touch(new List { - "6", - "8", - "9" - }); + cache.touch(new List { "6", "8", "9" }); - cache.touch(new List { - "6", - "9" - }); + cache.touch(new List { "6", "9" }); - cache.touch(new List { - "6", - "8", - "9" - }); + cache.touch(new List { "6", "8", "9" }); - cache.touch(new List { - "6", - "9" - }); + cache.touch(new List { "6", "9" }); cache.removeLRU(limit: 1, deleteWithHighestPriority: false); - var shouldRemain = preloadedContent.Concat(new List{ - "6", - "9" - }); + var shouldRemain = preloadedContent.Concat(new List { "6", "9" }); Debug.Log($"keys: {string.Join(", ", cache.Keys())}"); Assert.IsTrue(cache.Keys().All(k => shouldRemain.Contains(k))); @@ -177,19 +127,13 @@ public IEnumerator TestDontDeleteHighestPrio() { yield return true; } - [UnityTest] - public IEnumerator TestIntegerLimits() { - - var preloadedContent = new List() { - "1", - "2", - "3", - "4", - "5" - }; + [UnityTest] + public IEnumerator TestIntegerLimits() + { + var preloadedContent = new List() { "1", "2", "3", "4", "5" }; - int minRankingVal = int.MaxValue-2; - int maxRankingVal = int.MaxValue-1; + int minRankingVal = int.MaxValue - 2; + int maxRankingVal = int.MaxValue - 1; var cache = new ProceduralLRUCacheAssetMap( preloadedContent.GroupBy(p => p).ToDictionary(p => p.Key, p => p.First()), @@ -200,19 +144,15 @@ public IEnumerator TestIntegerLimits() { cache.addAsset("6", "6", procedural: true); cache.addAsset("7", "7", procedural: true); cache.addAsset("8", "8", procedural: true); - + Assert.AreEqual(cache.Count(), 8); - cache.touch(new List { - "6", - }); + cache.touch(new List { "6", }); Assert.AreEqual(cache.priorityMinValue, minRankingVal); Assert.AreEqual(cache.priorityMaxValue, maxRankingVal); - cache.touch(new List { - "6", - }); + cache.touch(new List { "6", }); Assert.AreEqual(cache.priorityMinValue, minRankingVal); Assert.AreEqual(cache.priorityMaxValue, maxRankingVal); @@ -221,5 +161,3 @@ public IEnumerator TestIntegerLimits() { } } } - - diff --git a/unity/Assets/UnitTests/Procedural/Movement/TestProceduralTeleport.cs b/unity/Assets/UnitTests/Procedural/Movement/TestProceduralTeleport.cs index ce4aa3c29d..4f08054e24 100644 --- a/unity/Assets/UnitTests/Procedural/Movement/TestProceduralTeleport.cs +++ b/unity/Assets/UnitTests/Procedural/Movement/TestProceduralTeleport.cs @@ -1,24 +1,24 @@ +using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using NUnit.Framework; -using System; +using Thor.Procedural; +using Thor.Procedural.Data; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -using Thor.Procedural; -using Thor.Procedural.Data; -using System.Linq; -namespace Tests { +namespace Tests +{ public class TestProceduralTeleport : TestBaseProcedural { - - protected HouseTemplate houseTemplate = new HouseTemplate() { - metadata = new HouseMetadata() { - schema = ProceduralTools.CURRENT_HOUSE_SCHEMA - }, - id = "house_0", - layout = $@" + protected HouseTemplate houseTemplate = new HouseTemplate() + { + metadata = new HouseMetadata() { schema = ProceduralTools.CURRENT_HOUSE_SCHEMA }, + id = "house_0", + layout = + $@" 0 0 0 0 0 0 0 2 2 2 2 0 0 2 2 2 2 0 @@ -26,17 +26,17 @@ 0 1 1 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 ", - objectsLayouts = new List() { - $@" + objectsLayouts = new List() + { + $@" 0 0 0 0 0 0 0 2 2 2 2 0 0 2 2 2 = 0 0 1 1 1 = 0 0 1 * 1 + 0 0 0 0 0 0 0 - " - , - $@" + ", + $@" 0 0 0 0 0 0 0 2 2 2 2 0 0 2 2 2 2 0 @@ -44,66 +44,97 @@ 0 1 1 1 1 0 0 1 1 1 $ 0 0 0 0 0 0 0 " - }, - rooms = new Dictionary() { - {"1", new RoomTemplate(){ - wallTemplate = new PolygonWall() { - material = new MaterialProperties() { - color = SerializableColor.fromUnityColor(Color.red), - unlit = true - } - }, - floorTemplate = new RoomHierarchy() { - floorMaterial = new MaterialProperties() { name = "DarkWoodFloors" }, - roomType = "Bedroom" - }, - wallHeight = 3.0f - }}, - {"2", new RoomTemplate(){ - wallTemplate = new PolygonWall() { - material = new MaterialProperties() { - color = SerializableColor.fromUnityColor(Color.blue), - unlit = true - } - }, - floorTemplate = new RoomHierarchy() { - floorMaterial = new MaterialProperties() { name = "RedBrick" }, - roomType = "LivingRoom" - }, - wallHeight = 3.0f - }} - }, - doors = new Dictionary() { - {"=", new Thor.Procedural.Data.Door(){ - openness = 1.0f, - assetId = "Doorway_1", - room0 = "1" - - }} - }, - objects = new Dictionary() { - {"*", new HouseObject(){ - assetId = "Dining_Table_16_2", - rotation = new FlexibleRotation() { axis = new Vector3(0, 1, 0), degrees = 90} - }}, - {"+", new HouseObject(){ - assetId = "Chair_007_1" - }}, - {"$", new HouseObject(){ - assetId = "Apple_4", - position = new Vector3(0, 2, 0) - }} - }, - proceduralParameters = new ProceduralParameters() { - ceilingMaterial = new MaterialProperties() { name = "ps_mat" }, - floorColliderThickness = 1.0f, - receptacleHeight = 0.7f, - skyboxId = "Sky1", + }, + rooms = new Dictionary() + { + { + "1", + new RoomTemplate() + { + wallTemplate = new PolygonWall() + { + material = new MaterialProperties() + { + color = SerializableColor.fromUnityColor(Color.red), + unlit = true + } + }, + floorTemplate = new RoomHierarchy() + { + floorMaterial = new MaterialProperties() { name = "DarkWoodFloors" }, + roomType = "Bedroom" + }, + wallHeight = 3.0f + } + }, + { + "2", + new RoomTemplate() + { + wallTemplate = new PolygonWall() + { + material = new MaterialProperties() + { + color = SerializableColor.fromUnityColor(Color.blue), + unlit = true + } + }, + floorTemplate = new RoomHierarchy() + { + floorMaterial = new MaterialProperties() { name = "RedBrick" }, + roomType = "LivingRoom" + }, + wallHeight = 3.0f + } + } + }, + doors = new Dictionary() + { + { + "=", + new Thor.Procedural.Data.Door() + { + openness = 1.0f, + assetId = "Doorway_1", + room0 = "1" + } + } + }, + objects = new Dictionary() + { + { + "*", + new HouseObject() + { + assetId = "Dining_Table_16_2", + rotation = new FlexibleRotation() + { + axis = new Vector3(0, 1, 0), + degrees = 90 + } } - }; + }, + { + "+", + new HouseObject() { assetId = "Chair_007_1" } + }, + { + "$", + new HouseObject() { assetId = "Apple_4", position = new Vector3(0, 2, 0) } + } + }, + proceduralParameters = new ProceduralParameters() + { + ceilingMaterial = new MaterialProperties() { name = "ps_mat" }, + floorColliderThickness = 1.0f, + receptacleHeight = 0.7f, + skyboxId = "Sky1", + } + }; [UnityTest] - public IEnumerator TestTeleport() { + public IEnumerator TestTeleport() + { // House Layout: // $@" // 0 0 0 0 0 0 @@ -114,40 +145,42 @@ public IEnumerator TestTeleport() { // 0 0 0 0 0 0 // ", - var house = Templates.createHouseFromTemplate( - this.houseTemplate - ); + var house = Templates.createHouseFromTemplate(this.houseTemplate); - yield return step(new Dictionary() { - { "gridSize", 0.25f}, - { "agentCount", 1}, - { "fieldOfView", 90f}, - { "snapToGrid", false}, - { "procedural", true}, - { "action", "Initialize"}, - {"agentMode", "stretch"} - }); + yield return step( + new Dictionary() + { + { "gridSize", 0.25f }, + { "agentCount", 1 }, + { "fieldOfView", 90f }, + { "snapToGrid", false }, + { "procedural", true }, + { "action", "Initialize" }, + { "agentMode", "stretch" } + } + ); yield return new WaitForSeconds(2f); Debug.Log($"ActionSuccess: {lastActionSuccess}"); yield return step( - new Dictionary() { - { "house", house}, - { "action", "CreateHouse"} - }); + new Dictionary() { { "house", house }, { "action", "CreateHouse" } } + ); Debug.Log($"ActionSuccess: {lastActionSuccess}"); - - yield return step(new Dictionary() { - { "action", "TeleportFull"}, - { "position", new Vector3(3f, 0.91f, 1.0f)}, //adjusting Y value to be within the error (0.05) of the floor. - { "rotation", new Vector3(0f, 180f, 0f)}, + + yield return step( + new Dictionary() + { + { "action", "TeleportFull" }, + { "position", new Vector3(3f, 0.91f, 1.0f) }, //adjusting Y value to be within the error (0.05) of the floor. + { "rotation", new Vector3(0f, 180f, 0f) }, // {"forceAction", true}, - { "horizon", -20f}, - {"standing", true} - }); + { "horizon", -20f }, + { "standing", true } + } + ); - Debug.Log($"ActionSuccess: {lastActionSuccess}"); + Debug.Log($"ActionSuccess: {lastActionSuccess}"); //yield return new WaitForSeconds(60f); @@ -158,12 +191,9 @@ public IEnumerator TestTeleport() { // Debug.Log("180 rot_manipulator " + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y); - - + + yield return true; } - } } - - diff --git a/unity/Assets/UnitTests/Procedural/Physics/TestOpenClose.cs b/unity/Assets/UnitTests/Procedural/Physics/TestOpenClose.cs index ef7f7f5cf8..027c8479d6 100644 --- a/unity/Assets/UnitTests/Procedural/Physics/TestOpenClose.cs +++ b/unity/Assets/UnitTests/Procedural/Physics/TestOpenClose.cs @@ -1,80 +1,109 @@ +using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using NUnit.Framework; -using System; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -using System.Linq; -namespace Tests { - public class TestOpenClose : TestBase { +namespace Tests +{ + public class TestOpenClose : TestBase + { [SetUp] - public override void Setup() { + public override void Setup() + { UnityEngine.SceneManagement.SceneManager.LoadScene("FloorPlan1_physics"); } [UnityTest] - public IEnumerator TestOpening() { - - yield return step(new Dictionary() { - { "action", "Initialize"}, - { "agentMode", "arm"}, - { "agentControllerType", "mid-level"}, - { "renderInstanceSegmentation", true} - }); + public IEnumerator TestOpening() + { + yield return step( + new Dictionary() + { + { "action", "Initialize" }, + { "agentMode", "arm" }, + { "agentControllerType", "mid-level" }, + { "renderInstanceSegmentation", true } + } + ); yield return new WaitForSeconds(2f); - yield return step(new Dictionary() { - { "action", "MoveAgent"}, - { "right", -0.7f}, - { "physicsSimulationParams", new PhysicsSimulationParams() { autoSimulation = false}}, - { "returnToStart", true} - }); + yield return step( + new Dictionary() + { + { "action", "MoveAgent" }, + { "right", -0.7f }, + { + "physicsSimulationParams", + new PhysicsSimulationParams() { autoSimulation = false } + }, + { "returnToStart", true } + } + ); //yield return new WaitForSeconds(2f); - yield return step(new Dictionary() { - { "action", "MoveArm"}, - { "coordinateSpace", "world"}, - { "physicsSimulationParams", new PhysicsSimulationParams() { autoSimulation = false}}, - { "position", new Vector3(-1.3149f, 0.6049995f, 0.04580003f)} - }); + yield return step( + new Dictionary() + { + { "action", "MoveArm" }, + { "coordinateSpace", "world" }, + { + "physicsSimulationParams", + new PhysicsSimulationParams() { autoSimulation = false } + }, + { "position", new Vector3(-1.3149f, 0.6049995f, 0.04580003f) } + } + ); //yield return new WaitForSeconds(2f); - yield return step(new Dictionary() { - { "action", "LookDown"}, - { "degrees", 30f} - }); + yield return step( + new Dictionary() { { "action", "LookDown" }, { "degrees", 30f } } + ); //yield return new WaitForSeconds(2f); - yield return step(new Dictionary() { - { "action", "OpenObject"}, - { "objectId", "Cabinet|-01.55|+00.50|+00.38"}, - { "useGripper", true}, - { "returnToStart", true}, - { "stopAtNonStaticCol", false} - }); + yield return step( + new Dictionary() + { + { "action", "OpenObject" }, + { "objectId", "Cabinet|-01.55|+00.50|+00.38" }, + { "useGripper", true }, + { "returnToStart", true }, + { "stopAtNonStaticCol", false } + } + ); // yield return new WaitUntil(() => getActiveAgent().agentState == AgentState.ActionComplete); //yield return new WaitForSeconds(2f); - Transform testCabinetDoor = GameObject.Find("Cabinet_67e9cbea").transform.Find("CabinetDoor"); - bool testCabinetDoorOpened = Mathf.Approximately((testCabinetDoor.localEulerAngles.y + 360) % 360, 270); - Debug.Log($"testCabinetDoorOpened-- {testCabinetDoorOpened} angles y {testCabinetDoor.localEulerAngles.y}"); + Transform testCabinetDoor = GameObject + .Find("Cabinet_67e9cbea") + .transform.Find("CabinetDoor"); + bool testCabinetDoorOpened = Mathf.Approximately( + (testCabinetDoor.localEulerAngles.y + 360) % 360, + 270 + ); + Debug.Log( + $"testCabinetDoorOpened-- {testCabinetDoorOpened} angles y {testCabinetDoor.localEulerAngles.y}" + ); Assert.AreEqual(testCabinetDoorOpened, true); yield return true; } - protected string serializeObject(object obj) { + protected string serializeObject(object obj) + { var jsonResolver = new ShouldSerializeContractResolver(); return Newtonsoft.Json.JsonConvert.SerializeObject( obj, Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { + new Newtonsoft.Json.JsonSerializerSettings() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver } ); } } -} \ No newline at end of file +} diff --git a/unity/Assets/UnitTests/Procedural/Physics/TestStretchAdvancedRotate.cs b/unity/Assets/UnitTests/Procedural/Physics/TestStretchAdvancedRotate.cs index 06f43baa3e..6e0f310bee 100644 --- a/unity/Assets/UnitTests/Procedural/Physics/TestStretchAdvancedRotate.cs +++ b/unity/Assets/UnitTests/Procedural/Physics/TestStretchAdvancedRotate.cs @@ -1,120 +1,210 @@ +using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using NUnit.Framework; -using System; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -using System.Linq; -namespace Tests { - public class TestStretchAdvancedRotate : TestBase { +namespace Tests +{ + public class TestStretchAdvancedRotate : TestBase + { [SetUp] - public override void Setup() { + public override void Setup() + { UnityEngine.SceneManagement.SceneManager.LoadScene("FloorPlan1_physics"); } [UnityTest] - public IEnumerator TestAbsoluteRotating() { - - yield return step(new Dictionary() { - { "action", "Initialize"}, - { "agentMode", "stretch"}, - { "agentControllerType", "stretch"}, - { "renderInstanceSegmentation", true} - }); + public IEnumerator TestAbsoluteRotating() + { + yield return step( + new Dictionary() + { + { "action", "Initialize" }, + { "agentMode", "stretch" }, + { "agentControllerType", "stretch" }, + { "renderInstanceSegmentation", true } + } + ); yield return new WaitForSeconds(2f); - Debug.Log("0 rot_manipulator " + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y); + Debug.Log( + "0 rot_manipulator " + + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y + ); // set wrist to default 180-state (i.e. fingers facing back towards the main agent body) - yield return step(new Dictionary() { - { "action", "RotateWrist"}, - { "yaw", 180f}, - { "physicsSimulationParams", new PhysicsSimulationParams() { autoSimulation = false}}, - { "returnToStart", false} - }); - Debug.Log("180 rot_manipulator " + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y); + yield return step( + new Dictionary() + { + { "action", "RotateWrist" }, + { "yaw", 180f }, + { + "physicsSimulationParams", + new PhysicsSimulationParams() { autoSimulation = false } + }, + { "returnToStart", false } + } + ); + Debug.Log( + "180 rot_manipulator " + + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y + ); // These two commands stress-test the degree input-normalization, the procedural directionality, AND the dead-zone encroachment of the wrist-rotation - yield return step(new Dictionary() { - { "action", "RotateWrist"}, - { "yaw", -271f}, - { "physicsSimulationParams", new PhysicsSimulationParams() { autoSimulation = false}}, - { "returnToStart", false} - }); - - Debug.Log("rot_manipulator " + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y); - Assert.AreEqual(Mathf.Approximately(GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y, 69.06705f), true); - - yield return step(new Dictionary() { - { "action", "RotateWrist"}, - { "yaw", 451f}, - { "physicsSimulationParams", new PhysicsSimulationParams() { autoSimulation = false}}, - { "returnToStart",false} - }); - Assert.AreEqual(Mathf.Approximately(GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y, 111.0896f), true); + yield return step( + new Dictionary() + { + { "action", "RotateWrist" }, + { "yaw", -271f }, + { + "physicsSimulationParams", + new PhysicsSimulationParams() { autoSimulation = false } + }, + { "returnToStart", false } + } + ); + + Debug.Log( + "rot_manipulator " + + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y + ); + Assert.AreEqual( + Mathf.Approximately( + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y, + 69.06705f + ), + true + ); + + yield return step( + new Dictionary() + { + { "action", "RotateWrist" }, + { "yaw", 451f }, + { + "physicsSimulationParams", + new PhysicsSimulationParams() { autoSimulation = false } + }, + { "returnToStart", false } + } + ); + Assert.AreEqual( + Mathf.Approximately( + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y, + 111.0896f + ), + true + ); yield return true; } [UnityTest] - public IEnumerator TestRelativeRotating() { - - yield return step(new Dictionary() { - { "action", "Initialize"}, - { "agentMode", "stretch"}, - { "agentControllerType", "stretch"}, - { "renderInstanceSegmentation", true} - }); + public IEnumerator TestRelativeRotating() + { + yield return step( + new Dictionary() + { + { "action", "Initialize" }, + { "agentMode", "stretch" }, + { "agentControllerType", "stretch" }, + { "renderInstanceSegmentation", true } + } + ); yield return new WaitForSeconds(2f); - Debug.Log("0 rot_manipulator " + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y); - + Debug.Log( + "0 rot_manipulator " + + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y + ); // set wrist to default 180-state (i.e. fingers facing back towards the main agent body) - yield return step(new Dictionary() { - { "action", "RotateWrist"}, - { "yaw", 180f}, - { "physicsSimulationParams", new PhysicsSimulationParams() { autoSimulation = false}}, - { "returnToStart", false} - }); + yield return step( + new Dictionary() + { + { "action", "RotateWrist" }, + { "yaw", 180f }, + { + "physicsSimulationParams", + new PhysicsSimulationParams() { autoSimulation = false } + }, + { "returnToStart", false } + } + ); - Debug.Log("180 rot_manipulator " + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y); + Debug.Log( + "180 rot_manipulator " + + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y + ); - // These two commands stress-test the degree input-normalization AND the dead-zone encroachment of the wrist relative-rotation - yield return step(new Dictionary() { - { "action", "RotateWristRelative"}, - { "yaw", 630f}, - { "physicsSimulationParams", new PhysicsSimulationParams() { autoSimulation = false}}, - { "returnToStart", false} - }); - Debug.Log("630 rot_manipulator " + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y); - - Assert.AreEqual(Mathf.Approximately(GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y, 69.56489f), true); - - yield return step(new Dictionary() { - { "action", "RotateWristRelative"}, - { "yaw", -699.56489f}, - { "physicsSimulationParams", new PhysicsSimulationParams() { autoSimulation = false}}, - { "returnToStart", false} - }); - Debug.Log("-699 rot_manipulator " + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y); - - Assert.AreEqual(Mathf.Approximately(GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y, 110.8419f), true); + yield return step( + new Dictionary() + { + { "action", "RotateWristRelative" }, + { "yaw", 630f }, + { + "physicsSimulationParams", + new PhysicsSimulationParams() { autoSimulation = false } + }, + { "returnToStart", false } + } + ); + Debug.Log( + "630 rot_manipulator " + + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y + ); + + Assert.AreEqual( + Mathf.Approximately( + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y, + 69.56489f + ), + true + ); + + yield return step( + new Dictionary() + { + { "action", "RotateWristRelative" }, + { "yaw", -699.56489f }, + { + "physicsSimulationParams", + new PhysicsSimulationParams() { autoSimulation = false } + }, + { "returnToStart", false } + } + ); + Debug.Log( + "-699 rot_manipulator " + + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y + ); + + Assert.AreEqual( + Mathf.Approximately( + GameObject.Find("stretch_robot_pos_rot_manipulator").transform.eulerAngles.y, + 110.8419f + ), + true + ); } - protected string serializeObject(object obj) { + protected string serializeObject(object obj) + { var jsonResolver = new ShouldSerializeContractResolver(); return Newtonsoft.Json.JsonConvert.SerializeObject( obj, Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { + new Newtonsoft.Json.JsonSerializerSettings() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver } ); } } -} \ No newline at end of file +} diff --git a/unity/Assets/UnitTests/Procedural/Rendering/TestRendering.cs b/unity/Assets/UnitTests/Procedural/Rendering/TestRendering.cs index db4aeaba44..f60590d026 100644 --- a/unity/Assets/UnitTests/Procedural/Rendering/TestRendering.cs +++ b/unity/Assets/UnitTests/Procedural/Rendering/TestRendering.cs @@ -1,25 +1,27 @@ +using System; using System.Collections; using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Media; using NUnit.Framework; -using System; -using UnityEngine; -using UnityEngine.TestTools; using Thor.Procedural; using Thor.Procedural.Data; -using System.Linq; -using System.IO; -using System.Media; +using UnityEngine; +using UnityEngine.TestTools; -namespace Tests { - public class TestRendering : TestBaseProcedural { - protected HouseTemplate houseTemplate = new HouseTemplate() { - metadata = new HouseMetadata() { - schema = "1.0.0" - }, +namespace Tests +{ + public class TestRendering : TestBaseProcedural + { + protected HouseTemplate houseTemplate = new HouseTemplate() + { + metadata = new HouseMetadata() { schema = "1.0.0" }, id = "house_0", // TODO, some assumptions can be done to place doors and objects in `layout` // and use `objectsLayouts` for any possible inconsistencies or layering instead of being mandatory for objects - layout = $@" + layout = + $@" 0 0 0 0 0 0 0 2 2 2 2 0 0 2 2 2 2 0 @@ -27,8 +29,9 @@ 0 1 1 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 ", - objectsLayouts = new List() { - $@" + objectsLayouts = new List() + { + $@" 0 0 0 0 0 0 0 2 2 2 2 0 0 2 2 2 = 0 @@ -36,44 +39,64 @@ 0 2 2 2 2 0 0 1 1 1 1 0 0 0 0 0 0 0 " - }, - rooms = new Dictionary() { - {"1", new RoomTemplate(){ - wallTemplate = new PolygonWall() { - material = new MaterialProperties() { - color = SerializableColor.fromUnityColor(Color.red), - unlit = true - } - }, - floorTemplate = new RoomHierarchy() { - floorMaterial = new MaterialProperties() { name ="DarkWoodFloors" }, - roomType = "Bedroom" - }, - wallHeight = 3.0f - }}, - {"2", new RoomTemplate(){ - wallTemplate = new PolygonWall() { - material = new MaterialProperties() { - color = SerializableColor.fromUnityColor(Color.blue), - unlit = true - } - }, - floorTemplate = new RoomHierarchy() { - floorMaterial = new MaterialProperties() { name = "RedBrick" }, - roomType = "LivingRoom" - }, - wallHeight = 3.0f - }} - }, - doors = new Dictionary() { - {"=", new Thor.Procedural.Data.Door(){ - openness = 1.0f, - assetId = "Doorway_1", - room0 = "1" - - }} - }, - proceduralParameters = new ProceduralParameters() { + }, + rooms = new Dictionary() + { + { + "1", + new RoomTemplate() + { + wallTemplate = new PolygonWall() + { + material = new MaterialProperties() + { + color = SerializableColor.fromUnityColor(Color.red), + unlit = true + } + }, + floorTemplate = new RoomHierarchy() + { + floorMaterial = new MaterialProperties() { name = "DarkWoodFloors" }, + roomType = "Bedroom" + }, + wallHeight = 3.0f + } + }, + { + "2", + new RoomTemplate() + { + wallTemplate = new PolygonWall() + { + material = new MaterialProperties() + { + color = SerializableColor.fromUnityColor(Color.blue), + unlit = true + } + }, + floorTemplate = new RoomHierarchy() + { + floorMaterial = new MaterialProperties() { name = "RedBrick" }, + roomType = "LivingRoom" + }, + wallHeight = 3.0f + } + } + }, + doors = new Dictionary() + { + { + "=", + new Thor.Procedural.Data.Door() + { + openness = 1.0f, + assetId = "Doorway_1", + room0 = "1" + } + } + }, + proceduralParameters = new ProceduralParameters() + { ceilingMaterial = new MaterialProperties() { name = "ps_mat" }, floorColliderThickness = 1.0f, receptacleHeight = 0.7f, @@ -82,7 +105,8 @@ 0 0 0 0 0 0 }; [UnityTest] - public IEnumerator TestUnlitRgbImage() { + public IEnumerator TestUnlitRgbImage() + { // $@" // 0 0 0 0 0 0 // 0 2 2 2 2 0 @@ -93,46 +117,52 @@ public IEnumerator TestUnlitRgbImage() { // ", var house = createTestHouse(); - yield return step(new Dictionary() { - { "gridSize", 0.25f}, - { "agentCount", 1}, - { "fieldOfView", 45.0f}, - { "snapToGrid", true}, - { "procedural", true}, - { "action", "Initialize"} - }); + yield return step( + new Dictionary() + { + { "gridSize", 0.25f }, + { "agentCount", 1 }, + { "fieldOfView", 45.0f }, + { "snapToGrid", true }, + { "procedural", true }, + { "action", "Initialize" } + } + ); Debug.Log("Pre Agent pos " + this.getLastActionMetadata().agent.position); ProceduralTools.CreateHouse(house, ProceduralTools.GetMaterials()); yield return step( - new Dictionary() { - { "position", new Vector3(3.0f, 1.0f, 0.2f)}, - { "rotation", new Vector3(0, 180, 0)}, - { "horizon", 0.0f}, - { "standing", true}, - { "forceAction", true}, - { "action", "TeleportFull"} - }); + new Dictionary() + { + { "position", new Vector3(3.0f, 1.0f, 0.2f) }, + { "rotation", new Vector3(0, 180, 0) }, + { "horizon", 0.0f }, + { "standing", true }, + { "forceAction", true }, + { "action", "TeleportFull" } + } + ); var rgbBytes = this.renderPayload.Find(e => e.Key == "image").Value; var eps = 40; - var assertResult = rgbBytes.Select((pixel, index) => (pixel, index)) - .All( - e => - (e.index % 3 == 0 && 255 - e.pixel <= eps) || - (e.index % 3 != 0 && e.pixel <= eps) + var assertResult = rgbBytes + .Select((pixel, index) => (pixel, index)) + .All(e => + (e.index % 3 == 0 && 255 - e.pixel <= eps) + || (e.index % 3 != 0 && e.pixel <= eps) ); - if (!assertResult) { + if (!assertResult) + { savePng(rgbBytes, getBuildMachineTestOutputPath("test_comp.png", false)); } // TODO: Disabling test because lighting in build machine is always enabled, // requires investigation, probably save the scene in this test with editor tools - // and examine scene in machine + // and examine scene in machine // Unlit red wall // Assert.True( // assertResult @@ -140,7 +170,8 @@ public IEnumerator TestUnlitRgbImage() { } [UnityTest] - public IEnumerator TestLitRgbImage() { + public IEnumerator TestLitRgbImage() + { // $@" // A is agent // 0 0 0 0 0 0 // 0 2 2 2 2 0 @@ -149,11 +180,14 @@ public IEnumerator TestLitRgbImage() { // 0 1 1 1 1 0 // 0 0 0 0 0 0 // ", - foreach (var room in houseTemplate.rooms.Values) { + foreach (var room in houseTemplate.rooms.Values) + { room.wallTemplate.unlit = false; } - houseTemplate.objectsLayouts = houseTemplate.objectsLayouts.Concat( - new List() { + houseTemplate.objectsLayouts = houseTemplate + .objectsLayouts.Concat( + new List() + { $@" 0 0 0 0 0 0 0 2 2 2 2 0 @@ -163,12 +197,14 @@ 0 1 1 1 + 0 0 0 0 0 0 0 " } - ).ToList(); - houseTemplate.objects = new Dictionary() { - {"+", new HouseObject(){ - assetId = "Chair_007_1", - kinematic = true - }} + ) + .ToList(); + houseTemplate.objects = new Dictionary() + { + { + "+", + new HouseObject() { assetId = "Chair_007_1", kinematic = true } + } }; var house = createTestHouse(); @@ -183,14 +219,16 @@ 0 0 0 0 0 0 Debug.Log($"After Window width {Screen.width} height {Screen.height}"); yield return step( - new Dictionary() { - { "position", new Vector3(3.0f, 1.0f, 1.0f)}, - { "rotation", new Vector3(0, 0, 0)}, - { "horizon", 0.0f}, - { "standing", true}, - { "forceAction", true}, - { "action", "TeleportFull"} - }); + new Dictionary() + { + { "position", new Vector3(3.0f, 1.0f, 1.0f) }, + { "rotation", new Vector3(0, 0, 0) }, + { "horizon", 0.0f }, + { "standing", true }, + { "forceAction", true }, + { "action", "TeleportFull" } + } + ); var rgbBytes = this.renderPayload.Find(e => e.Key == "image").Value; //Debug.Break(); @@ -214,16 +252,17 @@ 0 0 0 0 0 0 // rgbBytes.Zip(compareToPixels, (pixel, comp) => (pixel, comp)) // .All(e => e.pixel == e.comp) // ); - } - Texture2D duplicateTexture(Texture2D source) { + Texture2D duplicateTexture(Texture2D source) + { RenderTexture renderTex = RenderTexture.GetTemporary( - source.width, - source.height, - 0, - RenderTextureFormat.Default, - RenderTextureReadWrite.Linear); + source.width, + source.height, + 0, + RenderTextureFormat.Default, + RenderTextureReadWrite.Linear + ); Graphics.Blit(source, renderTex); RenderTexture previous = RenderTexture.active; @@ -237,8 +276,8 @@ Texture2D duplicateTexture(Texture2D source) { } [UnityTest] - - public IEnumerator TestDepth() { + public IEnumerator TestDepth() + { // $@" // A is agent // 0 0 0 0 0 0 // 0 2 2 2 2 0 @@ -248,28 +287,32 @@ public IEnumerator TestDepth() { // 0 0 0 0 0 0 // ", Screen.SetResolution(600, 600, false); - yield return step(new Dictionary() { - { "gridSize", 0.25f}, - { "agentCount", 1}, - { "fieldOfView", 90f}, - { "snapToGrid", false}, - { "procedural", true}, - { "renderDepthImage", true}, - { "action", "Initialize"} - }); + yield return step( + new Dictionary() + { + { "gridSize", 0.25f }, + { "agentCount", 1 }, + { "fieldOfView", 90f }, + { "snapToGrid", false }, + { "procedural", true }, + { "renderDepthImage", true }, + { "action", "Initialize" } + } + ); var house = createTestHouse(); ProceduralTools.CreateHouse(house, ProceduralTools.GetMaterials()); yield return step( - new Dictionary() { - - { "position", new Vector3(3.0f, 1.0f, 4.0f)}, - { "rotation", new Vector3(0, 180, 0)}, - { "horizon", 0.0f}, - { "standing", true}, - { "forceAction", true}, - { "action", "TeleportFull"} - }); + new Dictionary() + { + { "position", new Vector3(3.0f, 1.0f, 4.0f) }, + { "rotation", new Vector3(0, 180, 0) }, + { "horizon", 0.0f }, + { "standing", true }, + { "forceAction", true }, + { "action", "TeleportFull" } + } + ); var depth = this.renderPayload.Find(e => e.Key == "image_depth").Value; @@ -277,38 +320,44 @@ public IEnumerator TestDepth() { var centerIndex = (Screen.height / 2) + ((Screen.width / 2) * Screen.height); - Debug.Log($"Screen width: {Screen.width} height: {Screen.height}, Depth Element size: {itemSize}"); + Debug.Log( + $"Screen width: {Screen.width} height: {Screen.height}, Depth Element size: {itemSize}" + ); // TODO: Convert byte array into floats - Debug.Log($"r {depth[centerIndex]} g {depth[centerIndex + 1]} b {depth[centerIndex + 2]} a {depth[centerIndex + 3]} r1 {depth[centerIndex + 4]}"); - + Debug.Log( + $"r {depth[centerIndex]} g {depth[centerIndex + 1]} b {depth[centerIndex + 2]} a {depth[centerIndex + 3]} r1 {depth[centerIndex + 4]}" + ); } - protected virtual ProceduralHouse createTestHouse() { - var house = Templates.createHouseFromTemplate( - this.houseTemplate - ); + protected virtual ProceduralHouse createTestHouse() + { + var house = Templates.createHouseFromTemplate(this.houseTemplate); Debug.Log($"####### TEST HOUSE:\n {serializeHouse(house)}"); return house; } - protected string serializeObject(object obj) { + protected string serializeObject(object obj) + { var jsonResolver = new ShouldSerializeContractResolver(); return Newtonsoft.Json.JsonConvert.SerializeObject( obj, Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { + new Newtonsoft.Json.JsonSerializerSettings() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver } ); } - protected string serializeHouse(ProceduralHouse house) { + protected string serializeHouse(ProceduralHouse house) + { var jsonResolver = new ShouldSerializeContractResolver(); var houseString = Newtonsoft.Json.JsonConvert.SerializeObject( house, Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { + new Newtonsoft.Json.JsonSerializerSettings() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver } @@ -317,4 +366,4 @@ protected string serializeHouse(ProceduralHouse house) { return houseString; } } -} \ No newline at end of file +} diff --git a/unity/Assets/UnitTests/Procedural/Templates/TestProceduralTemplates.cs b/unity/Assets/UnitTests/Procedural/Templates/TestProceduralTemplates.cs index 3f8f7bef0a..4b10b60f57 100644 --- a/unity/Assets/UnitTests/Procedural/Templates/TestProceduralTemplates.cs +++ b/unity/Assets/UnitTests/Procedural/Templates/TestProceduralTemplates.cs @@ -1,26 +1,26 @@ +using System; using System.Collections; using System.Collections.Generic; +using System.Linq; using NUnit.Framework; -using System; +using Thor.Procedural; +using Thor.Procedural.Data; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -using Thor.Procedural; -using Thor.Procedural.Data; -using System.Linq; -namespace Tests { +namespace Tests +{ public class TestProceduralTemplates : TestBaseProcedural { - - protected HouseTemplate houseTemplate = new HouseTemplate() { - metadata = new HouseMetadata() { - schema = ProceduralTools.CURRENT_HOUSE_SCHEMA - }, - id = "house_0", - // TODO, some assumptions can be done to place doors and objects in `layout` - // and use `objectsLayouts` for any possible inconsistencies or layering instead of being mandatory for objects - layout = $@" + protected HouseTemplate houseTemplate = new HouseTemplate() + { + metadata = new HouseMetadata() { schema = ProceduralTools.CURRENT_HOUSE_SCHEMA }, + id = "house_0", + // TODO, some assumptions can be done to place doors and objects in `layout` + // and use `objectsLayouts` for any possible inconsistencies or layering instead of being mandatory for objects + layout = + $@" 0 0 0 0 0 0 0 2 2 2 2 0 0 2 2 2 2 0 @@ -28,17 +28,17 @@ 0 1 1 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 ", - objectsLayouts = new List() { - $@" + objectsLayouts = new List() + { + $@" 0 0 0 0 0 0 0 2 2 2 2 0 0 2 2 2 = 0 0 1 1 1 = 0 0 1 * 1 + 0 0 0 0 0 0 0 - " - , - $@" + ", + $@" 0 0 0 0 0 0 0 2 2 2 2 0 0 2 2 2 2 0 @@ -46,66 +46,97 @@ 0 1 1 1 1 0 0 1 1 1 $ 0 0 0 0 0 0 0 " - }, - rooms = new Dictionary() { - {"1", new RoomTemplate(){ - wallTemplate = new PolygonWall() { - material = new MaterialProperties() { - color = SerializableColor.fromUnityColor(Color.red), - unlit = true - } - }, - floorTemplate = new RoomHierarchy() { - floorMaterial = new MaterialProperties() { name = "DarkWoodFloors" }, - roomType = "Bedroom" - }, - wallHeight = 3.0f - }}, - {"2", new RoomTemplate(){ - wallTemplate = new PolygonWall() { - material = new MaterialProperties() { - color = SerializableColor.fromUnityColor(Color.blue), - unlit = true - } - }, - floorTemplate = new RoomHierarchy() { - floorMaterial = new MaterialProperties() { name = "RedBrick" }, - roomType = "LivingRoom" - }, - wallHeight = 3.0f - }} - }, - doors = new Dictionary() { - {"=", new Thor.Procedural.Data.Door(){ - openness = 1.0f, - assetId = "Doorway_1", - room0 = "1" - - }} - }, - objects = new Dictionary() { - {"*", new HouseObject(){ - assetId = "Dining_Table_16_2", - rotation = new FlexibleRotation() { axis = new Vector3(0, 1, 0), degrees = 90} - }}, - {"+", new HouseObject(){ - assetId = "Chair_007_1" - }}, - {"$", new HouseObject(){ - assetId = "Apple_4", - position = new Vector3(0, 2, 0) - }} - }, - proceduralParameters = new ProceduralParameters() { - ceilingMaterial = new MaterialProperties() { name = "ps_mat" }, - floorColliderThickness = 1.0f, - receptacleHeight = 0.7f, - skyboxId = "Sky1", + }, + rooms = new Dictionary() + { + { + "1", + new RoomTemplate() + { + wallTemplate = new PolygonWall() + { + material = new MaterialProperties() + { + color = SerializableColor.fromUnityColor(Color.red), + unlit = true + } + }, + floorTemplate = new RoomHierarchy() + { + floorMaterial = new MaterialProperties() { name = "DarkWoodFloors" }, + roomType = "Bedroom" + }, + wallHeight = 3.0f + } + }, + { + "2", + new RoomTemplate() + { + wallTemplate = new PolygonWall() + { + material = new MaterialProperties() + { + color = SerializableColor.fromUnityColor(Color.blue), + unlit = true + } + }, + floorTemplate = new RoomHierarchy() + { + floorMaterial = new MaterialProperties() { name = "RedBrick" }, + roomType = "LivingRoom" + }, + wallHeight = 3.0f } - }; + } + }, + doors = new Dictionary() + { + { + "=", + new Thor.Procedural.Data.Door() + { + openness = 1.0f, + assetId = "Doorway_1", + room0 = "1" + } + } + }, + objects = new Dictionary() + { + { + "*", + new HouseObject() + { + assetId = "Dining_Table_16_2", + rotation = new FlexibleRotation() + { + axis = new Vector3(0, 1, 0), + degrees = 90 + } + } + }, + { + "+", + new HouseObject() { assetId = "Chair_007_1" } + }, + { + "$", + new HouseObject() { assetId = "Apple_4", position = new Vector3(0, 2, 0) } + } + }, + proceduralParameters = new ProceduralParameters() + { + ceilingMaterial = new MaterialProperties() { name = "ps_mat" }, + floorColliderThickness = 1.0f, + receptacleHeight = 0.7f, + skyboxId = "Sky1", + } + }; [UnityTest] - public IEnumerator TestRooms() { + public IEnumerator TestRooms() + { // $@" // 0 0 0 0 0 0 // 0 2 2 2 2 0 @@ -115,30 +146,47 @@ public IEnumerator TestRooms() { // 0 0 0 0 0 0 // ", var house = createTestHouse(); - + Assert.AreEqual(house.rooms.Count, 2); - var roomIds = new HashSet() { "1", "2"}; - Assert.IsTrue(new HashSet(house.rooms.Select(x => x.id).Intersect(roomIds)).SetEquals(roomIds)); - var room2Poly = new List() { + var roomIds = new HashSet() { "1", "2" }; + Assert.IsTrue( + new HashSet(house.rooms.Select(x => x.id).Intersect(roomIds)).SetEquals( + roomIds + ) + ); + var room2Poly = new List() + { Vector3.zero, new Vector3(0.0f, 0.0f, 4.0f), new Vector3(2.0f, 0.0f, 4.0f), new Vector3(2.0f, 0.0f, 0.0f) }; - Assert.IsTrue(house.rooms.Find(r => r.id == "2").floorPolygon.Select((p, i) => (point: p, index: i)).All(e => room2Poly.ElementAt(e.index) == e.point)); + Assert.IsTrue( + house + .rooms.Find(r => r.id == "2") + .floorPolygon.Select((p, i) => (point: p, index: i)) + .All(e => room2Poly.ElementAt(e.index) == e.point) + ); - var room1Poly = new List() { + var room1Poly = new List() + { new Vector3(2.0f, 0.0f, 0.0f), new Vector3(2.0f, 0.0f, 4.0f), new Vector3(4.0f, 0.0f, 4.0f), new Vector3(4.0f, 0.0f, 0.0f) }; - Assert.IsTrue(house.rooms.Find(r => r.id == "1").floorPolygon.Select((p, i) => (point: p, index: i)).All(e => room1Poly.ElementAt(e.index) == e.point)); + Assert.IsTrue( + house + .rooms.Find(r => r.id == "1") + .floorPolygon.Select((p, i) => (point: p, index: i)) + .All(e => room1Poly.ElementAt(e.index) == e.point) + ); yield return true; } [UnityTest] - public IEnumerator TestWalls() { + public IEnumerator TestWalls() + { // $@" // 0 0 0 0 0 0 // 0 2 2 2 2 0 @@ -148,34 +196,53 @@ public IEnumerator TestWalls() { // 0 0 0 0 0 0 // ", var house = createTestHouse(); - - + Assert.AreEqual(house.walls.Count, 8); - Assert.IsTrue(house.walls.All(w => w.polygon.Max(p => p.y) == houseTemplate.rooms[w.roomId].wallHeight)); - - var room2WallPoints = new List<(Vector3, Vector3)>() { + Assert.IsTrue( + house.walls.All(w => + w.polygon.Max(p => p.y) == houseTemplate.rooms[w.roomId].wallHeight + ) + ); + + var room2WallPoints = new List<(Vector3, Vector3)>() + { (new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 4.0f)), (new Vector3(0.0f, 0.0f, 4.0f), new Vector3(2.0f, 0.0f, 4.0f)), (new Vector3(2.0f, 0.0f, 4.0f), new Vector3(2.0f, 0.0f, 0.0f)), (new Vector3(2.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 0.0f)) }; - Assert.IsTrue(house.walls.Where(w => w.roomId == "2").Select((wall, index) => (wall, index)).All(e => room2WallPoints.ElementAt(e.index) == (e.wall.polygon[0], e.wall.polygon[1]))); + Assert.IsTrue( + house + .walls.Where(w => w.roomId == "2") + .Select((wall, index) => (wall, index)) + .All(e => + room2WallPoints.ElementAt(e.index) == (e.wall.polygon[0], e.wall.polygon[1]) + ) + ); - var room1WallPoints = new List<(Vector3, Vector3)>() { + var room1WallPoints = new List<(Vector3, Vector3)>() + { (new Vector3(2.0f, 0.0f, 0.0f), new Vector3(2.0f, 0.0f, 4.0f)), (new Vector3(2.0f, 0.0f, 4.0f), new Vector3(4.0f, 0.0f, 4.0f)), (new Vector3(4.0f, 0.0f, 4.0f), new Vector3(4.0f, 0.0f, 0.0f)), (new Vector3(4.0f, 0.0f, 0.0f), new Vector3(2.0f, 0.0f, 0.0f)) }; - Assert.IsTrue(house.walls.Where(w => w.roomId == "1").Select((wall, index) => (wall, index)).All(e => room1WallPoints.ElementAt(e.index) == (e.wall.polygon[0], e.wall.polygon[1]))); - + Assert.IsTrue( + house + .walls.Where(w => w.roomId == "1") + .Select((wall, index) => (wall, index)) + .All(e => + room1WallPoints.ElementAt(e.index) == (e.wall.polygon[0], e.wall.polygon[1]) + ) + ); + yield return true; } - [UnityTest] - public IEnumerator TestObjects() { + public IEnumerator TestObjects() + { // $@" // 0 0 0 0 0 0 // 0 2 2 2 2 0 @@ -185,8 +252,7 @@ public IEnumerator TestObjects() { // 0 0 0 0 0 0 // " var house = createTestHouse(); - - + Assert.AreEqual(house.objects.Count, 3); var table = house.objects.Find(x => x.id == "*"); @@ -198,28 +264,38 @@ public IEnumerator TestObjects() { // Without bounding box center offset // Assert.IsTrue(table.position == new Vector3(4.0f, 0.0f, 2.0f)); var delta = 1e-1; - Assert.That(Vector3.Distance(table.position, new Vector3(3.7f, 0.8f, 1.7f)), Is.LessThanOrEqualTo(delta)); + Assert.That( + Vector3.Distance(table.position, new Vector3(3.7f, 0.8f, 1.7f)), + Is.LessThanOrEqualTo(delta) + ); Assert.IsTrue(table.assetId == "Dining_Table_16_2"); Debug.Log(chair.position); // Assert.IsTrue(chair.position == new Vector3(4.0f, 0.0f, 4.0f)); - Assert.That(Vector3.Distance(chair.position, new Vector3(3.2f, 1.1f, 3.2f)), Is.LessThanOrEqualTo(delta)); + Assert.That( + Vector3.Distance(chair.position, new Vector3(3.2f, 1.1f, 3.2f)), + Is.LessThanOrEqualTo(delta) + ); Assert.IsTrue(chair.assetId == "Chair_007_1"); Debug.Log(apple.position); // Assert.IsTrue(apple.position == new Vector3(4.0f, 2.0f, 4.0f)); - Assert.That(Vector3.Distance(apple.position, new Vector3(3.1f, 2.1f, 3.1f)), Is.LessThanOrEqualTo(delta)); - + Assert.That( + Vector3.Distance(apple.position, new Vector3(3.1f, 2.1f, 3.1f)), + Is.LessThanOrEqualTo(delta) + ); + Assert.IsTrue(apple.assetId == "Apple_4"); Assert.AreEqual(table.room, "1"); Assert.AreEqual(chair.room, "1"); Assert.AreEqual(apple.room, "1"); - + yield return true; } [UnityTest] - public IEnumerator TestDoors() { + public IEnumerator TestDoors() + { // $@" // 0 0 0 0 0 0 // 0 2 2 2 2 0 @@ -229,8 +305,7 @@ public IEnumerator TestDoors() { // 0 0 0 0 0 0 // " var house = createTestHouse(); - - + Assert.AreEqual(house.doors.Count, 1); var door = house.doors[0]; @@ -241,28 +316,35 @@ public IEnumerator TestDoors() { Assert.IsTrue(door.holePolygon[0] == new Vector3(3.0f, 0.0f, 0.0f)); Assert.AreEqual( - house.walls.Where(w => w.roomId =="1") - .Select( - w => (id: w.id, coords: (w.polygon[0], w.polygon[1])) - ).ToList() - .Find(w => w.coords == (new Vector3(2.0f, 0.0f, 0.0f), new Vector3(2.0f, 0.0f, 4.0f))).id, + house + .walls.Where(w => w.roomId == "1") + .Select(w => (id: w.id, coords: (w.polygon[0], w.polygon[1]))) + .ToList() + .Find(w => + w.coords == (new Vector3(2.0f, 0.0f, 0.0f), new Vector3(2.0f, 0.0f, 4.0f)) + ) + .id, door.wall0 ); Assert.AreEqual( - house.walls.Where(w => w.roomId =="2") - .Select( - w => (id: w.id, coords: (w.polygon[0], w.polygon[1])) - ).ToList() - .Find(w => w.coords == (new Vector3(2.0f, 0.0f, 4.0f), new Vector3(2.0f, 0.0f, 0.0f))).id, + house + .walls.Where(w => w.roomId == "2") + .Select(w => (id: w.id, coords: (w.polygon[0], w.polygon[1]))) + .ToList() + .Find(w => + w.coords == (new Vector3(2.0f, 0.0f, 4.0f), new Vector3(2.0f, 0.0f, 0.0f)) + ) + .id, door.wall1 - ); + ); yield return true; } [UnityTest] - public IEnumerator TestCeilings() { + public IEnumerator TestCeilings() + { // $@" // 0 0 0 0 0 0 // 0 2 2 2 2 0 @@ -272,8 +354,9 @@ public IEnumerator TestCeilings() { // 0 0 0 0 0 0 // ", var house = createTestHouse(); - - var room2Poly = new List() { + + var room2Poly = new List() + { Vector3.zero, new Vector3(0.0f, 0.0f, 4.0f), new Vector3(2.0f, 0.0f, 4.0f), @@ -282,10 +365,18 @@ public IEnumerator TestCeilings() { var room2 = house.rooms.Find(r => r.id == "2"); Assert.IsTrue(room2.ceilings.Count == 1); - Assert.IsTrue(room2.ceilings[0].material == houseTemplate.proceduralParameters.ceilingMaterial); - Assert.IsTrue(room2.ceilings[0].polygon.Select((p, i) => (point: p, index: i)).All(e => room2Poly.ElementAt(e.index) == e.point)); + Assert.IsTrue( + room2.ceilings[0].material == houseTemplate.proceduralParameters.ceilingMaterial + ); + Assert.IsTrue( + room2 + .ceilings[0] + .polygon.Select((p, i) => (point: p, index: i)) + .All(e => room2Poly.ElementAt(e.index) == e.point) + ); - var room1Poly = new List() { + var room1Poly = new List() + { new Vector3(2.0f, 0.0f, 0.0f), new Vector3(2.0f, 0.0f, 4.0f), new Vector3(4.0f, 0.0f, 4.0f), @@ -294,68 +385,86 @@ public IEnumerator TestCeilings() { var room1 = house.rooms.Find(r => r.id == "1"); Assert.IsTrue(room1.ceilings.Count == 1); - Assert.IsTrue(room1.ceilings[0].material == houseTemplate.proceduralParameters.ceilingMaterial); - Assert.IsTrue(room1.ceilings[0].polygon.Select((p, i) => (point: p, index: i)).All(e => room1Poly.ElementAt(e.index) == e.point)); + Assert.IsTrue( + room1.ceilings[0].material == houseTemplate.proceduralParameters.ceilingMaterial + ); + Assert.IsTrue( + room1 + .ceilings[0] + .polygon.Select((p, i) => (point: p, index: i)) + .All(e => room1Poly.ElementAt(e.index) == e.point) + ); yield return true; } [UnityTest] - public IEnumerator TestHouseNullVersion() { - Assert.That(() => { - var house = createTestHouse(); - house.metadata.schema = null; - Debug.Log(house.metadata.schema); - ProceduralTools.CreateHouse(house, ProceduralTools.GetMaterials()); - }, Throws.ArgumentException); + public IEnumerator TestHouseNullVersion() + { + Assert.That( + () => + { + var house = createTestHouse(); + house.metadata.schema = null; + Debug.Log(house.metadata.schema); + ProceduralTools.CreateHouse(house, ProceduralTools.GetMaterials()); + }, + Throws.ArgumentException + ); yield return true; } [UnityTest] - public IEnumerator TestHouseLowerVersion() { - Assert.That(() => { - var house = createTestHouse(); - house.metadata.schema = "0.0.1"; - Debug.Log(house.metadata.schema); - ProceduralTools.CreateHouse(house, ProceduralTools.GetMaterials()); - }, Throws.ArgumentException); + public IEnumerator TestHouseLowerVersion() + { + Assert.That( + () => + { + var house = createTestHouse(); + house.metadata.schema = "0.0.1"; + Debug.Log(house.metadata.schema); + ProceduralTools.CreateHouse(house, ProceduralTools.GetMaterials()); + }, + Throws.ArgumentException + ); yield return true; } - protected virtual ProceduralHouse createTestHouse() { - var house = Templates.createHouseFromTemplate( - this.houseTemplate - ); + protected virtual ProceduralHouse createTestHouse() + { + var house = Templates.createHouseFromTemplate(this.houseTemplate); Debug.Log($"####### TEST HOUSE:\n {serializeHouse(house)}"); return house; } - protected string serializeObject(object obj) { + protected string serializeObject(object obj) + { var jsonResolver = new ShouldSerializeContractResolver(); return Newtonsoft.Json.JsonConvert.SerializeObject( obj, Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { + new Newtonsoft.Json.JsonSerializerSettings() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver } ); } - protected string serializeHouse(ProceduralHouse house) { + protected string serializeHouse(ProceduralHouse house) + { var jsonResolver = new ShouldSerializeContractResolver(); var houseString = Newtonsoft.Json.JsonConvert.SerializeObject( house, Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { + new Newtonsoft.Json.JsonSerializerSettings() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver } ); - return houseString; + return houseString; } } } - - diff --git a/unity/Assets/UnitTests/Procedural/TestBaseProcedural.cs b/unity/Assets/UnitTests/Procedural/TestBaseProcedural.cs index 61ecc9af31..d36248fcb4 100644 --- a/unity/Assets/UnitTests/Procedural/TestBaseProcedural.cs +++ b/unity/Assets/UnitTests/Procedural/TestBaseProcedural.cs @@ -1,61 +1,80 @@ - +using System; using System.Collections; using System.Collections.Generic; +using System.IO; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Serialization; using NUnit.Framework; -using System; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; -using System.IO; -namespace Tests { - public class TestBaseProcedural : TestBase +namespace Tests +{ + public class TestBaseProcedural : TestBase { - public override IEnumerator Initialize() { - Dictionary action = new Dictionary() { - { "gridSize", 0.25f}, - { "agentCount", 1}, - { "fieldOfView", 90f}, - { "snapToGrid", true}, - { "procedural", true}, - { "action", "Initialize"} + public override IEnumerator Initialize() + { + Dictionary action = new Dictionary() + { + { "gridSize", 0.25f }, + { "agentCount", 1 }, + { "fieldOfView", 90f }, + { "snapToGrid", true }, + { "procedural", true }, + { "action", "Initialize" } }; yield return step(action); } [SetUp] - public override void Setup() { + public override void Setup() + { UnityEngine.Screen.SetResolution(600, 600, false); - UnityEngine.SceneManagement.SceneManager.sceneLoaded += (scene, mode) => { + UnityEngine.SceneManagement.SceneManager.sceneLoaded += (scene, mode) => + { var debugCanvas = GameObject.Find("DebugCanvasPhysics"); - if (debugCanvas != null) { + if (debugCanvas != null) + { debugCanvas.SetActive(false); } - UnityEngine.Screen.SetResolution(600, 600, false); + UnityEngine.Screen.SetResolution(600, 600, false); }; UnityEngine.SceneManagement.SceneManager.LoadScene("Procedural"); } - protected string getTestResourcesPath(string filename = "", bool resourcesRelative = true) { + protected string getTestResourcesPath(string filename = "", bool resourcesRelative = true) + { var prefix = !resourcesRelative ? "Assets/Resources/" : ""; - var path = prefix + string.Join("/", NUnit.Framework.TestContext.CurrentContext.Test.FullName.Split('.')); + var path = + prefix + + string.Join( + "/", + NUnit.Framework.TestContext.CurrentContext.Test.FullName.Split('.') + ); return string.IsNullOrEmpty(filename) ? path : $"{path}/{filename}"; } - protected string getBuildMachineTestOutputPath(string filename = "", bool resourcesRelative = true) { + protected string getBuildMachineTestOutputPath( + string filename = "", + bool resourcesRelative = true + ) + { var directory = !resourcesRelative ? "Assets/../../../../images-debug/" : ""; // if (Directory.Exists(prefix)) { // } - var filenamePrefix = string.Join("_", NUnit.Framework.TestContext.CurrentContext.Test.FullName.Split('.')); - var finalFileName = string.IsNullOrEmpty(filename) ? filenamePrefix : $"{filenamePrefix}{filename}"; + var filenamePrefix = string.Join( + "_", + NUnit.Framework.TestContext.CurrentContext.Test.FullName.Split('.') + ); + var finalFileName = string.IsNullOrEmpty(filename) + ? filenamePrefix + : $"{filenamePrefix}{filename}"; Directory.CreateDirectory(directory); return $"{directory}/{finalFileName}"; } - } } diff --git a/unity/Assets/UnitTests/TestBase.cs b/unity/Assets/UnitTests/TestBase.cs index b70ae9b5ab..3f74840848 100644 --- a/unity/Assets/UnitTests/TestBase.cs +++ b/unity/Assets/UnitTests/TestBase.cs @@ -1,30 +1,31 @@ - +using System; using System.Collections; using System.Collections.Generic; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Newtonsoft.Json.Serialization; using NUnit.Framework; -using System; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; -namespace Tests { - public class TestBase { +namespace Tests +{ + public class TestBase + { protected int sequenceId = 0; protected bool lastActionSuccess; protected string error; protected object actionReturn; - protected MultiAgentMetadata metadata; // = new MultiAgentMetadata(); + protected MultiAgentMetadata metadata; // = new MultiAgentMetadata(); protected List> renderPayload; protected ThirdPartyCameraMetadata[] cameraMetadata; - public IEnumerator step(Dictionary action) { - + public IEnumerator step(Dictionary action) + { var agentManager = GameObject.FindObjectOfType(); action["sequenceId"] = sequenceId; agentManager.ProcessControlCommand(new DynamicServerAction(action)); @@ -41,47 +42,62 @@ public IEnumerator step(Dictionary action) { } [SetUp] - public virtual void Setup() { + public virtual void Setup() + { // metadata = new MultiAgentMetadata(); UnityEngine.SceneManagement.SceneManager.LoadScene("FloorPlan1_physics"); } - public virtual IEnumerator Initialize() { - Dictionary action = new Dictionary() { - { "gridSize", 0.25f}, - { "agentCount", 1}, - { "fieldOfView", 90f}, - { "snapToGrid", true}, - { "action", "Initialize"} + public virtual IEnumerator Initialize() + { + Dictionary action = new Dictionary() + { + { "gridSize", 0.25f }, + { "agentCount", 1 }, + { "fieldOfView", 90f }, + { "snapToGrid", true }, + { "action", "Initialize" } }; yield return step(action); } - public BaseFPSAgentController getActiveAgent() { + public BaseFPSAgentController getActiveAgent() + { var agentManager = GameObject.FindObjectOfType(); return agentManager.GetActiveAgent(); } - - protected AgentManager agentManager { + protected AgentManager agentManager + { get => GameObject.FindObjectOfType(); } - protected MetadataWrapper getLastActionMetadata(int agentId = -1) { + protected MetadataWrapper getLastActionMetadata(int agentId = -1) + { var id = agentId == -1 ? this.agentManager.GetActiveAgentId() : agentId; return this.metadata.agents[id]; } - protected void savePng(byte[] img, string filePath) { - var pngBytes = UnityEngine.ImageConversion.EncodeArrayToPNG(img, agentManager.tex.graphicsFormat, (uint)UnityEngine.Screen.width, (uint)UnityEngine.Screen.height); - + protected void savePng(byte[] img, string filePath) + { + var pngBytes = UnityEngine.ImageConversion.EncodeArrayToPNG( + img, + agentManager.tex.graphicsFormat, + (uint)UnityEngine.Screen.width, + (uint)UnityEngine.Screen.height + ); + System.IO.File.WriteAllBytes(filePath, pngBytes); } - private void generateMetadata() { + private void generateMetadata() + { MultiAgentMetadata multiMeta = new MultiAgentMetadata(); - ThirdPartyCameraMetadata[] cameraMetadata = new ThirdPartyCameraMetadata[agentManager.GetThirdPartyCameraCount()]; - List> renderPayload = new List>(); + ThirdPartyCameraMetadata[] cameraMetadata = new ThirdPartyCameraMetadata[ + agentManager.GetThirdPartyCameraCount() + ]; + List> renderPayload = + new List>(); agentManager.createPayload(multiMeta, cameraMetadata, renderPayload, true, true); this.renderPayload = renderPayload; this.cameraMetadata = cameraMetadata; diff --git a/unity/Assets/UnitTests/TestCachedObjectOrientedBoundsRotation.cs b/unity/Assets/UnitTests/TestCachedObjectOrientedBoundsRotation.cs index a057f431b0..dfa19cfaaa 100644 --- a/unity/Assets/UnitTests/TestCachedObjectOrientedBoundsRotation.cs +++ b/unity/Assets/UnitTests/TestCachedObjectOrientedBoundsRotation.cs @@ -1,20 +1,21 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using NUnit.Framework; -using System; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -namespace Tests { +namespace Tests +{ public class TestCachedObjectOrientedBoundsRotation : TestBase { - //check to make sure the automatic caching of the object oriented bounds is assigning //the localRotation of the BoundingBox child object of any given SimObject is set to //(0,0,0) or Quaternion.identity, correctly [UnityTest] - public IEnumerator TestCachedBoundsRotation() { + public IEnumerator TestCachedBoundsRotation() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -38,5 +39,3 @@ public IEnumerator TestCachedBoundsRotation() { } } } - - diff --git a/unity/Assets/UnitTests/TestDispatcher.cs b/unity/Assets/UnitTests/TestDispatcher.cs index f047974eaf..6284f1bd38 100644 --- a/unity/Assets/UnitTests/TestDispatcher.cs +++ b/unity/Assets/UnitTests/TestDispatcher.cs @@ -1,123 +1,149 @@ +using System; using System.Collections; using System.Collections.Generic; +using System.Threading.Tasks; using NUnit.Framework; -using System; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -using System.Threading.Tasks; -namespace Tests { - public class TestDispatcher : TestBase { - - public class TestController : ActionInvokable { +namespace Tests +{ + public class TestDispatcher : TestBase + { + public class TestController : ActionInvokable + { protected AgentManager agentManager; public bool ranAsCoroutine; public bool ranAsBackCompat; public bool ranCompleteCallback = false; public ActionFinished actionFinished; - public TestController(AgentManager agentManager) { - this.agentManager =agentManager; + + public TestController(AgentManager agentManager) + { + this.agentManager = agentManager; } - public void BackCompatAction(int x) { + + public void BackCompatAction(int x) + { ranAsBackCompat = true; // Calls action finished/changes internal state, who knows? ... } - public ActionFinished NewAction(int x) { - return new ActionFinished() { - success = true, - actionReturn = x, - }; + + public ActionFinished NewAction(int x) + { + return new ActionFinished() { success = true, actionReturn = x, }; } - public IEnumerator AsyncAction(int x) { - for (var i = 0; i < x; i++) { + public IEnumerator AsyncAction(int x) + { + for (var i = 0; i < x; i++) + { yield return new WaitForFixedUpdate(); } - yield return new ActionFinished() { - success = true, - actionReturn = x, - }; + yield return new ActionFinished() { success = true, actionReturn = x, }; } - public IEnumerator AsyncActionMeasureUnityTime(int x) { - for (var i = 0; i < x; i++) { + public IEnumerator AsyncActionMeasureUnityTime(int x) + { + for (var i = 0; i < x; i++) + { yield return new WaitForFixedUpdate(); } - yield return new ActionFinished() { + yield return new ActionFinished() + { success = true, actionReturn = Time.fixedTime, }; } // For ActionFinished return type it's a compile error - public IEnumerator AsyncActionMissingActionFinished() { + public IEnumerator AsyncActionMissingActionFinished() + { yield return new WaitForFixedUpdate(); } - - public IEnumerator AsyncActionThrows() { + public IEnumerator AsyncActionThrows() + { yield return new WaitForFixedUpdate(); object k = null; // Null Ref exception k.ToString(); } - public IEnumerator AsyncActionPhysicsParams(PhysicsSimulationParams physicsSimulationParams) { - var count = (int)Math.Round(physicsSimulationParams.minSimulateTimeSeconds / physicsSimulationParams.fixedDeltaTime); - for (var i = 0; i < count; i++) { + public IEnumerator AsyncActionPhysicsParams( + PhysicsSimulationParams physicsSimulationParams + ) + { + var count = (int) + Math.Round( + physicsSimulationParams.minSimulateTimeSeconds + / physicsSimulationParams.fixedDeltaTime + ); + for (var i = 0; i < count; i++) + { yield return new WaitForFixedUpdate(); } - yield return new ActionFinished() { + yield return new ActionFinished() + { success = true, actionReturn = physicsSimulationParams }; } - public void Complete(ActionFinished actionFinished) { + public void Complete(ActionFinished actionFinished) + { // Simulating what BaseFPSDoes for old actions where isDummy will be true - if (!actionFinished.isDummy) { + if (!actionFinished.isDummy) + { ranCompleteCallback = true; } this.actionFinished = actionFinished; } - public Coroutine StartCoroutine(IEnumerator routine) { + + public Coroutine StartCoroutine(IEnumerator routine) + { ranAsCoroutine = true; return agentManager.StartCoroutine(routine); } } [UnityTest] - public IEnumerator TestDispatchInvalidArguments() { + public IEnumerator TestDispatchInvalidArguments() + { yield return Initialize(); - var args = new Dictionary() { - {"action", "PutObject"}, - {"x", 0.3f}, - {"y", 0.3f}, - {"z", 0.3f}, - {"forceAction", false}, - {"placeStationary", true} - }; - Assert.Throws(() => { + var args = new Dictionary() + { + { "action", "PutObject" }, + { "x", 0.3f }, + { "y", 0.3f }, + { "z", 0.3f }, + { "forceAction", false }, + { "placeStationary", true } + }; + Assert.Throws(() => + { ActionDispatcher.Dispatch(agentManager.PrimaryAgent, new DynamicServerAction(args)); }); } [UnityTest] - public IEnumerator TestStepInvalidArguments() { + public IEnumerator TestStepInvalidArguments() + { yield return Initialize(); - var args = new Dictionary() { - {"action", "PutObject"}, - {"x", 0.3f}, - {"y", 0.3f}, - {"z", 0.3f}, - {"forceAction", false}, - {"placeStationary", true} + var args = new Dictionary() + { + { "action", "PutObject" }, + { "x", 0.3f }, + { "y", 0.3f }, + { "z", 0.3f }, + { "forceAction", false }, + { "placeStationary", true } }; yield return step(args); @@ -126,15 +152,16 @@ public IEnumerator TestStepInvalidArguments() { } [UnityTest] - public IEnumerator TestBackCompatAction() { - + public IEnumerator TestBackCompatAction() + { var controller = new TestController(this.agentManager); - var args = new Dictionary() { - {"action", "BackCompatAction"}, - {"x", 0} + var args = new Dictionary() + { + { "action", "BackCompatAction" }, + { "x", 0 } }; - + ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); Assert.IsTrue(controller.ranAsBackCompat); // Complete interface is not called so this simulates not calling action finished to change inner state @@ -145,23 +172,24 @@ public IEnumerator TestBackCompatAction() { } [UnityTest] - public IEnumerator TestNewAction() { - + public IEnumerator TestNewAction() + { var controller = new TestController(this.agentManager); var result = 5; - var args = new Dictionary() { - {"action", "NewAction"}, - {"x", result} + var args = new Dictionary() + { + { "action", "NewAction" }, + { "x", result } }; // This happens at init - PhysicsSceneManager.SetDefaultSimulationParams(new PhysicsSimulationParams() { - autoSimulation = false - }); - + PhysicsSceneManager.SetDefaultSimulationParams( + new PhysicsSimulationParams() { autoSimulation = false } + ); + ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); - + // Complete (new actionFinished) was called automatically Assert.IsTrue(controller.ranCompleteCallback); @@ -176,33 +204,43 @@ public IEnumerator TestNewAction() { } [UnityTest] - public IEnumerator TestBackCompatActionPhysicsPadding() { - + public IEnumerator TestBackCompatActionPhysicsPadding() + { var controller = new TestController(this.agentManager); var result = 5; - var physicsSimulationParams = new PhysicsSimulationParams() { + var physicsSimulationParams = new PhysicsSimulationParams() + { fixedDeltaTime = 0.02f, minSimulateTimeSeconds = 0.1f, autoSimulation = false }; - var args = new Dictionary() { - {"action", "BackCompatAction"}, - {"x", result}, - {"physicsSimulationParams", physicsSimulationParams} + var args = new Dictionary() + { + { "action", "BackCompatAction" }, + { "x", result }, + { "physicsSimulationParams", physicsSimulationParams } }; - + ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); - + // For legacy actions we don't want to call Complete as they handle their own state. Avoid call to actionFinished twice Assert.IsFalse(controller.ranCompleteCallback); // 5 physics steps of pure padding - Assert.AreEqual(PhysicsSceneManager.PhysicsSimulateCallCount, physicsSimulationParams.minSimulateTimeSeconds / physicsSimulationParams.fixedDeltaTime); + Assert.AreEqual( + PhysicsSceneManager.PhysicsSimulateCallCount, + physicsSimulationParams.minSimulateTimeSeconds + / physicsSimulationParams.fixedDeltaTime + ); - var simulateTimeMatched = Math.Abs(PhysicsSceneManager.PhysicsSimulateTimeSeconds - physicsSimulationParams.minSimulateTimeSeconds) < 1e-5; + var simulateTimeMatched = + Math.Abs( + PhysicsSceneManager.PhysicsSimulateTimeSeconds + - physicsSimulationParams.minSimulateTimeSeconds + ) < 1e-5; // Mathf.Approximately(PhysicsSceneManager.PhysicsSimulateTimeSeconds, physicsSimulationParams.maxActionTimeMilliseconds / 1000.0f); Assert.IsTrue(simulateTimeMatched); @@ -212,72 +250,91 @@ public IEnumerator TestBackCompatActionPhysicsPadding() { } [UnityTest] - public IEnumerator TestNewActionPhysicsPadding() { - + public IEnumerator TestNewActionPhysicsPadding() + { var controller = new TestController(this.agentManager); var result = 5; const float eps = 1e-5f; - var physicsSimulationParams = new PhysicsSimulationParams() { + var physicsSimulationParams = new PhysicsSimulationParams() + { fixedDeltaTime = 0.02f, minSimulateTimeSeconds = 0.1f, autoSimulation = false }; - var args = new Dictionary() { - {"action", "NewAction"}, - {"x", result}, - {"physicsSimulationParams", physicsSimulationParams} + var args = new Dictionary() + { + { "action", "NewAction" }, + { "x", result }, + { "physicsSimulationParams", physicsSimulationParams } }; ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); - // New Action types call Complete Assert.IsTrue(controller.ranCompleteCallback); // 5 physics steps of pure padding - Assert.AreEqual(PhysicsSceneManager.PhysicsSimulateCallCount, physicsSimulationParams.minSimulateTimeSeconds / physicsSimulationParams.fixedDeltaTime); + Assert.AreEqual( + PhysicsSceneManager.PhysicsSimulateCallCount, + physicsSimulationParams.minSimulateTimeSeconds + / physicsSimulationParams.fixedDeltaTime + ); - var simulateTimeMatched = Math.Abs(PhysicsSceneManager.PhysicsSimulateTimeSeconds - physicsSimulationParams.minSimulateTimeSeconds) < eps; + var simulateTimeMatched = + Math.Abs( + PhysicsSceneManager.PhysicsSimulateTimeSeconds + - physicsSimulationParams.minSimulateTimeSeconds + ) < eps; // Mathf.Approximately(PhysicsSceneManager.PhysicsSimulateTimeSeconds, physicsSimulationParams.maxActionTimeMilliseconds / 1000.0f); Assert.IsTrue(simulateTimeMatched); - - // 1 Iterator expansion from the return Action Finished + + // 1 Iterator expansion from the return Action Finished Assert.AreEqual(PhysicsSceneManager.IteratorExpandCount, 1); yield return true; } [UnityTest] - public IEnumerator TestAsyncAction() { - + public IEnumerator TestAsyncAction() + { var controller = new TestController(this.agentManager); var simulateTimes = 5; const float eps = 1e-5f; - var physicsSimulationParams = new PhysicsSimulationParams() { + var physicsSimulationParams = new PhysicsSimulationParams() + { fixedDeltaTime = 0.01f, autoSimulation = false }; - var args = new Dictionary() { - {"action", "AsyncAction"}, - {"x", simulateTimes} + var args = new Dictionary() + { + { "action", "AsyncAction" }, + { "x", simulateTimes } }; // This happens at init PhysicsSceneManager.SetDefaultSimulationParams(physicsSimulationParams); ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); - + // New Action types call Complete Assert.IsTrue(controller.ranCompleteCallback); // 5 simulations steps, simulatetime / fixedDeltaTime - Assert.AreEqual(PhysicsSceneManager.PhysicsSimulateCallCount, PhysicsSceneManager.PhysicsSimulateTimeSeconds / physicsSimulationParams.fixedDeltaTime); + Assert.AreEqual( + PhysicsSceneManager.PhysicsSimulateCallCount, + PhysicsSceneManager.PhysicsSimulateTimeSeconds + / physicsSimulationParams.fixedDeltaTime + ); - var simulateTimeMatched = Math.Abs(PhysicsSceneManager.PhysicsSimulateTimeSeconds - (physicsSimulationParams.fixedDeltaTime * simulateTimes)) < eps; + var simulateTimeMatched = + Math.Abs( + PhysicsSceneManager.PhysicsSimulateTimeSeconds + - (physicsSimulationParams.fixedDeltaTime * simulateTimes) + ) < eps; // Mathf.Approximately(PhysicsSceneManager.PhysicsSimulateTimeSeconds, physicsSimulationParams.maxActionTimeMilliseconds / 1000.0f); Assert.IsTrue(simulateTimeMatched); // Times of simulation + yield return ActionFinished @@ -285,36 +342,47 @@ public IEnumerator TestAsyncAction() { Assert.AreEqual(controller.actionFinished.actionReturn, simulateTimes); yield return true; - } [UnityTest] - public IEnumerator TestAsyncActionPassPhysicsSimulationParams() { - + public IEnumerator TestAsyncActionPassPhysicsSimulationParams() + { var controller = new TestController(this.agentManager); var simulateTimes = 10; const float eps = 1e-5f; - var physicsSimulationParams = new PhysicsSimulationParams() { + var physicsSimulationParams = new PhysicsSimulationParams() + { fixedDeltaTime = 0.01f, autoSimulation = false }; - var args = new Dictionary() { - {"action", "AsyncAction"}, - {"x", simulateTimes}, - {"physicsSimulationParams", physicsSimulationParams} + var args = new Dictionary() + { + { "action", "AsyncAction" }, + { "x", simulateTimes }, + { "physicsSimulationParams", physicsSimulationParams } }; ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); - + // New Action types call Complete Assert.IsTrue(controller.ranCompleteCallback); - Assert.IsTrue(Math.Abs(PhysicsSceneManager.PhysicsSimulateCallCount - PhysicsSceneManager.PhysicsSimulateTimeSeconds / physicsSimulationParams.fixedDeltaTime) < eps); + Assert.IsTrue( + Math.Abs( + PhysicsSceneManager.PhysicsSimulateCallCount + - PhysicsSceneManager.PhysicsSimulateTimeSeconds + / physicsSimulationParams.fixedDeltaTime + ) < eps + ); - var simulateTimeMatched = Math.Abs(PhysicsSceneManager.PhysicsSimulateTimeSeconds - (physicsSimulationParams.fixedDeltaTime * simulateTimes)) < eps; + var simulateTimeMatched = + Math.Abs( + PhysicsSceneManager.PhysicsSimulateTimeSeconds + - (physicsSimulationParams.fixedDeltaTime * simulateTimes) + ) < eps; // Mathf.Approximately(PhysicsSceneManager.PhysicsSimulateTimeSeconds, physicsSimulationParams.maxActionTimeMilliseconds / 1000.0f); Assert.IsTrue(simulateTimeMatched); // Times of simulation + yield return ActionFinished @@ -322,38 +390,51 @@ public IEnumerator TestAsyncActionPassPhysicsSimulationParams() { // Returns value in action return Assert.AreEqual(controller.actionFinished.actionReturn, simulateTimes); yield return true; - } [UnityTest] - public IEnumerator TestAsyncActionPassPhysicsSimulationParamsAndPadding() { - + public IEnumerator TestAsyncActionPassPhysicsSimulationParamsAndPadding() + { var controller = new TestController(this.agentManager); var simulateTimes = 10; const float eps = 1e-5f; - var physicsSimulationParams = new PhysicsSimulationParams() { + var physicsSimulationParams = new PhysicsSimulationParams() + { fixedDeltaTime = 0.01f, autoSimulation = false, // has to run 1 second so 0.1 seconds of action time and 0.9 of padding minSimulateTimeSeconds = 1 }; - var args = new Dictionary() { - {"action", "AsyncAction"}, - {"x", simulateTimes}, - {"physicsSimulationParams", physicsSimulationParams} + var args = new Dictionary() + { + { "action", "AsyncAction" }, + { "x", simulateTimes }, + { "physicsSimulationParams", physicsSimulationParams } }; ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); - + // New Action types call Complete Assert.IsTrue(controller.ranCompleteCallback); - Assert.IsTrue(Math.Abs(PhysicsSceneManager.PhysicsSimulateCallCount - (physicsSimulationParams.minSimulateTimeSeconds / physicsSimulationParams.fixedDeltaTime)) < eps); - - var simulateTimeMatched = Math.Abs(PhysicsSceneManager.PhysicsSimulateTimeSeconds - physicsSimulationParams.minSimulateTimeSeconds) < eps; + Assert.IsTrue( + Math.Abs( + PhysicsSceneManager.PhysicsSimulateCallCount + - ( + physicsSimulationParams.minSimulateTimeSeconds + / physicsSimulationParams.fixedDeltaTime + ) + ) < eps + ); + + var simulateTimeMatched = + Math.Abs( + PhysicsSceneManager.PhysicsSimulateTimeSeconds + - physicsSimulationParams.minSimulateTimeSeconds + ) < eps; // Mathf.Approximately(PhysicsSceneManager.PhysicsSimulateTimeSeconds, physicsSimulationParams.maxActionTimeMilliseconds / 1000.0f); Assert.IsTrue(simulateTimeMatched); // Times of simulation + yield return ActionFinished @@ -361,83 +442,113 @@ public IEnumerator TestAsyncActionPassPhysicsSimulationParamsAndPadding() { // Returns value in action return Assert.AreEqual(controller.actionFinished.actionReturn, simulateTimes); yield return true; - } [UnityTest] - public IEnumerator TestAsyncActionPhysicsParams() { - + public IEnumerator TestAsyncActionPhysicsParams() + { var controller = new TestController(this.agentManager); // Target value var simulateTimes = 20; const float eps = 1e-5f; - var physicsSimulationParams = new PhysicsSimulationParams() { + var physicsSimulationParams = new PhysicsSimulationParams() + { fixedDeltaTime = 0.01f, autoSimulation = false, minSimulateTimeSeconds = 0.2f }; - var args = new Dictionary() { - {"action", "AsyncActionPhysicsParams"}, - {"physicsSimulationParams", physicsSimulationParams} + var args = new Dictionary() + { + { "action", "AsyncActionPhysicsParams" }, + { "physicsSimulationParams", physicsSimulationParams } }; ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); - + // New Action types call Complete Assert.IsTrue(controller.ranCompleteCallback); - Assert.IsTrue(Math.Abs(PhysicsSceneManager.PhysicsSimulateCallCount - PhysicsSceneManager.PhysicsSimulateTimeSeconds / physicsSimulationParams.fixedDeltaTime) < eps); + Assert.IsTrue( + Math.Abs( + PhysicsSceneManager.PhysicsSimulateCallCount + - PhysicsSceneManager.PhysicsSimulateTimeSeconds + / physicsSimulationParams.fixedDeltaTime + ) < eps + ); - var simulateTimeMatched = Math.Abs(PhysicsSceneManager.PhysicsSimulateTimeSeconds - (physicsSimulationParams.fixedDeltaTime * simulateTimes)) < eps; + var simulateTimeMatched = + Math.Abs( + PhysicsSceneManager.PhysicsSimulateTimeSeconds + - (physicsSimulationParams.fixedDeltaTime * simulateTimes) + ) < eps; // Mathf.Approximately(PhysicsSceneManager.PhysicsSimulateTimeSeconds, physicsSimulationParams.maxActionTimeMilliseconds / 1000.0f); Assert.IsTrue(simulateTimeMatched); // Times of simulation + yield return ActionFinished Assert.AreEqual(PhysicsSceneManager.IteratorExpandCount, simulateTimes + 1); - var returnPhysicsParams = controller.actionFinished.actionReturn as PhysicsSimulationParams; - Debug.Log($"{returnPhysicsParams.autoSimulation} {returnPhysicsParams.fixedDeltaTime} {returnPhysicsParams.minSimulateTimeSeconds}"); - Debug.Log($"{physicsSimulationParams.autoSimulation} {physicsSimulationParams.fixedDeltaTime} {physicsSimulationParams.minSimulateTimeSeconds}"); + var returnPhysicsParams = + controller.actionFinished.actionReturn as PhysicsSimulationParams; + Debug.Log( + $"{returnPhysicsParams.autoSimulation} {returnPhysicsParams.fixedDeltaTime} {returnPhysicsParams.minSimulateTimeSeconds}" + ); + Debug.Log( + $"{physicsSimulationParams.autoSimulation} {physicsSimulationParams.fixedDeltaTime} {physicsSimulationParams.minSimulateTimeSeconds}" + ); // Returns back the physics params Assert.AreEqual(controller.actionFinished.actionReturn, physicsSimulationParams); yield return true; - } [UnityTest] - public IEnumerator TestAsyncActionDefaultPhysicsParams() { - + public IEnumerator TestAsyncActionDefaultPhysicsParams() + { var controller = new TestController(this.agentManager); - const float eps = 1e-5f; - var physicsSimulationParams = new PhysicsSimulationParams() { + var physicsSimulationParams = new PhysicsSimulationParams() + { fixedDeltaTime = 0.01f, autoSimulation = false, minSimulateTimeSeconds = 0.1f }; - var simulateTimes = (int)((physicsSimulationParams.minSimulateTimeSeconds / physicsSimulationParams.fixedDeltaTime) + eps); + var simulateTimes = (int)( + ( + physicsSimulationParams.minSimulateTimeSeconds + / physicsSimulationParams.fixedDeltaTime + ) + eps + ); - var args = new Dictionary() { - {"action", "AsyncActionPhysicsParams"}, + var args = new Dictionary() + { + { "action", "AsyncActionPhysicsParams" }, }; // This happens at init PhysicsSceneManager.SetDefaultSimulationParams(physicsSimulationParams); - ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); - + // New Action types call Complete Assert.IsTrue(controller.ranCompleteCallback); - Assert.IsTrue(Math.Abs(PhysicsSceneManager.PhysicsSimulateCallCount - PhysicsSceneManager.PhysicsSimulateTimeSeconds / physicsSimulationParams.fixedDeltaTime) < eps); + Assert.IsTrue( + Math.Abs( + PhysicsSceneManager.PhysicsSimulateCallCount + - PhysicsSceneManager.PhysicsSimulateTimeSeconds + / physicsSimulationParams.fixedDeltaTime + ) < eps + ); - var simulateTimeMatched = Math.Abs(PhysicsSceneManager.PhysicsSimulateTimeSeconds - (physicsSimulationParams.fixedDeltaTime * simulateTimes)) < eps; + var simulateTimeMatched = + Math.Abs( + PhysicsSceneManager.PhysicsSimulateTimeSeconds + - (physicsSimulationParams.fixedDeltaTime * simulateTimes) + ) < eps; // Mathf.Approximately(PhysicsSceneManager.PhysicsSimulateTimeSeconds, physicsSimulationParams.maxActionTimeMilliseconds / 1000.0f); Assert.IsTrue(simulateTimeMatched); // Times of simulation + yield return ActionFinished @@ -445,28 +556,29 @@ public IEnumerator TestAsyncActionDefaultPhysicsParams() { // Returns back the physics params Assert.AreEqual(controller.actionFinished.actionReturn, physicsSimulationParams); yield return true; - } [UnityTest] - public IEnumerator TestAsyncActionAutosimulation() { - + public IEnumerator TestAsyncActionAutosimulation() + { var controller = new TestController(this.agentManager); // Target value - var simulateTimes =8; + var simulateTimes = 8; // For unity time epsilon is much larger, therfore non-deterministic behavior const float eps = 1e-2f; - var physicsSimulationParams = new PhysicsSimulationParams() { + var physicsSimulationParams = new PhysicsSimulationParams() + { fixedDeltaTime = 0.01f, autoSimulation = true }; - var args = new Dictionary() { - {"action", "AsyncAction"}, - {"x", simulateTimes}, - {"physicsSimulationParams", physicsSimulationParams} + var args = new Dictionary() + { + { "action", "AsyncAction" }, + { "x", simulateTimes }, + { "physicsSimulationParams", physicsSimulationParams } }; var startTime = Time.time; @@ -478,7 +590,7 @@ public IEnumerator TestAsyncActionAutosimulation() { yield return new WaitUntil(() => controller.ranCompleteCallback == true); var endTime = Time.time; var endFixedTime = Time.fixedTime; - + // New Action types call Complete Assert.IsTrue(controller.ranCompleteCallback); // Because of autosimulation it was launched as an async coroutine @@ -491,10 +603,10 @@ public IEnumerator TestAsyncActionAutosimulation() { Debug.Log($"------ Fixed time {startFixedTime} {endFixedTime} _ {runTimeFixed}"); // Flaky because WaitUntil can run longer // var simulateTimeMatched = Math.Abs(runFixedTime - (physicsSimulationParams.fixedDeltaTime * (simulateTimes + 1))) < smallEps; - var simulateTimeMatched = physicsSimulationParams.fixedDeltaTime * simulateTimes - smallEps < runTimeFixed; + var simulateTimeMatched = + physicsSimulationParams.fixedDeltaTime * simulateTimes - smallEps < runTimeFixed; Assert.IsTrue(simulateTimeMatched); - - + // Assert.IsTrue(simulateTimeMatched); // Below is flaky assert as Time.time is virtual and finding good epsilon is tricky // Assert.IsTrue( (runTime + eps) >= physicsSimulationParams.fixedDeltaTime * simulateTimes); @@ -502,26 +614,28 @@ public IEnumerator TestAsyncActionAutosimulation() { // Returns back the physics params Assert.AreEqual(controller.actionFinished.actionReturn, simulateTimes); yield return true; - } [UnityTest] - public IEnumerator TestAsyncActionAutosimulationExactTime() { + public IEnumerator TestAsyncActionAutosimulationExactTime() + { // Same as above but action itself measures Time.fixedTime to get accurate simulation time var controller = new TestController(this.agentManager); // Target value - var simulateTimes =8; + var simulateTimes = 8; - var physicsSimulationParams = new PhysicsSimulationParams() { + var physicsSimulationParams = new PhysicsSimulationParams() + { fixedDeltaTime = 0.01f, autoSimulation = true }; - var args = new Dictionary() { - {"action", "AsyncActionMeasureUnityTime"}, - {"x", simulateTimes}, - {"physicsSimulationParams", physicsSimulationParams} + var args = new Dictionary() + { + { "action", "AsyncActionMeasureUnityTime" }, + { "x", simulateTimes }, + { "physicsSimulationParams", physicsSimulationParams } }; var startFixedTime = Time.fixedTime; @@ -530,7 +644,7 @@ public IEnumerator TestAsyncActionAutosimulationExactTime() { yield return new WaitUntil(() => controller.actionFinished != null); var endFixedTime = (float)controller.actionFinished.actionReturn; - + // New Action types call Complete Assert.IsTrue(controller.ranCompleteCallback); // Because of autosimulation it was launched as an async coroutine @@ -541,33 +655,35 @@ public IEnumerator TestAsyncActionAutosimulationExactTime() { Debug.Log($"------ Fixed time {startFixedTime} {endFixedTime} _ {runTimeFixed}"); - var simulateTimeMatched = Math.Abs(runTimeFixed - (physicsSimulationParams.fixedDeltaTime * simulateTimes)) < smallEps; + var simulateTimeMatched = + Math.Abs(runTimeFixed - (physicsSimulationParams.fixedDeltaTime * simulateTimes)) + < smallEps; Assert.IsTrue(simulateTimeMatched); - - yield return true; + yield return true; } - [UnityTest] - public IEnumerator TestNewActionAutosimulation() { - + [UnityTest] + public IEnumerator TestNewActionAutosimulation() + { var controller = new TestController(this.agentManager); var result = 5; - var args = new Dictionary() { - {"action", "NewAction"}, - {"x", result} + var args = new Dictionary() + { + { "action", "NewAction" }, + { "x", result } }; // This happens at init - PhysicsSceneManager.SetDefaultSimulationParams(new PhysicsSimulationParams() { - autoSimulation = true - }); - + PhysicsSceneManager.SetDefaultSimulationParams( + new PhysicsSimulationParams() { autoSimulation = true } + ); + ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); yield return new WaitUntil(() => controller.ranCompleteCallback); - + // Complete (new actionFinished) was called automatically Assert.IsTrue(controller.ranCompleteCallback); @@ -579,26 +695,28 @@ public IEnumerator TestNewActionAutosimulation() { yield return true; } - [UnityTest] - public IEnumerator TestBackCompatActionAutosimulation() { - + [UnityTest] + public IEnumerator TestBackCompatActionAutosimulation() + { var controller = new TestController(this.agentManager); var x = 10; - var physicsSimulationParams = new PhysicsSimulationParams() { + var physicsSimulationParams = new PhysicsSimulationParams() + { fixedDeltaTime = 0.01f, autoSimulation = true }; - var args = new Dictionary() { - {"action", "BackCompatAction"}, - {"x", x}, - {"physicsSimulationParams", physicsSimulationParams} + var args = new Dictionary() + { + { "action", "BackCompatAction" }, + { "x", x }, + { "physicsSimulationParams", physicsSimulationParams } }; ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); - + // Old Action types don't call true Complete, they have their own actionFinished Assert.IsFalse(controller.ranCompleteCallback); Assert.IsTrue(controller.ranAsBackCompat); @@ -606,31 +724,33 @@ public IEnumerator TestBackCompatActionAutosimulation() { yield return true; } - [UnityTest] - public IEnumerator TestBackCompatActionAutosimulationWithPadding() { + [UnityTest] + public IEnumerator TestBackCompatActionAutosimulationWithPadding() + { // Can't add padding to legacy actions run in coroutines, as actionFinished // returns controll and can't add padding if not blocked because can create "deathloop" var controller = new TestController(this.agentManager); var x = 10; - var physicsSimulationParams = new PhysicsSimulationParams() { + var physicsSimulationParams = new PhysicsSimulationParams() + { fixedDeltaTime = 0.01f, autoSimulation = true, minSimulateTimeSeconds = 0.1f }; - var args = new Dictionary() { - {"action", "BackCompatAction"}, - {"x", x}, - {"physicsSimulationParams", physicsSimulationParams} + var args = new Dictionary() + { + { "action", "BackCompatAction" }, + { "x", x }, + { "physicsSimulationParams", physicsSimulationParams } }; - ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); // No time simulating physics because of autosim - Assert.IsTrue(PhysicsSceneManager.PhysicsSimulateTimeSeconds < 1e-5); + Assert.IsTrue(PhysicsSceneManager.PhysicsSimulateTimeSeconds < 1e-5); // Old actions don't call real complete Assert.IsFalse(controller.ranCompleteCallback); @@ -640,21 +760,21 @@ public IEnumerator TestBackCompatActionAutosimulationWithPadding() { } [UnityTest] - public IEnumerator TestAsyncActionMissingActionFinished() { - + public IEnumerator TestAsyncActionMissingActionFinished() + { var controller = new TestController(this.agentManager); - var args = new Dictionary() { - {"action", "AsyncActionMissingActionFinished"}, + var args = new Dictionary() + { + { "action", "AsyncActionMissingActionFinished" }, }; PhysicsSceneManager.SetDefaultSimulationParams( - new PhysicsSimulationParams() { - autoSimulation = false - } + new PhysicsSimulationParams() { autoSimulation = false } ); - - Assert.Throws(() => { + + Assert.Throws(() => + { ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); }); @@ -662,46 +782,44 @@ public IEnumerator TestAsyncActionMissingActionFinished() { } [UnityTest] - public IEnumerator TestAsyncActionCoroutineMissingActionFinished() { - + public IEnumerator TestAsyncActionCoroutineMissingActionFinished() + { var controller = new TestController(this.agentManager); - var args = new Dictionary() { - {"action", "AsyncActionMissingActionFinished"}, + var args = new Dictionary() + { + { "action", "AsyncActionMissingActionFinished" }, }; PhysicsSceneManager.SetDefaultSimulationParams( - new PhysicsSimulationParams() { - autoSimulation = true - } + new PhysicsSimulationParams() { autoSimulation = true } ); - - ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); + ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); yield return new WaitUntil(() => controller.actionFinished != null); Assert.IsTrue(controller.ranCompleteCallback); Assert.IsFalse(controller.actionFinished.success); - Assert.AreEqual(controller.actionFinished.errorCode, ServerActionErrorCode.MissingActionFinished); + Assert.AreEqual( + controller.actionFinished.errorCode, + ServerActionErrorCode.MissingActionFinished + ); } [UnityTest] - public IEnumerator TestAsyncActionThrows() { - + public IEnumerator TestAsyncActionThrows() + { var controller = new TestController(this.agentManager); - var args = new Dictionary() { - {"action", "AsyncActionThrows"}, - }; + var args = new Dictionary() { { "action", "AsyncActionThrows" }, }; PhysicsSceneManager.SetDefaultSimulationParams( - new PhysicsSimulationParams() { - autoSimulation = false - } + new PhysicsSimulationParams() { autoSimulation = false } ); // Exceptions are handlede in ProcessControll command of FPS Controller - Assert.Throws(() => { + Assert.Throws(() => + { ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); }); @@ -709,22 +827,17 @@ public IEnumerator TestAsyncActionThrows() { } [UnityTest] - public IEnumerator TestAsyncActionThrowsCoroutine() { - + public IEnumerator TestAsyncActionThrowsCoroutine() + { var controller = new TestController(this.agentManager); - var args = new Dictionary() { - {"action", "AsyncActionThrows"}, - }; + var args = new Dictionary() { { "action", "AsyncActionThrows" }, }; PhysicsSceneManager.SetDefaultSimulationParams( - new PhysicsSimulationParams() { - autoSimulation = true - } + new PhysicsSimulationParams() { autoSimulation = true } ); - - ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); + ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); yield return new WaitUntil(() => controller.actionFinished != null); @@ -732,39 +845,47 @@ public IEnumerator TestAsyncActionThrowsCoroutine() { // Bacause it's run in an "async" coroutine exception is handled inside and propagates to ActionFinished Assert.IsFalse(controller.actionFinished.success); Debug.Log(controller.actionFinished.errorMessage); - Assert.AreEqual(controller.actionFinished.errorCode, ServerActionErrorCode.UnhandledException); + Assert.AreEqual( + controller.actionFinished.errorCode, + ServerActionErrorCode.UnhandledException + ); } - public class TestControllerChild : TestController { - public TestControllerChild(AgentManager agentManager) : base(agentManager) {} + public class TestControllerChild : TestController + { + public TestControllerChild(AgentManager agentManager) + : base(agentManager) { } + public bool calledChild = false; + // Ambiguous actions - public void BackCompatAction(int x, string defaultParam = "") { + public void BackCompatAction(int x, string defaultParam = "") + { ranAsBackCompat = true; calledChild = true; } - public ActionFinished NewAction(int x) { + public ActionFinished NewAction(int x) + { calledChild = true; - return new ActionFinished() { - success = true, - actionReturn = x, - }; + return new ActionFinished() { success = true, actionReturn = x, }; } } [UnityTest] - public IEnumerator TestChildAmbiguousAction() { - + public IEnumerator TestChildAmbiguousAction() + { var controller = new TestControllerChild(this.agentManager); - var args = new Dictionary() { - {"action", "BackCompatAction"}, - {"x", 1}, + var args = new Dictionary() + { + { "action", "BackCompatAction" }, + { "x", 1 }, }; - + // TODO: we may want to remove this happening - Assert.Throws(() => { + Assert.Throws(() => + { ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); }); @@ -772,15 +893,12 @@ public IEnumerator TestChildAmbiguousAction() { } [UnityTest] - public IEnumerator TestChildAmbiguousNewAction() { - + public IEnumerator TestChildAmbiguousNewAction() + { var controller = new TestControllerChild(this.agentManager); - var args = new Dictionary() { - {"action", "NewAction"}, - {"x", 1}, - }; - + var args = new Dictionary() { { "action", "NewAction" }, { "x", 1 }, }; + ActionDispatcher.Dispatch(controller, new DynamicServerAction(args)); Assert.IsTrue(controller.calledChild); @@ -789,7 +907,5 @@ public IEnumerator TestChildAmbiguousNewAction() { yield return true; } - - } } diff --git a/unity/Assets/UnitTests/TestGetShortestPath.cs b/unity/Assets/UnitTests/TestGetShortestPath.cs index 149a59b77c..be08558f56 100644 --- a/unity/Assets/UnitTests/TestGetShortestPath.cs +++ b/unity/Assets/UnitTests/TestGetShortestPath.cs @@ -1,15 +1,18 @@ +using System; using System.Collections; using System.Collections.Generic; using NUnit.Framework; -using System; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -namespace Tests { - public class TestGetShortestPath : TestBase { +namespace Tests +{ + public class TestGetShortestPath : TestBase + { [UnityTest] - public IEnumerator TestShortestPath() { + public IEnumerator TestShortestPath() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -56,7 +59,6 @@ public IEnumerator TestShortestPath() { result = Mathf.Approximately(-1.26f, path.corners[2].z); Assert.AreEqual(result, true); - } } -} \ No newline at end of file +} diff --git a/unity/Assets/UnitTests/TestObstructed.cs b/unity/Assets/UnitTests/TestObstructed.cs index 7751633f3c..431465b8ed 100644 --- a/unity/Assets/UnitTests/TestObstructed.cs +++ b/unity/Assets/UnitTests/TestObstructed.cs @@ -1,23 +1,29 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using NUnit.Framework; -using System; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -namespace Tests { - public class TestObstructed : TestBase { - +namespace Tests +{ + public class TestObstructed : TestBase + { [SetUp] - public override void Setup() { + public override void Setup() + { UnityEngine.SceneManagement.SceneManager.LoadScene("FloorPlan402_physics"); } [UnityTest] - public IEnumerator TestBehindGlassThenOpenDoor() { - Debug.Log("what is the current scene? " + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name); - + public IEnumerator TestBehindGlassThenOpenDoor() + { + Debug.Log( + "what is the current scene? " + + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + ); + Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -38,7 +44,8 @@ public IEnumerator TestBehindGlassThenOpenDoor() { action.Clear(); action["action"] = "SetObjectPoses"; - ObjectPose pose = new ObjectPose() { + ObjectPose pose = new ObjectPose() + { objectName = "SoapBottle_a48be41a", position = new Vector3(-1.022f, 0f, 1.456f), rotation = new Vector3(0, -180f, 0) @@ -70,6 +77,6 @@ public IEnumerator TestBehindGlassThenOpenDoor() { yield return step(action); Assert.AreEqual(lastActionSuccess, true); - } + } } } diff --git a/unity/Assets/UnitTests/TestPutObject.cs b/unity/Assets/UnitTests/TestPutObject.cs index a6192fec5a..8a31134945 100644 --- a/unity/Assets/UnitTests/TestPutObject.cs +++ b/unity/Assets/UnitTests/TestPutObject.cs @@ -1,15 +1,18 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using NUnit.Framework; -using System; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -namespace Tests { - public class TestPutObject : TestBase { +namespace Tests +{ + public class TestPutObject : TestBase + { [UnityTest] - public IEnumerator TestPutObject_PutNearXY_True() { + public IEnumerator TestPutObject_PutNearXY_True() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -61,7 +64,8 @@ public IEnumerator TestPutObject_PutNearXY_True() { } [UnityTest] - public IEnumerator TestPutObject_PutNearXY_False() { + public IEnumerator TestPutObject_PutNearXY_False() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -110,7 +114,6 @@ public IEnumerator TestPutObject_PutNearXY_False() { result = Mathf.Approximately(creditCard.transform.position.z, 0.7573217f); Assert.AreEqual(result, true); - } // this should fail if user calls PlaceHeldObject directly and tries to pass in a z value @@ -118,7 +121,8 @@ public IEnumerator TestPutObject_PutNearXY_False() { // note: if a user passes in both 'z' and 'maxDistance' then they may get a silent, unintended behavior. // we should decide how to handle extraneous parameters in the future [UnityTest] - public IEnumerator PlaceHeldObject_Deprecated_Z_objectId() { + public IEnumerator PlaceHeldObject_Deprecated_Z_objectId() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -161,7 +165,8 @@ public IEnumerator PlaceHeldObject_Deprecated_Z_objectId() { } [UnityTest] - public IEnumerator PlaceHeldObject_Deprecated_Z_XY() { + public IEnumerator PlaceHeldObject_Deprecated_Z_XY() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -205,7 +210,8 @@ public IEnumerator PlaceHeldObject_Deprecated_Z_XY() { } [UnityTest] - public IEnumerator PlaceHeldObject_Deprecated_Z_XY_PutNearXY_True() { + public IEnumerator PlaceHeldObject_Deprecated_Z_XY_PutNearXY_True() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -249,4 +255,4 @@ public IEnumerator PlaceHeldObject_Deprecated_Z_XY_PutNearXY_True() { Assert.AreEqual(agentManager.PrimaryAgent.lastActionSuccess, false); } } -} \ No newline at end of file +} diff --git a/unity/Assets/UnitTests/TestResourceAssetManager.cs b/unity/Assets/UnitTests/TestResourceAssetManager.cs index 45fb57e531..1499a51e63 100644 --- a/unity/Assets/UnitTests/TestResourceAssetManager.cs +++ b/unity/Assets/UnitTests/TestResourceAssetManager.cs @@ -1,37 +1,43 @@ +using System; using System.Collections; using System.Collections.Generic; using NUnit.Framework; -using System; -using UnityEngine; using UnityEditor; using UnityEditor.VersionControl; +using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; using Assert = UnityEngine.Assertions.Assert; -namespace Tests { - public class TestResourceAssetManager : TestBase { +namespace Tests +{ + public class TestResourceAssetManager : TestBase + { [UnityTest] - public IEnumerator TestFindAssets() { + public IEnumerator TestFindAssets() + { yield return null; string testAssetPath = "Assets/Resources/FakeResourceAssetManagerMaterial.mat"; string label = "FakeFindAssetsLabel"; ResourceAssetManager manager = new ResourceAssetManager(); - try { - List> mats = manager.FindResourceAssetReferences(label); + try + { + List> mats = + manager.FindResourceAssetReferences(label); Assert.AreEqual(mats.Count, 0); - + Material material = new Material(Shader.Find("Standard")); AssetDatabase.CreateAsset(material, testAssetPath); material = AssetDatabase.LoadMainAssetAtPath(testAssetPath) as Material; - AssetDatabase.SetLabels(material, new string[]{label}); + AssetDatabase.SetLabels(material, new string[] { label }); manager.RefreshCatalog(); mats = manager.FindResourceAssetReferences(label); Assert.AreEqual(mats.Count, 1); - } finally { + } + finally + { AssetDatabase.DeleteAsset(testAssetPath); } - } } } diff --git a/unity/Assets/UnitTests/TestRotateAndLook.cs b/unity/Assets/UnitTests/TestRotateAndLook.cs index b04c3d65c6..b7412d1cd7 100644 --- a/unity/Assets/UnitTests/TestRotateAndLook.cs +++ b/unity/Assets/UnitTests/TestRotateAndLook.cs @@ -1,15 +1,18 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using NUnit.Framework; -using System; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -namespace Tests { - public class TestRotateAndLook : TestBase { +namespace Tests +{ + public class TestRotateAndLook : TestBase + { [UnityTest] - public IEnumerator TestRotateRight() { + public IEnumerator TestRotateRight() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -31,7 +34,8 @@ public IEnumerator TestRotateRight() { } [UnityTest] - public IEnumerator TestLookUpDownDefault () { + public IEnumerator TestLookUpDownDefault() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -69,7 +73,8 @@ public IEnumerator TestLookUpDownDefault () { } [UnityTest] - public IEnumerator TestLookUpDownDefaultLocobot () { + public IEnumerator TestLookUpDownDefaultLocobot() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -108,7 +113,8 @@ public IEnumerator TestLookUpDownDefaultLocobot () { } [UnityTest] - public IEnumerator TestLookUpDownDefaultStretch () { + public IEnumerator TestLookUpDownDefaultStretch() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -153,7 +159,8 @@ public IEnumerator TestLookUpDownDefaultStretch () { } [UnityTest] - public IEnumerator TestSetLookUpDownLimits () { + public IEnumerator TestSetLookUpDownLimits() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -200,7 +207,8 @@ public IEnumerator TestSetLookUpDownLimits () { } [UnityTest] - public IEnumerator TestSetLookUpDownLimitsLocoBot () { + public IEnumerator TestSetLookUpDownLimitsLocoBot() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -248,7 +256,8 @@ public IEnumerator TestSetLookUpDownLimitsLocoBot () { } [UnityTest] - public IEnumerator TestSetLookUpDownLimitsArm () { + public IEnumerator TestSetLookUpDownLimitsArm() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -296,7 +305,8 @@ public IEnumerator TestSetLookUpDownLimitsArm () { } [UnityTest] - public IEnumerator TestSetLookUpDownLimitsStretch () { + public IEnumerator TestSetLookUpDownLimitsStretch() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -334,7 +344,7 @@ public IEnumerator TestSetLookUpDownLimitsStretch () { yield return step(action); yield return step(action); yield return step(action); - + // Debug.Log("LookDown 6. RAW: " + agentCamera.transform.eulerAngles.x // + " vs. INT: " + (int)agentCamera.transform.eulerAngles.x // + " vs ROUNDED INT: " + (int)Mathf.Round(agentCamera.transform.eulerAngles.x)); diff --git a/unity/Assets/UnitTests/TestSetObjectPoses.cs b/unity/Assets/UnitTests/TestSetObjectPoses.cs index 6a9c5054f8..62001a653b 100644 --- a/unity/Assets/UnitTests/TestSetObjectPoses.cs +++ b/unity/Assets/UnitTests/TestSetObjectPoses.cs @@ -1,15 +1,18 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using NUnit.Framework; -using System; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -namespace Tests { - public class TestSetObjectPoses : TestBase { +namespace Tests +{ + public class TestSetObjectPoses : TestBase + { [UnityTest] - public IEnumerator TestSetObjectPoses_ObjectHierarchyReset_True() { + public IEnumerator TestSetObjectPoses_ObjectHierarchyReset_True() + { Dictionary action = new Dictionary(); var agentManager = GameObject.FindObjectOfType(); @@ -18,17 +21,26 @@ public IEnumerator TestSetObjectPoses_ObjectHierarchyReset_True() { GameObject topObject = GameObject.Find("Objects"); int numObjectsWithBadParents = 0; List ops = new List(); - foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) { - if ((!sop.isStatic) || sop.IsPickupable) { - numObjectsWithBadParents += sop.gameObject.transform.parent != topObject.transform ? 1 : 0; - ops.Add(new ObjectPose(objectName: sop.name, position: sop.transform.position, rotation: sop.transform.eulerAngles)); + foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) + { + if ((!sop.isStatic) || sop.IsPickupable) + { + numObjectsWithBadParents += + sop.gameObject.transform.parent != topObject.transform ? 1 : 0; + ops.Add( + new ObjectPose( + objectName: sop.name, + position: sop.transform.position, + rotation: sop.transform.eulerAngles + ) + ); } } Assert.That( numObjectsWithBadParents > 0, - "Looks like there are not sim objects whose parents are sim objects." + - " This test isn't meaningful without this so you'll need to set it up so that there are." + "Looks like there are not sim objects whose parents are sim objects." + + " This test isn't meaningful without this so you'll need to set it up so that there are." ); action["action"] = "SetObjectPoses"; @@ -36,8 +48,10 @@ public IEnumerator TestSetObjectPoses_ObjectHierarchyReset_True() { action["placeStationary"] = true; yield return step(action); - foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) { - if ((!sop.isStatic) || sop.IsPickupable) { + foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) + { + if ((!sop.isStatic) || sop.IsPickupable) + { Assert.That(sop.gameObject.transform.parent == topObject.transform); } } diff --git a/unity/Assets/UnitTests/TestStretchArmMeta.cs b/unity/Assets/UnitTests/TestStretchArmMeta.cs index ef2600b69f..5fa4a42e72 100644 --- a/unity/Assets/UnitTests/TestStretchArmMeta.cs +++ b/unity/Assets/UnitTests/TestStretchArmMeta.cs @@ -1,16 +1,18 @@ +using System; using System.Collections; using System.Collections.Generic; using NUnit.Framework; -using System; using UnityEngine; using UnityEngine.TestTools; using UnityStandardAssets.Characters.FirstPerson; -namespace Tests { +namespace Tests +{ public class TestStretchArmMeta : TestBase { [UnityTest] - public IEnumerator TestStretchArmGripperOpennessMetadata () { + public IEnumerator TestStretchArmGripperOpennessMetadata() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -18,7 +20,8 @@ public IEnumerator TestStretchArmGripperOpennessMetadata () { yield return step(action); BaseFPSAgentController agent = agentManager.PrimaryAgent; - Stretch_Robot_Arm_Controller armController = agent.GetComponentInChildren(); + Stretch_Robot_Arm_Controller armController = + agent.GetComponentInChildren(); action.Clear(); @@ -37,7 +40,7 @@ public IEnumerator TestStretchArmGripperOpennessMetadata () { action["action"] = "SetGripperOpenness"; action["openness"] = 10f; //this should set the gripper to state 2 - yield return step(action); + yield return step(action); meta = armController.GenerateMetadata(); Debug.Log($"openness should be 2 but is: {meta.gripperOpennessState}"); @@ -45,7 +48,8 @@ public IEnumerator TestStretchArmGripperOpennessMetadata () { } [UnityTest] - public IEnumerator TestStretchArmRootRelativeHandSphere () { + public IEnumerator TestStretchArmRootRelativeHandSphere() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -53,7 +57,8 @@ public IEnumerator TestStretchArmRootRelativeHandSphere () { yield return step(action); BaseFPSAgentController agent = agentManager.PrimaryAgent; - Stretch_Robot_Arm_Controller armController = agent.GetComponentInChildren(); + Stretch_Robot_Arm_Controller armController = + agent.GetComponentInChildren(); action.Clear(); @@ -69,10 +74,8 @@ public IEnumerator TestStretchArmRootRelativeHandSphere () { string rootRelativeCenter = meta.rootRelativeHandSphereCenter.ToString("F5"); Assert.AreEqual(rootRelativeCenter, "(-0.00007, 0.16460, -0.20476)"); - //Debug.Log($"world handSphereCenter is {meta.handSphereCenter.ToString("F5")}"); //Debug.Log($"root relative sphere center: {meta.rootRelativeHandSphereCenter.ToString("F5")}"); } } - } diff --git a/unity/Assets/UnitTests/TestThirdPartyCameraAndMainCamera.cs b/unity/Assets/UnitTests/TestThirdPartyCameraAndMainCamera.cs index 5af1062b5f..5ac54dd841 100644 --- a/unity/Assets/UnitTests/TestThirdPartyCameraAndMainCamera.cs +++ b/unity/Assets/UnitTests/TestThirdPartyCameraAndMainCamera.cs @@ -1,14 +1,17 @@ -using System.Collections; +using System; +using System.Collections; using System.Collections.Generic; using NUnit.Framework; -using System; using UnityEngine; using UnityEngine.TestTools; -namespace Tests { - public class TestThirdPartyCameraAndMainCamera : TestBase { +namespace Tests +{ + public class TestThirdPartyCameraAndMainCamera : TestBase + { [UnityTest] - public IEnumerator TestAddThirdPartyCamera() { + public IEnumerator TestAddThirdPartyCamera() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -67,7 +70,8 @@ public IEnumerator TestAddThirdPartyCamera() { } [UnityTest] - public IEnumerator TestAddMultipleThirdPartyCamera() { + public IEnumerator TestAddMultipleThirdPartyCamera() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -90,7 +94,8 @@ public IEnumerator TestAddMultipleThirdPartyCamera() { } [UnityTest] - public IEnumerator TestUpdateThirdPartyCamera() { + public IEnumerator TestUpdateThirdPartyCamera() + { Dictionary action = new Dictionary(); action["action"] = "Initialize"; @@ -112,13 +117,13 @@ public IEnumerator TestUpdateThirdPartyCamera() { //update third party camera to be attached to agent action["action"] = "UpdateThirdPartyCamera"; - action["thirdPartyCameraId"]=0; + action["thirdPartyCameraId"] = 0; action["position"] = new Vector3(1, 2, 3); action["rotation"] = new Vector3(20, 20, 20); action["parent"] = "agent"; action["orthographic"] = true; action["orthographicSize"] = 5; - action["agentPositionRelativeCoordinates"]=true; + action["agentPositionRelativeCoordinates"] = true; yield return step(action); //make sure camera is now a child of the primary agent @@ -146,13 +151,13 @@ public IEnumerator TestUpdateThirdPartyCamera() { action.Clear(); //ok now update camera so it detaches from the agent and also repositions in world space action["action"] = "UpdateThirdPartyCamera"; - action["thirdPartyCameraId"]=0; + action["thirdPartyCameraId"] = 0; action["position"] = new Vector3(10, 10, 10); action["rotation"] = new Vector3(1f, 1f, 1f); action["parent"] = "world"; action["orthographic"] = true; action["orthographicSize"] = 5; - action["agentPositionRelativeCoordinates"]=false; + action["agentPositionRelativeCoordinates"] = false; action["parent"] = "agent"; yield return step(action); @@ -169,7 +174,9 @@ public IEnumerator TestUpdateThirdPartyCamera() { result = Mathf.Approximately(agentThirdPartyCam.transform.position.z, 10.0f); Assert.AreEqual(result, true); - Debug.Log($"ok what even are the eulers: {agentThirdPartyCam.transform.eulerAngles.x}, {agentThirdPartyCam.transform.eulerAngles.y}, {agentThirdPartyCam.transform.eulerAngles.z}"); + Debug.Log( + $"ok what even are the eulers: {agentThirdPartyCam.transform.eulerAngles.x}, {agentThirdPartyCam.transform.eulerAngles.y}, {agentThirdPartyCam.transform.eulerAngles.z}" + ); //check rotation set as expected Debug.Log("x rot"); result = Mathf.Approximately(agentThirdPartyCam.transform.eulerAngles.x, 1.0f); @@ -185,7 +192,8 @@ public IEnumerator TestUpdateThirdPartyCamera() { } [UnityTest] - public IEnumerator TestUpdateMainCamera() { + public IEnumerator TestUpdateMainCamera() + { Dictionary action = new Dictionary(); action["action"] = "Initialize";