From 828edf83c329c1596d3f161eddd892dcf429cc83 Mon Sep 17 00:00:00 2001 From: AlvaroHG Date: Thu, 1 Aug 2024 11:57:12 -0700 Subject: [PATCH 1/7] Trigger build --- tasks.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tasks.py b/tasks.py index ee8839a098..e747f03b13 100644 --- a/tasks.py +++ b/tasks.py @@ -1209,7 +1209,6 @@ def ci_build( 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() From fcd40b0fb5a425079738fd57352189b5f5eb39c5 Mon Sep 17 00:00:00 2001 From: AlvaroHG Date: Thu, 1 Aug 2024 13:49:13 -0700 Subject: [PATCH 2/7] New build in mac --- tasks.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tasks.py b/tasks.py index e747f03b13..399f911800 100644 --- a/tasks.py +++ b/tasks.py @@ -4907,3 +4907,4 @@ def procedural_asset_cache_test(ctx, asset_dir, house_path, asset_ids="", cache_ print(f"Action {controller.last_action['action']} success: {evt.metadata['lastActionSuccess']}") print(f'Error: {evt.metadata["errorMessage"]}') print(f'return {evt.metadata["actionReturn"]}') + From 7afaf39ba8dc969f3029fa88eb1849491b35fcab Mon Sep 17 00:00:00 2001 From: AlvaroHG Date: Thu, 1 Aug 2024 15:23:18 -0700 Subject: [PATCH 3/7] Build after gicahce delete --- tasks.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tasks.py b/tasks.py index 399f911800..e747f03b13 100644 --- a/tasks.py +++ b/tasks.py @@ -4907,4 +4907,3 @@ def procedural_asset_cache_test(ctx, asset_dir, house_path, asset_ids="", cache_ print(f"Action {controller.last_action['action']} success: {evt.metadata['lastActionSuccess']}") print(f'Error: {evt.metadata["errorMessage"]}') print(f'return {evt.metadata["actionReturn"]}') - From b10f3175af6587359dc054e85decb4c3e2a21695 Mon Sep 17 00:00:00 2001 From: winthos Date: Fri, 2 Aug 2024 13:47:03 -0700 Subject: [PATCH 4/7] Fix to arm metadata unit test updating arm metadata unit test to correctly check for the default gripper state of the arm. The default state used to be completely closed but has since been changed to be in a slightly opened configuration by default. --- unity/Assets/UnitTests/TestStretchArmMeta.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/unity/Assets/UnitTests/TestStretchArmMeta.cs b/unity/Assets/UnitTests/TestStretchArmMeta.cs index 5fa4a42e72..ed9b04b9cb 100644 --- a/unity/Assets/UnitTests/TestStretchArmMeta.cs +++ b/unity/Assets/UnitTests/TestStretchArmMeta.cs @@ -33,7 +33,7 @@ public IEnumerator TestStretchArmGripperOpennessMetadata() ArmMetadata meta = armController.GenerateMetadata(); //check meta is in correct state Debug.Log($"openness should be 0 but is: {meta.gripperOpennessState}"); - Assert.AreEqual(meta.gripperOpennessState, 0); + Assert.AreEqual(meta.gripperOpennessState, 1); //now lets open the gripper a bit action.Clear(); From 2f0661d14d031bfcd7a071746b8691d39b075a1a Mon Sep 17 00:00:00 2001 From: Winson Han Date: Fri, 2 Aug 2024 14:29:13 -0700 Subject: [PATCH 5/7] running formatting --- ai2thor/benchmarking.py | 1 - ai2thor/build.py | 2 -- ai2thor/docker.py | 2 -- ai2thor/downloader.py | 1 - ai2thor/hooks/metadata_hook.py | 3 ++- ai2thor/interact.py | 2 -- ai2thor/offline_controller.py | 3 --- ai2thor/platform.py | 3 --- ai2thor/robot_controller.py | 1 - ai2thor/server.py | 8 -------- ai2thor/tests/test_controller.py | 8 -------- ai2thor/tests/test_event.py | 1 - ai2thor/tests/test_fifo_server.py | 3 --- ai2thor/tests/test_server.py | 5 ----- ai2thor/tests/test_unity.py | 7 ------- ai2thor/tests/test_unity_procedural.py | 1 - ai2thor/util/depth.py | 1 - ai2thor/util/scene_yaml_edit.py | 1 - ai2thor/util/trials.py | 6 ++++-- ai2thor/video_controller.py | 1 - ai2thor/wsgi_server.py | 5 ----- arm_test/base.py | 1 - arm_test/check_determinism_different_machines.py | 1 - ...heck_determinism_event_collision_different_machines.py | 2 -- 24 files changed, 6 insertions(+), 63 deletions(-) diff --git a/ai2thor/benchmarking.py b/ai2thor/benchmarking.py index 9b916aa5a0..bef7669d56 100644 --- a/ai2thor/benchmarking.py +++ b/ai2thor/benchmarking.py @@ -451,7 +451,6 @@ def __create_experiments(self): return experiment_list def benchmark(self, action_map={}): - env, controller_params = self.__init_env() experiment_list = self.__create_experiments() hostname = "" diff --git a/ai2thor/build.py b/ai2thor/build.py index 5e8a36c15e..dc426d2f09 100644 --- a/ai2thor/build.py +++ b/ai2thor/build.py @@ -109,7 +109,6 @@ def base_dir(self): class Build(object): def __init__(self, platform, commit_id, include_private_scenes, releases_dir=None): - if type(platform) is str: if platform in STR_PLATFORM_MAP: platform = STR_PLATFORM_MAP[platform] @@ -126,7 +125,6 @@ def __init__(self, platform, commit_id, include_private_scenes, releases_dir=Non self.tmp_dir = os.path.normpath(self.releases_dir + "/../tmp") def download(self): - makedirs(self.releases_dir) makedirs(self.tmp_dir) diff --git a/ai2thor/docker.py b/ai2thor/docker.py index c8bd470382..a09456623c 100644 --- a/ai2thor/docker.py +++ b/ai2thor/docker.py @@ -77,7 +77,6 @@ def nvidia_version(): def generate_dockerfile(tag): - driver_url = "http://us.download.nvidia.com/XFree86/Linux-x86_64/{version}/NVIDIA-Linux-x86_64-{version}.run".format( version=nvidia_version() ) @@ -127,7 +126,6 @@ def kill_container(container_id): def build_image(): - version = nvidia_version() image_name = "ai2thor/ai2thor-nvidia-%s:%s" % (version, COMMIT_ID) diff --git a/ai2thor/downloader.py b/ai2thor/downloader.py index 6c9d97cad7..ab9a0a46eb 100644 --- a/ai2thor/downloader.py +++ b/ai2thor/downloader.py @@ -9,7 +9,6 @@ def download(url, sha256_digest, include_private_scenes=False): - auth = None if include_private_scenes: auth = ai2thor.build.boto_auth() diff --git a/ai2thor/hooks/metadata_hook.py b/ai2thor/hooks/metadata_hook.py index 5f08d631ad..2225c1721e 100644 --- a/ai2thor/hooks/metadata_hook.py +++ b/ai2thor/hooks/metadata_hook.py @@ -10,4 +10,5 @@ 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/interact.py b/ai2thor/interact.py index 8e0593d7dd..341b39e894 100644 --- a/ai2thor/interact.py +++ b/ai2thor/interact.py @@ -91,7 +91,6 @@ def interact( color_frame=False, metadata=False, ): - if not sys.stdout.isatty(): raise RuntimeError("controller.interact() must be run from a terminal") @@ -198,7 +197,6 @@ def add_command(cc, action, **args): print(" ".join(command_info)) def next_interact_command(self): - current_buffer = "" while True: commands = self._interact_commands diff --git a/ai2thor/offline_controller.py b/ai2thor/offline_controller.py index 32ec6c1e69..48cda4c7de 100644 --- a/ai2thor/offline_controller.py +++ b/ai2thor/offline_controller.py @@ -18,7 +18,6 @@ class Controller(object): def __init__(self, base_dir, grid_size=0.25): - self.grid_size = grid_size self.base_dir = base_dir if grid_size < 0.25: @@ -153,7 +152,6 @@ def inc(self): def write_frame(event, base_dir, scene_name, frame_name): - events_dir = "%s/%s/events" % (base_dir, scene_name) met_dir = "%s/%s/metadata" % (base_dir, scene_name) os.makedirs(met_dir, exist_ok=True) @@ -167,7 +165,6 @@ def write_frame(event, base_dir, scene_name, frame_name): def look_up_down_write(controller, base_dir, fc, scene_name): - fc.inc() write_frame(controller.step(action="LookUp"), base_dir, scene_name, fc.counter) fc.inc() diff --git a/ai2thor/platform.py b/ai2thor/platform.py index f70557e407..f3d3bcb951 100644 --- a/ai2thor/platform.py +++ b/ai2thor/platform.py @@ -16,7 +16,6 @@ def __init__(self, system, width, height, x_display, headless): class BasePlatform: - enabled = True @classmethod @@ -65,7 +64,6 @@ def dependency_instructions(cls, request): @classmethod def _select_x_display(cls, width, height): - valid_displays = cls._valid_x_displays(width, height) if valid_displays: return valid_displays[0] @@ -173,7 +171,6 @@ def executable_path(cls, base_dir, name): @classmethod def parse_plist(cls, base_dir, name): - plist_path = os.path.join(base_dir, name + ".app", "Contents/Info.plist") with open(plist_path) as f: diff --git a/ai2thor/robot_controller.py b/ai2thor/robot_controller.py index c96fe2c0be..9e11580b6f 100644 --- a/ai2thor/robot_controller.py +++ b/ai2thor/robot_controller.py @@ -83,7 +83,6 @@ def reset(self, scene_name=None): return self.last_event def step(self, action=None, **action_args): - if type(action) is dict: action = copy.deepcopy(action) # prevent changes from leaking else: diff --git a/ai2thor/server.py b/ai2thor/server.py index 46e5f09b10..047e5cecdd 100644 --- a/ai2thor/server.py +++ b/ai2thor/server.py @@ -28,12 +28,10 @@ def default(self, obj): class LazyMask(Mapping): - def __contains__(self, key: object) -> bool: return self.mask(cast(str, key)) is not None def __getitem__(self, key: str): - m = self.mask(key) if m is None: @@ -59,7 +57,6 @@ def __len__(self): class LazyInstanceSegmentationMasks(LazyMask): - def __init__(self, image_ids_data: bytes, metadata: dict): self._masks: Dict[str, np.ndarray] = {} self._loaded = False @@ -213,7 +210,6 @@ def mask(self, key: str, default: Optional[np.ndarray] = None) -> Optional[np.nd class LazyDetections2D(Mapping): def __init__(self, instance_masks: LazyInstanceSegmentationMasks): - self.instance_masks = instance_masks def mask_bounding_box(self, mask: np.ndarray) -> Optional[Tuple[int, int, int, int]]: @@ -239,7 +235,6 @@ def __eq__(self, other: object): class LazyInstanceDetections2D(LazyDetections2D): - def __init__(self, instance_masks: LazyInstanceSegmentationMasks): super().__init__(instance_masks) self._detections2d: Dict[str, Optional[Tuple[int, int, int, int]]] = {} @@ -282,9 +277,7 @@ def __iter__(self): class LazyClassDetections2D(LazyDetections2D): - def __init__(self, instance_masks: LazyInstanceSegmentationMasks): - super().__init__(instance_masks) self._loaded = False self._detections2d: Dict[str, Optional[Tuple[Tuple[int, int, int, int], ...]]] = {} @@ -533,7 +526,6 @@ def objects_by_type(self, object_type): return [obj for obj in self.metadata["objects"] if obj["objectType"] == object_type] def process_colors_ids(self, image_ids_data): - self.instance_masks = LazyInstanceSegmentationMasks(image_ids_data, self.metadata) self.class_masks = LazyClassSegmentationMasks(self.instance_masks) self.class_detections2D = LazyClassDetections2D(self.instance_masks) diff --git a/ai2thor/tests/test_controller.py b/ai2thor/tests/test_controller.py index 71b38c9515..abca08106a 100644 --- a/ai2thor/tests/test_controller.py +++ b/ai2thor/tests/test_controller.py @@ -103,7 +103,6 @@ def empty(self): def controller(**args): - # delete display so the tests can run on Linux if "DISPLAY" in os.environ: del os.environ["DISPLAY"] @@ -171,7 +170,6 @@ def test_linux_explicit_xdisplay(mocker): def test_linux_invalid_linux64_invalid_cr(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) @@ -195,7 +193,6 @@ def test_linux_invalid_linux64_invalid_cr(mocker): def test_linux_invalid_linux64_valid_cr(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) @@ -215,7 +212,6 @@ def test_linux_invalid_linux64_valid_cr(mocker): 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) @@ -229,7 +225,6 @@ def test_linux_valid_linux64_valid_cloudrendering(mocker): def test_linux_valid_linux64_valid_cloudrendering_enabled_cr(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) @@ -246,7 +241,6 @@ def test_linux_valid_linux64_valid_cloudrendering_enabled_cr(mocker): def test_linux_valid_linux64_invalid_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) @@ -263,7 +257,6 @@ def test_linux_valid_linux64_invalid_cloudrendering(mocker): 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) @@ -278,7 +271,6 @@ def test_linux_missing_linux64(mocker): def test_linux_missing_cloudrendering(mocker): - mocker.patch("ai2thor.controller.platform_system", fake_linux_system) mocker.patch("ai2thor.controller.ai2thor.build.Build.exists", fake_linux64_exists) mocker.patch("ai2thor.controller.ai2thor.build.Build.download", noop_download) diff --git a/ai2thor/tests/test_event.py b/ai2thor/tests/test_event.py index bec7873395..70eff1e2d8 100644 --- a/ai2thor/tests/test_event.py +++ b/ai2thor/tests/test_event.py @@ -3602,7 +3602,6 @@ def test_lazy_class_segmentation(event_with_segmentation): @pytest.mark.parametrize("event_with_segmentation", segmentation_events) def test_lazy_class_segmentation_missing(event_with_segmentation): - with pytest.raises(KeyError): event_with_segmentation.class_masks["Stove"] diff --git a/ai2thor/tests/test_fifo_server.py b/ai2thor/tests/test_fifo_server.py index bbf6e2c14a..6cb223f613 100644 --- a/ai2thor/tests/test_fifo_server.py +++ b/ai2thor/tests/test_fifo_server.py @@ -9,7 +9,6 @@ def test_multi_agent_train(): - s = ai2thor.fifo_server.FifoServer(width=300, height=300) s.send(dict(action="RotateRight")) c = FifoClient(s.server_pipe_path, s.client_pipe_path) @@ -25,7 +24,6 @@ def test_multi_agent_train(): def test_train_numpy_action(): - s = ai2thor.fifo_server.FifoServer(width=300, height=300) s.send( dict( @@ -56,7 +54,6 @@ def generate_multi_agent_metadata_payload(metadata, sequence_id): def test_simple(): - s = ai2thor.fifo_server.FifoServer(width=300, height=300) s.send(dict(action="RotateRight")) c = FifoClient(s.server_pipe_path, s.client_pipe_path) diff --git a/ai2thor/tests/test_server.py b/ai2thor/tests/test_server.py index a9a16b8ce3..84a3c93f9c 100644 --- a/ai2thor/tests/test_server.py +++ b/ai2thor/tests/test_server.py @@ -75,7 +75,6 @@ def test_ping(client): def test_multi_agent_train(): - s = ai2thor.wsgi_server.WsgiServer(host="127.0.0.1") s.send(dict(action="RotateRight")) c = s.app.test_client() @@ -89,7 +88,6 @@ def test_multi_agent_train(): def test_train_numpy_action(): - s = ai2thor.wsgi_server.WsgiServer(host="127.0.0.1") s.send( dict( @@ -118,7 +116,6 @@ def test_train_numpy_action(): def test_train(): - s = ai2thor.wsgi_server.WsgiServer(host="127.0.0.1") s.send(dict(action="RotateRight")) c = s.app.test_client() @@ -132,7 +129,6 @@ def test_train(): def test_client_token_mismatch(): - s = ai2thor.wsgi_server.WsgiServer(host="127.0.0.1") s.send(dict(action="RotateRight")) s.client_token = "123456" @@ -166,7 +162,6 @@ def test_non_multipart(): def test_sequence_id_mismatch(): - s = ai2thor.wsgi_server.WsgiServer(host="127.0.0.1") s.send(dict(action="RotateRight")) c = s.app.test_client() diff --git a/ai2thor/tests/test_unity.py b/ai2thor/tests/test_unity.py index 9db19cdcb1..80437433e5 100644 --- a/ai2thor/tests/test_unity.py +++ b/ai2thor/tests/test_unity.py @@ -257,7 +257,6 @@ def test_third_party_camera_with_image_synthesis(fifo_controller): def test_rectangle_aspect(fifo_controller): - fifo_controller.reset(TEST_SCENE, width=600, height=300) event = fifo_controller.step(dict(action="Initialize", gridSize=0.25)) assert event.frame.shape == (300, 600, 3) @@ -385,7 +384,6 @@ def test_lookdown(controller): @pytest.mark.parametrize("controller", fifo_wsgi) def test_no_leak_params(controller): - action = dict(action="RotateLook", rotation=0, horizon=0) e = controller.step(action) assert "sequenceId" not in action @@ -404,7 +402,6 @@ def test_target_invocation_exception(controller): @pytest.mark.parametrize("controller", fifo_wsgi) def test_lookup(controller): - e = controller.step(dict(action="RotateLook", rotation=0, horizon=0)) position = controller.last_event.metadata["agent"]["position"] horizon = controller.last_event.metadata["agent"]["cameraHorizon"] @@ -419,7 +416,6 @@ def test_lookup(controller): @pytest.mark.parametrize("controller", fifo_wsgi) def test_rotate_left(controller): - e = controller.step(dict(action="RotateLook", rotation=0, horizon=0)) position = controller.last_event.metadata["agent"]["position"] rotation = controller.last_event.metadata["agent"]["rotation"] @@ -435,7 +431,6 @@ def test_rotate_left(controller): @pytest.mark.parametrize("controller", fifo_wsgi) def test_simobj_filter(controller): - objects = controller.last_event.metadata["objects"] unfiltered_object_ids = sorted([o["objectId"] for o in objects]) filter_object_ids = sorted([o["objectId"] for o in objects[0:3]]) @@ -645,7 +640,6 @@ def test_update_third_party_camera(fifo_controller): @pytest.mark.parametrize("controller", fifo_wsgi) def test_rotate_look(controller): - e = controller.step(dict(action="RotateLook", rotation=0, horizon=0)) position = controller.last_event.metadata["agent"]["position"] rotation = controller.last_event.metadata["agent"]["rotation"] @@ -660,7 +654,6 @@ def test_rotate_look(controller): @pytest.mark.parametrize("controller", fifo_wsgi) def test_rotate_right(controller): - e = controller.step(dict(action="RotateLook", rotation=0, horizon=0)) position = controller.last_event.metadata["agent"]["position"] rotation = controller.last_event.metadata["agent"]["rotation"] diff --git a/ai2thor/tests/test_unity_procedural.py b/ai2thor/tests/test_unity_procedural.py index 20dfe4b357..2bef03250f 100644 --- a/ai2thor/tests/test_unity_procedural.py +++ b/ai2thor/tests/test_unity_procedural.py @@ -279,7 +279,6 @@ def test_determinism(controller_args): print(f"{pos}") object_positions.append(pos) if prev_pos: - diffs = list(diff(pos, prev_pos, tolerance=0.00001)) print(diffs) assert [] == diffs diff --git a/ai2thor/util/depth.py b/ai2thor/util/depth.py index 78f14e5a09..a3eb2613fb 100644 --- a/ai2thor/util/depth.py +++ b/ai2thor/util/depth.py @@ -35,7 +35,6 @@ def generate_noise_indices(img_size): corner = t for i, c in enumerate(corner): - offset = 0 i_offset = 0 if j % 2 != 0: diff --git a/ai2thor/util/scene_yaml_edit.py b/ai2thor/util/scene_yaml_edit.py index 6a96656644..4e7747baae 100755 --- a/ai2thor/util/scene_yaml_edit.py +++ b/ai2thor/util/scene_yaml_edit.py @@ -39,7 +39,6 @@ def GetSceneNames(start_index, last_index, nameTemplate="", prefix_path="unity/A def main(): - # testSceneNames = GetRoboSceneNames(3, 5, "Val") # valSceneNames = GetRoboSceneNames(2, 2, "test-dev", "unity/Assets/Private/Scenes") # trainSceneNames = GetRoboSceneNames(12, 5, "Train") diff --git a/ai2thor/util/trials.py b/ai2thor/util/trials.py index 5a2f84c63a..327086d137 100644 --- a/ai2thor/util/trials.py +++ b/ai2thor/util/trials.py @@ -3,9 +3,11 @@ 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): diff --git a/ai2thor/video_controller.py b/ai2thor/video_controller.py index e4196ecf9b..f16cd05544 100644 --- a/ai2thor/video_controller.py +++ b/ai2thor/video_controller.py @@ -27,7 +27,6 @@ def __init__( cam_fov=60, **controller_kwargs, ): - self.saved_frames = [] self.ceiling_off = False self.initial_cam_rot = cam_rot.copy() diff --git a/ai2thor/wsgi_server.py b/ai2thor/wsgi_server.py index d901289e04..cd0d448fe8 100644 --- a/ai2thor/wsgi_server.py +++ b/ai2thor/wsgi_server.py @@ -105,7 +105,6 @@ def get_boundary(request_headers): return None def __init__(self, data, boundary): - self.form = {} self.files = {} @@ -125,7 +124,6 @@ def __init__(self, data, boundary): headers = {} for header in raw_headers.tobytes().decode("ascii").strip().split("\r\n"): - k, v = header.split(":") headers[k.strip()] = v.strip() @@ -149,7 +147,6 @@ def __init__(self, data, boundary): class WsgiServer(ai2thor.server.Server): - server_type = "WSGI" def __init__( @@ -163,7 +160,6 @@ def __init__( width=300, height=300, ): - app = Flask( __name__, template_folder=os.path.realpath( @@ -204,7 +200,6 @@ def ping(): @app.route("/train", methods=["post"]) def train(): - action_returns = [] if request.headers["Content-Type"].split(";")[0] == "multipart/form-data": diff --git a/arm_test/base.py b/arm_test/base.py index 2fdaa39c79..b71009625b 100644 --- a/arm_test/base.py +++ b/arm_test/base.py @@ -114,7 +114,6 @@ def standard_pose(): def execute_actions(actions, **kwargs): - for a in actions: if a == {} or a == {"action": ""}: continue diff --git a/arm_test/check_determinism_different_machines.py b/arm_test/check_determinism_different_machines.py index 1e82ac3bd6..9c85469a68 100644 --- a/arm_test/check_determinism_different_machines.py +++ b/arm_test/check_determinism_different_machines.py @@ -93,7 +93,6 @@ def get_reachable_positions(controller): def execute_command(controller, command, action_dict_addition_by_action): - base_position = get_current_arm_state(controller) change_height = MOVE_CONSTANT change_value = change_height diff --git a/arm_test/check_determinism_event_collision_different_machines.py b/arm_test/check_determinism_event_collision_different_machines.py index 4465586687..1267768f8d 100644 --- a/arm_test/check_determinism_event_collision_different_machines.py +++ b/arm_test/check_determinism_event_collision_different_machines.py @@ -48,7 +48,6 @@ def get_reachable_positions(controller): def execute_command(controller, command, action_dict_addition): - base_position = get_current_arm_state(controller) change_height = action_dict_addition["move_constant"] change_value = change_height @@ -118,7 +117,6 @@ def execute_command(controller, command, action_dict_addition): action_details = {} if command in ["w", "z", "s", "a", "3", "4"]: - controller.step( action="MoveMidLevelArm", position=dict(x=base_position["x"], y=base_position["y"], z=base_position["z"]), From b2b77e8a173b08be0ded15554a8bb7d69c8223fb Mon Sep 17 00:00:00 2001 From: Winson Han Date: Fri, 2 Aug 2024 14:32:12 -0700 Subject: [PATCH 6/7] more formatting --- unity/Assets/Scripts/ActionDispatcher.cs | 290 +- unity/Assets/Scripts/AgentManager.cs | 982 +- unity/Assets/Scripts/Arm.cs | 3 +- unity/Assets/Scripts/ArmAgentController.cs | 107 +- unity/Assets/Scripts/ArmCollisionResolver.cs | 34 +- unity/Assets/Scripts/ArmController.cs | 169 +- .../Scripts/ArticulatedAgentController.cs | 255 +- .../Assets/Scripts/ArticulatedAgentSolver.cs | 141 +- .../Scripts/ArticulatedArmController.cs | 222 +- .../Assets/Scripts/ArticulatedArmExtender.cs | 21 +- .../Scripts/ArticulatedArmJointSolver.cs | 162 +- unity/Assets/Scripts/BaseAgentComponent.cs | 42 +- .../Assets/Scripts/BaseFPSAgentController.cs | 3635 ++++-- unity/Assets/Scripts/BatchRename.cs | 27 +- unity/Assets/Scripts/Bathtub.cs | 24 +- unity/Assets/Scripts/Bed.cs | 24 +- unity/Assets/Scripts/Blinds.cs | 31 +- unity/Assets/Scripts/Box.cs | 28 +- unity/Assets/Scripts/Break.cs | 108 +- unity/Assets/Scripts/Breakdown.cs | 12 +- unity/Assets/Scripts/Cabinet.cs | 55 +- unity/Assets/Scripts/CameraControls.cs | 12 +- unity/Assets/Scripts/CameraDepthSetup.cs | 6 +- unity/Assets/Scripts/CanOpen_Object.cs | 275 +- unity/Assets/Scripts/CanToggleOnOff.cs | 163 +- unity/Assets/Scripts/ChangeLighting.cs | 9 +- unity/Assets/Scripts/ColdZone.cs | 12 +- .../Assets/Scripts/CollisionEventResolver.cs | 28 +- unity/Assets/Scripts/CollisionListener.cs | 143 +- unity/Assets/Scripts/CollisionListenerAB.cs | 6 +- .../Assets/Scripts/CollisionListenerChild.cs | 42 +- unity/Assets/Scripts/ColorChanger.cs | 134 +- unity/Assets/Scripts/ConnectionProperties.cs | 12 +- unity/Assets/Scripts/Contains.cs | 172 +- unity/Assets/Scripts/ContinuousMovement.cs | 109 +- unity/Assets/Scripts/Convertable.cs | 49 +- unity/Assets/Scripts/CookObject.cs | 27 +- unity/Assets/Scripts/CopyLightingSettings.cs | 48 +- unity/Assets/Scripts/CrackedCameraManager.cs | 6 +- unity/Assets/Scripts/CreatePrefab.cs | 9 +- .../Scripts/DebugDiscreteAgentController.cs | 230 +- .../Assets/Scripts/DebugFPSAgentController.cs | 122 +- unity/Assets/Scripts/DebugInputField.cs | 9792 +++++++++-------- unity/Assets/Scripts/DecalCollision.cs | 108 +- unity/Assets/Scripts/DecalSpawner.cs | 108 +- unity/Assets/Scripts/DeferredDecal.cs | 52 +- unity/Assets/Scripts/DirtAndWrite.cs | 3 +- unity/Assets/Scripts/Dirty.cs | 66 +- .../DiscreteHidenSeekAgentController.cs | 170 +- .../DiscretePointClickAgentController.cs | 93 +- unity/Assets/Scripts/Door.cs | 21 +- unity/Assets/Scripts/DraggablePoint.cs | 21 +- unity/Assets/Scripts/DroneBasket.cs | 18 +- .../Assets/Scripts/DroneFPSAgentController.cs | 217 +- unity/Assets/Scripts/DroneObjectLauncher.cs | 24 +- .../Scripts/EditorSetupSimObjPhysics.cs | 9 +- .../ArmAgentController_partial_ExpRoom.cs | 15 +- ...IK_Robot_Arm_Controller_partial_ExpRoom.cs | 18 +- ...emoteFPSAgentController_partial_ExpRoom.cs | 540 +- .../Scripts/ExperimentRoomSceneManager.cs | 171 +- unity/Assets/Scripts/Extensions.cs | 31 +- unity/Assets/Scripts/FifoServer.cs | 57 +- unity/Assets/Scripts/Fill.cs | 60 +- .../Scripts/FirstPersonCharacterCull.cs | 33 +- unity/Assets/Scripts/Flame.cs | 18 +- unity/Assets/Scripts/FpinAgentController.cs | 419 +- unity/Assets/Scripts/FpinMovableContinuous.cs | 27 +- unity/Assets/Scripts/FrameCollider.cs | 9 +- unity/Assets/Scripts/FreezeObject.cs | 41 +- unity/Assets/Scripts/Fridge.cs | 30 +- unity/Assets/Scripts/GenerateRoboTHOR.cs | 170 +- .../Scripts/GetAllScenesInstanceCount.cs | 3 +- unity/Assets/Scripts/GroupCommand.cs | 12 +- unity/Assets/Scripts/HeatZone.cs | 27 +- unity/Assets/Scripts/HoleMetadata.cs | 12 +- .../Assets/Scripts/IK_Robot_Arm_Controller.cs | 130 +- unity/Assets/Scripts/IgnoreCollision.cs | 30 +- .../Scripts/ImageSynthesis/ColorEncoding.cs | 27 +- .../Scripts/ImageSynthesis/ExampleUI.cs | 9 +- .../Scripts/ImageSynthesis/ImageSynthesis.cs | 199 +- unity/Assets/Scripts/InstantiatePrefabTest.cs | 256 +- unity/Assets/Scripts/JavaScriptInterface.cs | 3 +- .../Scripts/KinovaArmAgentController.cs | 66 +- unity/Assets/Scripts/Lamp.cs | 34 +- unity/Assets/Scripts/Laptop.cs | 31 +- unity/Assets/Scripts/LightSwitch.cs | 34 +- unity/Assets/Scripts/ListExtensions.cs | 24 +- .../Scripts/LocobotFPSAgentController.cs | 153 +- unity/Assets/Scripts/Microwave.cs | 31 +- unity/Assets/Scripts/MinimalFPSController.cs | 45 +- unity/Assets/Scripts/Mirror.cs | 24 +- unity/Assets/Scripts/NavMeshSetup.cs | 75 +- .../Assets/Scripts/NavMeshSurfaceExtended.cs | 132 +- unity/Assets/Scripts/ObjaverseAnnotation.cs | 9 +- .../Scripts/ObjectHighlightController.cs | 163 +- unity/Assets/Scripts/ObjectSpawner.cs | 3 +- .../Scripts/ObjectSpecificReceptacle.cs | 27 +- unity/Assets/Scripts/PenDraw.cs | 28 +- unity/Assets/Scripts/PhysicsExtensions.cs | 99 +- .../PhysicsRemoteFPSAgentController.cs | 4676 +++++--- unity/Assets/Scripts/PhysicsSceneManager.cs | 591 +- unity/Assets/Scripts/PlacementManager.cs | 30 +- unity/Assets/Scripts/PlaneGizmo.cs | 6 +- unity/Assets/Scripts/PlayerControllers.cs | 9 +- unity/Assets/Scripts/PrefabNameRevert.cs | 37 +- .../Assets/Scripts/ProceduralAssetDatabase.cs | 117 +- unity/Assets/Scripts/ProceduralAssetEditor.cs | 183 +- unity/Assets/Scripts/ProceduralData.cs | 181 +- unity/Assets/Scripts/ProceduralRoomEditor.cs | 246 +- unity/Assets/Scripts/ProceduralTemplates.cs | 297 +- unity/Assets/Scripts/ProceduralTools.cs | 916 +- unity/Assets/Scripts/RandomExtensions.cs | 12 +- unity/Assets/Scripts/Rearrangeable.cs | 80 +- unity/Assets/Scripts/Receptacle.cs | 67 +- unity/Assets/Scripts/ResourceAssetManager.cs | 100 +- .../Scripts/RobotArmTest/Adjust_Slider.cs | 16 +- .../RobotArmTest/Align_to_Joint_Normal.cs | 13 +- .../Scripts/RobotArmTest/FK_IK_Solver.cs | 39 +- .../Scripts/RobotArmTest/Manipulator_Clamp.cs | 30 +- .../RobotArmTest/Stretch_Arm_Solver.cs | 9 +- unity/Assets/Scripts/RoomProperties.cs | 3 +- unity/Assets/Scripts/RuntimePrefab.cs | 36 +- unity/Assets/Scripts/SceneManager.cs | 145 +- unity/Assets/Scripts/ScreenShotFromCamera.cs | 15 +- unity/Assets/Scripts/Screenshot360.cs | 19 +- unity/Assets/Scripts/SerializeMesh.cs | 100 +- unity/Assets/Scripts/SimObj.cs | 310 +- unity/Assets/Scripts/SimObjPhysics.cs | 1100 +- unity/Assets/Scripts/SimObjType.cs | 9 +- unity/Assets/Scripts/SimTesting.cs | 65 +- unity/Assets/Scripts/SimUtil.cs | 366 +- unity/Assets/Scripts/SliceObject.cs | 61 +- unity/Assets/Scripts/SpongeClean.cs | 9 +- unity/Assets/Scripts/StandardShaderUtils.cs | 12 +- unity/Assets/Scripts/StoveKnob.cs | 21 +- unity/Assets/Scripts/StoveTopElectric.cs | 9 +- .../Assets/Scripts/StretchAgentController.cs | 224 +- .../Scripts/Stretch_Robot_Arm_Controller.cs | 224 +- unity/Assets/Scripts/StructureObject.cs | 6 +- unity/Assets/Scripts/SyncTransform.cs | 19 +- .../Scripts/THORDocumentationExporter.cs | 91 +- unity/Assets/Scripts/Television.cs | 35 +- unity/Assets/Scripts/TestCabinetVisibility.cs | 92 +- .../ThorContractlessStandardResolver.cs | 138 +- unity/Assets/Scripts/Toaster.cs | 9 +- unity/Assets/Scripts/Toilet.cs | 24 +- unity/Assets/Scripts/TransformExtension.cs | 16 +- unity/Assets/Scripts/UsedUp.cs | 12 +- unity/Assets/Scripts/UtilityFunctions.cs | 376 +- .../Assets/Scripts/VisualizationHeatmapCSV.cs | 12 +- unity/Assets/Scripts/WallProperties.cs | 3 +- .../Scripts/WhatIsInsideMagnetSphere.cs | 21 +- .../Scripts/agent_trackball_rotation.cs | 11 +- unity/Assets/Scripts/childcollider.cs | 6 +- unity/Assets/Scripts/coffeemachine.cs | 18 +- 155 files changed, 21114 insertions(+), 12171 deletions(-) diff --git a/unity/Assets/Scripts/ActionDispatcher.cs b/unity/Assets/Scripts/ActionDispatcher.cs index 966ca60a67..6c06f841ba 100644 --- a/unity/Assets/Scripts/ActionDispatcher.cs +++ b/unity/Assets/Scripts/ActionDispatcher.cs @@ -7,7 +7,8 @@ using Newtonsoft.Json.Linq; using UnityEngine; -public class ActionFinished { +public class ActionFinished +{ public bool success; public object actionReturn; public string errorMessage; @@ -27,7 +28,8 @@ public ActionFinished( bool toEmitState = false, ServerActionErrorCode errorCode = 0, bool isDummy = false - ) { + ) + { this.success = success; this.actionReturn = actionReturn; this.errorMessage = errorMessage; @@ -36,7 +38,8 @@ public ActionFinished( this.isDummy = isDummy; } - public ActionFinished(ActionFinished toCopy) { + public ActionFinished(ActionFinished toCopy) + { this.success = toCopy.success; this.actionReturn = toCopy.actionReturn; this.errorMessage = toCopy.errorMessage; @@ -48,12 +51,14 @@ public ActionFinished(ActionFinished toCopy) { public static ActionFinished Success = new ActionFinished() { success = true }; public static ActionFinished Fail = new ActionFinished() { success = false }; - public static ActionFinished SuccessToEmitState = new ActionFinished() { + public static ActionFinished SuccessToEmitState = new ActionFinished() + { success = true, toEmitState = true }; - public IEnumerator GetEnumerator() { + public IEnumerator GetEnumerator() + { yield return this; } } @@ -65,7 +70,8 @@ public IEnumerator GetEnumerator() { // } // } -public interface ActionInvokable { +public interface ActionInvokable +{ void Complete(ActionFinished actionFinished); Coroutine StartCoroutine(System.Collections.IEnumerator routine); } @@ -147,7 +153,8 @@ public void LookUp(float degrees, bool forceThing) value for forceThing. */ -public static class ActionDispatcher { +public static class ActionDispatcher +{ private static Dictionary>> allMethodDispatchTable = new Dictionary>>(); private static Dictionary methodCache = @@ -155,39 +162,49 @@ public static class ActionDispatcher { // 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) { + public static List FindAmbiguousActions(Type targetType) + { List actions = new List(); System.Reflection.MethodInfo[] allMethods = targetType.GetMethods( BindingFlags.Public | BindingFlags.Instance ); HashSet methodNames = new HashSet(); - foreach (var method in allMethods) { + foreach (var method in allMethods) + { methodNames.Add(method.Name); } - foreach (var methodName in methodNames) { - try { + foreach (var methodName in methodNames) + { + try + { Dictionary act = new Dictionary(); act["action"] = methodName; DynamicServerAction dynamicServerAction = new DynamicServerAction(act); MethodInfo m = getDispatchMethod(targetType, dynamicServerAction); - } catch (AmbiguousActionException) { + } + catch (AmbiguousActionException) + { actions.Add(methodName); } } return actions; } - private static MethodInfo[] getMethods(Type targetType) { - if (!methodCache.ContainsKey(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) - ) { + ) + { methods.Add(mi); } } @@ -200,39 +217,48 @@ MethodInfo mi in targetType.GetMethods(BindingFlags.Public | BindingFlags.Instan // Find public/void methods that have matching Method names and identical parameter names, // but either different parameter order or parameter types which make dispatching // ambiguous. This method is used during testing to find conflicts. - public static Dictionary> FindMethodVariableNameConflicts(Type targetType) { + public static Dictionary> FindMethodVariableNameConflicts(Type targetType) + { MethodInfo[] allMethods = getMethods(targetType); Dictionary> methodConflicts = new Dictionary>(); - for (int i = 0; i < allMethods.Length - 1; i++) { + for (int i = 0; i < allMethods.Length - 1; i++) + { MethodInfo methodOut = allMethods[i]; HashSet paramSet = new HashSet(); ParameterInfo[] methodOutParams = methodOut.GetParameters(); - foreach (var p in methodOutParams) { + foreach (var p in methodOutParams) + { paramSet.Add(p.Name); } - for (int j = i + 1; j < allMethods.Length; j++) { + 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 - ) { + ) + { bool allVariableNamesMatch = true; bool allParamsMatch = true; - for (int k = 0; k < methodInParams.Length; k++) { + for (int k = 0; k < methodInParams.Length; k++) + { var mpIn = methodInParams[k]; var mpOut = methodOutParams[k]; // we assume the method is overriding if everything matches - if (mpIn.Name != mpOut.Name || mpOut.ParameterType != mpIn.ParameterType) { + if (mpIn.Name != mpOut.Name || mpOut.ParameterType != mpIn.ParameterType) + { allParamsMatch = false; } - if (!paramSet.Contains(mpIn.Name)) { + if (!paramSet.Contains(mpIn.Name)) + { allVariableNamesMatch = false; break; } } - if (allVariableNamesMatch && !allParamsMatch) { + if (allVariableNamesMatch && !allParamsMatch) + { methodConflicts[methodOut.Name] = new List(paramSet); } } @@ -241,32 +267,39 @@ public static Dictionary> FindMethodVariableNameConflicts(T return methodConflicts; } - private static Dictionary> getMethodDispatchTable(Type targetType) { - if (!allMethodDispatchTable.ContainsKey(targetType)) { + private static Dictionary> getMethodDispatchTable(Type targetType) + { + if (!allMethodDispatchTable.ContainsKey(targetType)) + { allMethodDispatchTable[targetType] = new Dictionary>(); } return allMethodDispatchTable[targetType]; } - private static List getCandidateMethods(Type targetType, string action) { + private static List getCandidateMethods(Type targetType, string action) + { Dictionary> methodDispatchTable = getMethodDispatchTable( targetType ); - if (!methodDispatchTable.ContainsKey(action)) { + if (!methodDispatchTable.ContainsKey(action)) + { List methods = new List(); List hierarchy = new List(); // not completely generic Type ht = targetType; - while (ht != typeof(object)) { + while (ht != typeof(object)) + { hierarchy.Add(ht); ht = ht.BaseType; } - foreach (MethodInfo mi in getMethods(targetType)) { - if (mi.Name != action) { + foreach (MethodInfo mi in getMethods(targetType)) + { + if (mi.Name != action) + { continue; } bool replaced = false; @@ -276,12 +309,15 @@ private static List getCandidateMethods(Type targetType, string acti // are not used ParameterInfo[] sourceParams = mi.GetParameters(); - for (int j = 0; j < methods.Count && !replaced; j++) { + for (int j = 0; j < methods.Count && !replaced; j++) + { bool signatureMatch = true; ParameterInfo[] targetParams = methods[j].GetParameters(); int minCommon = Math.Min(sourceParams.Length, targetParams.Length); - for (int k = 0; k < minCommon; k++) { - if (sourceParams[k].ParameterType != targetParams[k].ParameterType) { + for (int k = 0; k < minCommon; k++) + { + if (sourceParams[k].ParameterType != targetParams[k].ParameterType) + { signatureMatch = false; break; } @@ -290,21 +326,26 @@ private static List getCandidateMethods(Type targetType, string acti 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) { + if (signatureMatch) + { // this happens if one method has a trailing optional value and all // other parameter types match - if (targetParams.Length != sourceParams.Length) { + 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 @@ -317,13 +358,15 @@ private static List getCandidateMethods(Type targetType, string acti if ( hierarchy.IndexOf(mi.DeclaringType) < hierarchy.IndexOf(methods[j].DeclaringType) - ) { + ) + { methods[j] = mi; } } } - if (!replaced) { + if (!replaced) + { // we sort the list of methods so that we evaluate // methods with fewer and possible no params first // and then match methods with greater params @@ -344,7 +387,8 @@ private static List getCandidateMethods(Type targetType, string acti public static MethodInfo getDispatchMethod( Type targetType, DynamicServerAction dynamicServerAction - ) { + ) + { List actionMethods = getCandidateMethods( targetType, dynamicServerAction.action @@ -358,7 +402,8 @@ DynamicServerAction dynamicServerAction // 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 // (i.e. number -> [short, float, int], bool -> bool, string -> string, dict -> object, list -> list) - foreach (var method in actionMethods) { + foreach (var method in actionMethods) + { int matchCount = 0; ParameterInfo[] mParams = method.GetParameters(); @@ -379,7 +424,8 @@ DynamicServerAction dynamicServerAction // 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) { + 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}"))}"}"))}" ); @@ -398,11 +444,16 @@ DynamicServerAction dynamicServerAction matchedMethod == null && mParams.Length == 1 && mParams[0].ParameterType == typeof(ServerAction) - ) { + ) + { matchedMethod = method; - } else { - foreach (var p in method.GetParameters()) { - if (dynamicServerAction.ContainsKey(p.Name)) { + } + else + { + foreach (var p in method.GetParameters()) + { + if (dynamicServerAction.ContainsKey(p.Name)) + { matchCount++; } } @@ -422,7 +473,8 @@ DynamicServerAction dynamicServerAction && 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 @@ -440,7 +492,8 @@ DynamicServerAction dynamicServerAction public static IEnumerable getMatchingMethodOverwrites( Type targetType, DynamicServerAction dynamicServerAction - ) { + ) + { return getCandidateMethods(targetType, dynamicServerAction.action) .Select(method => ( @@ -455,10 +508,12 @@ DynamicServerAction dynamicServerAction } public static void Dispatch(T target, DynamicServerAction dynamicServerAction) - where T : ActionInvokable { + where T : ActionInvokable + { MethodInfo method = getDispatchMethod(target.GetType(), dynamicServerAction); - if (method == null) { + if (method == null) + { throw new InvalidActionException(); } @@ -486,23 +541,29 @@ public static void Dispatch(T target, DynamicServerAction dynamicServerAction 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)) { + if (paramDict.ContainsKey(DynamicServerAction.physicsSimulationParamsVariable)) + { dynamicServerAction.AddPhysicsSimulationParams(physicsSimulationParams); } } // TODO: deprecate, eventually when no void actions are left - if (methodParams.Length == 1 && methodParams[0].ParameterType == typeof(ServerAction)) { + if (methodParams.Length == 1 && methodParams[0].ParameterType == typeof(ServerAction)) + { ServerAction serverAction = dynamicServerAction.ToObject(); serverAction.dynamicServerAction = dynamicServerAction; arguments[0] = serverAction; - } else { + } + else + { var argumentKeys = dynamicServerAction.ArgumentKeys().ToList(); var invalidArgs = argumentKeys .Where(argName => !paramDict.ContainsKey(argName)) .ToList(); - if (invalidArgs.Count > 0) { + if (invalidArgs.Count > 0) + { Func paramToString = (ParameterInfo param) => $"{param.ParameterType.Name} {param.Name}{(param.HasDefaultValue ? " = " + param.DefaultValue : "")}"; var matchingMethodOverWrites = getMatchingMethodOverwrites( @@ -522,14 +583,19 @@ public static void Dispatch(T target, DynamicServerAction dynamicServerAction matchingMethodOverWrites ); } - for (int i = 0; i < methodParams.Length; i++) { + for (int i = 0; i < methodParams.Length; i++) + { System.Reflection.ParameterInfo pi = methodParams[i]; - if (dynamicServerAction.ContainsKey(pi.Name)) { - try { + if (dynamicServerAction.ContainsKey(pi.Name)) + { + try + { arguments[i] = dynamicServerAction .GetValue(pi.Name) .ToObject(pi.ParameterType); - } catch (ArgumentException ex) { + } + catch (ArgumentException ex) + { throw new ToObjectArgumentActionException( parameterName: pi.Name, parameterType: pi.ParameterType, @@ -537,9 +603,13 @@ public static void Dispatch(T target, DynamicServerAction dynamicServerAction ex: ex ); } - } else { - if (!pi.HasDefaultValue) { - if (missingArguments == null) { + } + else + { + if (!pi.HasDefaultValue) + { + if (missingArguments == null) + { missingArguments = new List(); } missingArguments.Add(pi.Name); @@ -548,7 +618,8 @@ public static void Dispatch(T target, DynamicServerAction dynamicServerAction } } } - if (missingArguments != null) { + if (missingArguments != null) + { throw new MissingArgumentsActionException(missingArguments); } @@ -556,30 +627,39 @@ public static void Dispatch(T target, DynamicServerAction dynamicServerAction object methodReturn; // TODO: deprecated actions called in the old way that return void - if (!usePhysicsSimulationParams && method.ReturnType == typeof(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; - if (method.ReturnType == typeof(System.Collections.IEnumerator)) { + if (method.ReturnType == typeof(System.Collections.IEnumerator)) + { methodReturn = method.Invoke(target, arguments); action = methodReturn as IEnumerator; runAsCoroutine = physicsSimulationParams.autoSimulation; - } else if (method.ReturnType == typeof(ActionFinished)) { + } + 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(() => { + // 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, @@ -587,7 +667,9 @@ public static void Dispatch(T target, DynamicServerAction dynamicServerAction ); // 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( @@ -600,34 +682,43 @@ public static void Dispatch(T target, DynamicServerAction dynamicServerAction } } - public static IEnumerator ActionFinishedWrapper(ActionFinished actionFinished) { + public static IEnumerator ActionFinishedWrapper(ActionFinished actionFinished) + { yield return actionFinished; } - public static IEnumerator ActionFinishedDelayActionWrapper(Func action) { + public static IEnumerator ActionFinishedDelayActionWrapper(Func action) + { yield return action(); } } -public class MethodParamComparer : IComparer { - public int Compare(MethodInfo a, MethodInfo b) { +public class MethodParamComparer : IComparer +{ + public int Compare(MethodInfo a, MethodInfo b) + { int requiredParamCountA = requiredParamCount(a); int requiredParamCountB = requiredParamCount(b); int result = requiredParamCountA.CompareTo(requiredParamCountB); - if (result == 0) { + if (result == 0) + { result = paramCount(a).CompareTo(paramCount(b)); } return result; } - private static int paramCount(MethodInfo method) { + private static int paramCount(MethodInfo method) + { return method.GetParameters().Length; } - private static int requiredParamCount(MethodInfo method) { + private static int requiredParamCount(MethodInfo method) + { int count = 0; - foreach (var p in method.GetParameters()) { - if (!p.HasDefaultValue) { + foreach (var p in method.GetParameters()) + { + if (!p.HasDefaultValue) + { count++; } } @@ -639,19 +730,22 @@ private static int requiredParamCount(MethodInfo method) { [Serializable] public class InvalidActionException : Exception { } -public class InvalidActionCallWithPhysicsSimulationParams : Exception { +public class InvalidActionCallWithPhysicsSimulationParams : Exception +{ public InvalidActionCallWithPhysicsSimulationParams(string message) : base(message) { } } [Serializable] -public class AmbiguousActionException : Exception { +public class AmbiguousActionException : Exception +{ public AmbiguousActionException(string message) : base(message) { } } [Serializable] -public class ToObjectArgumentActionException : Exception { +public class ToObjectArgumentActionException : Exception +{ public string parameterName; public ArgumentException innerException; public Type parameterType; @@ -662,7 +756,8 @@ public ToObjectArgumentActionException( Type parameterType, string parameterValueAsStr, ArgumentException ex - ) { + ) + { this.parameterName = parameterName; this.parameterType = parameterType; this.parameterValueAsStr = parameterValueAsStr; @@ -671,16 +766,19 @@ ArgumentException ex } [Serializable] -public class MissingArgumentsActionException : Exception { +public class MissingArgumentsActionException : Exception +{ public List ArgumentNames; - public MissingArgumentsActionException(List argumentNames) { + public MissingArgumentsActionException(List argumentNames) + { this.ArgumentNames = argumentNames; } } [Serializable] -public class InvalidArgumentsException : Exception { +public class InvalidArgumentsException : Exception +{ public IEnumerable ArgumentNames; public IEnumerable InvalidArgumentNames; public IEnumerable ParameterNames; @@ -691,7 +789,8 @@ public InvalidArgumentsException( IEnumerable invalidArgumentNames, IEnumerable parameterNames = null, IEnumerable possibleOverwrites = null - ) { + ) + { this.ArgumentNames = argumentNames; this.InvalidArgumentNames = invalidArgumentNames; this.ParameterNames = parameterNames ?? new List(); @@ -700,7 +799,8 @@ public InvalidArgumentsException( } [Serializable] -public class MissingActionFinishedException : Exception { +public class MissingActionFinishedException : Exception +{ public MissingActionFinishedException(string message = "") : base(message) { } } diff --git a/unity/Assets/Scripts/AgentManager.cs b/unity/Assets/Scripts/AgentManager.cs index 6dc119e148..96653a9767 100644 --- a/unity/Assets/Scripts/AgentManager.cs +++ b/unity/Assets/Scripts/AgentManager.cs @@ -30,7 +30,8 @@ using UnityEngine.CloudRendering; #endif -public class AgentManager : MonoBehaviour, ActionInvokable { +public class AgentManager : MonoBehaviour, ActionInvokable +{ public List agents = new List(); protected int frameCounter; protected bool serverSideScreenshot; @@ -69,7 +70,8 @@ public class AgentManager : MonoBehaviour, ActionInvokable { public PhysicsSceneManager physicsSceneManager { get; private set; } private FifoServer.Client fifoClient = null; - private enum serverTypes { + private enum serverTypes + { WSGI, FIFO }; @@ -101,9 +103,12 @@ private enum serverTypes { public string agentMode; public Bounds sceneBounds = UtilityFunctions.CreateEmptyBounds(); - public Bounds SceneBounds { - get { - if (sceneBounds.min.x == float.PositiveInfinity) { + public Bounds SceneBounds + { + get + { + if (sceneBounds.min.x == float.PositiveInfinity) + { ResetSceneBounds(); } return sceneBounds; @@ -111,7 +116,8 @@ public Bounds SceneBounds { set { sceneBounds = value; } } - void Awake() { + void Awake() + { tex = new Texture2D( UnityEngine.Screen.width, UnityEngine.Screen.height, @@ -139,15 +145,18 @@ void Awake() { typeof(serverTypes), LoadStringVariable(serverTypes.WSGI.ToString(), "SERVER_TYPE").ToUpper() ); - if (serverType == serverTypes.FIFO) { + if (serverType == serverTypes.FIFO) + { string serverPipePath = LoadStringVariable(null, "FIFO_SERVER_PIPE_PATH"); string clientPipePath = LoadStringVariable(null, "FIFO_CLIENT_PIPE_PATH"); // TODO: Create dir if not exists - if (string.IsNullOrEmpty(serverPipePath)) { + if (string.IsNullOrEmpty(serverPipePath)) + { serverPipePath = "fifo_pipe/server.pipe"; } - if (string.IsNullOrEmpty(clientPipePath)) { + if (string.IsNullOrEmpty(clientPipePath)) + { clientPipePath = "fifo_pipe/client.pipe"; } @@ -156,7 +165,8 @@ void Awake() { this.fifoClient = FifoServer.Client.GetInstance(serverPipePath, clientPipePath); } #if UNITY_EDITOR - if (serverType == serverTypes.WSGI) { + if (serverType == serverTypes.WSGI) + { serverSideScreenshot = true; print("---ServerSideScreenshot enabled"); } @@ -173,7 +183,8 @@ void Awake() { actionDuration = LoadIntVariable(actionDuration, prefix + "ACTION_LENGTH"); } - void Start() { + void Start() + { // default primary agent's agentController type to "PhysicsRemoteFPSAgentController" initializePrimaryAgent(); // primaryAgent.stand @@ -205,37 +216,55 @@ void Start() { StartCoroutine(EmitFrame()); } - public void Complete(ActionFinished result) { + public void Complete(ActionFinished result) + { this.activeAgent().Complete(result); } - private void initializePrimaryAgent() { - if (this.PrimaryAgent == null) { + private void initializePrimaryAgent() + { + if (this.PrimaryAgent == null) + { SetUpPhysicsController(); } } - public void Initialize(ServerAction action) { + public void Initialize(ServerAction action) + { this.agentMode = action.agentMode.ToLower(); // first parse agentMode and agentControllerType //"default" agentMode can use either default or "stochastic" agentControllerType //"locobot" agentMode can use either default or "stochastic" agentControllerType //"drone" agentMode can ONLY use "drone" agentControllerType, and NOTHING ELSE (for now?) - if (action.agentMode.ToLower() == "default") { + if (action.agentMode.ToLower() == "default") + { SetUpPhysicsController(); - } else if (action.agentMode.ToLower() == "locobot") { + } + else if (action.agentMode.ToLower() == "locobot") + { // LocobotController is a subclass of Stochastic which just the agentMode (VisibilityCapsule) changed SetUpLocobotController(action); - } else if (action.agentMode.ToLower() == "drone") { + } + else if (action.agentMode.ToLower() == "drone") + { SetUpDroneController(action); - } else if (agentMode == "stretch" || agentMode == "arm" || agentMode == "stretchab") { - if (agentMode == "stretch") { + } + else if (agentMode == "stretch" || agentMode == "arm" || agentMode == "stretchab") + { + if (agentMode == "stretch") + { SetUpStretchController(action); - } else if (agentMode == "arm") { + } + else if (agentMode == "arm") + { SetUpArmController(true); - } else if (agentMode == "stretchab") { + } + else if (agentMode == "stretchab") + { SetUpStretchABController(action); - } else { + } + else + { // Should not be possible but being very defensive. throw new ArgumentException($"Invalid agentMode {action.agentMode}"); } @@ -247,7 +276,9 @@ public void Initialize(ServerAction action) { // } physicsSceneManager.MakeAllObjectsMoveable(); - } else if (agentMode == "fpin") { + } + else if (agentMode == "fpin") + { SetUpFpinController(action); // TODO refactor initialization funtionality @@ -282,7 +313,8 @@ public void Initialize(ServerAction action) { Debug.Log( $"BackwardsCompatibleInitialize of AgentController. lastActionSuccess: {actionFinished.success}, errorMessage: {actionFinished.errorMessage} actionReturn: {actionFinished.actionReturn}, agentState: {primaryAgent.agentState}" ); - if (!actionFinished.success) { + if (!actionFinished.success) + { primaryAgent.actionFinished( false, $"Error running 'BackwardsCompatibleInitialize' failed with error: {actionFinished.errorMessage}" @@ -291,17 +323,23 @@ public void Initialize(ServerAction action) { } // if (actiongF) // actionFinished. - } else { + } + else + { var error = $"Invalid agentMode {action.agentMode}"; Debug.Log(error); primaryAgent.actionFinished(success: false, errorMessage: error); return; } - if (action.massThreshold.HasValue) { - if (action.massThreshold.Value > 0.0) { + if (action.massThreshold.HasValue) + { + if (action.massThreshold.Value > 0.0) + { SetUpMassThreshold(action.massThreshold.Value); - } else { + } + else + { var error = $"massThreshold must have nonzero value - invalid value: {action.massThreshold.Value}"; Debug.Log(error); @@ -323,7 +361,8 @@ public void Initialize(ServerAction action) { $"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) { + if (action.targetFrameRate > 0) + { Application.targetFrameRate = action.targetFrameRate; } @@ -347,7 +386,8 @@ public void Initialize(ServerAction action) { Physics.autoSimulation = action.autoSimulation; Physics.autoSyncTransforms = Physics.autoSimulation; - if (action.alwaysReturnVisibleRange) { + if (action.alwaysReturnVisibleRange) + { ((PhysicsRemoteFPSAgentController)primaryAgent).alwaysReturnVisibleRange = action.alwaysReturnVisibleRange; } @@ -355,15 +395,19 @@ public void Initialize(ServerAction action) { //if multi agent requested, add duplicates of primary agent now addAgents(action); this.agents[0].m_Camera.depth = 9999; - if (action.startAgentsRotatedBy != 0f) { + if (action.startAgentsRotatedBy != 0f) + { RotateAgentsByRotatingUniverse(action.startAgentsRotatedBy); - } else { + } + else + { ResetSceneBounds(); } this.agentManagerState = AgentState.ActionComplete; } - private void SetUpLocobotController(ServerAction action) { + private void SetUpLocobotController(ServerAction action) + { this.agents.Clear(); // force snapToGrid to be false since we are stochastic action.snapToGrid = false; @@ -371,7 +415,8 @@ private void SetUpLocobotController(ServerAction action) { primaryAgent = createAgentType(typeof(LocobotFPSAgentController), baseAgentComponent); } - private void SetUpDroneController(ServerAction action) { + private void SetUpDroneController(ServerAction action) + { this.agents.Clear(); // force snapToGrid to be false action.snapToGrid = false; @@ -379,7 +424,8 @@ private void SetUpDroneController(ServerAction action) { primaryAgent = createAgentType(typeof(DroneFPSAgentController), baseAgentComponent); } - private void SetUpStretchController(ServerAction action) { + private void SetUpStretchController(ServerAction action) + { this.agents.Clear(); // force snapToGrid to be false action.snapToGrid = false; @@ -388,7 +434,8 @@ private void SetUpStretchController(ServerAction action) { baseAgentComponent.StretchBodyColliders.SetActive(true); } - private void SetUpStretchABController(ServerAction action) { + private void SetUpStretchABController(ServerAction action) + { this.agents.Clear(); // force snapToGrid to be false action.snapToGrid = false; @@ -398,13 +445,15 @@ private void SetUpStretchABController(ServerAction action) { // note: this doesn't take a ServerAction because we don't have to force the snpToGrid bool // to be false like in other controller types. - public void SetUpPhysicsController() { + public void SetUpPhysicsController() + { this.agents.Clear(); BaseAgentComponent baseAgentComponent = GameObject.FindObjectOfType(); primaryAgent = createAgentType(typeof(PhysicsRemoteFPSAgentController), baseAgentComponent); } - public void SetUpFpinController(ServerAction action) { + public void SetUpFpinController(ServerAction action) + { Debug.Log("inside SetUpFpinController"); this.agents.Clear(); BaseAgentComponent baseAgentComponent = GameObject.FindObjectOfType(); @@ -414,7 +463,8 @@ public void SetUpFpinController(ServerAction action) { private BaseFPSAgentController createAgentType( Type agentType, BaseAgentComponent agentComponent - ) { + ) + { BaseFPSAgentController agent = Activator.CreateInstance(agentType, new object[] { agentComponent, this }) as BaseFPSAgentController; @@ -422,7 +472,8 @@ BaseAgentComponent agentComponent return agent; } - private void SetUpArmController(bool midLevelArm) { + private void SetUpArmController(bool midLevelArm) + { this.agents.Clear(); BaseAgentComponent baseAgentComponent = GameObject.FindObjectOfType(); primaryAgent = createAgentType(typeof(KinovaArmAgentController), baseAgentComponent); @@ -435,19 +486,23 @@ private void SetUpArmController(bool midLevelArm) { // on initialization of agentMode = "arm" and agentControllerType = "mid-level" // if mass threshold should be used to prevent arm from knocking over objects that // are too big (table, sofa, shelf, etc) use this - private void SetUpMassThreshold(float massThreshold) { + private void SetUpMassThreshold(float massThreshold) + { CollisionListener.useMassThreshold = true; CollisionListener.massThreshold = massThreshold; primaryAgent.MakeObjectsStaticKinematicMassThreshold(); } // return reference to primary agent in case we need a reference to the primary - public BaseFPSAgentController PrimaryAgent { + public BaseFPSAgentController PrimaryAgent + { get => this.primaryAgent; } - private void addAgents(ServerAction action) { - if (action.agentCount > 1) { + private void addAgents(ServerAction action) + { + if (action.agentCount > 1) + { // note: for procedural scenes, adding multiple agents in will need to be done differently as currently // initializing additional agents assumes the scene is already setup, and Houses initialize the // primary agent floating in space, then generates the house, then teleports the primary agent. @@ -457,7 +512,8 @@ private void addAgents(ServerAction action) { UnityEngine .SceneManagement.SceneManager.GetActiveScene() .name.StartsWith("Procedural") - ) { + ) + { throw new NotImplementedException( $"Procedural scenes only support a single agent currently." ); @@ -470,38 +526,46 @@ private void addAgents(ServerAction action) { 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; addAgent(action); Physics.SyncTransforms(); // must do this so that when we CapsuleCast we see the most recently added agent } - for (int i = 1; i < this.agents.Count; i++) { + for (int i = 1; i < this.agents.Count; i++) + { this.agents[i].m_Camera.depth = 1; } } } - public void ResetSceneBounds() { + public void ResetSceneBounds() + { // Recording initially disabled renderers and scene bounds sceneBounds = UtilityFunctions.CreateEmptyBounds(); - foreach (Renderer r in GameObject.FindObjectsOfType()) { - if (r.enabled) { + foreach (Renderer r in GameObject.FindObjectsOfType()) + { + if (r.enabled) + { sceneBounds.Encapsulate(r.bounds); } } } - public void RotateAgentsByRotatingUniverse(float rotation) { + public void RotateAgentsByRotatingUniverse(float rotation) + { List startAgentRots = new List(); - foreach (BaseFPSAgentController agent in this.agents) { + foreach (BaseFPSAgentController agent in this.agents) + { startAgentRots.Add(agent.transform.rotation); } GameObject superObject = GameObject.Find("SuperTopLevel"); - if (superObject == null) { + if (superObject == null) + { superObject = new GameObject("SuperTopLevel"); } @@ -512,24 +576,28 @@ public void RotateAgentsByRotatingUniverse(float rotation) { GameObject go in UnityEngine .SceneManagement.SceneManager.GetActiveScene() .GetRootGameObjects() - ) { + ) + { topLevelObjects.Add(go); go.transform.SetParent(superObject.transform); } superObject.transform.rotation = Quaternion.Euler(0f, rotation, 0f); - foreach (GameObject go in topLevelObjects) { + foreach (GameObject go in topLevelObjects) + { go.transform.SetParent(null); } - for (int i = 0; i < this.agents.Count; i++) { + for (int i = 0; i < this.agents.Count; i++) + { agents[i].transform.rotation = startAgentRots[i]; } ResetSceneBounds(); } - public void registerAsThirdPartyCamera(Camera camera) { + public void registerAsThirdPartyCamera(Camera camera) + { this.thirdPartyCameras.Add(camera); #if PLATFORM_CLOUD_RENDERING camera.targetTexture = createRenderTexture( @@ -545,23 +613,30 @@ private float ClampFieldOfView( float defaultVal = 90f, float min = 0f, float max = 180f - ) { + ) + { return (fov <= min || fov > max) ? defaultVal : fov; } - public void updateImageSynthesis(bool status) { - foreach (var agent in this.agents) { + public void updateImageSynthesis(bool status) + { + foreach (var agent in this.agents) + { agent.updateImageSynthesis(status); } } - public void updateThirdPartyCameraImageSynthesis(bool status) { - if (status) { - foreach (var camera in this.thirdPartyCameras) { + public void updateThirdPartyCameraImageSynthesis(bool status) + { + if (status) + { + foreach (var camera in this.thirdPartyCameras) + { GameObject gameObject = camera.gameObject; var imageSynthesis = gameObject.GetComponentInChildren() as ImageSynthesis; - if (imageSynthesis == null) { + if (imageSynthesis == null) + { gameObject.AddComponent(typeof(ImageSynthesis)); } imageSynthesis = @@ -585,8 +660,10 @@ private void updateCameraProperties( bool agentPositionRelativeCoordinates = false, string parent = null, int agentId = 0 - ) { - if (orthographic != true && orthographicSize != null) { + ) + { + 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." @@ -594,7 +671,8 @@ private void updateCameraProperties( ); } - if (parent != null && parent != "agent" && parent != "world") { + if (parent != null && parent != "agent" && parent != "world") + { throw new InvalidOperationException( $"parent: {parent} must be one of: null, agent, or world." ); @@ -602,35 +680,47 @@ private void updateCameraProperties( var agent = this.agents[agentId]; - if (agentPositionRelativeCoordinates) { + if (agentPositionRelativeCoordinates) + { Transform oldParent = camera.transform.parent; camera.transform.SetParent(agent.transform); camera.transform.localScale = Vector3.one; // Previous comment suggested that these local scale changes are necessary after reparenting - if (position.HasValue) { + if (position.HasValue) + { camera.transform.localPosition = position.Value; } - if (rotation.HasValue) { + if (rotation.HasValue) + { camera.transform.localEulerAngles = rotation.Value; } camera.transform.SetParent(oldParent); camera.transform.localScale = Vector3.one; - } else { - if (position.HasValue) { + } + else + { + if (position.HasValue) + { camera.gameObject.transform.position = position.Value; } - if (rotation.HasValue) { + if (rotation.HasValue) + { camera.gameObject.transform.eulerAngles = rotation.Value; } } - if (parent == "agent") { + if (parent == "agent") + { camera.transform.SetParent(agent.transform); camera.transform.localScale = Vector3.one; - } else if (parent == "world") { + } + else if (parent == "world") + { camera.transform.SetParent(null); camera.transform.localScale = Vector3.one; - } else if (parent != null) { + } + else if (parent != null) + { throw new InvalidOperationException( $"parent: {parent} must be one of: null, agent, or world." ); @@ -638,9 +728,11 @@ private void updateCameraProperties( // updates the camera's perspective camera.fieldOfView = fieldOfView; - if (orthographic != null) { + if (orthographic != null) + { camera.orthographic = (bool)orthographic; - if (orthographic == true && orthographicSize != null) { + if (orthographic == true && orthographicSize != null) + { camera.orthographicSize = (float)orthographicSize; } } @@ -648,32 +740,42 @@ private void updateCameraProperties( //updates camera near and far clipping planes //default to near and far clipping planes of agent camera, which are currently //static values and are not exposed in anything like Initialize - if (nearClippingPlane != null) { + if (nearClippingPlane != null) + { camera.nearClipPlane = (float)nearClippingPlane; } //default to primary agent's near clip plane value - else { + else + { camera.nearClipPlane = this.primaryAgent.m_Camera.nearClipPlane; } - if (farClippingPlane != null) { + if (farClippingPlane != null) + { camera.farClipPlane = (float)farClippingPlane; } //default to primary agent's far clip plane value - else { + else + { camera.farClipPlane = this.primaryAgent.m_Camera.farClipPlane; } // supports a solid color skybox, which work well with videos and images (i.e., white/black/orange/blue backgrounds) - if (skyboxColor == "default") { + if (skyboxColor == "default") + { camera.clearFlags = CameraClearFlags.Skybox; - } else if (skyboxColor != null) { + } + else if (skyboxColor != null) + { Color color; bool successfullyParsed = ColorUtility.TryParseHtmlString(skyboxColor, out color); - if (successfullyParsed) { + if (successfullyParsed) + { camera.clearFlags = CameraClearFlags.SolidColor; camera.backgroundColor = color; - } else { + } + else + { throw new ArgumentException( $"Invalid skyboxColor: {skyboxColor}! Cannot be parsed as an HTML color." ); @@ -681,7 +783,8 @@ private void updateCameraProperties( } // Anti-aliasing - if (antiAliasing != null) { + if (antiAliasing != null) + { updateAntiAliasing( postProcessLayer: camera.gameObject.GetComponentInChildren(), antiAliasing: antiAliasing @@ -689,28 +792,36 @@ private void updateCameraProperties( } ImageSynthesis imageSynthesis = camera.gameObject.GetComponentInChildren(); - if (imageSynthesis != null && imageSynthesis.enabled) { + if (imageSynthesis != null && imageSynthesis.enabled) + { imageSynthesis.OnCameraChange(); } this.activeAgent().actionFinished(success: true); } - private void assertFovInBounds(float fov) { - if (fov <= MIN_FOV || fov >= MAX_FOV) { + 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}." ); } } - public void updateAntiAliasing(PostProcessLayer postProcessLayer, string antiAliasing) { + public void updateAntiAliasing(PostProcessLayer postProcessLayer, string antiAliasing) + { antiAliasing = antiAliasing.ToLower(); - if (antiAliasing == "none") { + if (antiAliasing == "none") + { postProcessLayer.enabled = false; - } else { + } + else + { postProcessLayer.enabled = true; - switch (antiAliasing) { + switch (antiAliasing) + { case "fxaa": postProcessLayer.antialiasingMode = PostProcessLayer .Antialiasing @@ -748,7 +859,8 @@ public void AddThirdPartyCamera( bool agentPositionRelativeCoordinates = false, string parent = "world", int agentId = 0 - ) { + ) + { // adds error if fieldOfView is out of bounds assertFovInBounds(fov: fieldOfView); @@ -765,7 +877,8 @@ public void AddThirdPartyCamera( || renderInstanceSegmentation || renderNormalsImage || renderFlowImage - ) { + ) + { gameObject.AddComponent(typeof(ImageSynthesis)); } @@ -795,8 +908,10 @@ public void AddThirdPartyCamera( } // helper that can be used when converting Dictionary to a Vector3. - private Vector3 parseOptionalVector3(OptionalVector3 optionalVector3, Vector3 defaultsOnNull) { - if (optionalVector3 == null) { + private Vector3 parseOptionalVector3(OptionalVector3 optionalVector3, Vector3 defaultsOnNull) + { + if (optionalVector3 == null) + { return defaultsOnNull; } return new Vector3( @@ -807,12 +922,14 @@ private Vector3 parseOptionalVector3(OptionalVector3 optionalVector3, Vector3 de } // Here, we don't want some dimensions set. For instance, set x, but not y. - public class OptionalVector3 { + public class OptionalVector3 + { public float? x = null; public float? y = null; public float? z = null; - public OptionalVector3(float? x = null, float? y = null, float? z = null) { + public OptionalVector3(float? x = null, float? y = null, float? z = null) + { this.x = x; this.y = y; this.z = z; @@ -832,9 +949,11 @@ public void UpdateMainCamera( float? farClippingPlane = null, string antiAliasing = null, int agentId = 0 - ) { + ) + { // adds error if fieldOfView is out of bounds - if (fieldOfView != null) { + if (fieldOfView != null) + { assertFovInBounds(fov: (float)fieldOfView); } @@ -887,14 +1006,17 @@ public void UpdateThirdPartyCamera( bool agentPositionRelativeCoordinates = false, string parent = null, int agentId = 0 - ) { + ) + { // adds error if fieldOfView is out of bounds - if (fieldOfView != null) { + if (fieldOfView != null) + { assertFovInBounds(fov: (float)fieldOfView); } // count is out of bounds - if (thirdPartyCameraId >= thirdPartyCameras.Count || thirdPartyCameraId < 0) { + if (thirdPartyCameraId >= thirdPartyCameras.Count || thirdPartyCameraId < 0) + { throw new ArgumentOutOfRangeException( $"thirdPartyCameraId: {thirdPartyCameraId} (int: default=0) must in 0 <= thirdPartyCameraId < len(thirdPartyCameras)={thirdPartyCameras.Count}." ); @@ -904,11 +1026,14 @@ public void UpdateThirdPartyCamera( Vector3 oldPosition; Vector3 oldRotation; - if (agentPositionRelativeCoordinates) { + if (agentPositionRelativeCoordinates) + { // keeps positions/rotations at default values, if unspecified. oldPosition = thirdPartyCamera.transform.localPosition; oldRotation = thirdPartyCamera.transform.localEulerAngles; - } else { + } + else + { // keeps positions/rotations at default values, if unspecified. oldPosition = thirdPartyCamera.transform.position; oldRotation = thirdPartyCamera.transform.eulerAngles; @@ -939,7 +1064,8 @@ public void UpdateThirdPartyCamera( ); } - private void addAgent(ServerAction action) { + private void addAgent(ServerAction action) + { Vector3 clonePosition = new Vector3(action.x, action.y, action.z); BaseAgentComponent componentClone = UnityEngine.Object.Instantiate( primaryAgent.baseAgentComponent @@ -960,7 +1086,8 @@ private void addAgent(ServerAction action) { agent.ProcessControlCommand(action.dynamicServerAction); } - private Vector3 agentStartPosition(BaseFPSAgentController agent) { + private Vector3 agentStartPosition(BaseFPSAgentController agent) + { Transform t = agent.transform; Vector3[] castDirections = new Vector3[] { @@ -977,78 +1104,99 @@ private Vector3 agentStartPosition(BaseFPSAgentController agent) { CharacterController charContr = agent.m_CharacterController; 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) { + 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)) { + if (maxHit.distance > (charContr.radius * 5)) + { return t.position + (maxDirection * (charContr.radius * 4)); } return Vector3.zero; } - public void UpdateAgentColor(BaseFPSAgentController agent, Color color) { + public void UpdateAgentColor(BaseFPSAgentController agent, Color color) + { foreach ( MeshRenderer r in agent.gameObject.GetComponentsInChildren() as MeshRenderer[] - ) { - foreach (Material m in r.materials) { - if (m.name.Contains("Agent_Color_Mat")) { + ) + { + foreach (Material m in r.materials) + { + if (m.name.Contains("Agent_Color_Mat")) + { m.color = color; } } } } - public IEnumerator ResetCoroutine(ServerAction response) { + public IEnumerator ResetCoroutine(ServerAction response) + { // Setting all the agents invisible here is silly but necessary // as otherwise the FirstPersonCharacterCull.cs script will // try to disable renderers that are invalid (but not null) // as the scene they existed in has changed. - for (int i = 0; i < agents.Count; i++) { + for (int i = 0; i < agents.Count; i++) + { Destroy(agents[i].baseAgentComponent); } yield return null; - if (string.IsNullOrEmpty(response.sceneName)) { + if (string.IsNullOrEmpty(response.sceneName)) + { UnityEngine.SceneManagement.SceneManager.LoadScene( UnityEngine.SceneManagement.SceneManager.GetActiveScene().name ); - } else { + } + else + { UnityEngine.SceneManagement.SceneManager.LoadScene(response.sceneName); } } - public void resetMaterials() { + public void resetMaterials() + { ColorChanger colorChangeComponent = physicsSceneManager.GetComponent(); colorChangeComponent.ResetMaterials(); doResetMaterials = false; doResetColors = false; } - public void resetColors() { + public void resetColors() + { ColorChanger colorChangeComponent = physicsSceneManager.GetComponent(); colorChangeComponent.ResetColors(); doResetColors = false; } - public void Reset(ServerAction response) { - if (doResetMaterials) { + public void Reset(ServerAction response) + { + if (doResetMaterials) + { resetMaterials(); - } else if (doResetColors) { + } + else if (doResetColors) + { resetColors(); } StartCoroutine(ResetCoroutine(response)); } - public bool SwitchScene(string sceneName) { - if (!string.IsNullOrEmpty(sceneName)) { + public bool SwitchScene(string sceneName) + { + if (!string.IsNullOrEmpty(sceneName)) + { UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName); return true; } @@ -1058,7 +1206,8 @@ public bool SwitchScene(string sceneName) { // Decide whether agent has stopped actions // And if we need to capture a new frame - private void Update() { + private void Update() + { physicsSceneManager.isSceneAtRest = true; // assume the scene is at rest by default } @@ -1066,26 +1215,33 @@ 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) { + (request) => + { + if (!request.hasError) + { var data = request.GetData().ToArray(); payload.Add(new KeyValuePair(key, data)); - } else { + } + else + { Debug.Log("Request error: " + request.hasError); } } ); } - private byte[] captureScreen() { - if (tex.height != UnityEngine.Screen.height || tex.width != UnityEngine.Screen.width) { + private byte[] captureScreen() + { + if (tex.height != UnityEngine.Screen.height || tex.width != UnityEngine.Screen.width) + { tex = new Texture2D( UnityEngine.Screen.width, UnityEngine.Screen.height, @@ -1099,7 +1255,8 @@ private byte[] captureScreen() { return tex.GetRawTextureData(); } - private void addThirdPartyCameraImage(List> payload, Camera camera) { + private void addThirdPartyCameraImage(List> payload, Camera camera) + { #if PLATFORM_CLOUD_RENDERING captureScreenAsync(payload, "image-thirdParty-camera", camera); #else @@ -1109,13 +1266,16 @@ private void addThirdPartyCameraImage(List> payload #endif } - private void addImage(List> payload, BaseFPSAgentController agent) { - if (this.renderImage) { + private void addImage(List> payload, BaseFPSAgentController agent) + { + if (this.renderImage) + { #if PLATFORM_CLOUD_RENDERING captureScreenAsync(payload, "image", agent.m_Camera); #else // XXX may not need this since we call render in captureScreenAsync - if (this.agents.Count > 1 || this.thirdPartyCameras.Count > 0) { + if (this.agents.Count > 1 || this.thirdPartyCameras.Count > 0) + { RenderTexture.active = agent.m_Camera.activeTexture; agent.m_Camera.Render(); } @@ -1124,27 +1284,35 @@ private void addImage(List> payload, BaseFPSAgentCo } } - private void resetImageSynthesis(Camera camera) { + private void resetImageSynthesis(Camera camera) + { ImageSynthesis imageSynthesis = camera.gameObject.GetComponentInChildren(); - if (imageSynthesis != null && imageSynthesis.enabled) { + if (imageSynthesis != null && imageSynthesis.enabled) + { imageSynthesis.OnCameraChange(); imageSynthesis.OnSceneChange(); } } - private void resetAllImageSynthesis() { - foreach (var agent in this.agents) { + private void resetAllImageSynthesis() + { + foreach (var agent in this.agents) + { resetImageSynthesis(agent.m_Camera); } - foreach (var camera in this.thirdPartyCameras) { + foreach (var camera in this.thirdPartyCameras) + { resetImageSynthesis(camera); } } - public IEnumerator WaitOnResolutionChange(int width, int height) { - for (int i = 0; i < 30; i++) { - if (UnityEngine.Screen.width == width && UnityEngine.Screen.height == height) { + public IEnumerator WaitOnResolutionChange(int width, int height) + { + for (int i = 0; i < 30; i++) + { + if (UnityEngine.Screen.width == width && UnityEngine.Screen.height == height) + { break; } yield return null; @@ -1152,7 +1320,8 @@ public IEnumerator WaitOnResolutionChange(int width, int height) { } bool success = true; - if (Screen.width != width || Screen.height != 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})." @@ -1164,10 +1333,13 @@ public IEnumerator WaitOnResolutionChange(int width, int height) { this.primaryAgent.actionFinished(success); } - public void ChangeQuality(string quality) { + public void ChangeQuality(string quality) + { string[] names = QualitySettings.names; - for (int i = 0; i < names.Length; i++) { - if (names[i] == quality) { + for (int i = 0; i < names.Length; i++) + { + if (names[i] == quality) + { QualitySettings.SetQualityLevel(i, true); break; } @@ -1176,7 +1348,8 @@ public void ChangeQuality(string quality) { this.primaryAgent.actionFinished(true); } - public void ChangeResolution(int x, int y) { + 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 @@ -1205,10 +1378,13 @@ private void addObjectImage( List> payload, BaseFPSAgentController agent, ref MetadataWrapper metadata - ) { - if (this.renderInstanceSegmentation || this.renderSemanticSegmentation) { + ) + { + if (this.renderInstanceSegmentation || this.renderSemanticSegmentation) + { Debug.Log($"imageSynthesis null {agent.ImageSynthesis == null}"); - if (!agent.ImageSynthesis.hasCapturePass("_id")) { + if (!agent.ImageSynthesis.hasCapturePass("_id")) + { Debug.LogError( "Object Image not available in imagesynthesis - returning empty image" ); @@ -1217,7 +1393,8 @@ ref MetadataWrapper metadata payload.Add(new KeyValuePair("image_ids", bytes)); List colors = new List(); - foreach (Color key in agent.ImageSynthesis.colorIds.Keys) { + foreach (Color key in agent.ImageSynthesis.colorIds.Keys) + { ColorId cid = new ColorId(); cid.color = new ushort[] { @@ -1239,9 +1416,12 @@ private void addImageSynthesisImage( bool flag, string captureName, string fieldName - ) { - if (flag) { - if (!synth.hasCapturePass(captureName)) { + ) + { + if (flag) + { + if (!synth.hasCapturePass(captureName)) + { Debug.LogError(captureName + " not available - sending empty image"); } byte[] bytes = synth.Encode(captureName); @@ -1251,12 +1431,14 @@ string fieldName // Used for benchmarking only the server-side // no call is made to the Python side - private IEnumerator EmitFrameNoClient() { + private IEnumerator EmitFrameNoClient() + { frameCounter += 1; bool shouldRender = this.renderImage; - if (shouldRender) { + if (shouldRender) + { // we should only read the screen buffer after rendering is complete yield return new WaitForEndOfFrame(); // must wait an additional frame when in synchronous mode otherwise the frame lags @@ -1274,16 +1456,19 @@ public void createPayload( List> renderPayload, bool shouldRender, bool shouldRenderImageSynthesis - ) { + ) + { multiMeta.agents = new MetadataWrapper[this.agents.Count]; multiMeta.activeAgentId = this.activeAgentId; multiMeta.sequenceId = this.currentSequenceId; RenderTexture currentTexture = null; - if (shouldRender) { + if (shouldRender) + { currentTexture = RenderTexture.active; - for (int i = 0; i < this.thirdPartyCameras.Count; i++) { + for (int i = 0; i < this.thirdPartyCameras.Count; i++) + { ThirdPartyCameraMetadata cMetadata = new ThirdPartyCameraMetadata(); Camera camera = thirdPartyCameras.ToArray()[i]; cMetadata.thirdPartyCameraId = i; @@ -1293,7 +1478,8 @@ 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()) { + if (camera.GetComponentInParent()) + { cMetadata.agentPositionRelativeThirdPartyCameraPosition = camera .gameObject .transform @@ -1302,7 +1488,9 @@ bool shouldRenderImageSynthesis .gameObject .transform .localEulerAngles; - } else { + } + 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 @@ -1319,7 +1507,8 @@ bool shouldRenderImageSynthesis cameraMetadata[i] = cMetadata; addThirdPartyCameraImage(renderPayload, camera); - if (shouldRenderImageSynthesis) { + if (shouldRenderImageSynthesis) + { ImageSynthesis imageSynthesis = camera.gameObject.GetComponentInChildren() as ImageSynthesis; @@ -1361,7 +1550,8 @@ bool shouldRenderImageSynthesis } } } - for (int i = 0; i < this.agents.Count; i++) { + for (int i = 0; i < this.agents.Count; i++) + { BaseFPSAgentController agent = this.agents[i]; MetadataWrapper metadata = agent.generateMetadataWrapper(); // This value may never change, but the purpose is to provide a way @@ -1372,9 +1562,11 @@ bool shouldRenderImageSynthesis // we don't need to render the agent's camera for the first agent - if (shouldRender) { + if (shouldRender) + { addImage(renderPayload, agent); - if (shouldRenderImageSynthesis) { + if (shouldRenderImageSynthesis) + { addImageSynthesisImage( renderPayload, agent.imageSynthesis, @@ -1411,27 +1603,33 @@ bool shouldRenderImageSynthesis multiMeta.agents[i] = metadata; } - if (shouldRender) { + if (shouldRender) + { RenderTexture.active = currentTexture; } } - private string serializeMetadataJson(MultiAgentMetadata multiMeta) { + private string serializeMetadataJson(MultiAgentMetadata multiMeta) + { var jsonResolver = new ShouldSerializeContractResolver(); return Newtonsoft.Json.JsonConvert.SerializeObject( multiMeta, Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { + new Newtonsoft.Json.JsonSerializerSettings() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver } ); } - private bool canEmit() { + private bool canEmit() + { bool emit = true; - foreach (BaseFPSAgentController agent in this.agents) { - if (agent.agentState != AgentState.Emit) { + foreach (BaseFPSAgentController agent in this.agents) + { + if (agent.agentState != AgentState.Emit) + { emit = false; break; } @@ -1441,7 +1639,8 @@ private bool canEmit() { || this.agentManagerState == AgentState.Error; } - private RenderTexture createRenderTexture(int width, int height) { + private RenderTexture createRenderTexture(int width, int height) + { RenderTexture rt = new RenderTexture( width: width, height: height, @@ -1449,27 +1648,36 @@ private RenderTexture createRenderTexture(int width, int height) { GraphicsFormat.R8G8B8A8_UNorm ); rt.antiAliasing = 4; - if (rt.Create()) { + if (rt.Create()) + { Debug.Log(" created render texture with width= " + width + " height=" + height); return rt; - } else { + } + else + { // throw exception ? Debug.LogError("Could not create a renderTexture"); return null; } } - public IEnumerator EmitFrame() { - while (true) { + public IEnumerator EmitFrame() + { + while (true) + { bool shouldRender = this.renderImage && serverSideScreenshot; bool shouldRenderImageSynthesis = shouldRender && this.renderImageSynthesis; - if (renderImageSynthesisChanged) { - foreach (BaseFPSAgentController agent in this.agents) { + if (renderImageSynthesisChanged) + { + foreach (BaseFPSAgentController agent in this.agents) + { foreach ( ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() - ) { - if (ims.enabled) { + ) + { + if (ims.enabled) + { ims.updateCameraStatuses(this.renderImageSynthesis); } } @@ -1480,17 +1688,21 @@ ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() frameCounter += 1; - if (this.agentManagerState == AgentState.ActionComplete) { + if (this.agentManagerState == AgentState.ActionComplete) + { this.agentManagerState = AgentState.Emit; } - foreach (BaseFPSAgentController agent in this.agents) { - if (agent.agentState == AgentState.ActionComplete) { + foreach (BaseFPSAgentController agent in this.agents) + { + if (agent.agentState == AgentState.ActionComplete) + { agent.agentState = AgentState.Emit; } } - if (!this.canEmit()) { + if (!this.canEmit()) + { continue; } MultiAgentMetadata multiMeta = new MultiAgentMetadata(); @@ -1520,16 +1732,19 @@ ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() // creation failure // Not running code below loses compatibility with python controlled editor #if !UNITY_WEBGL - if (serverType == serverTypes.WSGI) { + if (serverType == serverTypes.WSGI) + { WWWForm form = new WWWForm(); form.AddField("metadata", serializeMetadataJson(multiMeta)); AsyncGPUReadback.WaitAllRequests(); - foreach (var item in renderPayload) { + foreach (var item in renderPayload) + { form.AddBinaryData(item.Key, item.Value); } form.AddField("token", robosimsClientToken); - if (this.sock == null) { + if (this.sock == null) + { // Debug.Log("connecting to host: " + robosimsHost); IPAddress host = IPAddress.Parse(robosimsHost); IPEndPoint hostep = new IPEndPoint(host, robosimsPort); @@ -1538,9 +1753,12 @@ ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() SocketType.Stream, ProtocolType.Tcp ); - try { + try + { this.sock.Connect(hostep); - } catch (SocketException e) { + } + 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 @@ -1555,7 +1773,8 @@ ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() } } - if (this.sock != null && this.sock.Connected) { + if (this.sock != null && this.sock.Connected) + { byte[] rawData = form.data; string request = @@ -1564,7 +1783,8 @@ ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() + rawData.Length.ToString() + "\r\n"; - foreach (KeyValuePair entry in form.headers) { + foreach (KeyValuePair entry in form.headers) + { request += entry.Key + ": " + entry.Value + "\r\n"; } request += "\r\n"; @@ -1584,14 +1804,16 @@ ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() int contentLength = 0; // read header - while (true) { + while (true) + { int received = this.sock.Receive( headerBuffer, bytesReceived, headerBuffer.Length - bytesReceived, SocketFlags.None ); - if (received == 0) { + if (received == 0) + { Debug.LogError( "0 bytes received attempting to read header - connection closed" ); @@ -1602,7 +1824,8 @@ ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() ; string headerMsg = Encoding.ASCII.GetString(headerBuffer, 0, bytesReceived); int offset = headerMsg.IndexOf("\r\n\r\n"); - if (offset > 0) { + if (offset > 0) + { contentLength = parseContentLength(headerMsg.Substring(0, offset)); bodyBuffer = new byte[contentLength]; bodyBytesReceived = bytesReceived - (offset + 4); @@ -1612,7 +1835,8 @@ ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() } // read body - while (bodyBytesReceived < contentLength) { + while (bodyBytesReceived < contentLength) + { // check for 0 bytes received int received = this.sock.Receive( bodyBuffer, @@ -1620,7 +1844,8 @@ ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() bodyBuffer.Length - bodyBytesReceived, SocketFlags.None ); - if (received == 0) { + if (received == 0) + { Debug.LogError( "0 bytes received attempting to read body - connection closed" ); @@ -1634,7 +1859,9 @@ ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() string msg = Encoding.ASCII.GetString(bodyBuffer, 0, bodyBytesReceived); ProcessControlCommand(msg); } - } else if (serverType == serverTypes.FIFO) { + } + else if (serverType == serverTypes.FIFO) + { byte[] msgPackMetadata = MessagePack.MessagePackSerializer.Serialize( multiMeta, @@ -1653,7 +1880,8 @@ ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() ) .Wait(2000); Debug.Log("ReachedTimeout " + !completed); - if (!completed) { + if (!completed) + { Debug.Log( "FIFO Timeout Reached. Start FIFO server first if remote control is needed." ); @@ -1667,14 +1895,16 @@ ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() #endif AsyncGPUReadback.WaitAllRequests(); - foreach (var item in renderPayload) { + foreach (var item in renderPayload) + { this.fifoClient.SendMessage(FifoServer.Client.FormMap[item.Key], item.Value); } this.fifoClient.SendEOM(); string msg = this.fifoClient.ReceiveMessage(); ProcessControlCommand(msg); - while (canEmit() && this.fastActionEmit) { + while (canEmit() && this.fastActionEmit) + { MetadataPatch patch = this.activeAgent().generateMetadataPatch(); patch.agentId = this.activeAgentId; msgPackMetadata = MessagePack.MessagePackSerializer.Serialize( @@ -1708,7 +1938,8 @@ ImageSynthesis ims in agent.gameObject.GetComponentsInChildren() } // Uniform entry point for both the test runner and the python server for step dispatch calls - public void ProcessControlCommand(DynamicServerAction controlCommand) { + public void ProcessControlCommand(DynamicServerAction controlCommand) + { this.renderInstanceSegmentation = this.initializedInstanceSeg; this.currentSequenceId = controlCommand.sequenceId; @@ -1724,17 +1955,21 @@ public void ProcessControlCommand(DynamicServerAction controlCommand) { 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}'"; return; } - if (agentManagerActions.Contains(controlCommand.action)) { + if (agentManagerActions.Contains(controlCommand.action)) + { // let's look in this class for the action this.activeAgent().ProcessControlCommand(controlCommand: controlCommand, target: this); - } else { + } + else + { // we only allow renderInstanceSegmentation to be flipped on // on a per step() basis, since by default the param is null // so we don't know if a request is meant to turn the param off @@ -1743,7 +1978,8 @@ public void ProcessControlCommand(DynamicServerAction controlCommand) { // was initialized to be true, but any particular step() may not set it // so we don't want to disable it inadvertently - if (controlCommand.renderInstanceSegmentation) { + if (controlCommand.renderInstanceSegmentation) + { this.renderInstanceSegmentation = true; } @@ -1752,7 +1988,8 @@ public void ProcessControlCommand(DynamicServerAction controlCommand) { || this.renderSemanticSegmentation || this.renderInstanceSegmentation || this.renderNormalsImage - ) { + ) + { updateImageSynthesis(true); updateThirdPartyCameraImageSynthesis(true); } @@ -1762,24 +1999,30 @@ public void ProcessControlCommand(DynamicServerAction controlCommand) { } } - public BaseFPSAgentController GetActiveAgent() { + public BaseFPSAgentController GetActiveAgent() + { return this.agents[activeAgentId]; } - public int GetActiveAgentId() { + public int GetActiveAgentId() + { return this.activeAgentId; } - public int GetThirdPartyCameraCount() { + public int GetThirdPartyCameraCount() + { return this.thirdPartyCameras.Count; } - private int parseContentLength(string header) { + private int parseContentLength(string header) + { // Debug.Log("got header: " + header); string[] fields = header.Split(new char[] { '\r', '\n' }); - foreach (string field in fields) { + foreach (string field in fields) + { string[] elements = field.Split(new char[] { ':' }); - if (elements[0].ToLower() == "content-length") { + if (elements[0].ToLower() == "content-length") + { return Int32.Parse(elements[1].Trim()); } } @@ -1787,48 +2030,56 @@ private int parseContentLength(string header) { return 0; } - private BaseFPSAgentController activeAgent() { + private BaseFPSAgentController activeAgent() + { return this.agents[activeAgentId]; } - private void ProcessControlCommand(string msg) { + private void ProcessControlCommand(string msg) + { DynamicServerAction controlCommand = new DynamicServerAction(jsonMessage: msg); this.ProcessControlCommand(controlCommand); } // Extra helper functions - protected string LoadStringVariable(string variable, string name) { + protected string LoadStringVariable(string variable, string name) + { string envVarName = ENVIRONMENT_PREFIX + name.ToUpper(); string envVarValue = Environment.GetEnvironmentVariable(envVarName); return envVarValue == null ? variable : envVarValue; } - protected int LoadIntVariable(int variable, string name) { + protected int LoadIntVariable(int variable, string name) + { string envVarName = ENVIRONMENT_PREFIX + name.ToUpper(); string envVarValue = Environment.GetEnvironmentVariable(envVarName); return envVarValue == null ? variable : int.Parse(envVarValue); } - protected float LoadFloatVariable(float variable, string name) { + protected float LoadFloatVariable(float variable, string name) + { string envVarName = ENVIRONMENT_PREFIX + name.ToUpper(); string envVarValue = Environment.GetEnvironmentVariable(envVarName); return envVarValue == null ? variable : float.Parse(envVarValue); } - protected bool LoadBoolVariable(bool variable, string name) { + protected bool LoadBoolVariable(bool variable, string name) + { string envVarName = ENVIRONMENT_PREFIX + name.ToUpper(); string envVarValue = Environment.GetEnvironmentVariable(envVarName); return envVarValue == null ? variable : bool.Parse(envVarValue); } - public void SetCriticalErrorState() { + public void SetCriticalErrorState() + { this.agentManagerState = AgentState.Error; } } [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class MultiAgentMetadata { +public class MultiAgentMetadata +{ public MetadataWrapper[] agents; public ThirdPartyCameraMetadata[] thirdPartyCameras; public int activeAgentId; @@ -1837,7 +2088,8 @@ public class MultiAgentMetadata { [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class ThirdPartyCameraMetadata { +public class ThirdPartyCameraMetadata +{ public int thirdPartyCameraId; public Vector3 position; public Vector3 rotation; @@ -1851,7 +2103,8 @@ public class ThirdPartyCameraMetadata { [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class MetadataPatch { +public class MetadataPatch +{ public string lastAction; public string errorMessage; public string errorCode; @@ -1864,7 +2117,8 @@ public class MetadataPatch { // overlap between ObjectMetadata and AgentMetadata [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class AgentMetadata { +public class AgentMetadata +{ public string name; public Vector3 position; public Vector3 rotation; @@ -1885,7 +2139,8 @@ public AgentMetadata() { } [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class DroneAgentMetadata : AgentMetadata { +public class DroneAgentMetadata : AgentMetadata +{ // why is the launcher position even attached to the agent's metadata // and not the generic metdata? public Vector3 launcherPosition; @@ -1894,7 +2149,8 @@ public class DroneAgentMetadata : AgentMetadata { // additional metadata for drone objects (only use with Drone controller) [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class DroneObjectMetadata : ObjectMetadata { +public class DroneObjectMetadata : ObjectMetadata +{ // Drone Related Metadata public int numSimObjHits; public int numFloorHits; @@ -1908,7 +2164,8 @@ public DroneObjectMetadata() { } [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class ObjectMetadata { +public class ObjectMetadata +{ public string name; public Vector3 position; public Vector3 rotation; @@ -2042,7 +2299,8 @@ public ObjectMetadata() { } [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class MinimalObjectMetadata { +public class MinimalObjectMetadata +{ public string name; // what type of object is this? @@ -2059,7 +2317,8 @@ public MinimalObjectMetadata() { } [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class SceneBounds { +public class SceneBounds +{ // 8 corners of the world axis aligned box that bounds a sim object // 8 rows - 8 corners, one per row // 3 columns - x, y, z of each corner respectively @@ -2076,7 +2335,8 @@ public class SceneBounds { // if an object is rotated, the dimensions of this box are subject to change [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class AxisAlignedBoundingBox { +public class AxisAlignedBoundingBox +{ // 8 corners of the world axis aligned box that bounds a sim object // 8 rows - 8 corners, one per row // 3 columns - x, y, z of each corner respectively @@ -2093,7 +2353,8 @@ public class AxisAlignedBoundingBox { // if an object is rotated, this object oriented box will not change dimensions [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class ObjectOrientedBoundingBox { +public class ObjectOrientedBoundingBox +{ // probably return these from the BoundingBox component of the object for now? // this means that it will only work for Pickupable objects at the moment public float[][] cornerPoints; @@ -2101,28 +2362,32 @@ public class ObjectOrientedBoundingBox { [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class InventoryObject { +public class InventoryObject +{ public string objectId; public string objectType; } [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class ColorId { +public class ColorId +{ public ushort[] color; public string name; } [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class ColorBounds { +public class ColorBounds +{ public ushort[] color; public int[] bounds; } [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class HandMetadata { +public class HandMetadata +{ public Vector3 position; public Vector3 rotation; public Vector3 localPosition; @@ -2131,7 +2396,8 @@ public class HandMetadata { [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class JointMetadata { +public class JointMetadata +{ public string name; public Vector3 position; public Vector3 rootRelativePosition; @@ -2144,7 +2410,8 @@ public class JointMetadata { [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class ArmMetadata { +public class ArmMetadata +{ // public Vector3 handTarget; // joints 1 to 4, joint 4 is the wrist and joint 1 is the base that never moves public JointMetadata[] joints; @@ -2169,7 +2436,8 @@ public class ArmMetadata { public float handSphereRadius; } -public class ArticulationArmMetadata { +public class ArticulationArmMetadata +{ //additional metadata for each joint in the articulated arm (currently base, extend joint, and wrist) public ArticulationJointMetadata[] joints; @@ -2190,7 +2458,8 @@ public class ArticulationArmMetadata { } //this should include the arm base, the extend joint, and wrist joint for now -public class ArticulationJointMetadata { +public class ArticulationJointMetadata +{ //string name of this joint public string name; @@ -2222,18 +2491,21 @@ public class ArticulationJointMetadata { } [Serializable] -public class ObjectTypeCount { +public class ObjectTypeCount +{ public string objectType; // specify object by type in scene public int count; // the total count of objects of type objectType that we will try to make exist in the scene } [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class ObjectPose { +public class ObjectPose +{ public ObjectPose() : this("", new Vector3(), new Vector3()) { } - public ObjectPose(string objectName, Vector3 position, Vector3 rotation) { + public ObjectPose(string objectName, Vector3 position, Vector3 rotation) + { this.objectName = objectName; this.position = position; this.rotation = rotation; @@ -2250,7 +2522,8 @@ public ObjectPose(string objectName, Vector3 position, Vector3 rotation) { // also used to randomly do this ie: randomly slice all objects of type apple, randomly slice all objects that have sliceable property [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class SetObjectStates { +public class SetObjectStates +{ public string objectType = null; // valid strings are any Object Type listed in documentation (ie: AlarmClock, Apple, etc) public string stateChange = null; // valid strings are: openable, toggleable, breakable, canFillWithLiquid, dirtyable, cookable, sliceable, canBeUsedUp public bool isOpen; @@ -2265,7 +2538,8 @@ public class SetObjectStates { [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public struct MetadataWrapper { +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 AgentMetadata agent; @@ -2319,7 +2593,8 @@ Wraps the JObject created by JSON.net and used by the ActionDispatcher 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 { +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 = @@ -2342,37 +2617,47 @@ public class DynamicServerAction { public JObject jObject { get; private set; } - public int agentId { + public int agentId + { get { return this.GetValue("agentId", 0); } } - public int sequenceId { + public int sequenceId + { get { return (int)this.GetValue("sequenceId", 0); } } - public string action { + public string action + { get { return this.jObject["action"].ToString(); } } - public PhysicsSimulationParams physicsSimulationParams { - get { + public PhysicsSimulationParams physicsSimulationParams + { + get + { return this.jObject[physicsSimulationParamsVariable] ?.ToObject(); } } - public bool HasAgentInitializationParams() { + public bool HasAgentInitializationParams() + { return this.ContainsKey(agentInitializationParamsVariable); } - public DynamicServerAction agentInitializationParams { - get { + public DynamicServerAction agentInitializationParams + { + get + { var dict = this.jObject[agentInitializationParamsVariable] ?.ToObject>(); dict ??= new Dictionary(); - foreach (var extraneousParam in AllowedExtraneousParameters) { + foreach (var extraneousParam in AllowedExtraneousParameters) + { var parmaValue = this.GetValue(extraneousParam); - if (parmaValue != null) { + if (parmaValue != null) + { dict.Add( extraneousParam, this.GetValue(extraneousParam) //?.ToObject() @@ -2383,73 +2668,93 @@ public DynamicServerAction agentInitializationParams { } } - public int GetValue(string name, int defaultValue) { - if (this.ContainsKey(name)) { + public int GetValue(string name, int defaultValue) + { + if (this.ContainsKey(name)) + { return (int)this.GetValue(name); - } else { + } + else + { return defaultValue; } } - public bool GetValue(string name, bool defaultValue) { - if (this.ContainsKey(name)) { + public bool GetValue(string name, bool defaultValue) + { + if (this.ContainsKey(name)) + { return (bool)this.GetValue(name); - } else { + } + else + { return defaultValue; } } - public JToken GetValue(string name) { + public JToken GetValue(string name) + { return this.jObject.GetValue(name); } - public bool ContainsKey(string name) { + public bool ContainsKey(string name) + { return this.jObject.ContainsKey(name); } - public bool renderInstanceSegmentation { + public bool renderInstanceSegmentation + { get { return this.GetValue("renderInstanceSegmentation", false); } } - public bool renderImage { + public bool renderImage + { get { return this.GetValue("renderImage", true); } } - public bool renderImageSynthesis { + public bool renderImageSynthesis + { get { return this.GetValue("renderImageSynthesis", true); } } - public DynamicServerAction(Dictionary action) { + public DynamicServerAction(Dictionary action) + { var jsonResolver = new ShouldSerializeContractResolver(); this.jObject = JObject.FromObject( action, - new Newtonsoft.Json.JsonSerializer() { + new Newtonsoft.Json.JsonSerializer() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver } ); } - public DynamicServerAction(JObject action) { + public DynamicServerAction(JObject action) + { this.jObject = action; } - public DynamicServerAction(string jsonMessage) { + public DynamicServerAction(string jsonMessage) + { this.jObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonMessage); } - public System.Object ToObject(Type objectType) { + public System.Object ToObject(Type objectType) + { return this.jObject.ToObject(objectType); } - public T ToObject() { + public T ToObject() + { return this.jObject.ToObject(); } // this is primarily used when detecting invalid arguments // 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() { + public IEnumerable ArgumentKeys() + { return this .jObject.Properties() .Select(p => p.Name) @@ -2457,7 +2762,8 @@ public IEnumerable ArgumentKeys() { .ToList(); } - public IEnumerable ArgumentKeysWithPhysicsSimulationProperies() { + public IEnumerable ArgumentKeysWithPhysicsSimulationProperies() + { return this .jObject.Properties() .Select(p => p.Name) @@ -2469,45 +2775,55 @@ public IEnumerable ArgumentKeysWithPhysicsSimulationProperies() { .ToList(); } - public IEnumerable Keys() { + public IEnumerable Keys() + { return this.jObject.Properties().Select(p => p.Name).ToList(); } - public int Count() { + public int Count() + { return this.jObject.Count; } - public void AddPhysicsSimulationParams(PhysicsSimulationParams physicsSimulationParams) { + public void AddPhysicsSimulationParams(PhysicsSimulationParams physicsSimulationParams) + { var token = JToken.FromObject(physicsSimulationParams); this.jObject.Add(new JProperty(physicsSimulationParamsVariable, token)); } } [Serializable] -public class CameraParameters { +public class CameraParameters +{ public float? fieldOfView; public Vector3? localEulerAngles; public float? nearPlane; public float? farPlane; - public static void setCameraParameters(Camera camera, CameraParameters parameters) { - if (parameters.fieldOfView.HasValue) { + public static void setCameraParameters(Camera camera, CameraParameters parameters) + { + if (parameters.fieldOfView.HasValue) + { camera.fieldOfView = parameters.fieldOfView.Value; } - if (parameters.nearPlane.HasValue) { + if (parameters.nearPlane.HasValue) + { camera.nearClipPlane = parameters.nearPlane.Value; } - if (parameters.farPlane.HasValue) { + if (parameters.farPlane.HasValue) + { camera.farClipPlane = parameters.farPlane.Value; } - if (parameters.localEulerAngles.HasValue) { + if (parameters.localEulerAngles.HasValue) + { camera.transform.localEulerAngles = parameters.localEulerAngles.Value; } } } [Serializable] -public class ServerAction { +public class ServerAction +{ public string action; public int agentCount = 1; public string quality; @@ -2670,21 +2986,26 @@ public class ServerAction { public Dictionary thirdPartyCameraParameters; - public SimObjType ReceptableSimObjType() { - if (string.IsNullOrEmpty(receptacleObjectType)) { + public SimObjType ReceptableSimObjType() + { + if (string.IsNullOrEmpty(receptacleObjectType)) + { return SimObjType.Undefined; } return (SimObjType)Enum.Parse(typeof(SimObjType), receptacleObjectType); } - public static VisibilityScheme GetVisibilitySchemeFromString(string visibilityScheme) { + public static VisibilityScheme GetVisibilitySchemeFromString(string visibilityScheme) + { VisibilityScheme result = VisibilityScheme.Collider; - try { + try + { result = (VisibilityScheme)Enum.Parse(typeof(VisibilityScheme), visibilityScheme, true); } // including this pragma so the "ex variable declared but not used" warning stops yelling #pragma warning disable 0168 - catch (ArgumentException ex) { + catch (ArgumentException ex) + { #pragma warning restore 0168 Debug.LogError( "Error parsing visibilityScheme: '" + visibilityScheme + "' defaulting to Collider" @@ -2694,12 +3015,15 @@ public static VisibilityScheme GetVisibilitySchemeFromString(string visibilitySc return result; } - public VisibilityScheme GetVisibilityScheme() { + public VisibilityScheme GetVisibilityScheme() + { return GetVisibilitySchemeFromString(this.visibilityScheme); } - public SimObjType GetSimObjType() { - if (string.IsNullOrEmpty(objectType)) { + public SimObjType GetSimObjType() + { + if (string.IsNullOrEmpty(objectType)) + { return SimObjType.Undefined; } return (SimObjType)Enum.Parse(typeof(SimObjType), objectType); @@ -2707,25 +3031,29 @@ public SimObjType GetSimObjType() { // allows this to be passed in as a dynamic which we then // cast back to itself - public ServerAction ToObject() { + public ServerAction ToObject() + { return this; } - public ServerAction ToObject(Type t) { + public ServerAction ToObject(Type t) + { return this; } } [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class InitializeReturn { +public class InitializeReturn +{ public float cameraNearPlane; public float cameraFarPlane; } [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class Geometry3D { +public class Geometry3D +{ public Vector3[] vertices; public int[] triangleIndices; public Vector2[] uvs; @@ -2734,7 +3062,8 @@ public class Geometry3D { [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class ObjectSphereBounds { +public class ObjectSphereBounds +{ public string id; public Vector3 worldSpaceCenter; public float radius; @@ -2742,7 +3071,8 @@ public class ObjectSphereBounds { [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class CapsuleData { +public class CapsuleData +{ public Transform transform; public float radius; @@ -2751,7 +3081,8 @@ public class CapsuleData { public Vector3 center; } -public class DebugSphere { +public class DebugSphere +{ public Vector3 worldSpaceCenter; public float radius; public Color color; @@ -2759,14 +3090,16 @@ public class DebugSphere { [Serializable] [MessagePackObject(keyAsPropertyName: true)] -public class Waypoint { +public class Waypoint +{ public Vector3 position; public SerializableColor color; public float radius = 0.2f; public string text = ""; } -public enum ServerActionErrorCode { +public enum ServerActionErrorCode +{ Undefined, ReceptacleNotVisible, ReceptacleNotOpen, @@ -2787,12 +3120,14 @@ public enum ServerActionErrorCode { UnhandledException } -public enum VisibilityScheme { +public enum VisibilityScheme +{ Collider, Distance } -public enum Temperature { +public enum Temperature +{ RoomTemp, Hot, Cold @@ -2801,7 +3136,8 @@ public enum Temperature { // Salient materials are only for pickupable and moveable objects, // for now static only objects do not report material back since we have to assign them manually // They are the materials that make up an object (ie: cell phone - metal, glass). -public enum SalientObjectMaterial { +public enum SalientObjectMaterial +{ Metal, Wood, Plastic, @@ -2820,24 +3156,28 @@ public enum SalientObjectMaterial { }; [Serializable] -public class ControllerInitialization { +public class ControllerInitialization +{ public Dictionary variableInitializations; } [Serializable] -public class TypedVariable { +public class TypedVariable +{ public string type; public object value; } -public class ShouldSerializeContractResolver : DefaultContractResolver { +public class ShouldSerializeContractResolver : DefaultContractResolver +{ public static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver(); protected override JsonProperty CreateProperty( MemberInfo member, MemberSerialization memberSerialization - ) { + ) + { JsonProperty property = base.CreateProperty(member, memberSerialization); // exclude these properties to make serialization match JsonUtility @@ -2848,24 +3188,30 @@ MemberSerialization memberSerialization || property.PropertyName == "magnitude" || property.PropertyName == "normalized" ) - ) { - property.ShouldSerialize = instance => { + ) + { + property.ShouldSerialize = instance => + { return false; }; return property; - } else { + } + else + { return base.CreateProperty(member, memberSerialization); } } } -public enum DepthFormat { +public enum DepthFormat +{ Normalized, Meters, Millimeters } -public enum AgentState { +public enum AgentState +{ Processing, ActionComplete, PendingFixedUpdate, diff --git a/unity/Assets/Scripts/Arm.cs b/unity/Assets/Scripts/Arm.cs index 72579e6487..53a46a76aa 100644 --- a/unity/Assets/Scripts/Arm.cs +++ b/unity/Assets/Scripts/Arm.cs @@ -3,7 +3,8 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public interface Arm { +public interface Arm +{ // void ContinuousUpdate(); bool IsArmColliding(); diff --git a/unity/Assets/Scripts/ArmAgentController.cs b/unity/Assets/Scripts/ArmAgentController.cs index 5e3aea7317..1e88df5339 100644 --- a/unity/Assets/Scripts/ArmAgentController.cs +++ b/unity/Assets/Scripts/ArmAgentController.cs @@ -7,8 +7,10 @@ using UnityEngine; using UnityEngine.AI; -namespace UnityStandardAssets.Characters.FirstPerson { - public abstract class ArmAgentController : PhysicsRemoteFPSAgentController { +namespace UnityStandardAssets.Characters.FirstPerson +{ + public abstract class ArmAgentController : PhysicsRemoteFPSAgentController + { public ArmAgentController(BaseAgentComponent baseAgentComponent, AgentManager agentManager) : base(baseAgentComponent, agentManager) { } @@ -17,19 +19,24 @@ 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) { + public ActionFinished ToggleMagnetVisibility(bool? visible = null) + { MeshRenderer mr = GameObject .Find("MagnetRenderer") .GetComponentInChildren(); - if (visible.HasValue) { + if (visible.HasValue) + { mr.enabled = visible.Value; - } else { + } + else + { mr.enabled = !mr.enabled; } return ActionFinished.Success; } - public override void updateImageSynthesis(bool status) { + public override void updateImageSynthesis(bool status) + { base.updateImageSynthesis(status); // updateImageSynthesis is run in BaseFPSController's Initialize method after the @@ -64,7 +71,8 @@ public IEnumerator MoveArmRelative( bool returnToStart = true, string coordinateSpace = "armBase", bool restrictMovement = false - ) { + ) + { var arm = getArm(); return arm.moveArmRelative( controller: this, @@ -83,7 +91,8 @@ public virtual IEnumerator MoveArm( bool returnToStart = true, string coordinateSpace = "armBase", bool restrictMovement = false - ) { + ) + { var arm = getArm(); return arm.moveArmTarget( controller: this, @@ -99,7 +108,8 @@ public virtual IEnumerator MoveArm( // perhaps this should fail if no object is picked up? // currently action success happens as long as the arm is // enabled because it is a successful "attempt" to pickup something - public IEnumerator PickupObject(List objectIdCandidates = null) { + public IEnumerator PickupObject(List objectIdCandidates = null) + { var arm = getArm(); return arm.PickupObject(objectIdCandidates); } @@ -109,7 +119,8 @@ public override void PickupObject( float y, bool forceAction = false, bool manualInteract = false - ) { + ) + { throw new InvalidOperationException( "You are passing in iTHOR PickupObject parameters (x, y) to the arm agent!" ); @@ -119,21 +130,25 @@ 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!" ); } - public IEnumerator ReleaseObject() { + public IEnumerator ReleaseObject() + { var arm = getArm(); return arm.DropObject(); } // note this does not reposition the center point of the magnet orb // so expanding the radius too much will cause it to clip backward into the wrist joint - public ActionFinished SetHandSphereRadius(float radius) { - if (radius < 0.04f || radius > 0.5f) { + public ActionFinished SetHandSphereRadius(float radius) + { + if (radius < 0.04f || radius > 0.5f) + { throw new ArgumentOutOfRangeException( $"radius={radius} of hand cannot be less than 0.04m nor greater than 0.5m" ); @@ -149,8 +164,10 @@ public IEnumerator MoveAgent( float ahead = 0, float right = 0, float speed = 1 - ) { - if (ahead == 0 && right == 0) { + ) + { + if (ahead == 0 && right == 0) + { throw new ArgumentException("Must specify ahead or right!"); } Vector3 direction = new Vector3(x: right, y: 0, z: ahead); @@ -178,7 +195,8 @@ public IEnumerator MoveAhead( float? moveMagnitude = null, float speed = 1, bool returnToStart = true - ) { + ) + { return MoveAgent( ahead: moveMagnitude.GetValueOrDefault(gridSize), speed: speed, @@ -190,7 +208,8 @@ public IEnumerator MoveBack( float? moveMagnitude = null, float speed = 1, bool returnToStart = true - ) { + ) + { return MoveAgent( ahead: -moveMagnitude.GetValueOrDefault(gridSize), speed: speed, @@ -202,7 +221,8 @@ public IEnumerator MoveRight( float? moveMagnitude = null, float speed = 1, bool returnToStart = true - ) { + ) + { return MoveAgent( right: moveMagnitude.GetValueOrDefault(gridSize), speed: speed, @@ -214,7 +234,8 @@ public IEnumerator MoveLeft( float? moveMagnitude = null, float speed = 1, bool returnToStart = true - ) { + ) + { return MoveAgent( right: -moveMagnitude.GetValueOrDefault(gridSize), speed: speed, @@ -226,7 +247,8 @@ public IEnumerator RotateRight( float? degrees = null, float speed = 1.0f, bool returnToStart = true - ) { + ) + { return RotateAgent( degrees: degrees.GetValueOrDefault(rotateStepDegrees), speed: speed, @@ -238,7 +260,8 @@ public IEnumerator RotateLeft( float? degrees = null, float speed = 1.0f, bool returnToStart = true - ) { + ) + { return RotateAgent( degrees: -degrees.GetValueOrDefault(rotateStepDegrees), speed: speed, @@ -250,7 +273,8 @@ public virtual IEnumerator RotateAgent( float degrees, float speed = 1.0f, bool returnToStart = true - ) { + ) + { CollisionListener collisionListener = this.GetComponentInParent(); collisionListener.Reset(); @@ -282,7 +306,8 @@ public virtual IEnumerator RotateWristRelative( float roll = 0f, float speed = 10f, bool returnToStart = true - ) { + ) + { var arm = getArm(); return arm.rotateWrist( controller: this, @@ -301,8 +326,10 @@ public virtual IEnumerator MoveArmBase( float speed = 1, bool returnToStart = true, bool normalizedY = true - ) { - if (normalizedY && (y < 0f || y > 1f)) { + ) + { + 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." @@ -324,7 +351,8 @@ public virtual IEnumerator MoveArmBaseUp( float distance, float speed = 1, bool returnToStart = true - ) { + ) + { var arm = getArm(); return arm.moveArmBaseUp( controller: this, @@ -339,24 +367,31 @@ public virtual IEnumerator MoveArmBaseDown( float distance, float speed = 1, bool returnToStart = true - ) { + ) + { return MoveArmBaseUp(distance: -distance, speed: speed, returnToStart: returnToStart); } #if UNITY_EDITOR // debug for static arm collisions from collision listener - public void GetMidLevelArmCollisions() { + public void GetMidLevelArmCollisions() + { var arm = getArm(); CollisionListener collisionListener = arm.GetComponentInChildren(); - if (collisionListener != null) { + if (collisionListener != null) + { List> collisions = new List>(); - foreach (var sc in collisionListener.StaticCollisions()) { + foreach (var sc in collisionListener.StaticCollisions()) + { Dictionary element = new Dictionary(); - if (sc.simObjPhysics != null) { + if (sc.simObjPhysics != null) + { element["objectType"] = "simObjPhysics"; element["name"] = sc.simObjPhysics.objectID; - } else { + } + else + { element["objectType"] = "gameObject"; element["name"] = sc.gameObject.name; } @@ -367,11 +402,13 @@ public void GetMidLevelArmCollisions() { } // debug for static arm collisions from collision listener - public void DebugMidLevelArmCollisions() { + public void DebugMidLevelArmCollisions() + { var arm = getArm(); List scs = arm.collisionListener.StaticCollisions().ToList(); Debug.Log("Total current active static arm collisions: " + scs.Count); - foreach (StaticCollision sc in scs) { + foreach (StaticCollision sc in scs) + { Debug.Log("Arm static collision: " + sc.name); } actionFinished(true); diff --git a/unity/Assets/Scripts/ArmCollisionResolver.cs b/unity/Assets/Scripts/ArmCollisionResolver.cs index 00addb64c5..d32e214fc7 100644 --- a/unity/Assets/Scripts/ArmCollisionResolver.cs +++ b/unity/Assets/Scripts/ArmCollisionResolver.cs @@ -3,14 +3,16 @@ using System.Linq; using UnityEngine; -public class ArmCollisionResolver : CollisionEventResolver { +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; - protected new void Start() { + protected new void Start() + { base.Start(); arm = this.GetComponent(); var collisionListener = this.GetComponentInParent(); @@ -19,23 +21,33 @@ public class ArmCollisionResolver : CollisionEventResolver { public override StaticCollision resolveToStaticCollision( Collider externalCollider, HashSet internalColliders - ) { - if (externalCollider.transform.parent != null) { - if (externalCollider.transform.parent.gameObject.Equals(bodyCollidersParent)) { + ) + { + if (externalCollider.transform.parent != null) + { + if (externalCollider.transform.parent.gameObject.Equals(bodyCollidersParent)) + { // Collision with body Debug.Log("-------- RESOLVED COLLISION WITH BODY"); - return new StaticCollision() { + return new StaticCollision() + { gameObject = externalCollider.transform.parent.gameObject }; } } - if (externalCollider.GetComponentInParent() != null) { - if (internalColliders.Count == 1 && internalColliders.First() == bodyColliderIgnore) { + if (externalCollider.GetComponentInParent() != null) + { + if (internalColliders.Count == 1 && internalColliders.First() == bodyColliderIgnore) + { return null; - } else { - foreach (var objectColliderSet in arm.heldObjects.Values) { - if (objectColliderSet.Contains(externalCollider)) { + } + 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 }; diff --git a/unity/Assets/Scripts/ArmController.cs b/unity/Assets/Scripts/ArmController.cs index 7e9a725746..8c7c132b2b 100644 --- a/unity/Assets/Scripts/ArmController.cs +++ b/unity/Assets/Scripts/ArmController.cs @@ -5,7 +5,8 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public abstract class ArmController : MonoBehaviour, Arm, MovableContinuous { +public abstract class ArmController : MonoBehaviour, Arm, MovableContinuous +{ [SerializeField] public Transform FinalJoint; @@ -40,7 +41,8 @@ public abstract class ArmController : MonoBehaviour, Arm, MovableContinuous { protected bool ignoreHeldObjectToAgentCollisions = false; - protected virtual bool validArmTargetPosition(Vector3 targetWorldPosition) { + protected virtual bool validArmTargetPosition(Vector3 targetWorldPosition) + { return true; } @@ -56,7 +58,8 @@ protected virtual bool validArmTargetPosition(Vector3 targetWorldPosition) { public abstract void ContinuousUpdate(float fixedDeltaTime); - public virtual ActionFinished FinishContinuousMove(BaseFPSAgentController controller) { + public virtual ActionFinished FinishContinuousMove(BaseFPSAgentController controller) + { bool actionSuccess = !this.ShouldHalt(); string errorMessage = this.GetHaltMessage(); @@ -76,23 +79,28 @@ public virtual ActionFinished FinishContinuousMove(BaseFPSAgentController contro public abstract GameObject GetArmTarget(); public abstract ArmMetadata GenerateMetadata(); - public virtual bool ShouldHalt() { + public virtual bool ShouldHalt() + { return collisionListener.ShouldHalt(); } - public Vector3 MagnetSphereWorldCenter() { + public Vector3 MagnetSphereWorldCenter() + { return magnetSphere.transform.TransformPoint(magnetSphere.center); } - public virtual string GetHaltMessage() { + 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) { + if (staticCollisions.Count > 0) + { var sc = staticCollisions[0]; // if we hit a sim object - if (sc.isSimObj) { + if (sc.isSimObj) + { return "Collided with static/kinematic sim object: '" + sc.simObjPhysics.name + "', could not reach target: '" @@ -101,7 +109,8 @@ public virtual string GetHaltMessage() { } // if we hit a structural object that isn't a sim object but still has static collision - if (!sc.isSimObj) { + if (!sc.isSimObj) + { return "Collided with static structure in scene: '" + sc.gameObject.name + "', could not reach target: '" @@ -114,19 +123,23 @@ public virtual string GetHaltMessage() { // public virtual ActionFinished FinishContinuousMove( - public bool IsArmColliding() { + public bool IsArmColliding() + { HashSet colliders = this.currentArmCollisions(); return colliders.Count > 0; } - public IEnumerator withLastStepCallback(IEnumerator steps) { - while (steps.MoveNext()) { + public IEnumerator withLastStepCallback(IEnumerator steps) + { + while (steps.MoveNext()) + { yield return steps.Current; } lastStepCallback(); } - public HashSet currentArmCollisions() { + public HashSet currentArmCollisions() + { HashSet colliders = new HashSet(); // add the AgentCapsule to the ArmCapsuleColliders for the capsule collider check @@ -136,8 +149,10 @@ public HashSet currentArmCollisions() { capsules.Add(agentCapsuleCollider); // create overlap box/capsule for each collider and check the result I guess - foreach (CapsuleCollider c in capsules) { - if (c.isTrigger || !c.gameObject.active) { + foreach (CapsuleCollider c in capsules) + { + if (c.isTrigger || !c.gameObject.active) + { continue; } @@ -147,7 +162,8 @@ public HashSet currentArmCollisions() { // direction of CapsuleCollider's orientation in local space Vector3 dir = new Vector3(); - switch (c.direction) { + switch (c.direction) + { // x just in case case 0: // get world space direction of this capsule's local right vector @@ -204,14 +220,17 @@ public HashSet currentArmCollisions() { ), queryTriggerInteraction: QueryTriggerInteraction.Ignore ); - foreach (Collider col in cols) { + foreach (Collider col in cols) + { colliders.Add(col); } } // also check if the couple of box colliders are colliding - foreach (BoxCollider b in ArmBoxColliders) { - if (b.isTrigger || !b.gameObject.active) { + foreach (BoxCollider b in ArmBoxColliders) + { + if (b.isTrigger || !b.gameObject.active) + { continue; } Collider[] cols = Physics.OverlapBox( @@ -227,7 +246,8 @@ public HashSet currentArmCollisions() { ), queryTriggerInteraction: QueryTriggerInteraction.Ignore ); - foreach (Collider col in cols) { + foreach (Collider col in cols) + { colliders.Add(col); } } @@ -242,9 +262,11 @@ public virtual IEnumerator moveArmRelative( bool returnToStart, string coordinateSpace, bool restrictTargetPosition - ) { + ) + { Vector3 offsetWorldPos; - switch (coordinateSpace) { + switch (coordinateSpace) + { case "world": // world space, can be used to move directly toward positions // returned by sim objects @@ -280,7 +302,8 @@ public virtual IEnumerator moveArmTarget( bool returnToStart, string coordinateSpace, bool restrictTargetPosition - ) { + ) + { // clearing out colliders here since OnTriggerExit is not consistently called in Editor collisionListener.Reset(); @@ -288,7 +311,8 @@ bool restrictTargetPosition // Move arm based on hand space or arm origin space Vector3 targetWorldPos; - switch (coordinateSpace) { + switch (coordinateSpace) + { case "world": // world space, can be used to move directly toward positions // returned by sim objects @@ -306,7 +330,8 @@ bool restrictTargetPosition throw new ArgumentException("Invalid coordinateSpace: " + coordinateSpace); } - if (restrictTargetPosition && !validArmTargetPosition(targetWorldPos)) { + if (restrictTargetPosition && !validArmTargetPosition(targetWorldPos)) + { throw new InvalidOperationException( $"Invalid target: Position '{target}' in space '{coordinateSpace}' is behind shoulder." ); @@ -333,7 +358,8 @@ public virtual IEnumerator moveArmBase( float fixedDeltaTime, bool returnToStartPositionIfFailed, bool normalizedY - ) { + ) + { // clearing out colliders here since OnTriggerExit is not consistently called in Editor collisionListener.Reset(); @@ -344,11 +370,13 @@ bool normalizedY maxY; getCapsuleMinMaxY(controller, out minY, out maxY); - if (normalizedY) { + if (normalizedY) + { height = (maxY - minY) * height + minY; } - if (height < minY || height > maxY) { + if (height < minY || height > maxY) + { throw new ArgumentOutOfRangeException( $"height={height} value must be in [{minY}, {maxY}]." ); @@ -373,7 +401,8 @@ private void getCapsuleMinMaxY( PhysicsRemoteFPSAgentController controller, out float minY, out float maxY - ) { + ) + { CapsuleCollider cc = controller.GetComponent(); Vector3 capsuleWorldCenter = cc.transform.TransformPoint(cc.center); @@ -387,7 +416,8 @@ public virtual IEnumerator moveArmBaseUp( float unitsPerSecond, float fixedDeltaTime, bool returnToStartPositionIfFailed - ) { + ) + { // clearing out colliders here since OnTriggerExit is not consistently called in Editor collisionListener.Reset(); @@ -415,7 +445,8 @@ public virtual IEnumerator rotateWrist( float degreesPerSecond, float fixedDeltaTime, bool returnToStartPositionIfFailed - ) { + ) + { collisionListener.Reset(); return withLastStepCallback( ContinuousMovement.rotate( @@ -430,17 +461,20 @@ bool returnToStartPositionIfFailed ); } - public List WhatObjectsAreInsideMagnetSphereAsSOP(bool onlyPickupable) { + public List WhatObjectsAreInsideMagnetSphereAsSOP(bool onlyPickupable) + { //Debug.Log("calling WhatObjectsAreInsideMagnetSphereAsSOP"); return magnetSphereComp.CurrentlyContainedSimObjects(onlyPickupable: onlyPickupable); } public IEnumerator ReturnObjectsInMagnetAfterPhysicsUpdate( PhysicsRemoteFPSAgentController controller - ) { + ) + { yield return new WaitForFixedUpdate(); List listOfSOP = new List(); - foreach (SimObjPhysics sop in this.WhatObjectsAreInsideMagnetSphereAsSOP(false)) { + foreach (SimObjPhysics sop in this.WhatObjectsAreInsideMagnetSphereAsSOP(false)) + { listOfSOP.Add(sop.ObjectID); } Debug.Log("objs: " + string.Join(", ", listOfSOP)); @@ -451,15 +485,18 @@ private Dictionary getGameObjectToMultipliedScale( GameObject go, Vector3 currentScale, Dictionary gameObjectToScale = null - ) { - if (gameObjectToScale == null) { + ) + { + if (gameObjectToScale == null) + { gameObjectToScale = new Dictionary(); } currentScale = Vector3.Scale(currentScale, go.transform.localScale); gameObjectToScale[go] = currentScale; - foreach (Transform child in go.transform) { + foreach (Transform child in go.transform) + { getGameObjectToMultipliedScale( go: child.gameObject, currentScale: currentScale, @@ -470,15 +507,19 @@ 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; // grab all sim objects that are currently colliding with magnet sphere - foreach (SimObjPhysics sop in WhatObjectsAreInsideMagnetSphereAsSOP(onlyPickupable: true)) { - if (objectIds != null) { - if (!objectIds.Contains(sop.objectID)) { + foreach (SimObjPhysics sop in WhatObjectsAreInsideMagnetSphereAsSOP(onlyPickupable: true)) + { + if (objectIds != null) + { + if (!objectIds.Contains(sop.objectID)) + { continue; } } @@ -494,7 +535,8 @@ public virtual IEnumerator PickupObject(List objectIds) { rb.collisionDetectionMode = CollisionDetectionMode.Discrete; rb.detectCollisions = false; // Disable detecting of collisions - if (sop.IsOpenable) { + if (sop.IsOpenable) + { CanOpen_Object coj = sop.gameObject.GetComponent(); // if an openable object receives OnTriggerEnter events @@ -507,7 +549,8 @@ public virtual IEnumerator PickupObject(List objectIds) { // and parent them to the correct joint HashSet cols = new HashSet(); - foreach (Collider c in sop.MyColliders) { + foreach (Collider c in sop.MyColliders) + { // One set of colliders are used to check collisions // with kinematic objects Collider clone = Instantiate( @@ -544,15 +587,20 @@ public virtual IEnumerator PickupObject(List objectIds) { Debug.Log( $"------- ignoreHeldObjectToAgentCollisions {ignoreHeldObjectToAgentCollisions}" ); - if (ignoreHeldObjectToAgentCollisions) { - foreach (Collider c0 in colliders) { - foreach (Collider c1 in cols) { + if (ignoreHeldObjectToAgentCollisions) + { + foreach (Collider c0 in colliders) + { + foreach (Collider c1 in cols) + { Physics.IgnoreCollision(c0, c1); } } } - foreach (Collider c0 in cols) { - foreach (Collider c1 in cols) { + foreach (Collider c0 in cols) + { + foreach (Collider c1 in cols) + { Physics.IgnoreCollision(c0, c1); } } @@ -562,7 +610,8 @@ public virtual IEnumerator PickupObject(List objectIds) { } var errorMessage = ""; - if (!pickedUp) { + if (!pickedUp) + { errorMessage = ( objectIds != null ? "No objects (specified by objectId) were valid to be picked up by the arm" @@ -575,15 +624,18 @@ public virtual IEnumerator PickupObject(List objectIds) { yield return new ActionFinished() { success = pickedUp, errorMessage = errorMessage }; } - public virtual IEnumerator DropObject() { + public virtual IEnumerator DropObject() + { // grab all sim objects that are currently colliding with magnet sphere - foreach (KeyValuePair> sop in heldObjects) { + foreach (KeyValuePair> sop in heldObjects) + { Rigidbody rb = sop.Key.GetComponent(); rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; rb.isKinematic = false; // delete cloned colliders - foreach (Collider c in sop.Value) { + foreach (Collider c in sop.Value) + { Destroy(c.gameObject); } @@ -594,16 +646,20 @@ public virtual IEnumerator DropObject() { // c.enabled = true; // } - if (sop.Key.IsOpenable) { + if (sop.Key.IsOpenable) + { CanOpen_Object coj = sop.Key.gameObject.GetComponent(); coj.triggerEnabled = true; } GameObject topObject = GameObject.Find("Objects"); - if (topObject != null) { + if (topObject != null) + { sop.Key.transform.parent = topObject.transform; - } else { + } + else + { sop.Key.transform.parent = null; } @@ -616,7 +672,8 @@ public virtual IEnumerator DropObject() { yield return ActionFinished.Success; } - public void SetHandSphereRadius(float radius) { + public void SetHandSphereRadius(float radius) + { // Magnet.transform.localScale = new Vector3(radius, radius, radius); magnetSphere.radius = radius; MagnetRenderer.transform.localScale = new Vector3(2 * radius, 2 * radius, 2 * radius); diff --git a/unity/Assets/Scripts/ArticulatedAgentController.cs b/unity/Assets/Scripts/ArticulatedAgentController.cs index 618ccb4f6a..0861d7c060 100644 --- a/unity/Assets/Scripts/ArticulatedAgentController.cs +++ b/unity/Assets/Scripts/ArticulatedAgentController.cs @@ -7,8 +7,10 @@ using UnityEngine.AI; using UnityEngine.Rendering.PostProcessing; -namespace UnityStandardAssets.Characters.FirstPerson { - public partial class ArticulatedAgentController : ArmAgentController { +namespace UnityStandardAssets.Characters.FirstPerson +{ + public partial class ArticulatedAgentController : ArmAgentController + { public ArticulatedAgentController( BaseAgentComponent baseAgentComponent, AgentManager agentManager @@ -25,24 +27,30 @@ AgentManager agentManager private CapsuleData originalCapsule; - protected override CapsuleData GetAgentCapsule() { + protected override CapsuleData GetAgentCapsule() + { Debug.Log("calling Override GetAgentCapsule in ArticulatedAgentController"); - if (originalCapsule == null) { + if (originalCapsule == null) + { var cc = this.GetComponent(); - return new CapsuleData { + return new CapsuleData + { radius = cc.radius, height = cc.height, center = cc.center, transform = cc.transform }; - } else { + } + else + { return originalCapsule; } } // TODO: Reimplement for Articulation body - public override ActionFinished InitializeBody(ServerAction initializeAction) { + public override ActionFinished InitializeBody(ServerAction initializeAction) + { // TODO; Articulation Body init VisibilityCapsule = StretchVisCap; m_CharacterController.center = new Vector3(0, 1.5f, 0); @@ -55,7 +63,8 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { // TODO: REMOVE CapsuleCollider cc = this.GetComponent(); - originalCapsule = new CapsuleData { + originalCapsule = new CapsuleData + { radius = cc.radius, height = cc.height, center = cc.center, @@ -85,13 +94,16 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { // fp_camera_2.transform.localEulerAngles = new Vector3(45f, 90f, 0f); // fp_camera_2.fieldOfView = 90f; - if (initializeAction != null) { - if (initializeAction.cameraNearPlane > 0) { + if (initializeAction != null) + { + if (initializeAction.cameraNearPlane > 0) + { m_Camera.nearClipPlane = initializeAction.cameraNearPlane; // fp_camera_2.nearClipPlane = initializeAction.cameraNearPlane; } - if (initializeAction.cameraFarPlane > 0) { + if (initializeAction.cameraFarPlane > 0) + { m_Camera.farClipPlane = initializeAction.cameraFarPlane; // fp_camera_2.farClipPlane = initializeAction.cameraFarPlane; } @@ -128,9 +140,11 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { return ActionFinished.Success; } - private ArticulatedArmController getArmImplementation() { + private ArticulatedArmController getArmImplementation() + { ArticulatedArmController arm = GetComponentInChildren(); - if (arm == null) { + 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." @@ -139,12 +153,15 @@ private ArticulatedArmController getArmImplementation() { return arm; } - protected override ArmController getArm() { + protected override ArmController getArm() + { return getArmImplementation(); } - public IEnumerator setFloorToHighFrictionAsLastStep(IEnumerator steps) { - while (steps.MoveNext()) { + public IEnumerator setFloorToHighFrictionAsLastStep(IEnumerator steps) + { + while (steps.MoveNext()) + { yield return steps.Current; } SetFloorColliderToHighFriction(); @@ -154,7 +171,8 @@ public override IEnumerator MoveArmBaseUp( float distance, float speed = 1, bool returnToStart = true - ) { + ) + { Debug.Log("MoveArmBaseUp from ArticulatedAgentController"); SetFloorColliderToHighFriction(); var arm = getArmImplementation(); @@ -174,7 +192,8 @@ public IEnumerator MoveArmBaseUp( bool useLimits, float speed = 1, bool returnToStart = true - ) { + ) + { Debug.Log("MoveArmBaseUp from ArticulatedAgentController"); SetFloorColliderToHighFriction(); var arm = getArmImplementation(); @@ -192,7 +211,8 @@ public override IEnumerator MoveArmBaseDown( float distance, float speed = 1, bool returnToStart = true - ) { + ) + { Debug.Log( "MoveArmBaseDown from ArticulatedAgentController (pass negative distance to MoveArmBaseUp)" ); @@ -210,7 +230,8 @@ public IEnumerator MoveArmBaseDown( bool useLimits, float speed = 1, bool returnToStart = true - ) { + ) + { Debug.Log( "MoveArmBaseDown from ArticulatedAgentController (pass negative distance to MoveArmBaseUp)" ); @@ -228,7 +249,8 @@ public override IEnumerator MoveArm( bool returnToStart = true, string coordinateSpace = "armBase", bool restrictMovement = false - ) { + ) + { var arm = getArmImplementation(); SetFloorColliderToHighFriction(); return arm.moveArmTarget( @@ -240,7 +262,8 @@ 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( @@ -253,14 +276,16 @@ public IEnumerator MoveArm(Vector3 position, bool useLimits, float speed = 1) { } //helper functions to set physics material values - public void SetFloorColliderToSlippery() { + public void SetFloorColliderToSlippery() + { FloorColliderPhysicsMaterial.staticFriction = 0; FloorColliderPhysicsMaterial.frictionCombine = PhysicMaterialCombine.Minimum; //ensure min friction take priority //FloorColliderPhysicsMaterial.dynamicFriction = 0; } - public void SetFloorColliderToHighFriction() { + public void SetFloorColliderToHighFriction() + { FloorColliderPhysicsMaterial.staticFriction = 1; FloorColliderPhysicsMaterial.frictionCombine = PhysicMaterialCombine.Maximum; //ensure max friction takes priority //FloorColliderPhysicsMaterial.dynamicFriction = 1; @@ -271,14 +296,17 @@ public void TeleportFull( Vector3 rotation, float? horizon = null, bool forceAction = false - ) { + ) + { Debug.Log($"Original Position: {this.transform.position}"); - if (horizon == null) { + if (horizon == null) + { horizon = m_Camera.transform.localEulerAngles.x; } - if (!forceAction && (horizon > maxDownwardLookAngle || horizon < -maxUpwardLookAngle)) { + if (!forceAction && (horizon > maxDownwardLookAngle || horizon < -maxUpwardLookAngle)) + { throw new ArgumentOutOfRangeException( $"Each horizon must be in [{-maxUpwardLookAngle}:{maxDownwardLookAngle}]. You gave {horizon}." ); @@ -294,7 +322,8 @@ public void TeleportFull( ); } - IEnumerator TeleportThenWait(Vector3 position, Quaternion rotation, float cameraHorizon) { + IEnumerator TeleportThenWait(Vector3 position, Quaternion rotation, float cameraHorizon) + { Debug.Log("TeleportThenWait coroutine starting"); ArticulationBody myBody = this.GetComponent(); myBody.TeleportRoot(position, rotation); @@ -315,7 +344,8 @@ public override void GetInteractablePoses( bool[] standings = null, float? maxDistance = null, int maxPoses = int.MaxValue // works like infinity - ) { + ) + { getInteractablePosesAB( objectId: objectId, markActionFinished: true, @@ -337,10 +367,12 @@ public void getInteractablePosesAB( bool[] standings = null, float? maxDistance = null, int maxPoses = int.MaxValue // works like infinity - ) { + ) + { Debug.Log("Calling getInteractablePosesAB"); - if (standings != null) { + if (standings != null) + { errorMessage = "Articulation Agent does not support 'standings' for GetInteractablePoses"; throw new InvalidActionException(); @@ -349,35 +381,47 @@ public void getInteractablePosesAB( Debug.Log( $"Position of agent at start of getInteractablePosesAB: {this.transform.position}" ); - if (360 % rotateStepDegrees != 0 && rotations != null) { + if (360 % rotateStepDegrees != 0 && rotations != null) + { throw new InvalidOperationException( $"360 % rotateStepDegrees (360 % {rotateStepDegrees} != 0) must be 0, unless 'rotations: float[]' is overwritten." ); } - if (maxPoses <= 0) { + if (maxPoses <= 0) + { throw new ArgumentOutOfRangeException("maxPoses must be > 0."); } // default "visibility" distance float maxDistanceFloat; - if (maxDistance == null) { + if (maxDistance == null) + { maxDistanceFloat = maxVisibleDistance; - } else if ((float)maxDistance <= 0) { + } + else if ((float)maxDistance <= 0) + { throw new ArgumentOutOfRangeException( "maxDistance must be >= 0 meters from the object." ); - } else { + } + else + { maxDistanceFloat = (float)maxDistance; } // populate default horizons - if (horizons == null) { + if (horizons == null) + { horizons = new float[] { -30, 0, 30, 60 }; - } else { - foreach (float horizon in horizons) { + } + else + { + foreach (float horizon in horizons) + { // recall that horizon=60 is look down 60 degrees and horizon=-30 is look up 30 degrees - if (horizon > maxDownwardLookAngle || horizon < -maxUpwardLookAngle) { + if (horizon > maxDownwardLookAngle || horizon < -maxUpwardLookAngle) + { throw new ArgumentException( $"Each horizon must be in [{-maxUpwardLookAngle}:{maxDownwardLookAngle}]. You gave {horizon}." ); @@ -386,7 +430,8 @@ public void getInteractablePosesAB( } // populate the rotations based on rotateStepDegrees - if (rotations == null) { + if (rotations == null) + { // Consider the case where one does not want to move on a perfect grid, and is currently moving // with an offsetted set of rotations like {10, 100, 190, 280} instead of the default {0, 90, 180, 270}. // This may happen if the agent starts by teleports with the rotation of 10 degrees. @@ -401,7 +446,8 @@ public void getInteractablePosesAB( float rotation = offset; rotation < 360 + offset; rotation += rotateStepDegrees - ) { + ) + { rotations[i++] = rotation; } } @@ -412,7 +458,8 @@ public void getInteractablePosesAB( ); // populate the positions by those that are reachable - if (positions == null) { + if (positions == null) + { positions = getReachablePositions(); } @@ -421,7 +468,8 @@ public void getInteractablePosesAB( // which is then used to filter the set of all reachable positions to just those plausible positions. Bounds objectBounds = UtilityFunctions.CreateEmptyBounds(); objectBounds.Encapsulate(theObject.transform.position); - foreach (Transform vp in theObject.VisibilityPoints) { + foreach (Transform vp in theObject.VisibilityPoints) + { objectBounds.Encapsulate(vp.position); } float fudgeFactor = objectBounds.extents.magnitude; @@ -466,22 +514,26 @@ IEnumerator TeleportThenWaitThenCheckInteractable( Vector3 oldPosition, Vector3 oldHorizon, Quaternion oldRotation - ) { + ) + { // set each key to store a list List> validAgentPoses = new List>(); bool stopEarly = false; - foreach (float horizon in horizons) { + foreach (float horizon in horizons) + { m_Camera.transform.localEulerAngles = new Vector3(horizon, 0f, 0f); Debug.Log($"camera horizon set to: {m_Camera.transform.localEulerAngles.x}"); - foreach (float rotation in rotations) { + foreach (float rotation in rotations) + { Vector3 rotationVector = new Vector3(x: 0, y: rotation, z: 0); //SetTransform(transform: transform, rotation: (Quaternion?)Quaternion.Euler(rotationVector)); //yield return new WaitForFixedUpdate(); - foreach (Vector3 position in filteredPositions) { + foreach (Vector3 position in filteredPositions) + { Debug.Log("////////////////////"); Debug.Log($"position Before SetTransform: {transform.position}"); Debug.Log( @@ -498,9 +550,11 @@ Quaternion oldRotation // Each of these values is directly compatible with TeleportFull // and should be used with .step(action='TeleportFull', **interactable_positions[0]) - if (objectIsCurrentlyVisible(theObject, maxDistanceFloat)) { + if (objectIsCurrentlyVisible(theObject, maxDistanceFloat)) + { validAgentPoses.Add( - new Dictionary { + new Dictionary + { ["x"] = position.x, ["y"] = position.y, ["z"] = position.z, @@ -509,7 +563,8 @@ Quaternion oldRotation } ); - if (validAgentPoses.Count >= maxPoses) { + if (validAgentPoses.Count >= maxPoses) + { stopEarly = true; break; } @@ -525,11 +580,13 @@ Quaternion oldRotation #endif } } - if (stopEarly) { + if (stopEarly) + { break; } } - if (stopEarly) { + if (stopEarly) + { break; } } @@ -560,30 +617,36 @@ public IEnumerator MoveAgent( float moveMagnitude = 1, float speed = 1, float acceleration = 1 - ) { + ) + { // Debug.Log("(3) ArticulatedAgentController: PREPPING MOVEAGENT COMMAND"); int direction = 0; - if (moveMagnitude < 0) { + if (moveMagnitude < 0) + { direction = -1; } - if (moveMagnitude > 0) { + if (moveMagnitude > 0) + { direction = 1; } Debug.Log("Move magnitude is now officially " + moveMagnitude); // Debug.Log($"preparing agent {this.transform.name} to move"); - if (Mathf.Approximately(moveMagnitude, 0.0f)) { + 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 // to use yield return below and creates a nested Monad, (yield return (yield return val)) // better to return with .GetEnumerator(); - return new ActionFinished() { + return new ActionFinished() + { success = false, errorMessage = "Error! distance to move must be nonzero" }.GetEnumerator(); } - AgentMoveParams amp = new AgentMoveParams { + AgentMoveParams amp = new AgentMoveParams + { agentState = ABAgentState.Moving, distance = Mathf.Abs(moveMagnitude), speed = speed, @@ -613,7 +676,8 @@ public IEnumerator MoveAhead( float? moveMagnitude = null, float speed = 0.14f, float acceleration = 0.14f - ) { + ) + { return MoveAgent( moveMagnitude: moveMagnitude.GetValueOrDefault(gridSize), speed: speed, @@ -625,7 +689,8 @@ public IEnumerator MoveBack( float? moveMagnitude = null, float speed = 0.14f, float acceleration = 0.14f - ) { + ) + { return MoveAgent( moveMagnitude: -moveMagnitude.GetValueOrDefault(gridSize), speed: speed, @@ -637,7 +702,8 @@ public IEnumerator RotateRight( float? degrees = null, float speed = 22.5f, float acceleration = 22.5f - ) { + ) + { return RotateAgent( degrees: degrees.GetValueOrDefault(rotateStepDegrees), speed: speed, @@ -649,7 +715,8 @@ public IEnumerator RotateLeft( float? degrees = null, float speed = 22.5f, float acceleration = 22.5f - ) { + ) + { return RotateAgent( degrees: -degrees.GetValueOrDefault(rotateStepDegrees), speed: speed, @@ -661,25 +728,31 @@ public IEnumerator RotateAgent( float degrees, float speed = 22.5f, float acceleration = 22.5f - ) { + ) + { int direction = 0; - if (degrees < 0) { + if (degrees < 0) + { direction = -1; } - if (degrees > 0) { + if (degrees > 0) + { direction = 1; } Debug.Log($"preparing agent {this.transform.name} to rotate"); - if (Mathf.Approximately(degrees, 0.0f)) { + if (Mathf.Approximately(degrees, 0.0f)) + { Debug.Log("Error! distance to rotate must be nonzero"); - return new ActionFinished() { + return new ActionFinished() + { success = false, errorMessage = "Error! distance to rotate must be nonzero" }.GetEnumerator(); } - AgentMoveParams amp = new AgentMoveParams { + AgentMoveParams amp = new AgentMoveParams + { agentState = ABAgentState.Rotating, distance = Mathf.Abs(Mathf.Deg2Rad * degrees), speed = Mathf.Deg2Rad * speed, @@ -711,7 +784,8 @@ public ActionFinished TeleportArm( float? rotation = null, bool worldRelative = false, bool forceAction = false - ) { + ) + { GameObject posRotManip = this.GetComponent() .StretchArm.GetComponent() .GetArmTarget(); @@ -721,31 +795,40 @@ public ActionFinished TeleportArm( float oldLocalRotationAngle = posRotManip.transform.localEulerAngles.y; // establish defaults in the absence of inputs - if (position == null) { + if (position == null) + { position = new Vector3(0f, 0.1f, 0f); } - if (rotation == null) { + if (rotation == null) + { rotation = -180f; } // teleport arm! - if (!worldRelative) { + if (!worldRelative) + { posRotManip.transform.localPosition = (Vector3)position; posRotManip.transform.localEulerAngles = new Vector3(0, (float)rotation % 360, 0); - } else { + } + else + { posRotManip.transform.position = (Vector3)position; posRotManip.transform.eulerAngles = new Vector3(0, (float)rotation % 360, 0); } - if (SArm.IsArmColliding() && !forceAction) { + if (SArm.IsArmColliding() && !forceAction) + { posRotManip.transform.localPosition = oldLocalPosition; posRotManip.transform.localEulerAngles = new Vector3(0, oldLocalRotationAngle, 0); - return new ActionFinished() { + return new ActionFinished() + { success = false, errorMessage = "collision detected at desired transform, cannot teleport" }; - } else { + } + else + { return ActionFinished.Success; } } @@ -756,9 +839,11 @@ public override IEnumerator RotateWristRelative( float roll = 0f, float speed = 400f, bool returnToStart = true - ) { + ) + { // pitch and roll are not supported for the stretch and so we throw an error - if (pitch != 0f || roll != 0f) { + if (pitch != 0f || roll != 0f) + { throw new System.NotImplementedException( "Pitch and roll are not supported for the stretch agent." ); @@ -777,21 +862,25 @@ public override IEnumerator RotateWristRelative( ); } - private float CalculateTotalMass(Transform rootTransform) { + private float CalculateTotalMass(Transform rootTransform) + { float totalMass = 0f; ArticulationBody rootBody = rootTransform.GetComponent(); - if (rootBody != null) { + if (rootBody != null) + { totalMass += rootBody.mass; } - foreach (Transform childTransform in rootTransform) { + foreach (Transform childTransform in rootTransform) + { totalMass += CalculateTotalMass(childTransform); } return totalMass; } - private MovableContinuous getBodyMovable() { + private MovableContinuous getBodyMovable() + { return this.transform.GetComponent(); } } diff --git a/unity/Assets/Scripts/ArticulatedAgentSolver.cs b/unity/Assets/Scripts/ArticulatedAgentSolver.cs index 325fe151c0..c14f76a646 100644 --- a/unity/Assets/Scripts/ArticulatedAgentSolver.cs +++ b/unity/Assets/Scripts/ArticulatedAgentSolver.cs @@ -6,13 +6,15 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public enum ABAgentState { +public enum ABAgentState +{ Idle = 0, Moving = 1, Rotating = 2 }; -public class ABAgentPhysicsParams { +public class ABAgentPhysicsParams +{ public float distance; public float speed; public float maxTimePassed; @@ -26,14 +28,16 @@ public class ABAgentPhysicsParams { public List cachedFixedDeltaTimes; } -public class AgentMoveParams : ABAgentPhysicsParams { +public class AgentMoveParams : ABAgentPhysicsParams +{ public ABAgentState agentState; public float acceleration; public float agentMass; public Vector3 initialTransformation; } -public class ArticulatedAgentSolver : MonoBehaviour, MovableContinuous { +public class ArticulatedAgentSolver : MonoBehaviour, MovableContinuous +{ //pass in arm move parameters for Action based movement public AgentMoveParams currentAgentMoveParams = new AgentMoveParams(); @@ -59,7 +63,8 @@ public class ArticulatedAgentSolver : MonoBehaviour, MovableContinuous { private Transform fingersAB; private Vector3 fingersInitialOffset; - void Start() { + void Start() + { myAB = this.GetComponent(); currentAgentMoveParams.agentState = ABAgentState.Idle; @@ -70,9 +75,11 @@ void Start() { fingersInitialOffset = fingersAB.localPosition; } - public void PrepToControlAgentFromAction(AgentMoveParams agentMoveParams) { + public void PrepToControlAgentFromAction(AgentMoveParams agentMoveParams) + { Debug.Log($"preparing {this.transform.name} to move"); - if (Mathf.Approximately(agentMoveParams.distance, 0.0f)) { + if (Mathf.Approximately(agentMoveParams.distance, 0.0f)) + { Debug.Log("Error! distance to move must be nonzero"); return; } @@ -90,11 +97,14 @@ public void PrepToControlAgentFromAction(AgentMoveParams agentMoveParams) { currentAgentMoveParams.cachedPositions = new List(); currentAgentMoveParams.cachedFixedDeltaTimes = new List(); - if (currentAgentMoveParams.agentState == ABAgentState.Moving) { + if (currentAgentMoveParams.agentState == ABAgentState.Moving) + { // snapshot the initial agent position to compare with later during movement currentAgentMoveParams.initialTransformation = myAB.transform.position; prevStepTransformation = myAB.transform.position; - } else if (currentAgentMoveParams.agentState == ABAgentState.Rotating) { + } + else if (currentAgentMoveParams.agentState == ABAgentState.Rotating) + { currentAgentMoveParams.initialTransformation = myAB.transform.eulerAngles; prevStepTransformation = myAB.transform.eulerAngles; } @@ -106,7 +116,8 @@ public void PrepToControlAgentFromAction(AgentMoveParams agentMoveParams) { Mathf.Pow(currentAgentMoveParams.speed, 2) / (2 * currentAgentMoveParams.acceleration); Debug.Log("accelerationDistance by default equals " + accelerationDistance); - if (2 * accelerationDistance > currentAgentMoveParams.distance) { + if (2 * accelerationDistance > currentAgentMoveParams.distance) + { accelerationDistance = currentAgentMoveParams.distance / 2; Debug.Log("accelerationDistance now equals " + accelerationDistance); } @@ -114,7 +125,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; @@ -133,12 +145,14 @@ public void ContinuousUpdate(float fixedDeltaTime) { ); accelerationDistance = 0.0f; - if (currentAgentMoveParams.agentState == ABAgentState.Moving) { + 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) { + if (distanceTransformedSoFar < accelerationDistance) + { float desiredDistance = 0.5f * currentAgentMoveParams.acceleration @@ -165,11 +179,14 @@ public void ContinuousUpdate(float fixedDeltaTime) { 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 - ) { - if (beginDeceleration == false) { + } + else if ( + distanceTransformedSoFar + >= currentAgentMoveParams.distance - accelerationDistance + ) + { + if (beginDeceleration == false) + { beginDecelerationSpeed = currentSpeed; beginDeceleration = true; } @@ -197,7 +214,9 @@ public void ContinuousUpdate(float fixedDeltaTime) { myAB.AddRelativeForce(new Vector3(0, 0, relativeForce)); // CASE: Cruise Control - Apply force calculated from difference between intended velocity and current velocity - } else { + } + else + { float speedDelta = currentAgentMoveParams.speed - currentSpeed; float relativeForce = @@ -240,7 +259,9 @@ 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) { + } + 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) @@ -258,7 +279,8 @@ public void ContinuousUpdate(float fixedDeltaTime) { 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) { + if (distanceTransformedSoFar < accelerationDistance) + { float desiredAngularDistance = 0.5f * currentAgentMoveParams.acceleration @@ -281,11 +303,14 @@ public void ContinuousUpdate(float fixedDeltaTime) { 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 - ) { - if (beginDeceleration == false) { + } + else if ( + distanceTransformedSoFar + >= currentAgentMoveParams.distance - accelerationDistance + ) + { + if (beginDeceleration == false) + { beginDecelerationSpeed = currentAngularSpeed; beginDeceleration = true; } @@ -310,7 +335,9 @@ public void ContinuousUpdate(float fixedDeltaTime) { myAB.AddRelativeTorque(new Vector3(0, relativeTorque, 0)); // CASE: Cruise - Apply force calculated from difference between intended angular velocity and current angular velocity - } else { + } + else + { float angularSpeedDelta = currentAgentMoveParams.speed - currentAngularSpeed; float relativeTorque = Mathf.Clamp( @@ -346,9 +373,13 @@ public void ContinuousUpdate(float fixedDeltaTime) { // Store current values for comparing with next FixedUpdate prevStepTransformation = currentRotation; - } else if (currentAgentMoveParams.agentState == ABAgentState.Idle) { + } + else if (currentAgentMoveParams.agentState == ABAgentState.Idle) + { // Do nothing - } else { + } + else + { throw new System.NotImplementedException( $"Agent is not in a valid movement state: {currentAgentMoveParams.agentState}." ); @@ -366,7 +397,8 @@ public void ContinuousUpdate(float fixedDeltaTime) { return; } - public bool ShouldHalt() { + public bool ShouldHalt() + { // Debug.Log("checking ArticulatedAgentController shouldHalt"); bool shouldStop = false; ArticulatedAgentSolver a = this; @@ -383,12 +415,15 @@ public bool ShouldHalt() { 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 { + } + else + { //this joint returns that it should stop! Debug.Log($"halted! Return shouldStop! Distance moved: {a.distanceTransformedSoFar}"); shouldStop = true; @@ -397,11 +432,13 @@ public bool ShouldHalt() { } // TODO remove from API - public virtual string GetHaltMessage() { + public virtual string GetHaltMessage() + { return ""; } - public ActionFinished FinishContinuousMove(BaseFPSAgentController controller) { + public ActionFinished FinishContinuousMove(BaseFPSAgentController controller) + { Debug.Log("starting continuousMoveFinishAB"); controller.transform.GetComponent().velocity = Vector3.zero; controller.transform.GetComponent().angularVelocity = Vector3.zero; @@ -415,7 +452,8 @@ public ActionFinished FinishContinuousMove(BaseFPSAgentController controller) { //controller.SetFloorColliderToSlippery(); bool actionSuccess = IsFingerTransformCorrect(); - if (!actionSuccess) { + if (!actionSuccess) + { controller.agentManager.SetCriticalErrorState(); } @@ -435,7 +473,8 @@ public bool shouldHalt( List cachedFixedTimeDeltas, double minMovementPerSecond, double haltCheckTimeWindow - ) { + ) + { bool shouldHalt = false; //halt if positions/rotations are within tolerance and effectively not changing @@ -448,21 +487,24 @@ double haltCheckTimeWindow minMovementPerSecond: minMovementPerSecond, haltCheckTimeWindow: haltCheckTimeWindow ) - ) { + ) + { shouldHalt = true; // IdleAllStates(); 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) { + else if (distanceTransformedSoFar >= currentAgentMoveParams.distance) + { shouldHalt = true; // IdleAllStates(); Debug.Log("halt due to distance reached/exceeded"); return shouldHalt; } //hard check for time limit - else if (currentAgentMoveParams.timePassed >= currentAgentMoveParams.maxTimePassed) { + else if (currentAgentMoveParams.timePassed >= currentAgentMoveParams.maxTimePassed) + { shouldHalt = true; // IdleAllStates(); Debug.Log("halt from timeout"); @@ -478,18 +520,22 @@ public static bool ApproximatelyNoChange( List timeDeltas, double minMovementPerSecond, double haltCheckTimeWindow - ) { + ) + { double totalTime = 0f; double totalDistanceTraveled = 0f; - for (int i = positionDeltas.Count - 1; i >= 0; i--) { + for (int i = positionDeltas.Count - 1; i >= 0; i--) + { totalTime += timeDeltas[i]; totalDistanceTraveled += Mathf.Abs((float)positionDeltas[i]); - if (totalTime >= haltCheckTimeWindow) { + if (totalTime >= haltCheckTimeWindow) + { break; } } - if (totalTime < haltCheckTimeWindow) { + if (totalTime < haltCheckTimeWindow) + { // Not enough time recorded to make a decision return false; } @@ -497,9 +543,11 @@ double haltCheckTimeWindow 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; @@ -507,7 +555,8 @@ void SetCenterOfMass(Vector3 worldCenterOfMass) { } } - private bool IsFingerTransformCorrect() { + private bool IsFingerTransformCorrect() + { var eps = 0.1; var diff = fingersAB.localPosition - fingersInitialOffset; return diff.magnitude <= eps; diff --git a/unity/Assets/Scripts/ArticulatedArmController.cs b/unity/Assets/Scripts/ArticulatedArmController.cs index cba4dbc10f..a760935460 100644 --- a/unity/Assets/Scripts/ArticulatedArmController.cs +++ b/unity/Assets/Scripts/ArticulatedArmController.cs @@ -5,7 +5,8 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public partial class ArticulatedArmController : ArmController { +public partial class ArticulatedArmController : ArmController +{ public ArticulatedArmJointSolver[] joints; [SerializeField] @@ -27,48 +28,58 @@ public partial class ArticulatedArmController : ArmController { 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() { + public override Transform pickupParent() + { return magnetSphere.transform; } - public override Vector3 wristSpaceOffsetToWorldPos(Vector3 offset) { + public override Vector3 wristSpaceOffsetToWorldPos(Vector3 offset) + { return handCameraTransform.TransformPoint(offset) - handCameraTransform.position + WristToManipulator; } - public override Vector3 armBaseSpaceOffsetToWorldPos(Vector3 offset) { + public override Vector3 armBaseSpaceOffsetToWorldPos(Vector3 offset) + { return this.transform.TransformPoint(offset) - this.transform.position; } - public override Vector3 pointToWristSpace(Vector3 point) { + public override Vector3 pointToWristSpace(Vector3 point) + { return handCameraTransform.TransformPoint(point) + WristToManipulator; } - public override Vector3 pointToArmBaseSpace(Vector3 point) { + public override Vector3 pointToArmBaseSpace(Vector3 point) + { return armBase.transform.TransformPoint(point); } - public override void ContinuousUpdate(float fixedDeltaTime) { + public override void ContinuousUpdate(float fixedDeltaTime) + { //so assume each joint that needs to move has had its `currentArmMoveParams` set //now we call `ControlJointFromAction` on all joints each physics update to get it to move... //Debug.Log("starting ArticulatedArmController.manipulateArm"); - foreach (ArticulatedArmJointSolver j in joints) { + foreach (ArticulatedArmJointSolver j in joints) + { j.ControlJointFromAction(fixedDeltaTime); } } - public override bool ShouldHalt() { + public override bool ShouldHalt() + { //Debug.Log("checking ArticulatedArmController shouldHalt"); bool shouldHalt = false; - foreach (ArticulatedArmJointSolver j in joints) { + foreach (ArticulatedArmJointSolver j in joints) + { //only halt if all joints report back that shouldHalt = true //joints that are idle and not moving will return shouldHalt = true by default //Debug.Log($"checking joint: {j.transform.name}"); //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.currentArmMoveParams != null) + { if ( !j.shouldHalt( distanceTransformedSoFar: j.distanceTransformedSoFar, @@ -77,14 +88,16 @@ public override bool ShouldHalt() { 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; @@ -96,14 +109,16 @@ public override bool ShouldHalt() { return shouldHalt; } - public override ActionFinished FinishContinuousMove(BaseFPSAgentController controller) { + public override ActionFinished FinishContinuousMove(BaseFPSAgentController controller) + { Debug.Log("starting continuousMoveFinishAB"); string debugMessage = "I guess everything is fine?"; // TODO inherit both solvers from common code // bool actionSuccess = IsFingerTransformCorrect(); bool actionSuccess = true; - if (!actionSuccess) { + if (!actionSuccess) + { controller.agentManager.SetCriticalErrorState(); } @@ -115,11 +130,13 @@ public override ActionFinished FinishContinuousMove(BaseFPSAgentController contr return new ActionFinished { success = actionSuccess, errorMessage = debugMessage }; } - public override GameObject GetArmTarget() { + public override GameObject GetArmTarget() + { return armTarget.gameObject; } - void Start() { + void Start() + { wristPlaceholderForwardOffset = wristPlaceholderTransform.transform.localPosition.z; agentCapsuleCollider = PhysicsController.GetComponent(); //Debug.Log($"wrist offset is: {wristPlaceholderForwardOffset}"); @@ -142,7 +159,8 @@ public override IEnumerator moveArmRelative( bool returnToStart, string coordinateSpace, bool restrictTargetPosition - ) { + ) + { yield return new ActionFinished() { success = false, errorMessage = "Not implemented" }; //not doing this one yet soooo uhhhhh ignore for now } @@ -153,7 +171,8 @@ public IEnumerator moveArmTarget( float unitsPerSecond, float fixedDeltaTime, bool useLimits = false - ) { + ) + { float minMovementPerSecond = 1e-3f; float maxTimePassed = 10.0f; float haltCheckTimeWindow = 0.2f; @@ -168,17 +187,20 @@ public IEnumerator moveArmTarget( int direction = 0; //this is sort of a wonky way to detect direction but it'll work for noooooow - if (target.z < 0) { + if (target.z < 0) + { direction = -1; } - if (target.z > 0) { + if (target.z > 0) + { direction = 1; } Dictionary jointToArmDistanceRatios = new Dictionary(); - ArmMoveParams amp = new ArmMoveParams { + ArmMoveParams amp = new ArmMoveParams + { distance = distance, speed = unitsPerSecond, minMovementPerSecond = minMovementPerSecond, @@ -204,15 +226,18 @@ public IEnumerator moveArmTarget( public float GetDriveUpperLimit( ArticulatedArmJointSolver joint, JointAxisType jointAxisType = JointAxisType.Extend - ) { + ) + { float upperLimit = 0.0f; - if (jointAxisType == JointAxisType.Extend) { + if (jointAxisType == JointAxisType.Extend) + { //z drive upperLimit = joint.myAB.zDrive.upperLimit; } - if (jointAxisType == JointAxisType.Lift) { + if (jointAxisType == JointAxisType.Lift) + { //y drive upperLimit = joint.myAB.yDrive.upperLimit; } @@ -230,21 +255,25 @@ public IEnumerator moveArmBase( bool returnToStartPositionIfFailed, bool normalizedY, bool useLimits - ) { + ) + { Debug.Log("starting moveArmBase in ArticulatedArmController"); float minMovementPerSecond = 1e-3f; float maxTimePassed = 10.0f; float haltCheckTimeWindow = 0.2f; int direction = 0; - if (distance < 0) { + if (distance < 0) + { direction = -1; } - if (distance > 0) { + if (distance > 0) + { direction = 1; } - ArmMoveParams amp = new ArmMoveParams { + ArmMoveParams amp = new ArmMoveParams + { distance = Mathf.Abs(distance), speed = unitsPerSecond, minMovementPerSecond = minMovementPerSecond, @@ -279,7 +308,8 @@ public IEnumerator moveArmBaseUp( float fixedDeltaTime, bool returnToStartPositionIfFailed, bool useLimits - ) { + ) + { return moveArmBase( controller: controller, distance: distance, @@ -294,7 +324,8 @@ bool useLimits private void prepAllTheThingsBeforeJointMoves( ArticulatedArmJointSolver joint, ArmMoveParams armMoveParams - ) { + ) + { //FloorCollider.material = sticky; joint.PrepToControlJointFromAction(armMoveParams); } @@ -305,21 +336,25 @@ public IEnumerator rotateWrist( float degreesPerSecond, float fixedDeltaTime, bool returnToStartPositionIfFailed - ) { + ) + { Debug.Log("starting rotateWrist in ArticulatedArmController"); float minMovementPerSecond = 1f * Mathf.Deg2Rad; float maxTimePassed = 10.0f; float haltCheckTimeWindow = 0.2f; int direction = 0; - if (distance < 0) { + if (distance < 0) + { direction = -1; } - if (distance > 0) { + if (distance > 0) + { direction = 1; } - ArmMoveParams amp = new ArmMoveParams { + ArmMoveParams amp = new ArmMoveParams + { distance = Mathf.Abs(distance), speed = degreesPerSecond, minMovementPerSecond = minMovementPerSecond, @@ -343,15 +378,19 @@ bool returnToStartPositionIfFailed ); } - public IEnumerable PickupObject(List objectIds) { + public IEnumerable PickupObject(List objectIds) + { Debug.Log("calling PickupObject from ArticulatedArmController"); bool pickedUp = false; - foreach (SimObjPhysics sop in WhatObjectsAreInsideMagnetSphereAsSOP(onlyPickupable: true)) { + foreach (SimObjPhysics sop in WhatObjectsAreInsideMagnetSphereAsSOP(onlyPickupable: true)) + { Debug.Log($"sop named: {sop.objectID} found inside sphere"); - if (objectIds != null) { + if (objectIds != null) + { //only grab objects specified by objectIds - if (!objectIds.Contains(sop.objectID)) { + if (!objectIds.Contains(sop.objectID)) + { continue; } } @@ -374,7 +413,8 @@ public IEnumerable PickupObject(List objectIds) { heldObjects.Add(sop); } var errorMessage = ""; - if (!pickedUp) { + if (!pickedUp) + { errorMessage = ( objectIds != null ? "No objects (specified by objectId) were valid to be picked up by the arm" @@ -386,8 +426,10 @@ public IEnumerable PickupObject(List objectIds) { } //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 @@ -400,23 +442,28 @@ public override IEnumerator DropObject() { yield return ActionFinished.Success; } - protected override void lastStepCallback() { - foreach (ArticulatedArmJointSolver joint in joints) { + protected override void lastStepCallback() + { + foreach (ArticulatedArmJointSolver joint in joints) + { ArticulationBody myAB = joint.myAB; - if (myAB == null) { + if (myAB == null) + { Debug.LogWarning("Articulated body is null, skipping."); continue; } // Check the joint type and get the current joint position and velocity - if (myAB.jointType == ArticulationJointType.PrismaticJoint) { + 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}"); - if (myAB.dofCount != 1) { + if (myAB.dofCount != 1) + { throw new NotImplementedException( "Prismatic joint must have 1 degree of freedom" ); @@ -430,11 +477,13 @@ protected override void lastStepCallback() { // Super hacky way to get which drive is active string whichDrive = "x"; ArticulationDrive activeDrive = xDrive; - if (yDrive.target != 0.0f) { + if (yDrive.target != 0.0f) + { activeDrive = yDrive; whichDrive = "y"; } - if (zDrive.target != 0.0f) { + if (zDrive.target != 0.0f) + { activeDrive = zDrive; whichDrive = "z"; } @@ -445,18 +494,24 @@ protected override void lastStepCallback() { activeDrive.target = currentPosition; activeDrive.targetVelocity = 0f; - if (whichDrive == "x") { + if (whichDrive == "x") + { myAB.xDrive = activeDrive; } - if (whichDrive == "y") { + if (whichDrive == "y") + { myAB.yDrive = activeDrive; } - if (whichDrive == "z") { + 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) { + if (myAB.dofCount != 1) + { throw new NotImplementedException( "Revolute joint must have 1 degree of freedom" ); @@ -471,21 +526,25 @@ protected override void lastStepCallback() { xDrive.targetVelocity = 0f; myAB.xDrive = xDrive; - } else { + } + else + { throw new NotImplementedException($"Unsupported joint type {myAB.jointType}"); } } } //ignore this, we need new metadata that makes more sense for the articulation heirarchy soooooo - public override ArmMetadata GenerateMetadata() { + public override ArmMetadata GenerateMetadata() + { // TODO: Reimplement, low prio for benchmark ArmMetadata meta = new ArmMetadata(); return meta; } //actual metadata implementation for articulation heirarchy - public ArticulationArmMetadata GenerateArticulationMetadata() { + public ArticulationArmMetadata GenerateArticulationMetadata() + { ArticulationArmMetadata meta = new ArticulationArmMetadata(); List metaJoints = new List(); @@ -495,7 +554,8 @@ public ArticulationArmMetadata GenerateArticulationMetadata() { float angleRot; Vector3 vectorRot; - for (int i = 0; i < joints.Count(); i++) { + for (int i = 0; i < joints.Count(); i++) + { ArticulationJointMetadata jMeta = new ArticulationJointMetadata(); jMeta.name = joints[i].name; @@ -511,10 +571,13 @@ public ArticulationArmMetadata GenerateArticulationMetadata() { currentRotation = joints[i].transform.rotation; // Check that world-relative rotation is angle-axis-notation-compatible - if (currentRotation != new Quaternion(0, 0, 0, -1)) { + if (currentRotation != new Quaternion(0, 0, 0, -1)) + { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); jMeta.rotation = new Vector4(vectorRot.x, vectorRot.y, vectorRot.z, angleRot); - } else { + } + else + { jMeta.rotation = new Vector4(1, 0, 0, 0); } @@ -522,7 +585,8 @@ public ArticulationArmMetadata GenerateArticulationMetadata() { // Grab rotation of current joint's angler relative to root joint currentRotation = Quaternion.Inverse(joints[0].transform.rotation) * joints[i].transform.rotation; - if (currentRotation != new Quaternion(0, 0, 0, -1)) { + if (currentRotation != new Quaternion(0, 0, 0, -1)) + { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); jMeta.rootRelativeRotation = new Vector4( vectorRot.x, @@ -530,20 +594,24 @@ public ArticulationArmMetadata GenerateArticulationMetadata() { vectorRot.z, angleRot ); - } else { + } + else + { jMeta.rootRelativeRotation = new Vector4(1, 0, 0, 0); } // LOCAL POSITION AND LOCAL ROTATION //get local position and local rotation relative to immediate parent in heirarchy - if (i != 0) { + 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)) { + if (currentLocalRotation != new Quaternion(0, 0, 0, -1)) + { currentLocalRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); jMeta.localRotation = new Vector4( vectorRot.x, @@ -551,10 +619,14 @@ public ArticulationArmMetadata GenerateArticulationMetadata() { vectorRot.z, angleRot ); - } else { + } + else + { jMeta.localRotation = new Vector4(1, 0, 0, 0); } - } else { + } + else + { //special case for the lift since its the base of the arm jMeta.localPosition = jMeta.position; jMeta.localRotation = jMeta.rootRelativeRotation; @@ -569,8 +641,10 @@ public ArticulationArmMetadata GenerateArticulationMetadata() { // note this is different from objects intersecting the hand's sphere, // there could be a case where an object is inside the sphere but not picked up by the hand List heldObjectIDs = new List(); - if (heldObjects != null) { - foreach (SimObjPhysics sop in heldObjects) { + if (heldObjects != null) + { + foreach (SimObjPhysics sop in heldObjects) + { heldObjectIDs.Add(sop.objectID); } } @@ -589,7 +663,8 @@ public ArticulationArmMetadata GenerateArticulationMetadata() { } #if UNITY_EDITOR - public class GizmoDrawCapsule { + public class GizmoDrawCapsule + { public Vector3 p0; public Vector3 p1; public float radius; @@ -597,9 +672,12 @@ public class GizmoDrawCapsule { List debugCapsules = new List(); - private void OnDrawGizmos() { - if (debugCapsules.Count > 0) { - foreach (GizmoDrawCapsule thing in debugCapsules) { + private void OnDrawGizmos() + { + if (debugCapsules.Count > 0) + { + foreach (GizmoDrawCapsule thing in debugCapsules) + { Gizmos.DrawWireSphere(thing.p0, thing.radius); Gizmos.DrawWireSphere(thing.p1, thing.radius); } diff --git a/unity/Assets/Scripts/ArticulatedArmExtender.cs b/unity/Assets/Scripts/ArticulatedArmExtender.cs index 12d0607d41..a6e95ebe09 100644 --- a/unity/Assets/Scripts/ArticulatedArmExtender.cs +++ b/unity/Assets/Scripts/ArticulatedArmExtender.cs @@ -3,7 +3,8 @@ using UnityEngine; // Handles collider stretching and arm extension animation -public class ArticulatedArmExtender : MonoBehaviour { +public class ArticulatedArmExtender : MonoBehaviour +{ public Transform arm2, arm3, arm4; @@ -15,16 +16,19 @@ public class ArticulatedArmExtender : MonoBehaviour { public float scaleMultiplier = 1f; - public void Start() { + public void Start() + { initialZPos = this.gameObject.transform.localPosition.z; arm2InitialZPos = arm2.gameObject.transform.localPosition.z; arm3InitialZPos = arm3.gameObject.transform.localPosition.z; arm4InitialZPos = arm4.gameObject.transform.localPosition.z; } - private void scaleColliders() { + private void scaleColliders() + { var currentZPos = this.gameObject.transform.localPosition.z; - foreach (Transform go in myColliders) { + foreach (Transform go in myColliders) + { go.localScale = new Vector3( go.localScale.x, go.localScale.y, @@ -33,7 +37,8 @@ private void scaleColliders() { } } - private void animate(float currentZPos) { + private void animate(float currentZPos) + { //Extend each part of arm by one-quarter of extension length, in local z-direction, also adds offset from origin of arm_1 to each arm position float armExtensionLength = currentZPos - initialZPos; arm2.localPosition = new Vector3(0, 0, 1 * (armExtensionLength / 4) + arm2InitialZPos); //+ 0.01300028f); @@ -43,11 +48,13 @@ private void animate(float currentZPos) { } //should this be in fixed update???? - public void FixedUpdate() { + public void FixedUpdate() + { Extend(); } - public void Extend() { + public void Extend() + { scaleColliders(); var currentZPos = this.gameObject.transform.localPosition.z; animate(currentZPos); diff --git a/unity/Assets/Scripts/ArticulatedArmJointSolver.cs b/unity/Assets/Scripts/ArticulatedArmJointSolver.cs index e3b21e10ec..e3a5ab4200 100644 --- a/unity/Assets/Scripts/ArticulatedArmJointSolver.cs +++ b/unity/Assets/Scripts/ArticulatedArmJointSolver.cs @@ -4,39 +4,45 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public enum ArmLiftState { +public enum ArmLiftState +{ Idle = 0, MovingDown = -1, MovingUp = 1 }; -public enum ArmExtendState { +public enum ArmExtendState +{ Idle = 0, MovingBackward = -1, MovingForward = 1 }; -public enum ArmRotateState { +public enum ArmRotateState +{ Idle = 0, Negative = -1, Positive = 1 }; -public enum JointAxisType { +public enum JointAxisType +{ Unassigned, Extend, Lift, Rotate }; -public class ArmMoveParams : ABAgentPhysicsParams { +public class ArmMoveParams : ABAgentPhysicsParams +{ public ArticulatedAgentController controller; public bool useLimits; public ArticulatedArmExtender armExtender; public float initialJointPosition; } -public class ArticulatedArmJointSolver : MonoBehaviour { +public class ArticulatedArmJointSolver : MonoBehaviour +{ [Header("What kind of joint is this?")] public JointAxisType jointAxisType = JointAxisType.Unassigned; @@ -65,13 +71,16 @@ public class ArticulatedArmJointSolver : MonoBehaviour { public float lowerArmExtendLimit = 0.0f; public float upperArmExtendLimit = 0.516f; - void Start() { + void Start() + { myAB = this.GetComponent(); } - public void PrepToControlJointFromAction(ArmMoveParams armMoveParams) { + public void PrepToControlJointFromAction(ArmMoveParams armMoveParams) + { Debug.Log($"preparing joint {this.transform.name} to move"); - if (Mathf.Approximately(armMoveParams.distance, 0.0f)) { + if (Mathf.Approximately(armMoveParams.distance, 0.0f)) + { Debug.Log("Error! distance to move must be nonzero"); return; } @@ -91,47 +100,65 @@ public void PrepToControlJointFromAction(ArmMoveParams armMoveParams) { prevStepTransformation = myAB.jointPosition[0]; //we are a lift type joint, moving along the local y axis - if (jointAxisType == JointAxisType.Lift) { - if (liftState == ArmLiftState.Idle) { + 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) { + if (armMoveParams.direction < 0) + { Debug.Log("setting lift state to move down"); liftState = ArmLiftState.MovingDown; - } else if (armMoveParams.direction > 0) { + } + else if (armMoveParams.direction > 0) + { Debug.Log("setting lift state to move up"); liftState = ArmLiftState.MovingUp; } } } //we are an extending joint, moving along the local z axis - else if (jointAxisType == JointAxisType.Extend) { - if (extendState == ArmExtendState.Idle) { + else if (jointAxisType == JointAxisType.Extend) + { + if (extendState == ArmExtendState.Idle) + { currentArmMoveParams.armExtender = this.GetComponent(); //currentArmMoveParams.armExtender.Init(); //set if we are extending or retracting - if (armMoveParams.direction < 0) { + if (armMoveParams.direction < 0) + { extendState = ArmExtendState.MovingBackward; - } else if (armMoveParams.direction > 0) { + } + else if (armMoveParams.direction > 0) + { extendState = ArmExtendState.MovingForward; } } //we are a rotating joint, rotating around the local y axis - } else if (jointAxisType == JointAxisType.Rotate) { - if (rotateState == ArmRotateState.Idle) { + } + else if (jointAxisType == JointAxisType.Rotate) + { + if (rotateState == ArmRotateState.Idle) + { //set if we are rotating left or right - if (armMoveParams.direction < 0) { + if (armMoveParams.direction < 0) + { rotateState = ArmRotateState.Negative; - } else if (armMoveParams.direction > 0) { + } + else if (armMoveParams.direction > 0) + { rotateState = ArmRotateState.Positive; } } } } - public void ControlJointFromAction(float fixedDeltaTime) { - if (currentArmMoveParams == null) { + public void ControlJointFromAction(float fixedDeltaTime) + { + if (currentArmMoveParams == null) + { return; } @@ -139,9 +166,11 @@ public void ControlJointFromAction(float fixedDeltaTime) { // Debug.Log($"Type: {jointAxisType.ToString()} pos"); //we are a lift type joint - if (jointAxisType == JointAxisType.Lift) { + if (jointAxisType == JointAxisType.Lift) + { //if instead we are moving up or down actively - if (liftState != ArmLiftState.Idle) { + if (liftState != ArmLiftState.Idle) + { //Debug.Log("start ControlJointFromAction for axis type LIFT"); var drive = myAB.yDrive; float currentPosition = myAB.jointPosition[0]; @@ -164,7 +193,8 @@ public void ControlJointFromAction(float fixedDeltaTime) { // Store current values for comparing with next FixedUpdate prevStepTransformation = currentPosition; - if (currentArmMoveParams.useLimits) { + if (currentArmMoveParams.useLimits) + { Debug.Log("extending/retracting arm with limits"); float distanceRemaining = currentArmMoveParams.distance - distanceTransformedSoFar; @@ -178,13 +208,16 @@ public void ControlJointFromAction(float fixedDeltaTime) { targetPosition = currentPosition + direction * distanceRemaining; float offset = 1e-2f; - if (liftState == ArmLiftState.MovingUp) { + if (liftState == ArmLiftState.MovingUp) + { drive.upperLimit = Mathf.Min(upperArmBaseLimit, targetPosition + offset); drive.lowerLimit = Mathf.Min( Mathf.Max(lowerArmBaseLimit, currentPosition), targetPosition ); - } else if (liftState == ArmLiftState.MovingDown) { + } + else if (liftState == ArmLiftState.MovingDown) + { drive.lowerLimit = Mathf.Max(lowerArmBaseLimit, targetPosition); drive.upperLimit = Mathf.Max( Mathf.Min(upperArmBaseLimit, currentPosition + offset), @@ -216,10 +249,13 @@ public void ControlJointFromAction(float fixedDeltaTime) { drive.target = targetPosition; - if (willReachTargetSoon) { + if (willReachTargetSoon) + { drive.stiffness = 10000f; drive.targetVelocity = -direction * (distanceRemaining / slowDownTime); - } else { + } + else + { drive.stiffness = 0f; drive.targetVelocity = -direction * currentArmMoveParams.speed; } @@ -246,8 +282,10 @@ 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 - else if (jointAxisType == JointAxisType.Extend) { - if (extendState != ArmExtendState.Idle) { + else if (jointAxisType == JointAxisType.Extend) + { + if (extendState != ArmExtendState.Idle) + { //Debug.Log("start ControlJointFromAction for axis type EXTEND"); var drive = myAB.zDrive; float currentPosition = myAB.jointPosition[0]; @@ -264,7 +302,8 @@ public void ControlJointFromAction(float fixedDeltaTime) { // Store current values for comparing with next FixedUpdate prevStepTransformation = currentPosition; - if (!currentArmMoveParams.useLimits) { + if (!currentArmMoveParams.useLimits) + { float targetPosition = currentPosition + (float)extendState * fixedDeltaTime * currentArmMoveParams.speed; @@ -273,7 +312,9 @@ public void ControlJointFromAction(float fixedDeltaTime) { Debug.Log($"currentPosition: {currentPosition}"); Debug.Log($"targetPosition: {targetPosition}"); - } else { + } + else + { float distanceRemaining = currentArmMoveParams.distance - distanceTransformedSoFar; Debug.Log("DISTANCE REMAINING: " + distanceRemaining); @@ -286,13 +327,16 @@ public void ControlJointFromAction(float fixedDeltaTime) { float targetPosition = currentPosition + direction * distanceRemaining; float offset = 1e-2f; - if (extendState == ArmExtendState.MovingForward) { + if (extendState == ArmExtendState.MovingForward) + { drive.upperLimit = Mathf.Min(upperArmExtendLimit, targetPosition + offset); drive.lowerLimit = Mathf.Min( Mathf.Max(lowerArmExtendLimit, currentPosition), targetPosition ); - } else if (extendState == ArmExtendState.MovingBackward) { + } + else if (extendState == ArmExtendState.MovingBackward) + { drive.lowerLimit = Mathf.Max(lowerArmExtendLimit, targetPosition); drive.upperLimit = Mathf.Max( Mathf.Min(upperArmExtendLimit, currentPosition + offset), @@ -324,10 +368,13 @@ public void ControlJointFromAction(float fixedDeltaTime) { drive.target = targetPosition; - if (willReachTargetSoon) { + if (willReachTargetSoon) + { drive.stiffness = 100000f; drive.targetVelocity = -direction * (distanceRemaining / slowDownTime); - } else { + } + else + { drive.stiffness = 0f; Debug.Log($"stiffness should be 0 but it is: {drive.stiffness}"); drive.targetVelocity = -direction * currentArmMoveParams.speed; @@ -356,8 +403,10 @@ public void ControlJointFromAction(float fixedDeltaTime) { } } //if we are a revolute joint - else if (jointAxisType == JointAxisType.Rotate) { - if (rotateState != ArmRotateState.Idle) { + else if (jointAxisType == JointAxisType.Rotate) + { + if (rotateState != ArmRotateState.Idle) + { //seems like revolute joints always only have an xDrive, and to change where its rotating //you just rotate the anchor itself, but always access the xDrive var drive = myAB.xDrive; @@ -404,17 +453,21 @@ public bool shouldHalt( List cachedFixedTimeDeltas, double minMovementPerSecond, double haltCheckTimeWindow - ) { + ) + { //if we are already in an idle, state, immeidately return true - if (jointAxisType == JointAxisType.Lift && liftState == ArmLiftState.Idle) { + if (jointAxisType == JointAxisType.Lift && liftState == ArmLiftState.Idle) + { return true; } - if (jointAxisType == JointAxisType.Extend && extendState == ArmExtendState.Idle) { + if (jointAxisType == JointAxisType.Extend && extendState == ArmExtendState.Idle) + { return true; } - if (jointAxisType == JointAxisType.Rotate && rotateState == ArmRotateState.Idle) { + if (jointAxisType == JointAxisType.Rotate && rotateState == ArmRotateState.Idle) + { return true; } @@ -428,21 +481,24 @@ double haltCheckTimeWindow minMovementPerSecond: minMovementPerSecond, haltCheckTimeWindow: haltCheckTimeWindow ) - ) { + ) + { shouldHalt = true; IdleAllStates(); Debug.Log("halt due to position delta within tolerance"); return shouldHalt; } //check if the amount moved/rotated exceeds this joints target - else if (distanceTransformedSoFar >= currentArmMoveParams.distance) { + else if (distanceTransformedSoFar >= currentArmMoveParams.distance) + { shouldHalt = true; IdleAllStates(); Debug.Log("halt due to distance reached/exceeded"); return shouldHalt; } //hard check for time limit - else if (currentArmMoveParams.timePassed >= currentArmMoveParams.maxTimePassed) { + else if (currentArmMoveParams.timePassed >= currentArmMoveParams.maxTimePassed) + { shouldHalt = true; IdleAllStates(); Debug.Log("halt from timeout"); @@ -452,14 +508,18 @@ double haltCheckTimeWindow return shouldHalt; } - private void IdleAllStates() { - if (jointAxisType == JointAxisType.Lift) { + 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; } diff --git a/unity/Assets/Scripts/BaseAgentComponent.cs b/unity/Assets/Scripts/BaseAgentComponent.cs index 2c86c1bd6f..9e292e6e21 100644 --- a/unity/Assets/Scripts/BaseAgentComponent.cs +++ b/unity/Assets/Scripts/BaseAgentComponent.cs @@ -1,9 +1,11 @@ using System.Collections.Generic; using UnityEngine; -namespace UnityStandardAssets.Characters.FirstPerson { +namespace UnityStandardAssets.Characters.FirstPerson +{ [RequireComponent(typeof(CharacterController))] - public class BaseAgentComponent : MonoBehaviour { + public class BaseAgentComponent : MonoBehaviour + { // debug draw bounds of objects in editor #if UNITY_EDITOR protected List gizmobounds = new List(); @@ -36,8 +38,10 @@ public class BaseAgentComponent : MonoBehaviour { public DroneObjectLauncher DroneObjectLauncher; - void LateUpdate() { - if (this.agent == null) { + void LateUpdate() + { + if (this.agent == null) + { return; } @@ -55,44 +59,54 @@ void LateUpdate() { #endif } - void FixedUpdate() { - if (this.agent != null) { + void FixedUpdate() + { + if (this.agent != null) + { 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) { - if (this.agent == null) { + protected void OnControllerColliderHit(ControllerColliderHit hit) + { + if (this.agent == null) + { return; } - if (hit.gameObject.GetComponent()) { + if (hit.gameObject.GetComponent()) + { if ( hit.gameObject.GetComponent().WhatIsMyStructureObjectTag == StructureObjectTag.Floor - ) { + ) + { return; } } - if (!this.agent.collisionsInAction.Contains(hit.gameObject.name)) { + if (!this.agent.collisionsInAction.Contains(hit.gameObject.name)) + { this.agent.collisionsInAction.Add(hit.gameObject.name); } Rigidbody body = hit.collider.attachedRigidbody; // don't move the rigidbody if the character is on top of it - if (this.agent.m_CollisionFlags == CollisionFlags.Below) { + if (this.agent.m_CollisionFlags == CollisionFlags.Below) + { return; } - if (body == null || body.isKinematic) { + if (body == null || body.isKinematic) + { return; } // push objects out of the way if moving through them and they are Moveable or CanPickup (Physics) - if (this.agent.PushMode) { + if (this.agent.PushMode) + { float pushPower = 2.0f; Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z); body.velocity = pushDir * pushPower; diff --git a/unity/Assets/Scripts/BaseFPSAgentController.cs b/unity/Assets/Scripts/BaseFPSAgentController.cs index e691c093c9..48e04bd1ea 100644 --- a/unity/Assets/Scripts/BaseFPSAgentController.cs +++ b/unity/Assets/Scripts/BaseFPSAgentController.cs @@ -24,114 +24,141 @@ using UnityStandardAssets.Utility; using Random = UnityEngine.Random; -namespace UnityStandardAssets.Characters.FirstPerson { - public abstract class BaseFPSAgentController : ActionInvokable { +namespace UnityStandardAssets.Characters.FirstPerson +{ + public abstract class BaseFPSAgentController : ActionInvokable + { // debug draw bounds of objects in editor #if UNITY_EDITOR protected List gizmobounds = new List(); #endif public BaseAgentComponent baseAgentComponent; - public Transform transform { + public Transform transform + { get => this.baseAgentComponent.transform; } - public GameObject gameObject { + public GameObject gameObject + { get => this.baseAgentComponent.gameObject; } - public Coroutine StartCoroutine(IEnumerator routine) { + public Coroutine StartCoroutine(IEnumerator routine) + { return this.baseAgentComponent.StartCoroutine(routine); } public SimObjPhysics[] VisibleSimObjPhysics; - public GameObject AgentCamera { + public GameObject AgentCamera + { get => this.baseAgentComponent.AgentCamera; } - public GameObject AgentHand { + public GameObject AgentHand + { get => this.baseAgentComponent.AgentHand; } - protected GameObject DefaultHandPosition { + protected GameObject DefaultHandPosition + { get => this.baseAgentComponent.DefaultHandPosition; } - protected Transform rotPoint { + protected Transform rotPoint + { get => this.baseAgentComponent.rotPoint; } - protected GameObject DebugPointPrefab { + protected GameObject DebugPointPrefab + { get => this.baseAgentComponent.DebugPointPrefab; } - protected GameObject GridRenderer { + protected GameObject GridRenderer + { get => this.baseAgentComponent.GridRenderer; } - protected GameObject DebugTargetPointPrefab { + protected GameObject DebugTargetPointPrefab + { get => this.baseAgentComponent.DebugPointPrefab; } - public GameObject VisibilityCapsule { + public GameObject VisibilityCapsule + { get => this.baseAgentComponent.VisibilityCapsule; set => this.baseAgentComponent.VisibilityCapsule = value; } - public GameObject TallVisCap { + public GameObject TallVisCap + { get => this.baseAgentComponent.TallVisCap; } - public GameObject BotVisCap { + public GameObject BotVisCap + { get => this.baseAgentComponent.BotVisCap; } - public GameObject StretchVisCap { + public GameObject StretchVisCap + { get => this.baseAgentComponent.StretchVisCap; } - public GameObject StretchArm { + public GameObject StretchArm + { get => this.baseAgentComponent.StretchArm; } - public GameObject DroneVisCap { + public GameObject DroneVisCap + { get => this.baseAgentComponent.DroneVisCap; } - public DroneObjectLauncher DroneObjectLauncher { + public DroneObjectLauncher DroneObjectLauncher + { get => this.baseAgentComponent.DroneObjectLauncher; } - public GameObject DroneBasket { + public GameObject DroneBasket + { get => this.baseAgentComponent.DroneBasket; } - public GameObject IKArm { + public GameObject IKArm + { get => this.baseAgentComponent.IKArm; } // reference to prefab for activiting the cracked camera effect via CameraCrack() - public GameObject CrackedCameraCanvas { + public GameObject CrackedCameraCanvas + { get => this.baseAgentComponent.CrackedCameraCanvas; } - public GameObject[] ToSetActive { + public GameObject[] ToSetActive + { get => this.baseAgentComponent.ToSetActive; } - public Material[] ScreenFaces { + public Material[] ScreenFaces + { get => this.baseAgentComponent.ScreenFaces; } - public MeshRenderer MyFaceMesh { + public MeshRenderer MyFaceMesh + { get => this.baseAgentComponent.MyFaceMesh; } - public GameObject[] TargetCircles { + public GameObject[] TargetCircles + { get => this.baseAgentComponent.TargetCircles; } - public GameObject[] GripperOpennessStates { + public GameObject[] GripperOpennessStates + { get => this.baseAgentComponent.GripperOpennessStates; } @@ -165,11 +192,15 @@ public GameObject[] GripperOpennessStates { protected bool continuousMode; // deprecated, use snapToGrid instead public ImageSynthesis imageSynthesis; - public ImageSynthesis ImageSynthesis { - get { - if (this.imageSynthesis == null) { + public ImageSynthesis ImageSynthesis + { + get + { + if (this.imageSynthesis == null) + { imageSynthesis = this.m_Camera.gameObject.GetComponent(); - if (imageSynthesis == null) { + if (imageSynthesis == null) + { throw new NullReferenceException( $"ImageSynthesis component is null or disabled in `{this.m_Camera.gameObject.name}` Gameobject." ); @@ -177,7 +208,9 @@ public ImageSynthesis ImageSynthesis { imageSynthesis.enabled = true; return imageSynthesis; - } else { + } + else + { return imageSynthesis; } } @@ -219,7 +252,8 @@ public ImageSynthesis ImageSynthesis { public BaseFPSAgentController( BaseAgentComponent baseAgentComponent, AgentManager agentManager - ) { + ) + { this.baseAgentComponent = baseAgentComponent; this.baseAgentComponent.agent = this; this.agentManager = agentManager; @@ -241,16 +275,21 @@ AgentManager agentManager // 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()) { + if (this.GetComponentInChildren()) + { this.GetComponentInChildren().enabled = false; } // Recording initially disabled renderers and scene bounds // then setting up sceneBounds based on encapsulating all renderers - foreach (Renderer r in GameObject.FindObjectsOfType()) { - if (!r.enabled) { + foreach (Renderer r in GameObject.FindObjectsOfType()) + { + if (!r.enabled) + { initiallyDisabledRenderers.Add(r.GetInstanceID()); - } else { + } + else + { agentManager.SceneBounds.Encapsulate(r.bounds); } } @@ -258,7 +297,8 @@ AgentManager agentManager // On start, activate gravity Vector3 movement = Vector3.zero; movement.y = Physics.gravity.y * m_GravityMultiplier; - if (this.gameObject.name != "ArticulatedFPSController") { + if (this.gameObject.name != "ArticulatedFPSController") + { m_CharacterController.Move(movement); } @@ -268,43 +308,52 @@ AgentManager agentManager #endif } - void Start() { + void Start() + { Debug.Log("------------- BASE FPS Start"); } // callback triggered by BaseAgentComponent public virtual void FixedUpdate() { } - public bool IsVisible { + public bool IsVisible + { get { return isVisible; } - set { + set + { // first default all Vis capsules of all modes to not enabled HideAllAgentRenderers(); // The VisibilityCapsule will be set to either Tall or Bot // from the InitializeBody call in BaseFPSAgentController's Initialize() - foreach (Renderer r in VisibilityCapsule.GetComponentsInChildren()) { + foreach (Renderer r in VisibilityCapsule.GetComponentsInChildren()) + { r.enabled = value; } isVisible = value; } } - public bool IsProcessing { + public bool IsProcessing + { get { return this.agentState == AgentState.Processing; } } // convenciance function that can be called // when autoSyncTransforms is disabled and the // transform has been manually moved - public void autoSyncTransforms() { - if (!Physics.autoSyncTransforms) { + public void autoSyncTransforms() + { + if (!Physics.autoSyncTransforms) + { Physics.SyncTransforms(); } } - public bool ReadyForCommand { - get { + public bool ReadyForCommand + { + get + { return this.agentState == AgentState.Emit || this.agentState == AgentState.ActionComplete; } @@ -381,9 +430,12 @@ public Quaternion TargetRotation private PhysicsSceneManager _physicsSceneManager = null; // use as reference to the PhysicsSceneManager object - protected PhysicsSceneManager physicsSceneManager { - get { - if (_physicsSceneManager == null) { + protected PhysicsSceneManager physicsSceneManager + { + get + { + if (_physicsSceneManager == null) + { _physicsSceneManager = GameObject .Find("PhysicsSceneManager") .GetComponent(); @@ -392,38 +444,49 @@ protected PhysicsSceneManager physicsSceneManager { } } - public void DeleteMe() { + public void DeleteMe() + { actionFinished(success: true, actionReturn: "called in build!"); } // defaults all agent renderers, from all modes (tall, bot, drone), to hidden for initialization default - protected void HideAllAgentRenderers() { + protected void HideAllAgentRenderers() + { if ( TallVisCap != null && BotVisCap != null && DroneVisCap != null && StretchVisCap != null - ) { - foreach (Renderer r in TallVisCap.GetComponentsInChildren()) { - if (r.enabled) { + ) + { + foreach (Renderer r in TallVisCap.GetComponentsInChildren()) + { + if (r.enabled) + { r.enabled = false; } } - foreach (Renderer r in BotVisCap.GetComponentsInChildren()) { - if (r.enabled) { + foreach (Renderer r in BotVisCap.GetComponentsInChildren()) + { + if (r.enabled) + { r.enabled = false; } } - foreach (Renderer r in DroneVisCap.GetComponentsInChildren()) { - if (r.enabled) { + foreach (Renderer r in DroneVisCap.GetComponentsInChildren()) + { + if (r.enabled) + { r.enabled = false; } } - foreach (Renderer r in StretchVisCap.GetComponentsInChildren()) { - if (r.enabled) { + foreach (Renderer r in StretchVisCap.GetComponentsInChildren()) + { + if (r.enabled) + { r.enabled = false; } } @@ -434,8 +497,10 @@ public void actionFinishedEmit( bool success, object actionReturn = null, string errorMessage = null - ) { - if (errorMessage != null) { + ) + { + if (errorMessage != null) + { this.errorMessage = errorMessage; } actionFinished(success: success, newState: AgentState.Emit, actionReturn: actionReturn); @@ -445,8 +510,10 @@ protected virtual void actionFinished( bool success, AgentState newState, object actionReturn = null - ) { - if (!this.IsProcessing) { + ) + { + if (!this.IsProcessing) + { Debug.LogError("ActionFinished called with agentState not in processing "); } @@ -454,7 +521,8 @@ protected virtual void actionFinished( (!Physics.autoSyncTransforms) && lastActionInitialPhysicsSimulateCount == PhysicsSceneManager.PhysicsSimulateCallCount - ) { + ) + { Physics.SyncTransforms(); } @@ -468,20 +536,26 @@ protected virtual void actionFinished( Debug.Log($"lastAction: '{this.lastAction}'"); Debug.Log($"lastActionSuccess: '{success}'"); Debug.Log($"actionReturn: '{actionReturn}'"); - if (!success) { + if (!success) + { Debug.Log($"Action failed with error message '{this.errorMessage}'."); - } else if (actionReturn != null) { + } + else if (actionReturn != null) + { Debug.Log($"actionReturn: '{actionReturn}'"); } #endif } - public virtual void Complete(ActionFinished result) { + 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. - if (!result.isDummy) { - if (result.errorMessage != null) { + if (!result.isDummy) + { + if (result.errorMessage != null) + { this.errorMessage = result.errorMessage; } this.errorCode = result.errorCode; @@ -498,8 +572,10 @@ public virtual void actionFinished( bool success, object actionReturn = null, string errorMessage = null - ) { - if (errorMessage != null) { + ) + { + if (errorMessage != null) + { this.errorMessage = errorMessage; } actionFinished( @@ -512,9 +588,11 @@ public virtual void actionFinished( protected virtual void resumePhysics() { } - protected virtual CapsuleData GetAgentCapsule() { + protected virtual CapsuleData GetAgentCapsule() + { var cc = GetComponent(); - return new CapsuleData { + return new CapsuleData + { radius = cc.radius, height = cc.height, center = cc.center, @@ -530,7 +608,8 @@ public Vector3[] getReachablePositions( float gridWidth = 0.045f, bool directionsRelativeAgent = false, float? gridSize = null - ) { // max step count represents a 100m * 100m room. Adjust this value later if we end up making bigger rooms? + ) + { // max step count represents a 100m * 100m room. Adjust this value later if we end up making bigger rooms? CapsuleData capsule = GetAgentCapsule(); // Debug.Log($"Capsule collider: {cc.radius}, height {cc.height}, innerheight: {cc.height / 2.0f - cc.radius;} startpos: {transform.position + cc.transform.TransformDirection(cc.center)}"); @@ -540,7 +619,8 @@ public Vector3[] getReachablePositions( $"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) { + if (!gridSize.HasValue) + { gridSize = BaseFPSAgentController.gridSize; } // TODO: skin width for ab @@ -551,10 +631,13 @@ public Vector3[] getReachablePositions( Vector3 right; Vector3 forward; - if (directionsRelativeAgent) { + if (directionsRelativeAgent) + { right = transform.right; forward = transform.forward; - } else { + } + else + { right = new Vector3(1.0f, 0.0f, 0.0f); forward = new Vector3(0.0f, 0.0f, 1.0f); } @@ -571,7 +654,8 @@ public Vector3[] getReachablePositions( "Procedural0" ); int stepsTaken = 0; - while (rightForwardQueue.Count != 0) { + while (rightForwardQueue.Count != 0) + { stepsTaken += 1; // Computing the new position based using an offset from the startPosition @@ -583,13 +667,15 @@ public Vector3[] getReachablePositions( + gridSize.Value * gridMultiplier * (right * rightForward.Item1 + forward * rightForward.Item2); - if (!goodPoints.Contains(p)) { + if (!goodPoints.Contains(p)) + { goodPoints.Add(p); HashSet objectsAlreadyColliding = new HashSet( objectsCollidingWithAgent() ); - foreach ((int, int) rightForwardOffset in rightForwardOffsets) { + foreach ((int, int) rightForwardOffset in rightForwardOffsets) + { (int, int) newRightForward = ( rightForward.Item1 + rightForwardOffset.Item1, rightForward.Item2 + rightForwardOffset.Item2 @@ -599,7 +685,8 @@ public Vector3[] getReachablePositions( + gridSize.Value * gridMultiplier * (right * newRightForward.Item1 + forward * newRightForward.Item2); - if (seenRightForwards.Contains(newRightForward)) { + if (seenRightForwards.Contains(newRightForward)) + { continue; } seenRightForwards.Add(newRightForward); @@ -615,23 +702,27 @@ public Vector3[] getReachablePositions( ); bool shouldEnqueue = true; - foreach (RaycastHit hit in hits) { + foreach (RaycastHit hit in hits) + { if ( !ancestorHasName(hit.transform.gameObject, "Floor") && !ancestorHasName(hit.transform.gameObject, "FPSController") && !objectsAlreadyColliding.Contains(hit.collider) - ) { + ) + { shouldEnqueue = false; break; } } - if (!shouldEnqueue) { + if (!shouldEnqueue) + { continue; } bool inBounds = agentManager.SceneBounds.Contains(newPosition); - if (shouldEnqueue && !inBounds) { + if (shouldEnqueue && !inBounds) + { throw new InvalidOperationException( "In " + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name @@ -650,16 +741,19 @@ public Vector3[] getReachablePositions( || handObjectCanFitInPosition(newPosition, 180.0f) || handObjectCanFitInPosition(newPosition, 270.0f) ); - if (shouldEnqueue) { + if (shouldEnqueue) + { rightForwardQueue.Enqueue(newRightForward); - if (visualize) { + if (visualize) + { var gridRenderer = Instantiate(GridRenderer, Vector3.zero, Quaternion.identity) as GameObject; var gridLineRenderer = gridRenderer.GetComponentInChildren(); - if (gridColor.HasValue) { + if (gridColor.HasValue) + { gridLineRenderer.startColor = gridColor.Value; gridLineRenderer.endColor = gridColor.Value; } @@ -684,7 +778,8 @@ public Vector3[] getReachablePositions( } } // default maxStepCount to scale based on gridSize - if (stepsTaken > Math.Floor(maxStepCount / (gridSize.Value * gridSize.Value))) { + if (stepsTaken > Math.Floor(maxStepCount / (gridSize.Value * gridSize.Value))) + { throw new InvalidOperationException( "Too many steps taken in GetReachablePositions." ); @@ -713,15 +808,19 @@ public void GetReachablePositions( int? maxStepCount = null, bool directionsRelativeAgent = false, float? gridSize = null - ) { + ) + { Vector3[] reachablePositions; - if (maxStepCount.HasValue) { + if (maxStepCount.HasValue) + { reachablePositions = getReachablePositions( maxStepCount: maxStepCount.Value, directionsRelativeAgent: directionsRelativeAgent, gridSize: gridSize ); - } else { + } + else + { reachablePositions = getReachablePositions( directionsRelativeAgent: directionsRelativeAgent, gridSize: gridSize @@ -733,7 +832,8 @@ public void GetReachablePositions( 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 @@ -741,27 +841,36 @@ protected bool ValidRotateStepDegreesWithSnapToGrid(float rotateDegrees) { || (rotateDegrees % 360.0f) == 0.0f; } - public void Initialize(ServerAction action) { + 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 - if (Mathf.Approximately(action.maxUpwardLookAngle, 0.0f)) { + if (Mathf.Approximately(action.maxUpwardLookAngle, 0.0f)) + { this.maxUpwardLookAngle = 30f; - } else { + } + else + { this.maxUpwardLookAngle = action.maxUpwardLookAngle; } - if (Mathf.Approximately(action.maxDownwardLookAngle, 0.0f)) { + if (Mathf.Approximately(action.maxDownwardLookAngle, 0.0f)) + { this.maxDownwardLookAngle = 60f; - } else { + } + else + { this.maxDownwardLookAngle = action.maxDownwardLookAngle; } - if (action.agentMode != "fpin") { + if (action.agentMode != "fpin") + { this.InitializeBody(action); } - if (action.antiAliasing != null) { + if (action.antiAliasing != null) + { agentManager.updateAntiAliasing( postProcessLayer: m_Camera.gameObject.GetComponentInChildren(), antiAliasing: action.antiAliasing @@ -771,40 +880,51 @@ public void Initialize(ServerAction action) { .GetComponent() .SwitchRenderersToHide(this.VisibilityCapsule); - if (action.gridSize == 0) { + if (action.gridSize == 0) + { action.gridSize = 0.25f; } // note: this overrides the default FOV values set in InitializeBody() - if (action.fieldOfView > 0 && action.fieldOfView < 180) { + if (action.fieldOfView > 0 && action.fieldOfView < 180) + { m_Camera.fieldOfView = action.fieldOfView; - } else if (action.fieldOfView < 0 || action.fieldOfView >= 180) { + } + else if (action.fieldOfView < 0 || action.fieldOfView >= 180) + { errorMessage = "fov must be set to (0, 180) noninclusive."; Debug.Log(errorMessage); actionFinished(false); return; } - if (action.cameraNearPlane > 0) { + if (action.cameraNearPlane > 0) + { m_Camera.nearClipPlane = action.cameraNearPlane; } - if (action.cameraFarPlane > 0) { + if (action.cameraFarPlane > 0) + { m_Camera.farClipPlane = action.cameraFarPlane; } - if (action.timeScale > 0) { - if (Time.timeScale != action.timeScale) { + if (action.timeScale > 0) + { + if (Time.timeScale != action.timeScale) + { Time.timeScale = action.timeScale; } - } else { + } + else + { errorMessage = "Time scale must be > 0"; Debug.Log(errorMessage); actionFinished(false); return; } - if (action.rotateStepDegrees <= 0.0) { + if (action.rotateStepDegrees <= 0.0) + { errorMessage = "rotateStepDegrees must be a non-zero, non-negative float"; Debug.Log(errorMessage); actionFinished(false); @@ -812,13 +932,15 @@ public void Initialize(ServerAction action) { } // default is 90 defined in the ServerAction class, specify whatever you want the default to be - if (action.rotateStepDegrees > 0.0) { + if (action.rotateStepDegrees > 0.0) + { 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."; Debug.Log(errorMessage); @@ -826,14 +948,16 @@ public void Initialize(ServerAction action) { 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); @@ -847,18 +971,21 @@ public void Initialize(ServerAction action) { || action.renderSemanticSegmentation || action.renderInstanceSegmentation || action.renderNormalsImage - ) { + ) + { this.updateImageSynthesis(true); } - if (action.visibilityDistance > 0.0f) { + if (action.visibilityDistance > 0.0f) + { this.maxVisibleDistance = action.visibilityDistance; } var navmeshAgent = this.GetComponentInChildren(); var collider = this.GetComponent(); - if (collider != null && navmeshAgent != null) { + if (collider != null && navmeshAgent != null) + { navmeshAgent.radius = collider.radius; navmeshAgent.height = collider.height; navmeshAgent.transform.localPosition = new Vector3( @@ -870,12 +997,15 @@ public void Initialize(ServerAction action) { // navmeshAgent.radius = - if (action.gridSize <= 0 || action.gridSize > 5) { + if (action.gridSize <= 0 || action.gridSize > 5) + { errorMessage = "grid size must be in the range (0,5]"; Debug.Log(errorMessage); actionFinished(false); return; - } else { + } + else + { gridSize = action.gridSize; StartCoroutine(checkInitializeAgentLocationAction()); } @@ -888,12 +1018,14 @@ public void Initialize(ServerAction action) { 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( @@ -910,10 +1042,12 @@ KeyValuePair entry in action // Debug.Log("True if physics is auto-simulating: " + Physics.autoSimulation); } - public IEnumerator checkInitializeAgentLocationAction() { + public IEnumerator checkInitializeAgentLocationAction() + { yield return null; - if (agentManager.agentMode != "stretchab") { + if (agentManager.agentMode != "stretchab") + { Vector3 startingPosition = this.transform.position; // move ahead // move back @@ -929,8 +1063,10 @@ public IEnumerator checkInitializeAgentLocationAction() { float[] xs = new float[] { grid_x1, grid_x1 + gridSize }; float[] zs = new float[] { grid_z1, grid_z1 + gridSize }; List validMovements = new List(); - foreach (float x in xs) { - foreach (float z in zs) { + foreach (float x in xs) + { + foreach (float z in zs) + { this.transform.position = startingPosition; autoSyncTransforms(); @@ -941,21 +1077,25 @@ public IEnumerator checkInitializeAgentLocationAction() { 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); - if (movement.magnitude > dir.magnitude) { + if (movement.magnitude > dir.magnitude) + { movement = dir; } // 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") { + 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++) { + 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)) { + if ((Math.Abs(diff.x) < 0.005) && (Math.Abs(diff.z) < 0.005)) + { validMovements.Add(movement); break; } @@ -967,7 +1107,8 @@ public IEnumerator checkInitializeAgentLocationAction() { autoSyncTransforms(); yield return null; - if (validMovements.Count > 0) { + 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); @@ -981,20 +1122,26 @@ public IEnumerator checkInitializeAgentLocationAction() { actionFinished( true, - new InitializeReturn { + new InitializeReturn + { cameraNearPlane = m_Camera.nearClipPlane, cameraFarPlane = m_Camera.farClipPlane } ); - } else { + } + else + { // Debug.Log("Initialize: no valid starting positions found"); actionFinished(false); } - } else { + } + else + { yield return null; actionFinished( true, - new InitializeReturn { + new InitializeReturn + { cameraNearPlane = m_Camera.nearClipPlane, cameraFarPlane = m_Camera.farClipPlane } @@ -1006,11 +1153,13 @@ public IEnumerator checkInitializeAgentLocationAction() { message: "This action is deprecated. Call RandomizeColors instead.", error: false )] - public void ChangeColorOfMaterials() { + public void ChangeColorOfMaterials() + { RandomizeColors(); } - public void RandomizeColors() { + public void RandomizeColors() + { ColorChanger colorChangeComponent = physicsSceneManager.GetComponent(); colorChangeComponent.RandomizeColor(); agentManager.doResetMaterials = true; @@ -1018,7 +1167,8 @@ public void RandomizeColors() { } // returns a dict of object types and all cached materials used in the Material Randomizer logic - public void GetMaterials() { + public void GetMaterials() + { ColorChanger colorChangeComponent = physicsSceneManager.GetComponent(); actionFinishedEmit(true, colorChangeComponent.GetMaterials()); } @@ -1036,7 +1186,8 @@ public void RandomizeMaterials( bool? useExternalMaterials = null, string[] inRoomTypes = null, List excludedObjectIds = null - ) { + ) + { string scene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; HashSet validRoomTypes = new HashSet() { @@ -1048,13 +1199,17 @@ public void RandomizeMaterials( }; HashSet chosenRoomTypes = new HashSet(); - if (inRoomTypes != null) { - if (inRoomTypes.Length == 0) { + if (inRoomTypes != null) + { + if (inRoomTypes.Length == 0) + { throw new ArgumentException("inRoomTypes must have a non-zero length!"); } - foreach (string roomType in inRoomTypes) { - if (!validRoomTypes.Contains(roomType.ToLower())) { + 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\"}" @@ -1065,7 +1220,8 @@ public void RandomizeMaterials( } } - if ((!scene.StartsWith("Procedural")) && excludedObjectIds != null) { + if ((!scene.StartsWith("Procedural")) && excludedObjectIds != null) + { // The reason for the error below is that we need to be sure that every // object contains references to its own materials. This is not // necessarily the case in some ithor scenes because some objects @@ -1076,21 +1232,26 @@ public void RandomizeMaterials( ); } - if (excludedObjectIds == null) { + if (excludedObjectIds == null) + { excludedObjectIds = new List(); } HashSet excludedMaterialNames = new HashSet(); - foreach (string objectId in excludedObjectIds) { + foreach (string objectId in excludedObjectIds) + { Debug.Log($"Exclude materials from {objectId}"); SimObjPhysics objectWhoseMaterialsToExclude = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; foreach ( var renderer in objectWhoseMaterialsToExclude.GetComponentsInChildren() - ) { - foreach (var mat in renderer.sharedMaterials) { - if (mat != null && mat.name != null) { + ) + { + foreach (var mat in renderer.sharedMaterials) + { + if (mat != null && mat.name != null) + { Debug.Log($"excluding {mat.name}"); excludedMaterialNames.Add(mat.name); } @@ -1099,7 +1260,8 @@ var renderer in objectWhoseMaterialsToExclude.GetComponentsInChildren( } ColorChanger colorChangeComponent; - if (scene.StartsWith("Procedural")) { + if (scene.StartsWith("Procedural")) + { colorChangeComponent = physicsSceneManager.GetComponent(); colorChangeComponent.RandomizeMaterials( useTrainMaterials: useTrainMaterials.HasValue ? useTrainMaterials.Value : true, @@ -1120,7 +1282,8 @@ var renderer in objectWhoseMaterialsToExclude.GetComponentsInChildren( } string sceneType; - if (scene.EndsWith("_physics")) { + if (scene.EndsWith("_physics")) + { // iTHOR scene int sceneNumber = Int32.Parse( @@ -1138,7 +1301,8 @@ var renderer in objectWhoseMaterialsToExclude.GetComponentsInChildren( ) ) / 100; - if (inRoomTypes != null) { + if (inRoomTypes != null) + { string sceneGroupName = new string[] { "kitchen", @@ -1146,24 +1310,33 @@ var renderer in objectWhoseMaterialsToExclude.GetComponentsInChildren( "bedroom", "bathroom" }[Math.Max(sceneGroup - 1, 0)]; - if (!chosenRoomTypes.Contains(sceneGroupName)) { + if (!chosenRoomTypes.Contains(sceneGroupName)) + { throw new ArgumentException( $"inRoomTypes must include \"{sceneGroupName}\" inside of a {sceneGroupName} scene: {scene}." ); } } - if (sceneNumber >= 1 && sceneNumber <= 20) { + if (sceneNumber >= 1 && sceneNumber <= 20) + { sceneType = "train"; - } else if (sceneNumber <= 25) { + } + else if (sceneNumber <= 25) + { sceneType = "val"; - } else { + } + else + { sceneType = "test"; } - } else { + } + else + { // RoboTHOR scene string chars = scene.Substring(startIndex: "FloorPlan_".Length, length: 2); - switch (chars) { + switch (chars) + { case "Tr": sceneType = "train"; break; @@ -1178,8 +1351,10 @@ var renderer in objectWhoseMaterialsToExclude.GetComponentsInChildren( $"Unknown scene name: {scene}. Please open an issue on allenai/ai2thor." ); } - if (inRoomTypes != null) { - if (!chosenRoomTypes.Contains("robothor")) { + if (inRoomTypes != null) + { + if (!chosenRoomTypes.Contains("robothor")) + { throw new ArgumentException( $"inRoomTypes must include \"RoboTHOR\" inside of a RoboTHOR scene: {scene}." ); @@ -1187,9 +1362,11 @@ var renderer in objectWhoseMaterialsToExclude.GetComponentsInChildren( } } - switch (sceneType) { + switch (sceneType) + { case "train": - if (useTrainMaterials.GetValueOrDefault(true) == false) { + if (useTrainMaterials.GetValueOrDefault(true) == false) + { throw new ArgumentException( "Inside of RandomizeMaterials, cannot set useTrainMaterials=false inside of a train scene." ); @@ -1200,7 +1377,8 @@ var renderer in objectWhoseMaterialsToExclude.GetComponentsInChildren( useExternalMaterials = useExternalMaterials.GetValueOrDefault(true); break; case "val": - if (useValMaterials.GetValueOrDefault(true) == false) { + if (useValMaterials.GetValueOrDefault(true) == false) + { throw new ArgumentException( "Inside of RandomizeMaterials, cannot set useValMaterials=false inside of a val scene." ); @@ -1211,7 +1389,8 @@ var renderer in objectWhoseMaterialsToExclude.GetComponentsInChildren( useExternalMaterials = useExternalMaterials.GetValueOrDefault(false); break; case "test": - if (useTestMaterials.GetValueOrDefault(true) == false) { + if (useTestMaterials.GetValueOrDefault(true) == false) + { throw new ArgumentException( "Inside of RandomizeMaterials, cannot set useTestMaterials=false inside of a test scene." ); @@ -1242,7 +1421,8 @@ var renderer in objectWhoseMaterialsToExclude.GetComponentsInChildren( actionFinished( success: true, - actionReturn: new Dictionary() { + actionReturn: new Dictionary() + { ["chosenRoomTypes"] = chosenRoomTypes.Count == 0 ? validRoomTypes : chosenRoomTypes, ["useTrainMaterials"] = useTrainMaterials.Value, @@ -1254,12 +1434,14 @@ var renderer in objectWhoseMaterialsToExclude.GetComponentsInChildren( ); } - public void ResetMaterials() { + public void ResetMaterials() + { agentManager.resetMaterials(); actionFinished(true); } - public void ResetColors() { + public void ResetColors() + { agentManager.resetColors(); actionFinished(true); } @@ -1296,56 +1478,69 @@ public void RandomizeLighting( bool randomizeColor = true, float[] hue = null, float[] saturation = null - ) { - if (!randomizeColor && (hue != null || saturation != null)) { - if (hue != null) { + ) + { + if (!randomizeColor && (hue != null || saturation != null)) + { + if (hue != null) + { throw new ArgumentException( $"Cannot pass in randomizeColor=False while also providing hue={hue}." ); } - if (saturation != null) { + if (saturation != null) + { throw new ArgumentException( $"Cannot pass in randomizeColor=False while also providing saturation={saturation}." ); } } - if (brightness == null) { + if (brightness == null) + { brightness = new float[] { 0.5f, 1.5f }; } - if (brightness[0] < 0 || brightness[1] < 0) { + if (brightness[0] < 0 || brightness[1] < 0) + { throw new ArgumentOutOfRangeException( $"Each brightness must be >= 0, not brightness={brightness}." ); } - if (hue == null) { + if (hue == null) + { hue = new float[] { 0, 1 }; } - if (saturation == null) { + if (saturation == null) + { saturation = new float[] { 0.5f, 1 }; } - if (saturation.Length != 2 || hue.Length != 2 || brightness.Length != 2) { + 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}." ); } - if (hue[0] < 0 || hue[0] > 1 || hue[1] < 0 || hue[1] > 1) { + if (hue[0] < 0 || hue[0] > 1 || hue[1] < 0 || hue[1] > 1) + { 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) { + 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}" ); } - float newRandomFloat() { + float newRandomFloat() + { return Random.Range(brightness[0], brightness[1]); } - Color newRandomColor() { + Color newRandomColor() + { // NOTE: This function weirdly IGNORES out of bounds arguments. // So, they are checked above. // NOTE: value is an extraneous degree of freedom here, @@ -1365,20 +1560,25 @@ Color newRandomColor() { Color randomColor = newRandomColor(); bool setOriginalMultipliers = originalLightingValues == null; - if (setOriginalMultipliers) { + if (setOriginalMultipliers) + { originalLightingValues = new Dictionary>(); } // include both lights and reflection probes Light[] lights = GameObject.FindObjectsOfType(); - foreach (Light light in lights) { - if (!synchronized) { + foreach (Light light in lights) + { + if (!synchronized) + { intensityMultiplier = newRandomFloat(); randomColor = newRandomColor(); } int id = light.gameObject.GetInstanceID(); - if (setOriginalMultipliers) { - originalLightingValues[id] = new Dictionary() { + if (setOriginalMultipliers) + { + originalLightingValues[id] = new Dictionary() + { // NOTE: make sure these are synced with ResetLighting()! ["intensity"] = light.intensity, ["range"] = light.range, @@ -1388,20 +1588,25 @@ Color newRandomColor() { light.intensity = (float)originalLightingValues[id]["intensity"] * intensityMultiplier; light.range = (float)originalLightingValues[id]["range"] * intensityMultiplier; - if (randomizeColor) { + if (randomizeColor) + { light.color = randomColor; } } ReflectionProbe[] reflectionProbes = GameObject.FindObjectsOfType(); - foreach (ReflectionProbe reflectionProbe in reflectionProbes) { - if (!synchronized) { + foreach (ReflectionProbe reflectionProbe in reflectionProbes) + { + if (!synchronized) + { intensityMultiplier = newRandomFloat(); } int id = reflectionProbe.gameObject.GetInstanceID(); - if (setOriginalMultipliers) { + if (setOriginalMultipliers) + { // NOTE: make sure these are synced with ResetLighting()! - originalLightingValues[id] = new Dictionary() { + originalLightingValues[id] = new Dictionary() + { ["intensity"] = reflectionProbe.intensity, ["blendDistance"] = reflectionProbe.intensity }; @@ -1417,14 +1622,17 @@ Color newRandomColor() { actionFinished(success: true); } - public void ResetLighting() { - if (originalLightingValues == null) { + public void ResetLighting() + { + if (originalLightingValues == null) + { actionFinishedEmit(success: true); return; } Light[] lights = GameObject.FindObjectsOfType(); - foreach (Light light in lights) { + foreach (Light light in lights) + { int id = light.gameObject.GetInstanceID(); light.intensity = (float)originalLightingValues[id]["intensity"]; light.range = (float)originalLightingValues[id]["range"]; @@ -1432,7 +1640,8 @@ public void ResetLighting() { } ReflectionProbe[] reflectionProbes = GameObject.FindObjectsOfType(); - foreach (ReflectionProbe reflectionProbe in reflectionProbes) { + foreach (ReflectionProbe reflectionProbe in reflectionProbes) + { int id = reflectionProbe.gameObject.GetInstanceID(); reflectionProbe.intensity = (float)originalLightingValues[id]["intensity"]; reflectionProbe.blendDistance = (float)originalLightingValues[id]["blendDistance"]; @@ -1455,16 +1664,19 @@ protected bool moveInDirection( bool forceAction = false, bool manualInteract = false, 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) - ) { + ) + { // only default hand if not manually interacting with things - if (!manualInteract) { + if (!manualInteract) + { DefaultAgentHand(); } @@ -1472,14 +1684,17 @@ protected bool moveInDirection( transform.position = targetPosition; this.snapAgentToGrid(); - if (objectId != "" && maxDistanceToObject > 0.0f) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + if (objectId != "" && maxDistanceToObject > 0.0f) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = "No object with ID " + objectId; transform.position = oldPosition; return false; } SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; - if (distanceToObject(sop) > maxDistanceToObject) { + if (distanceToObject(sop) > maxDistanceToObject) + { errorMessage = "Agent movement would bring it beyond the max distance of " + objectId; transform.position = oldPosition; @@ -1487,18 +1702,23 @@ protected bool moveInDirection( } } return true; - } else { + } + else + { return false; } } - public void MoveGlobal(float x, float z) { + public void MoveGlobal(float x, float z) + { actionFinished(moveInDirection(direction: new Vector3(x, 0f, z))); } - protected float distanceToObject(SimObjPhysics sop) { + protected float distanceToObject(SimObjPhysics sop) + { float dist = 10000.0f; - foreach (Collider c in sop.GetComponentsInChildren()) { + foreach (Collider c in sop.GetComponentsInChildren()) + { Vector3 closestPoint = c.ClosestPointOnBounds(transform.position); Vector3 p0 = new Vector3(transform.position.x, 0f, transform.position.z); Vector3 p1 = new Vector3(closestPoint.x, 0f, closestPoint.z); @@ -1507,7 +1727,8 @@ protected float distanceToObject(SimObjPhysics sop) { return dist; } - public void DistanceToObject(string objectId) { + public void DistanceToObject(string objectId) + { float dist = distanceToObject(physicsSceneManager.ObjectIdToSimObjPhysics[objectId]); #if UNITY_EDITOR Debug.Log(dist); @@ -1519,7 +1740,8 @@ public bool CheckIfAgentCanMove( Vector3 offset, HashSet ignoreColliders = null, bool ignoreAgentColliders = true - ) { + ) + { RaycastHit[] sweepResults = capsuleCastAllForAgent( GetAgentCapsule(), m_CharacterController.skinWidth, @@ -1536,33 +1758,41 @@ public bool CheckIfAgentCanMove( ) ); - if (ignoreColliders == null) { + if (ignoreColliders == null) + { ignoreColliders = new HashSet(); } // Make sure to ignore all of the colliders of the agent itself - if (ignoreAgentColliders) { - foreach (Collider c in GetComponentsInChildren()) { + if (ignoreAgentColliders) + { + foreach (Collider c in GetComponentsInChildren()) + { ignoreColliders.Add(c); } } // check if we hit an environmental structure or a sim object that we aren't actively holding. If so we can't move - if (sweepResults.Length > 0) { - foreach (RaycastHit res in sweepResults) { - if (ignoreColliders != null && ignoreColliders.Contains(res.collider)) { + if (sweepResults.Length > 0) + { + foreach (RaycastHit res in sweepResults) + { + if (ignoreColliders != null && ignoreColliders.Contains(res.collider)) + { continue; } // Don't worry if we hit something thats in our hand. - if (ItemInHand != null && ItemInHand.transform == res.transform) { + if (ItemInHand != null && ItemInHand.transform == res.transform) + { continue; } if ( res.transform.gameObject != this.gameObject && res.transform.GetComponent() - ) { + ) + { BaseAgentComponent maybeOtherAgent = res.transform.GetComponent(); int thisAgentNum = agentManager.agents.IndexOf(this); @@ -1580,7 +1810,8 @@ public bool CheckIfAgentCanMove( || 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")}."; @@ -1594,25 +1825,33 @@ public bool CheckIfAgentCanMove( //TODO: May need to track enabled/disabled objecst separately since some //actions loop through the ObjectIdTOSimObjPhysics dict and this may have adverse effects - public void DisableObject(string objectId) { - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void DisableObject(string objectId) + { + if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { physicsSceneManager.ObjectIdToSimObjPhysics[objectId].gameObject.SetActive(false); actionFinished(true); - } else { + } + else + { actionFinished(false); } } //TODO: May need to track enabled/disabled objecst separately since some //actions loop through the ObjectIdTOSimObjPhysics dict and this may have adverse effects - public void DisableAllObjectsOfType(ServerAction action) { + public void DisableAllObjectsOfType(ServerAction action) + { string type = action.objectType; - if (type == "") { + if (type == "") + { type = action.objectId; } - foreach (SimObjPhysics so in GameObject.FindObjectsOfType()) { - if (Enum.GetName(typeof(SimObjType), so.Type) == type) { + foreach (SimObjPhysics so in GameObject.FindObjectsOfType()) + { + if (Enum.GetName(typeof(SimObjType), so.Type) == type) + { so.gameObject.SetActive(false); } } @@ -1621,17 +1860,22 @@ public void DisableAllObjectsOfType(ServerAction action) { //TODO: May need to track enabled/disabled objecst separately since some //actions loop through the ObjectIdTOSimObjPhysics dict and this may have adverse effects - public void EnableObject(string objectId) { - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void EnableObject(string objectId) + { + if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { physicsSceneManager.ObjectIdToSimObjPhysics[objectId].gameObject.SetActive(true); actionFinished(true); - } else { + } + else + { actionFinished(false); } } // remove a given sim object from the scene. Pass in the object's objectID string to remove it. - public void RemoveFromScene(string objectId) { + public void RemoveFromScene(string objectId) + { SimObjPhysics sop = getSimObjectFromId(objectId: objectId); Destroy(sop.transform.gameObject); physicsSceneManager.SetupScene(generateObjectIds: false); @@ -1642,23 +1886,28 @@ public void RemoveFromScene(string objectId) { message: "This action is deprecated. Call RemoveFromScene instead.", error: false )] - public void RemoveObjsFromScene(string[] objectIds) { + public void RemoveObjsFromScene(string[] objectIds) + { RemoveFromScene(objectIds: objectIds); } // remove a list of given sim object from the scene. - public void RemoveFromScene(string[] objectIds) { - if (objectIds == null || objectIds.Length == 0) { + public void RemoveFromScene(string[] objectIds) + { + if (objectIds == null || objectIds.Length == 0) + { actionFinished(success: false, errorMessage: "objectIds must not be empty!"); } // make sure all objectIds are valid before destorying any GameObject[] gameObjects = new GameObject[objectIds.Length]; - for (int i = 0; i < objectIds.Length; i++) { + for (int i = 0; i < objectIds.Length; i++) + { GameObject go = getSimObjectFromId(objectId: objectIds[i]).transform.gameObject; gameObjects[i] = go; } - foreach (GameObject go in gameObjects) { + foreach (GameObject go in gameObjects) + { Destroy(go); } physicsSceneManager.SetupScene(generateObjectIds: false); @@ -1666,18 +1915,23 @@ public void RemoveFromScene(string[] objectIds) { } // Sweeptest to see if the object Agent is holding will prohibit movement - public bool CheckIfItemBlocksAgentMovement(Vector3 offset, bool forceAction = false) { + public bool CheckIfItemBlocksAgentMovement(Vector3 offset, bool forceAction = false) + { bool result = false; // if forceAction true, ignore collision restrictions caused by held objects - if (forceAction) { + if (forceAction) + { return true; } // if there is nothing in our hand, we are good, return! - if (ItemInHand == null) { + if (ItemInHand == null) + { // Debug.Log("Agent has nothing in hand blocking movement"); return true; - } else { + } + else + { // otherwise we are holding an object and need to do a sweep using that object's rb Rigidbody rb = ItemInHand.GetComponent(); @@ -1687,13 +1941,18 @@ public bool CheckIfItemBlocksAgentMovement(Vector3 offset, bool forceAction = fa offset.magnitude, QueryTriggerInteraction.Ignore ); - if (sweepResults.Length > 0) { - foreach (RaycastHit res in sweepResults) { + if (sweepResults.Length > 0) + { + foreach (RaycastHit res in sweepResults) + { // did the item in the hand touch the agent? if so, ignore it's fine - if (res.transform.tag == "Player") { + if (res.transform.tag == "Player") + { result = true; break; - } else { + } + else + { errorMessage = $"{res.transform.name} is blocking the Agent from moving by {offset.ToString("F4")} with {ItemInHand.name}"; result = false; @@ -1702,7 +1961,8 @@ public bool CheckIfItemBlocksAgentMovement(Vector3 offset, bool forceAction = fa } } // if the array is empty, nothing was hit by the sweeptest so we are clear to move - else { + else + { // Debug.Log("Agent Body can move " + orientation); result = true; } @@ -1711,11 +1971,15 @@ public bool CheckIfItemBlocksAgentMovement(Vector3 offset, bool forceAction = fa } } - protected bool checkIfSceneBoundsContainTargetPosition(Vector3 position) { - if (!agentManager.SceneBounds.Contains(position)) { + protected bool checkIfSceneBoundsContainTargetPosition(Vector3 position) + { + if (!agentManager.SceneBounds.Contains(position)) + { errorMessage = "Scene bounds do not contain target position: " + position; return false; - } else { + } + else + { return true; } } @@ -1724,16 +1988,20 @@ protected bool checkIfSceneBoundsContainTargetPosition(Vector3 position) { // during initialization and reduces the chance of an object held by the // arm from moving a large mass object. This also eliminates the chance // of a large mass object moving vs. relying on the CollisionListener to prevent it. - public void MakeObjectsStaticKinematicMassThreshold() { - foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) { + 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 this object is actively hung on its corresponding object specific receptacle... skip it so it doesn't fall on the floor - if (sop.GetComponentInParent()) { + ) + { + // 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; } } @@ -1741,7 +2009,8 @@ public void MakeObjectsStaticKinematicMassThreshold() { if ( CollisionListener.useMassThreshold && sop.Mass > CollisionListener.massThreshold - ) { + ) + { Rigidbody rb = sop.GetComponent(); rb.isKinematic = true; sop.PrimaryProperty = SimObjPrimaryProperty.Static; @@ -1756,13 +2025,16 @@ public void MakeObjectsStaticKinematicMassThreshold() { // use this by initializing the scene, then calling randomize if desired, and then call this action to prepare the scene so all objects will react to others upon collision. // note that SOMETIMES rigidbodies will continue to jitter or wiggle, especially if they are stacked against other rigidbodies. // this means that the isSceneAtRest bool will always be false - public void MakeAllObjectsMoveable() { + public void MakeAllObjectsMoveable() + { physicsSceneManager.MakeAllObjectsMoveable(); actionFinished(true); } - public void MakeAllObjectsStationary() { - foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) { + public void MakeAllObjectsStationary() + { + foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) + { Rigidbody rb = sop.GetComponent(); rb.isKinematic = true; @@ -1777,21 +2049,25 @@ public void MakeAllObjectsStationary() { // this does not appear to be used except for by the python unit test? // May deprecate this at some point? - public void RotateLook(ServerAction response) { + 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 - protected virtual void RotateView() { + protected virtual void RotateView() + { // turn up & down - if (Mathf.Abs(m_XRotation) > Mathf.Epsilon) { + if (Mathf.Abs(m_XRotation) > Mathf.Epsilon) + { transform.Rotate(Vector3.right * m_XRotation, Space.Self); } // turn left & right - if (Mathf.Abs(m_ZRotation) > Mathf.Epsilon) { + if (Mathf.Abs(m_ZRotation) > Mathf.Epsilon) + { transform.Rotate(Vector3.up * m_ZRotation, Space.Self); } @@ -1805,9 +2081,12 @@ protected virtual void RotateView() { // move this out of Unity // constrain vertical turns in safe range float X_SAFE_RANGE = 30.0f; - if (eulerX < 180.0f) { + if (eulerX < 180.0f) + { eulerX = Mathf.Min(X_SAFE_RANGE, eulerX); - } else { + } + else + { eulerX = 360.0f - Mathf.Min(X_SAFE_RANGE, 360.0f - eulerX); } @@ -1832,9 +2111,12 @@ private protected IEnumerator openAnimation( bool freezeContained = false, GameObject posRotManip = null, GameObject posRotRef = null - ) { - if (openableObject == null) { - if (markActionFinished) { + ) + { + if (openableObject == null) + { + if (markActionFinished) + { errorMessage = "Must pass in openable object!"; actionFinished(false); } @@ -1843,11 +2125,13 @@ private protected IEnumerator openAnimation( // stores the object id of each object within this openableObject Dictionary objectIdToOldParent = null; - if (freezeContained) { + if (freezeContained) + { SimObjPhysics target = ancestorSimObjPhysics(openableObject.gameObject); objectIdToOldParent = new Dictionary(); - foreach (string objectId in target.GetAllSimObjectsInReceptacleTriggersByObjectID()) { + foreach (string objectId in target.GetAllSimObjectsInReceptacleTriggersByObjectID()) + { SimObjPhysics toReParent = physicsSceneManager.ObjectIdToSimObjPhysics[ objectId ]; @@ -1880,7 +2164,8 @@ private protected IEnumerator openAnimation( 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) { + if (openableObject.GetFailState() != CanOpen_Object.failState.none) + { succeeded = false; openableObject.SetIsCurrentlyLerping(true); @@ -1895,18 +2180,23 @@ private protected IEnumerator openAnimation( ); yield return new WaitUntil(() => (openableObject.GetIsCurrentlyLerping() == false)); yield return null; - if (openableObject.GetFailState() == CanOpen_Object.failState.collision) { + if (openableObject.GetFailState() == CanOpen_Object.failState.collision) + { errorMessage = "Openable object collided with " + openableObject.GetFailureCollision().name; - } else if (openableObject.GetFailState() == CanOpen_Object.failState.hyperextension) { + } + else if (openableObject.GetFailState() == CanOpen_Object.failState.hyperextension) + { errorMessage = "Agent hyperextended arm while opening object"; } } // stops any object located within this openableObject from moving - if (freezeContained) { - foreach (string objectId in objectIdToOldParent.Keys) { + if (freezeContained) + { + foreach (string objectId in objectIdToOldParent.Keys) + { SimObjPhysics toReParent = physicsSceneManager.ObjectIdToSimObjPhysics[ objectId ]; @@ -1927,11 +2217,13 @@ private protected IEnumerator openAnimation( openableObject.SetStopAtNonStaticCol(false); // Remove PosRotRef from MovingPart - if (posRotRef != null) { + if (posRotRef != null) + { UnityEngine.Object.Destroy(posRotRef); } - if (markActionFinished) { + if (markActionFinished) + { actionFinished(succeeded); } } @@ -1949,40 +2241,50 @@ protected void openObject( float? physicsInterval = null, bool simplifyPhysics = false, float? moveMagnitude = null // moveMagnitude is supported for backwards compatibility. It's new name is 'openness'. - ) { + ) + { // backwards compatibility support - if (moveMagnitude != null) { + if (moveMagnitude != null) + { // Previously, when moveMagnitude==0, that meant full openness, since the default float was 0. openness = ((float)moveMagnitude) == 0 ? 1 : (float)moveMagnitude; } - if (openness > 1 || openness < 0) { + if (openness > 1 || openness < 0) + { errorMessage = "openness must be in [0:1]"; - if (markActionFinished) { + if (markActionFinished) + { actionFinished(false); } return; } - if (target == null) { + if (target == null) + { errorMessage = "Object not found!"; - if (markActionFinished) { + if (markActionFinished) + { actionFinished(false); } return; } - if (!forceAction && !IsInteractable(target)) { + if (!forceAction && !IsInteractable(target)) + { errorMessage = "object is visible but occluded by something: " + target.ObjectID; - if (markActionFinished) { + if (markActionFinished) + { actionFinished(false); } return; } - if (!target.GetComponent()) { + if (!target.GetComponent()) + { errorMessage = $"{target.ObjectID} is not an Openable object"; - if (markActionFinished) { + if (markActionFinished) + { actionFinished(false); } return; @@ -1995,29 +2297,36 @@ protected void openObject( if ( codd.WhatReceptaclesMustBeOffToOpen().Contains(target.Type) && target.GetComponent().isOn - ) { + ) + { errorMessage = "Target must be OFF to open!"; - if (markActionFinished) { + if (markActionFinished) + { actionFinished(false); } return; } - if (useGripper == true) { + if (useGripper == true) + { // Opening objects with the gripper only works with the IK-Arm // (it'd be preferable to reference the agentMode directly, but no such universal metadata exists) - if (this.GetComponent().IKArm.activeInHierarchy == false) { + if (this.GetComponent().IKArm.activeInHierarchy == false) + { errorMessage = "IK-Arm is required to open objects with gripper"; - if (markActionFinished) { + if (markActionFinished) + { actionFinished(false); } return; } // Opening objects with the gripper only works with an empty hand - if (ItemInHand != null) { + if (ItemInHand != null) + { errorMessage = "An empty hand is required to open objects with gripper"; - if (markActionFinished) { + if (markActionFinished) + { actionFinished(false); } return; @@ -2025,10 +2334,12 @@ 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) { + if (parentMovingPart == null) + { errorMessage = "Gripper must be making contact with at least one moving part's surface to open it!"; - if (markActionFinished) { + if (markActionFinished) + { actionFinished(false); } return; @@ -2077,7 +2388,8 @@ protected void openObject( } //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) { + public void OpenObjectImmediate(string objectId, float openness = 1.0f) + { SimObjPhysics target = getInteractableSimObjectFromId( objectId: objectId, forceAction: true @@ -2088,13 +2400,16 @@ public void OpenObjectImmediate(string objectId, float openness = 1.0f) { //helper function to confirm if GripperSphere overlaps with openable object's moving part(s), and which one - public GameObject FindOverlappingMovingPart(CanOpen_Object codd) { + public GameObject FindOverlappingMovingPart(CanOpen_Object codd) + { int layerMask = 1 << 8; GameObject magnetSphere = this.GetComponent() .IKArm.GetComponent() .GetMagnetSphere(); - foreach (GameObject movingPart in codd.GetComponent().MovingParts) { - foreach (Collider col in movingPart.GetComponentsInChildren()) { + foreach (GameObject movingPart in codd.GetComponent().MovingParts) + { + 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( @@ -2104,8 +2419,10 @@ Collider containedCol in Physics.OverlapSphere( magnetSphere.transform.GetComponent().radius, layerMask ) - ) { - if (col == containedCol) { + ) + { + if (col == containedCol) + { return movingPart; } } @@ -2124,7 +2441,8 @@ public void OpenObject( float? physicsInterval = null, bool useGripper = false, float? moveMagnitude = null // moveMagnitude is supported for backwards compatibility. Its new name is 'openness'. - ) { + ) + { SimObjPhysics target = getInteractableSimObjectFromId( objectId: objectId, forceAction: forceAction @@ -2149,7 +2467,8 @@ public void OpenObject( bool forceAction = false, float openness = 1, float? moveMagnitude = null // moveMagnitude is supported for backwards compatibility. It's new name is 'openness'. - ) { + ) + { SimObjPhysics target = getInteractableSimObjectFromXY( x: x, y: y, @@ -2164,14 +2483,16 @@ public void OpenObject( ); } - public void PhysicsSyncTransforms() { + public void PhysicsSyncTransforms() + { Physics.SyncTransforms(); actionFinished(true); } // pause physics autosimulation! Automatic physics simulation can be resumed using the UnpausePhysicsAutoSim() action. // additionally, auto simulation will automatically resume from the LateUpdate() check on AgentManager.cs - if the scene has come to rest, physics autosimulation will resume - public void PausePhysicsAutoSim() { + public void PausePhysicsAutoSim() + { physicsSceneManager.PausePhysicsAutoSim(); actionFinished(true); } @@ -2181,8 +2502,10 @@ public void AdvancePhysicsStep( float timeStep = 0.02f, float? simSeconds = null, bool allowAutoSimulation = false - ) { - if ((!allowAutoSimulation) && Physics.autoSimulation) { + ) + { + 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" @@ -2193,17 +2516,20 @@ public void AdvancePhysicsStep( return; } - if (timeStep <= 0.0f || timeStep > 0.05f) { + if (timeStep <= 0.0f || timeStep > 0.05f) + { errorMessage = "Please use a timeStep between 0.0f and 0.05f. Larger timeSteps produce inconsistent simulation results."; actionFinished(false); return; } - if (!simSeconds.HasValue) { + if (!simSeconds.HasValue) + { simSeconds = timeStep; } - if (simSeconds.Value < 0.0f) { + if (simSeconds.Value < 0.0f) + { errorMessage = $"simSeconds must be non-negative (simSeconds=={simSeconds})."; actionFinished(false); return; @@ -2214,18 +2540,22 @@ public void AdvancePhysicsStep( } // Use this to immediately unpause physics autosimulation and allow physics to resolve automatically like normal - public void UnpausePhysicsAutoSim() { + public void UnpausePhysicsAutoSim() + { physicsSceneManager.UnpausePhysicsAutoSim(); actionFinished(true); } // Check if agent is collided with other objects - protected bool IsCollided() { + protected bool IsCollided() + { return collisionsInAction.Count > 0; } - public bool IsInteractable(SimObjPhysics sop) { - if (sop == null) { + public bool IsInteractable(SimObjPhysics sop) + { + if (sop == null) + { throw new NullReferenceException("null SimObjPhysics passed to IsInteractable"); } @@ -2236,23 +2566,28 @@ public bool IsInteractable(SimObjPhysics sop) { ).Length == 1; } - public virtual SimpleSimObj[] allSceneObjects() { + public virtual SimpleSimObj[] allSceneObjects() + { return GameObject.FindObjectsOfType(); } - public void ResetObjectFilter() { + public void ResetObjectFilter() + { this.simObjFilter = null; // The result of this action should return all the objects. Thus we should NOT // make this return a `actionFinishedEmit` actionFinished(true); } - public void SetObjectFilter(string[] objectIds) { + public void SetObjectFilter(string[] objectIds) + { SimObjPhysics[] simObjects = GameObject.FindObjectsOfType(); HashSet filter = new HashSet(); HashSet filterObjectIds = new HashSet(objectIds); - foreach (var simObj in simObjects) { - if (filterObjectIds.Contains(simObj.ObjectID)) { + foreach (var simObj in simObjects) + { + if (filterObjectIds.Contains(simObj.ObjectID)) + { filter.Add(simObj); } } @@ -2262,12 +2597,15 @@ public void SetObjectFilter(string[] objectIds) { actionFinishedEmit(true); } - public void SetObjectFilterForType(string[] objectTypes) { + public void SetObjectFilterForType(string[] objectTypes) + { SimObjPhysics[] simObjects = GameObject.FindObjectsOfType(); HashSet filter = new HashSet(); HashSet filterObjectTypes = new HashSet(objectTypes); - foreach (var simObj in simObjects) { - if (filterObjectTypes.Contains(Enum.GetName(typeof(SimObjType), simObj.Type))) { + foreach (var simObj in simObjects) + { + if (filterObjectTypes.Contains(Enum.GetName(typeof(SimObjType), simObj.Type))) + { filter.Add(simObj); } } @@ -2277,12 +2615,15 @@ public void SetObjectFilterForType(string[] objectTypes) { actionFinishedEmit(true); } - public ObjectMetadata setReceptacleMetadata(ObjectMetadata meta) { + public ObjectMetadata setReceptacleMetadata(ObjectMetadata meta) + { return meta; } - public virtual ObjectMetadata[] generateObjectMetadata(SimObjPhysics[] simObjects) { - if (simObjects == null) { + public virtual ObjectMetadata[] generateObjectMetadata(SimObjPhysics[] simObjects) + { + if (simObjects == null) + { throw new NullReferenceException( "null SimObjPhysics passed to generateObjectMetadata" ); @@ -2312,32 +2653,39 @@ public virtual ObjectMetadata[] generateObjectMetadata(SimObjPhysics[] simObject gizmobounds.Clear(); #endif - for (int k = 0; k < numObj; k++) { + for (int k = 0; k < numObj; k++) + { SimObjPhysics simObj = simObjects[k]; ObjectMetadata meta = SimObjPhysics.ObjectMetadataFromSimObjPhysics( simObj, visibleSimObjsHash.Contains(simObj), interactableSimObjsHash.Contains(simObj) ); - if (meta.toggleable) { + if (meta.toggleable) + { SimObjPhysics[] controlled = simObj .GetComponent() .ReturnControlledSimObjects(); List controlledList = new List(); - foreach (SimObjPhysics csop in controlled) { + foreach (SimObjPhysics csop in controlled) + { controlledList.Add(csop.objectID); } meta.controlledObjects = controlledList.ToArray(); } - if (meta.receptacle) { + if (meta.receptacle) + { List containedObjectsAsID = new List(); - foreach (GameObject go in simObj.ContainedGameObjects()) { + foreach (GameObject go in simObj.ContainedGameObjects()) + { containedObjectsAsID.Add(go.GetComponent().ObjectID); } List roid = containedObjectsAsID; // simObj.Contains(); - foreach (string oid in roid) { - if (!parentReceptacles.ContainsKey(oid)) { + foreach (string oid in roid) + { + if (!parentReceptacles.ContainsKey(oid)) + { parentReceptacles[oid] = new List(); } parentReceptacles[oid].Add(simObj.ObjectID); @@ -2350,8 +2698,10 @@ public virtual ObjectMetadata[] generateObjectMetadata(SimObjPhysics[] simObject ); metadata.Add(meta); } - foreach (ObjectMetadata meta in metadata) { - if (parentReceptacles.ContainsKey(meta.objectId)) { + foreach (ObjectMetadata meta in metadata) + { + if (parentReceptacles.ContainsKey(meta.objectId)) + { meta.parentReceptacles = parentReceptacles[meta.objectId].ToArray(); } } @@ -2363,7 +2713,8 @@ public virtual ObjectMetadata ObjectMetadataFromSimObjPhysics( SimObjPhysics simObj, bool isVisible, bool isInteractable - ) { + ) + { ObjectMetadata objMeta = new ObjectMetadata(); GameObject o = simObj.gameObject; objMeta.name = o.name; @@ -2373,7 +2724,8 @@ bool isInteractable objMeta.receptacle = simObj.IsReceptacle; objMeta.openable = simObj.IsOpenable; - if (objMeta.openable) { + if (objMeta.openable) + { objMeta.isOpen = simObj.IsOpen; objMeta.openness = simObj.openness; } @@ -2386,28 +2738,33 @@ bool isInteractable simObj.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.CanToggleOnOff ) - ) { + ) + { objMeta.isToggled = simObj.IsToggled; } objMeta.breakable = simObj.IsBreakable; - if (objMeta.breakable) { + if (objMeta.breakable) + { objMeta.isBroken = simObj.IsBroken; } objMeta.canFillWithLiquid = simObj.IsFillable; - if (objMeta.canFillWithLiquid) { + if (objMeta.canFillWithLiquid) + { objMeta.isFilledWithLiquid = simObj.IsFilled; objMeta.fillLiquid = simObj.FillLiquid; } objMeta.dirtyable = simObj.IsDirtyable; - if (objMeta.dirtyable) { + if (objMeta.dirtyable) + { objMeta.isDirty = simObj.IsDirty; } objMeta.cookable = simObj.IsCookable; - if (objMeta.cookable) { + if (objMeta.cookable) + { objMeta.isCooked = simObj.IsCooked; } @@ -2416,12 +2773,14 @@ bool isInteractable 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]; - for (int i = 0; i < simObj.salientMaterials.Length; i++) { + for (int i = 0; i < simObj.salientMaterials.Length; i++) + { salientMaterialsToString[i] = simObj.salientMaterials[i].ToString(); } @@ -2444,12 +2803,14 @@ bool isInteractable // } objMeta.sliceable = simObj.IsSliceable; - if (objMeta.sliceable) { + if (objMeta.sliceable) + { objMeta.isSliced = simObj.IsSliced; } objMeta.canBeUsedUp = simObj.CanBeUsedUp; - if (objMeta.canBeUsedUp) { + if (objMeta.canBeUsedUp) + { objMeta.isUsedUp = simObj.IsUsedUp; } @@ -2484,8 +2845,10 @@ bool isInteractable public virtual MinimalObjectMetadata[] generateMinimalObjectMetadata( SimObjPhysics[] simObjects - ) { - if (simObjects == null) { + ) + { + if (simObjects == null) + { throw new NullReferenceException( "null SimObjPhysics passed to generateObjectMetadata" ); @@ -2494,7 +2857,8 @@ SimObjPhysics[] simObjects int numObj = simObjects.Length; List metadata = new List(); - for (int k = 0; k < numObj; k++) { + for (int k = 0; k < numObj; k++) + { SimObjPhysics simObj = simObjects[k]; MinimalObjectMetadata objMeta = new MinimalObjectMetadata(); @@ -2511,15 +2875,23 @@ SimObjPhysics[] simObjects return metadata.ToArray(); } - public void GetMinimalObjectMetadata(List objectIds = null) { + public void GetMinimalObjectMetadata(List objectIds = null) + { List sops = new List(); - if (objectIds == null) { + if (objectIds == null) + { sops = physicsSceneManager.ObjectIdToSimObjPhysics.Values.ToList(); - } else { - foreach (string objectId in objectIds) { - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + } + else + { + foreach (string objectId in objectIds) + { + if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { sops.Add(physicsSceneManager.ObjectIdToSimObjPhysics[objectId]); - } else { + } + else + { Debug.Log($"Object ID {objectId} not found in scene."); continue; } @@ -2530,15 +2902,23 @@ public void GetMinimalObjectMetadata(List objectIds = null) { actionFinishedEmit(true, objectMetadata); } - public void GetObjectMetadata(List objectIds = null) { + public void GetObjectMetadata(List objectIds = null) + { List sops = new List(); - if (objectIds == null) { + if (objectIds == null) + { sops = physicsSceneManager.ObjectIdToSimObjPhysics.Values.ToList(); - } else { - foreach (string objectId in objectIds) { - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + } + else + { + foreach (string objectId in objectIds) + { + if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { sops.Add(physicsSceneManager.ObjectIdToSimObjPhysics[objectId]); - } else { + } + else + { Debug.Log($"Object ID {objectId} not found in scene."); continue; } @@ -2549,7 +2929,8 @@ public void GetObjectMetadata(List objectIds = null) { actionFinishedEmit(true, objectMetadata); } - public SceneBounds GenerateSceneBounds(Bounds bounding) { + public SceneBounds GenerateSceneBounds(Bounds bounding) + { SceneBounds b = new SceneBounds(); List cornerPoints = new List(); float[] xs = new float[] @@ -2567,9 +2948,12 @@ public SceneBounds GenerateSceneBounds(Bounds bounding) { bounding.center.z + bounding.size.z / 2f, bounding.center.z - bounding.size.z / 2f }; - foreach (float x in xs) { - foreach (float y in ys) { - foreach (float z in zs) { + foreach (float x in xs) + { + foreach (float y in ys) + { + foreach (float z in zs) + { cornerPoints.Add(new float[] { x, y, z }); } } @@ -2582,19 +2966,22 @@ public SceneBounds GenerateSceneBounds(Bounds bounding) { return b; } - public virtual MetadataPatch generateMetadataPatch() { + public virtual MetadataPatch generateMetadataPatch() + { MetadataPatch patch = new MetadataPatch(); patch.lastAction = this.lastAction; patch.lastActionSuccess = this.lastActionSuccess; patch.actionReturn = this.actionReturn; - if (errorCode != ServerActionErrorCode.Undefined) { + if (errorCode != ServerActionErrorCode.Undefined) + { patch.errorCode = Enum.GetName(typeof(ServerActionErrorCode), errorCode); } patch.errorMessage = this.errorMessage; return patch; } - public virtual MetadataWrapper generateMetadataWrapper() { + public virtual MetadataWrapper generateMetadataWrapper() + { // AGENT METADATA AgentMetadata agentMeta = new AgentMetadata(); agentMeta.name = "agent"; @@ -2655,13 +3042,15 @@ public virtual MetadataWrapper generateMetadataWrapper() { metaMessage.errorMessage = errorMessage; metaMessage.actionReturn = this.actionReturn; - if (errorCode != ServerActionErrorCode.Undefined) { + if (errorCode != ServerActionErrorCode.Undefined) + { metaMessage.errorCode = Enum.GetName(typeof(ServerActionErrorCode), errorCode); } List ios = new List(); - if (ItemInHand != null) { + if (ItemInHand != null) + { SimObjPhysics so = ItemInHand.GetComponent(); InventoryObject io = new InventoryObject(); io.objectId = so.ObjectID; @@ -2681,11 +3070,16 @@ public virtual MetadataWrapper generateMetadataWrapper() { // TODO: remove from base. // ARM - if (Arm != null) { + 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(); } @@ -2702,7 +3096,8 @@ public virtual MetadataWrapper generateMetadataWrapper() { metaMessage.actionStringsReturn = actionStringsReturn; metaMessage.actionVector3sReturn = actionVector3sReturn; - if (alwaysReturnVisibleRange) { + if (alwaysReturnVisibleRange) + { metaMessage.visibleRange = visibleRange(); } @@ -2725,8 +3120,10 @@ public virtual MetadataWrapper generateMetadataWrapper() { return metaMessage; } - public virtual void updateImageSynthesis(bool status) { - if (this.imageSynthesis == null) { + public virtual void updateImageSynthesis(bool status) + { + if (this.imageSynthesis == null) + { imageSynthesis = this.m_Camera.gameObject.GetComponent() as ImageSynthesis; } @@ -2736,7 +3133,8 @@ public virtual void updateImageSynthesis(bool status) { // This should only be used by DebugInputField and HideNSeekController // Once all those invocations have been converted to Dictionary // this can be removed - public void ProcessControlCommand(ServerAction serverAction) { + public void ProcessControlCommand(ServerAction serverAction) + { lastActionInitialPhysicsSimulateCount = PhysicsSceneManager.PhysicsSimulateCallCount; errorMessage = ""; errorCode = ServerActionErrorCode.Undefined; @@ -2752,16 +3150,22 @@ public void ProcessControlCommand(ServerAction serverAction) { System.Reflection.MethodInfo method = this.GetType().GetMethod(serverAction.action); this.agentState = AgentState.Processing; - try { - if (method == null) { + try + { + if (method == null) + { errorMessage = "Invalid action: " + serverAction.action; errorCode = ServerActionErrorCode.InvalidAction; Debug.LogError(errorMessage); actionFinished(false); - } else { + } + else + { method.Invoke(this, new object[] { serverAction }); } - } catch (Exception e) { + } + catch (Exception e) + { Debug.LogError("Caught error with invoke for action: " + serverAction.action); Debug.LogError("Action error message: " + errorMessage); Debug.LogError(e); @@ -2774,16 +3178,19 @@ public void ProcessControlCommand(ServerAction serverAction) { // the parameter name is different to avoid failing a test // that looks for methods with identical param names, since // we dispatch using method + param names - public void ProcessControlCommand(Dictionary actionDict) { + public void ProcessControlCommand(Dictionary actionDict) + { ProcessControlCommand(new DynamicServerAction(actionDict)); } - public void ProcessControlCommand(DynamicServerAction controlCommand) { + public void ProcessControlCommand(DynamicServerAction controlCommand) + { ProcessControlCommand(controlCommand: controlCommand, target: this); } public void ProcessControlCommand(DynamicServerAction controlCommand, T target) - where T : ActionInvokable { + where T : ActionInvokable + { lastActionInitialPhysicsSimulateCount = PhysicsSceneManager.PhysicsSimulateCallCount; errorMessage = ""; errorCode = ServerActionErrorCode.Undefined; @@ -2798,10 +3205,13 @@ public void ProcessControlCommand(DynamicServerAction controlCommand, T targe ); this.agentState = AgentState.Processing; - try { + try + { // Debug.Log("Calling dispatch"); ActionDispatcher.Dispatch(target: target, dynamicServerAction: controlCommand); - } catch (InvalidArgumentsException e) { + } + 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)}" @@ -2814,7 +3224,9 @@ public void ProcessControlCommand(DynamicServerAction controlCommand, T targe controlCommand ); actionFinished(false); - } catch (ToObjectArgumentActionException e) { + } + catch (ToObjectArgumentActionException e) + { Dictionary typeMap = new Dictionary { { "Single", "float" }, @@ -2825,7 +3237,8 @@ public void ProcessControlCommand(DynamicServerAction controlCommand, T targe }; Type underlingType = Nullable.GetUnderlyingType(e.parameterType); string typeName = underlingType == null ? e.parameterType.Name : underlingType.Name; - if (typeMap.ContainsKey(typeName)) { + if (typeMap.ContainsKey(typeName)) + { typeName = typeMap[typeName]; } errorMessage = @@ -2833,7 +3246,9 @@ public void ProcessControlCommand(DynamicServerAction controlCommand, T targe + $" Cannot convert to: {typeName}"; errorCode = ServerActionErrorCode.InvalidArgument; actionFinished(false); - } catch (MissingArgumentsActionException e) { + } + catch (MissingArgumentsActionException e) + { errorMessage = "action: " + controlCommand.action @@ -2841,17 +3256,23 @@ public void ProcessControlCommand(DynamicServerAction controlCommand, T targe + string.Join(",", e.ArgumentNames.ToArray()); errorCode = ServerActionErrorCode.MissingArguments; actionFinished(false); - } catch (AmbiguousActionException e) { + } + catch (AmbiguousActionException e) + { errorMessage = "Ambiguous action: " + controlCommand.action + " " + e.Message; errorCode = ServerActionErrorCode.AmbiguousAction; actionFinished(false); - } catch (InvalidActionException) { + } + catch (InvalidActionException) + { errorCode = ServerActionErrorCode.InvalidAction; actionFinished( success: false, errorMessage: "Invalid action: " + controlCommand.action ); - } catch (TargetInvocationException e) { + } + catch (TargetInvocationException e) + { // TargetInvocationException is called whenever an action // throws an exception. It is used to short circuit errors, // which terminates the action immediately. @@ -2864,13 +3285,17 @@ public void ProcessControlCommand(DynamicServerAction controlCommand, T targe success: false, errorMessage: $"{e.InnerException.GetType().Name}: {e.InnerException.Message}. trace: {e.InnerException.StackTrace.ToString()}" ); - } catch (MissingActionFinishedException e) { + } + 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()}" ); - } catch (Exception e) { + } + catch (Exception e) + { Debug.LogError("Caught error with invoke for action: " + controlCommand.action); Debug.LogError("Action error message: " + errorMessage); errorMessage += e.ToString(); @@ -2885,29 +3310,34 @@ public void ProcessControlCommand(DynamicServerAction controlCommand, T targe } // no op action - public void Pass() { + public void Pass() + { actionFinished(true); } - protected IEnumerator waitForSecondsRealtime(int seconds) { + protected IEnumerator waitForSecondsRealtime(int seconds) + { yield return null; // Necessary as counting happens at the end of the last frame yield return new WaitForSecondsRealtime(seconds); actionFinished(true); } - public void Sleep(int seconds) { + public void Sleep(int seconds) + { StartCoroutine(waitForSecondsRealtime(seconds)); } #if UNITY_EDITOR // for use in Editor to test the Reset function. - public void Reset(ServerAction action) { + public void Reset(ServerAction action) + { physicsSceneManager.GetComponent().Reset(action); } #endif // no op action - public void Done() { + public void Done() + { actionFinished(true); } @@ -2916,16 +3346,19 @@ public void Done() { 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)) { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { throw new ArgumentException( $"objectId: {objectId} is not the objectId on any object in the scene!" ); } SimObjPhysics sop = getSimObjectFromId(objectId); - if (sop == null) { + if (sop == null) + { throw new NullReferenceException($"Object with id '{objectId}' is null"); } @@ -2939,13 +3372,15 @@ protected SimObjPhysics getInteractableSimObjectFromId( ).Length == 1; // target not found! - if (!visible && !forceAction) { + if (!visible && !forceAction) + { throw new NullReferenceException( "Target object not found within the specified visibility." ); } - if (interactable.Length == 0 && !forceAction) { + 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." ); @@ -2956,8 +3391,10 @@ protected SimObjPhysics getInteractableSimObjectFromId( // Helper method that parses (x and y) parameters to return the // sim object that they target. - protected SimObjPhysics getInteractableSimObjectFromXY(float x, float y, bool forceAction) { - if (x < 0 || x > 1 || y < 0 || y > 1) { + protected SimObjPhysics getInteractableSimObjectFromXY(float x, float y, bool forceAction) + { + if (x < 0 || x > 1 || y < 0 || y > 1) + { throw new ArgumentOutOfRangeException("x/y must be in [0:1]"); } @@ -2985,16 +3422,21 @@ protected SimObjPhysics getInteractableSimObjectFromXY(float x, float y, bool fo queryTriggerInteraction: QueryTriggerInteraction.Ignore ); - if (!hitObject || hit.transform.GetComponent() == null) { + if (!hitObject || hit.transform.GetComponent() == null) + { throw new InvalidOperationException($"No SimObject found at (x: {x}, y: {y})"); } SimObjPhysics target = hit.transform.GetComponent(); - if (!forceAction) { - try { + if (!forceAction) + { + try + { assertPosInView(targetPosition: hit.point); - } catch (InvalidOperationException e) { + } + 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=)." @@ -3011,12 +3453,14 @@ protected void assertPosInView( Vector3 targetPosition, bool inViewport = true, bool inMaxVisibleDistance = true - ) { + ) + { // now check if the target position is within bounds of the Agent's forward (z) view Vector3 tmp = m_Camera.transform.position; tmp.y = targetPosition.y; - if (inMaxVisibleDistance && Vector3.Distance(tmp, targetPosition) > maxVisibleDistance) { + if (inMaxVisibleDistance && Vector3.Distance(tmp, targetPosition) > maxVisibleDistance) + { throw new InvalidOperationException("target is outside of maxVisibleDistance"); } @@ -3024,7 +3468,8 @@ protected void assertPosInView( 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) - ) { + ) + { throw new InvalidOperationException("target is outside of Agent Viewport"); } } @@ -3035,7 +3480,8 @@ protected void screenToWorldTarget( ref SimObjPhysics target, bool forceAction = false, bool checkVisible = true - ) { + ) + { // this version doesn't use a RaycastHit, so pass just a default one RaycastHit hit = new RaycastHit(); screenToWorldTarget( @@ -3057,8 +3503,10 @@ protected void screenToWorldTarget( out RaycastHit hit, bool forceAction = false, bool checkVisible = true - ) { - if (x < 0 || x > 1 || y < 0 || y > 1) { + ) + { + if (x < 0 || x > 1 || y < 0 || y > 1) + { throw new ArgumentOutOfRangeException("x/y must be in [0:1]"); } @@ -3086,14 +3534,16 @@ protected void screenToWorldTarget( ), QueryTriggerInteraction.Ignore ) - ) { + ) + { // DEBUG STUFF PLEASE COMMENT OUT UNLESS USING////// // GameObject empty = new GameObject("empty"); // Instantiate(empty, hit.point, Quaternion.identity); // GameObject.Destroy(empty); /////////////////////////////////////// - if (!hit.transform.GetComponentInParent()) { + if (!hit.transform.GetComponentInParent()) + { // object hit was not a sim object throw new InvalidOperationException($"no sim objects found at ({x},{y})"); } @@ -3108,7 +3558,8 @@ protected void screenToWorldTarget( ); // now check if the object is flagged as Visible by the visibility point logic - if (checkVisible && !forceAction && !IsInteractable(target)) { + if (checkVisible && !forceAction && !IsInteractable(target)) + { // the potential target sim object hit by the ray is not currently visible to the agent throw new InvalidOperationException( $"target hit ({target.objectID}) at ({x}, {y}) is not currently Visible to Agent" @@ -3122,14 +3573,17 @@ protected void screenToWorldTarget( // if checkVisible is true and target is found, the object is also interactable to the agent // this does not account for objects behind transparent objects like shower glass, as the raycast check // will hit the transparent object FIRST - public void GetObjectInFrame(float x, float y, bool checkVisible = false) { + public void GetObjectInFrame(float x, float y, bool checkVisible = false) + { SimObjPhysics target = null; 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) { + 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})." ); @@ -3157,7 +3611,8 @@ public void GetCoordinateFromRaycast(float x, float y) { actionFinishedEmit(success: true, actionReturn: hit.point); } - public void GetObjectHitFromRaycast(Vector3 origin, Vector3 destination) { + public void GetObjectHitFromRaycast(Vector3 origin, Vector3 destination) + { RaycastHit hit; if ( !Physics.Raycast( @@ -3176,7 +3631,8 @@ public void GetObjectHitFromRaycast(Vector3 origin, Vector3 destination) { ), queryTriggerInteraction: QueryTriggerInteraction.Ignore ) - ) { + ) + { actionFinishedEmit( success: false, errorMessage: ( @@ -3188,7 +3644,8 @@ public void GetObjectHitFromRaycast(Vector3 origin, Vector3 destination) { return; } SimObjPhysics target = hit.transform.GetComponentInParent(); - if (target == null) { + if (target == null) + { actionFinishedEmit( success: false, errorMessage: ( @@ -3202,7 +3659,8 @@ public void GetObjectHitFromRaycast(Vector3 origin, Vector3 destination) { actionFinishedEmit(success: true, actionReturn: target.ObjectID); } - public void PerformRaycast(Vector3 origin, Vector3 destination) { + public void PerformRaycast(Vector3 origin, Vector3 destination) + { RaycastHit hit; if ( !Physics.Raycast( @@ -3221,7 +3679,8 @@ public void PerformRaycast(Vector3 origin, Vector3 destination) { ), queryTriggerInteraction: QueryTriggerInteraction.Ignore ) - ) { + ) + { actionFinishedEmit( success: false, errorMessage: ( @@ -3233,7 +3692,8 @@ public void PerformRaycast(Vector3 origin, Vector3 destination) { return; } SimObjPhysics target = hit.transform.GetComponentInParent(); - if (target == null) { + if (target == null) + { actionFinishedEmit( success: false, errorMessage: ( @@ -3246,7 +3706,8 @@ public void PerformRaycast(Vector3 origin, Vector3 destination) { } actionFinishedEmit( success: true, - actionReturn: new Dictionary() { + actionReturn: new Dictionary() + { ["objectId"] = target.ObjectID, ["hitPoint"] = hit.point, ["hitDistance"] = hit.distance @@ -3254,24 +3715,29 @@ public void PerformRaycast(Vector3 origin, Vector3 destination) { ); } - public void GetVisibilityPoints(string objectId) { + public void GetVisibilityPoints(string objectId) + { SimObjPhysics sop = getInteractableSimObjectFromId( objectId: objectId, forceAction: true ); - if (sop.VisibilityPoints == null) { + if (sop.VisibilityPoints == null) + { throw new ArgumentException($"objectId: {objectId} has no visibility points!"); } Vector3[] points = new Vector3[sop.VisibilityPoints.Length]; - for (int i = 0; i < points.Length; i++) { + for (int i = 0; i < points.Length; i++) + { points[i] = sop.VisibilityPoints[i].position; } actionFinishedEmit(success: true, actionReturn: points); } - protected void snapAgentToGrid() { - if (this.snapToGrid) { + protected void snapAgentToGrid() + { + if (this.snapToGrid) + { float mult = 1 / gridSize; float gridX = Convert.ToSingle(Math.Round(this.transform.position.x * mult) / mult); float gridZ = Convert.ToSingle(Math.Round(this.transform.position.z * mult) / mult); @@ -3280,24 +3746,30 @@ protected void snapAgentToGrid() { } } - protected bool isPositionOnGrid(Vector3 xyz) { - if (this.snapToGrid) { + protected bool isPositionOnGrid(Vector3 xyz) + { + if (this.snapToGrid) + { float mult = 1 / gridSize; 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)); - } else { + } + else + { return true; } } // move in cardinal directions - virtual protected void moveCharacter(ServerAction action, int targetOrientation) { + virtual protected void moveCharacter(ServerAction action, int targetOrientation) + { // TODO: Simplify this??? // resetHand(); when I looked at this resetHand in DiscreteRemoteFPSAgent was just commented out doing nothing so... moveMagnitude = gridSize; - if (action.moveMagnitude > 0) { + if (action.moveMagnitude > 0) + { moveMagnitude = action.moveMagnitude; } int currentRotation = (int)Math.Round(transform.rotation.eulerAngles.y, 0); @@ -3309,9 +3781,12 @@ virtual protected void moveCharacter(ServerAction action, int targetOrientation) int delta = (currentRotation + targetOrientation) % 360; Vector3 m; - if (actionOrientation.ContainsKey(delta)) { + if (actionOrientation.ContainsKey(delta)) + { m = actionOrientation[delta]; - } else { + } + else + { actionOrientation = new Dictionary(); actionOrientation.Add(0, transform.forward); actionOrientation.Add(90, transform.right); @@ -3329,18 +3804,21 @@ virtual protected void moveCharacter(ServerAction action, int targetOrientation) } // iterates to next allowed downward horizon angle for AgentCamera (max 60 degrees down) - public virtual void LookDown(ServerAction controlCommand) { + public virtual void LookDown(ServerAction controlCommand) + { m_Camera.transform.Rotate(controlCommand.degrees, 0, 0); actionFinished(true); } // iterates to next allowed upward horizon angle for agent camera (max 30 degrees up) - public virtual void LookUp(ServerAction controlCommand) { + public virtual void LookUp(ServerAction controlCommand) + { m_Camera.transform.Rotate(-controlCommand.degrees, 0, 0); actionFinished(true); } - protected bool checkForUpDownAngleLimit(string direction, float degrees) { + protected bool checkForUpDownAngleLimit(string direction, float degrees) + { bool result = true; // check the angle between the agent's forward vector and the proposed rotation vector // if it exceeds the min/max based on if we are rotating up or down, return false @@ -3351,7 +3829,8 @@ protected bool checkForUpDownAngleLimit(string direction, float degrees) { rotPoint.transform.rotation = m_Camera.transform.rotation; // print(Vector3.Angle(rotPoint.transform.forward, m_CharacterController.transform.forward)); - if (direction == "down") { + 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. @@ -3364,12 +3843,14 @@ protected bool checkForUpDownAngleLimit(string direction, float degrees) { ) * 10.0f ) / 10.0f < -maxDownwardLookAngle - ) { + ) + { result = false; } } - if (direction == "up") { + if (direction == "up") + { rotPoint.Rotate(new Vector3(-degrees, 0, 0)); if ( Mathf.Round( @@ -3380,7 +3861,8 @@ protected bool checkForUpDownAngleLimit(string direction, float degrees) { ) * 10.0f ) / 10.0f > maxUpwardLookAngle - ) { + ) + { result = false; } } @@ -3398,7 +3880,8 @@ protected void teleport( Vector3? rotation, float? horizon, bool forceAction - ) { + ) + { teleportFull( position: position, rotation: rotation, @@ -3412,9 +3895,11 @@ bool forceAction /////////////////////////////////////////// // this is not used with non-grounded agents (e.g., drones) - protected virtual void assertTeleportedNearGround(Vector3? targetPosition) { + protected virtual void assertTeleportedNearGround(Vector3? targetPosition) + { // position should not change if it's null. - if (targetPosition == null) { + if (targetPosition == null) + { return; } @@ -3428,7 +3913,8 @@ protected virtual void assertTeleportedNearGround(Vector3? targetPosition) { ); // 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) { + 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." @@ -3442,14 +3928,16 @@ protected virtual void teleportFull( Vector3? rotation, float? horizon, bool forceAction - ) { + ) + { 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")}." @@ -3461,7 +3949,8 @@ bool forceAction !forceAction && horizon.HasValue && (horizon.Value > maxDownwardLookAngle || horizon.Value < -maxUpwardLookAngle) - ) { + ) + { throw new ArgumentOutOfRangeException( $"Each horizon must be in [{-maxUpwardLookAngle}:{maxDownwardLookAngle}]. You gave {horizon}." ); @@ -3471,13 +3960,15 @@ bool forceAction !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." ); } - if (!forceAction && position.HasValue && !isPositionOnGrid(position.Value)) { + if (!forceAction && position.HasValue && !isPositionOnGrid(position.Value)) + { throw new ArgumentOutOfRangeException( $"Teleport position {position.Value.ToString("F6")} is not on the grid of size {gridSize}." ); @@ -3503,7 +3994,8 @@ bool forceAction collidersToIgnore: collidersToIgnoreDuringMovement, includeErrorMessage: true ) - ) { + ) + { transform.position = oldPosition; transform.rotation = oldRotation; m_Camera.transform.localEulerAngles = oldCameraLocalEulerAngles; @@ -3519,8 +4011,10 @@ public void TeleportObject( bool forceKinematic = false, bool allowTeleportOutOfHand = false, bool makeUnbreakable = false - ) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + ) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}"; actionFinished(false); return; @@ -3538,15 +4032,21 @@ public void TeleportObject( includeErrorMessage: true ); - if (teleportSuccess) { - if (!forceKinematic) { + if (teleportSuccess) + { + if (!forceKinematic) + { StartCoroutine(checkIfObjectHasStoppedMoving(sop: sop, useTimeout: true)); return; - } else { + } + else + { actionFinished(true); return; } - } else { + } + else + { actionFinished(false); return; } @@ -3560,8 +4060,10 @@ public void TeleportObject( bool forceKinematic = false, bool allowTeleportOutOfHand = false, bool makeUnbreakable = false - ) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + ) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}"; actionFinished(false); return; @@ -3569,7 +4071,8 @@ public void TeleportObject( SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; bool teleportSuccess = false; - foreach (Vector3 position in positions) { + foreach (Vector3 position in positions) + { teleportSuccess = TeleportObject( sop: sop, position: position, @@ -3580,13 +4083,15 @@ public void TeleportObject( makeUnbreakable: makeUnbreakable, includeErrorMessage: true ); - if (teleportSuccess) { + if (teleportSuccess) + { errorMessage = ""; break; } } - if (teleportSuccess) { + if (teleportSuccess) + { // TODO: Do we want to wait for objects to stop moving when teleported? // if (!forceKinematic) { // StartCoroutine(checkIfObjectHasStoppedMoving(sop, 0, true)); @@ -3594,7 +4099,9 @@ public void TeleportObject( // } actionFinished(true); return; - } else { + } + else + { actionFinished(false); return; } @@ -3609,10 +4116,13 @@ public bool TeleportObject( bool allowTeleportOutOfHand, bool makeUnbreakable, bool includeErrorMessage = false - ) { + ) + { bool sopInHand = ItemInHand != null && sop == ItemInHand.GetComponent(); - if (sopInHand && !allowTeleportOutOfHand) { - if (includeErrorMessage) { + if (sopInHand && !allowTeleportOutOfHand) + { + if (includeErrorMessage) + { errorMessage = "Cannot teleport object in hand."; } return false; @@ -3622,19 +4132,23 @@ public bool TeleportObject( sop.transform.position = position; sop.transform.rotation = Quaternion.Euler(rotation); - if (forceKinematic) { + if (forceKinematic) + { sop.GetComponent().isKinematic = true; } - if (!forceAction) { + if (!forceAction) + { Collider colliderHitIfTeleported = UtilityFunctions.firstColliderObjectCollidingWith(sop.gameObject); - if (colliderHitIfTeleported != null) { + if (colliderHitIfTeleported != null) + { sop.transform.position = oldPosition; sop.transform.rotation = oldRotation; SimObjPhysics hitSop = ancestorSimObjPhysics( colliderHitIfTeleported.gameObject ); - if (includeErrorMessage) { + if (includeErrorMessage) + { errorMessage = $"{sop.ObjectID} is colliding with {(hitSop != null ? hitSop.ObjectID : colliderHitIfTeleported.name)} after teleport."; } @@ -3642,23 +4156,30 @@ public bool TeleportObject( } } - if (makeUnbreakable) { - if (sop.GetComponent()) { + if (makeUnbreakable) + { + if (sop.GetComponent()) + { sop.GetComponent().Unbreakable = true; } } - if (sopInHand) { - if (!forceKinematic) { + if (sopInHand) + { + if (!forceKinematic) + { Rigidbody rb = ItemInHand.GetComponent(); rb.constraints = RigidbodyConstraints.None; rb.useGravity = true; rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; } GameObject topObject = GameObject.Find("Objects"); - if (topObject != null) { + if (topObject != null) + { ItemInHand.transform.parent = topObject.transform; - } else { + } + else + { ItemInHand.transform.parent = null; } @@ -3683,7 +4204,8 @@ public void TeleportObject( bool forceKinematic = false, bool allowTeleportOutOfHand = false, bool makeUnbreakable = false - ) { + ) + { TeleportObject( objectId: objectId, position: new Vector3(x, y, z), @@ -3701,23 +4223,28 @@ public void TeleportObject( protected IEnumerator checkIfObjectHasStoppedMoving( SimObjPhysics sop, bool useTimeout = false - ) { + ) + { // yield for the physics update to make sure this yield is consistent regardless of framerate yield return new WaitForFixedUpdate(); float startTime = Time.time; float waitTime = TimeToWaitForObjectsToComeToRest; - if (useTimeout) { + if (useTimeout) + { waitTime = 1.0f; } - if (sop != null) { + if (sop != null) + { Rigidbody rb = sop.GetComponentInChildren(); bool stoppedMoving = false; - while (Time.time - startTime < waitTime) { - if (sop == null) { + while (Time.time - startTime < waitTime) + { + if (sop == null) + { break; } @@ -3727,20 +4254,24 @@ protected IEnumerator checkIfObjectHasStoppedMoving( float accel = (currentVelocity - sop.lastVelocity) / Time.fixedDeltaTime; // ok the accel is basically zero, so it has stopped moving - if (Mathf.Abs(accel) <= 0.001f) { + if (Mathf.Abs(accel) <= 0.001f) + { // force the rb to stop moving just to be safe rb.velocity = Vector3.zero; rb.angularVelocity = Vector3.zero; rb.Sleep(); stoppedMoving = true; break; - } else { + } + else + { yield return new WaitForFixedUpdate(); } } // so we never stopped moving and we are using the timeout - if (!stoppedMoving && useTimeout) { + if (!stoppedMoving && useTimeout) + { errorMessage = "object couldn't come to rest"; // print(errorMessage); actionFinished(false); @@ -3749,15 +4280,19 @@ protected IEnumerator checkIfObjectHasStoppedMoving( DefaultAgentHand(); actionFinished(true, sop.transform.position); - } else { + } + else + { errorMessage = "null reference sim obj in checkIfObjectHasStoppedMoving call"; actionFinished(false); } } - public void SetObjectPoses(ServerAction action) { + 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) { + 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."; actionFinished(false); @@ -3770,7 +4305,8 @@ public void SetObjectPoses(ServerAction action) { // a frame does not pass prior to this AND the imageSynthesis // is enabled for say depth or normals, Unity will crash on // a subsequent scene reset() - protected IEnumerator setObjectPoses(ObjectPose[] objectPoses, bool placeStationary) { + protected IEnumerator setObjectPoses(ObjectPose[] objectPoses, bool placeStationary) + { yield return new WaitForEndOfFrame(); bool success = physicsSceneManager.SetObjectPoses( objectPoses, @@ -3779,7 +4315,8 @@ protected IEnumerator setObjectPoses(ObjectPose[] objectPoses, bool placeStation ); //update image synthesis since scene has changed - if (this.imageSynthesis && this.imageSynthesis.enabled) { + if (this.imageSynthesis && this.imageSynthesis.enabled) + { this.imageSynthesis.OnSceneChange(); } actionFinished(success, errorMessage); @@ -3792,8 +4329,10 @@ public void PlaceObjectAtPoint( Vector3 position, Vector3? rotation = null, bool forceKinematic = false - ) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + ) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; @@ -3810,15 +4349,21 @@ public void PlaceObjectAtPoint( includeErrorMessage: true ); - if (placeObjectSuccess) { - if (!forceKinematic) { + if (placeObjectSuccess) + { + if (!forceKinematic) + { StartCoroutine(checkIfObjectHasStoppedMoving(sop: target, useTimeout: true)); return; - } else { + } + else + { actionFinished(true); return; } - } else { + } + else + { actionFinished(false); return; } @@ -3830,10 +4375,13 @@ public bool PlaceObjectAtPoint( Vector3? rotation, bool forceKinematic, bool includeErrorMessage = false - ) { + ) + { // make sure point we are moving the object to is valid - if (!agentManager.sceneBounds.Contains(position)) { - if (includeErrorMessage) { + if (!agentManager.sceneBounds.Contains(position)) + { + if (includeErrorMessage) + { errorMessage = $"Position coordinate ({position}) is not within scene bounds ({agentManager.sceneBounds})"; } @@ -3841,20 +4389,24 @@ public bool PlaceObjectAtPoint( } Quaternion originalRotation = target.transform.rotation; - if (rotation.HasValue) { + if (rotation.HasValue) + { target.transform.rotation = Quaternion.Euler(rotation.Value); } Vector3 originalPos = target.transform.position; target.transform.position = agentManager.SceneBounds.min - new Vector3(-100f, -100f, -100f); - if (!Physics.autoSyncTransforms) { + if (!Physics.autoSyncTransforms) + { Physics.SyncTransforms(); } bool wasInHand = false; - if (ItemInHand) { - if (ItemInHand.transform.gameObject == target.transform.gameObject) { + if (ItemInHand) + { + if (ItemInHand.transform.gameObject == target.transform.gameObject) + { wasInHand = true; } } @@ -3879,7 +4431,8 @@ public bool PlaceObjectAtPoint( // Check spawn area here target.transform.position = finalPos; - if (!Physics.autoSyncTransforms) { + if (!Physics.autoSyncTransforms) + { Physics.SyncTransforms(); } @@ -3887,17 +4440,20 @@ public bool PlaceObjectAtPoint( target.gameObject ); - if (colliderHitIfSpawned == null) { + if (colliderHitIfSpawned == null) + { target.transform.position = finalPos; Rigidbody rb = target.GetComponent(); - if (forceKinematic) { + if (forceKinematic) + { rb.isKinematic = forceKinematic; } // Additional stuff we need to do if placing item that was in hand - if (wasInHand) { + if (wasInHand) + { rb.constraints = RigidbodyConstraints.None; rb.useGravity = true; @@ -3906,9 +4462,12 @@ public bool PlaceObjectAtPoint( rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; GameObject topObject = GameObject.Find("Objects"); - if (topObject != null) { + if (topObject != null) + { ItemInHand.transform.parent = topObject.transform; - } else { + } + else + { ItemInHand.transform.parent = null; } @@ -3926,14 +4485,16 @@ public bool PlaceObjectAtPoint( target.transform.rotation = originalRotation; // if the original position was in agent hand, reparent object to agent hand - if (wasInHand) { + if (wasInHand) + { target.transform.SetParent(AgentHand.transform); ItemInHand = target.gameObject; target.isInAgentHand = true; target.GetComponent().isKinematic = true; } - if (includeErrorMessage) { + if (includeErrorMessage) + { SimObjPhysics hitSop = ancestorSimObjPhysics(colliderHitIfSpawned.gameObject); errorMessage = ( $"Spawn area not clear ({(hitSop != null ? hitSop.ObjectID : colliderHitIfSpawned.name)})" @@ -3948,8 +4509,10 @@ public void PlaceObjectAtPoint( Vector3[] positions, Vector3? rotation = null, bool forceKinematic = false - ) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + ) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; @@ -3960,7 +4523,8 @@ public void PlaceObjectAtPoint( bool placeObjectSuccess = false; - foreach (Vector3 position in positions) { + foreach (Vector3 position in positions) + { placeObjectSuccess = PlaceObjectAtPoint( target: target, position: position, @@ -3968,42 +4532,54 @@ public void PlaceObjectAtPoint( forceKinematic: forceKinematic, includeErrorMessage: true ); - if (placeObjectSuccess) { + if (placeObjectSuccess) + { errorMessage = ""; break; } } - if (placeObjectSuccess) { - if (!forceKinematic) { + if (placeObjectSuccess) + { + if (!forceKinematic) + { StartCoroutine(checkIfObjectHasStoppedMoving(sop: target, useTimeout: true)); return; - } else { + } + else + { actionFinished(true); return; } - } else { + } + else + { actionFinished(false); return; } } // Similar to PlaceObjectAtPoint(...) above but returns a bool if successful - public bool placeObjectAtPoint(SimObjPhysics t, Vector3 position) { + public bool placeObjectAtPoint(SimObjPhysics t, Vector3 position) + { SimObjPhysics target = null; // find the object in the scene, disregard visibility - foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - if (sop.objectID == t.objectID) { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { + if (sop.objectID == t.objectID) + { target = sop; } } - if (target == null) { + if (target == null) + { return false; } // make sure point we are moving the object to is valid - if (!agentManager.sceneBounds.Contains(position)) { + if (!agentManager.sceneBounds.Contains(position)) + { return false; } @@ -4027,7 +4603,8 @@ public bool placeObjectAtPoint(SimObjPhysics t, Vector3 position) { // check spawn area, if its clear, then place object at finalPos InstantiatePrefabTest ipt = physicsSceneManager.GetComponent(); - if (ipt.CheckSpawnArea(target, finalPos, target.transform.rotation, false)) { + if (ipt.CheckSpawnArea(target, finalPos, target.transform.rotation, false)) + { target.transform.position = finalPos; return true; } @@ -4037,7 +4614,8 @@ public bool placeObjectAtPoint(SimObjPhysics t, Vector3 position) { // from given position in worldspace, raycast straight down and return a point of any surface hit // useful for getting a worldspace coordinate on the floor given any point in space. - public Vector3 GetSurfacePointBelowPosition(Vector3 position) { + public Vector3 GetSurfacePointBelowPosition(Vector3 position) + { Vector3 point = Vector3.zero; // raycast down from the position like 10m and see if you hit anything. If nothing hit, return the original position and an error message? @@ -4059,36 +4637,45 @@ public Vector3 GetSurfacePointBelowPosition(Vector3 position) { ), QueryTriggerInteraction.Ignore ) - ) { + ) + { point = hit.point; return point; } // nothing hit, return the original position? - else { + else + { return position; } } - protected T[] flatten2DimArray(T[,] array) { + protected T[] flatten2DimArray(T[,] array) + { int nrow = array.GetLength(0); int ncol = array.GetLength(1); T[] flat = new T[nrow * ncol]; - for (int i = 0; i < nrow; i++) { - for (int j = 0; j < ncol; j++) { + for (int i = 0; i < nrow; i++) + { + for (int j = 0; j < ncol; j++) + { flat[i * ncol + j] = array[i, j]; } } return flat; } - protected T[] flatten3DimArray(T[,,] array) { + protected T[] flatten3DimArray(T[,,] array) + { int n0 = array.GetLength(0); int n1 = array.GetLength(1); int n2 = array.GetLength(2); T[] flat = new T[n0 * n1 * n2]; - for (int i = 0; i < n0; i++) { - for (int j = 0; j < n1; j++) { - for (int k = 0; k < n2; k++) { + for (int i = 0; i < n0; i++) + { + for (int j = 0; j < n1; j++) + { + for (int k = 0; k < n2; k++) + { flat[i * n1 * n2 + j * n2 + k] = array[i, j, k]; } } @@ -4096,13 +4683,16 @@ protected T[] flatten3DimArray(T[,,] array) { return flat; } - protected List visibleRange() { + protected List visibleRange() + { int n = 5; List points = new List(); points.Add(transform.position); updateAllAgentCollidersForVisibilityCheck(false); - for (int i = 0; i < n; i++) { - for (int j = 0; j < n; j++) { + 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) @@ -4121,7 +4711,8 @@ protected List visibleRange() { "Agent" ) ) - ) { + ) + { points.Add(hit.point); } } @@ -4135,28 +4726,38 @@ protected List visibleRange() { // enableColliders == false and after with it equaling true). It, in particular, will // turn off/on all the colliders on agents which should not block visibility for the current agent // (invisible agents for example). - protected void updateAllAgentCollidersForVisibilityCheck(bool enableColliders) { - foreach (BaseFPSAgentController agent in this.agentManager.agents) { + protected void updateAllAgentCollidersForVisibilityCheck(bool enableColliders) + { + foreach (BaseFPSAgentController agent in this.agentManager.agents) + { bool overlapping = (transform.position - agent.transform.position).magnitude < 0.001f; - if (overlapping || agent == this || !agent.IsVisible) { + if (overlapping || agent == this || !agent.IsVisible) + { agent.updateCollidersForVisiblityCheck(enableColliders); } } } - protected virtual void updateCollidersForVisiblityCheck(bool enableColliders) { - if (enableColliders) { - foreach (Collider c in this.collidersDisabledForVisbilityCheck) { + protected virtual void updateCollidersForVisiblityCheck(bool enableColliders) + { + if (enableColliders) + { + foreach (Collider c in this.collidersDisabledForVisbilityCheck) + { c.enabled = true; } this.collidersDisabledForVisbilityCheck.Clear(); - } else { + } + else + { HashSet collidersToNotDisable = new HashSet(); // Don't disable colliders for the object held in the hand - if (ItemInHand != null) { - foreach (Collider c in ItemInHand.GetComponentsInChildren()) { + if (ItemInHand != null) + { + foreach (Collider c in ItemInHand.GetComponentsInChildren()) + { collidersToNotDisable.Add(c); } } @@ -4164,47 +4765,66 @@ protected virtual void updateCollidersForVisiblityCheck(bool enableColliders) { // Don't disable colliders for the arm (unless the agent is invisible) // or for any objects held by the arm // Standard IK arm - if (Arm != null && Arm.gameObject.activeSelf) { - if (this.IsVisible) { - foreach (Collider c in Arm.gameObject.GetComponentsInChildren()) { - if (!c.isTrigger) { + if (Arm != null && Arm.gameObject.activeSelf) + { + if (this.IsVisible) + { + foreach (Collider c in Arm.gameObject.GetComponentsInChildren()) + { + if (!c.isTrigger) + { collidersToNotDisable.Add(c); } } - } else { - foreach (HashSet hsc in Arm.heldObjects.Values) { - foreach (Collider c in hsc) { + } + else + { + foreach (HashSet hsc in Arm.heldObjects.Values) + { + foreach (Collider c in hsc) + { collidersToNotDisable.Add(c); } } } } // Stretch arm - else if (SArm != null && SArm.gameObject.activeSelf) { - if (this.IsVisible) { - foreach (Collider c in SArm.gameObject.GetComponentsInChildren()) { - if (!c.isTrigger) { + else if (SArm != null && SArm.gameObject.activeSelf) + { + if (this.IsVisible) + { + foreach (Collider c in SArm.gameObject.GetComponentsInChildren()) + { + if (!c.isTrigger) + { collidersToNotDisable.Add(c); } } - } else { - foreach (HashSet hsc in SArm.heldObjects.Values) { - foreach (Collider c in hsc) { + } + else + { + foreach (HashSet hsc in SArm.heldObjects.Values) + { + foreach (Collider c in hsc) + { collidersToNotDisable.Add(c); } } } } - foreach (Collider c in this.GetComponentsInChildren()) { + foreach (Collider c in this.GetComponentsInChildren()) + { if ( c.transform.gameObject.layer == LayerMask.NameToLayer("ArticulatedAgent") || c.transform.gameObject.layer == LayerMask.NameToLayer("FloorAgent") - ) { + ) + { continue; } - if (!collidersToNotDisable.Contains(c)) { + if (!collidersToNotDisable.Contains(c)) + { collidersDisabledForVisbilityCheck.Add(c); c.enabled = false; } @@ -4220,18 +4840,22 @@ can cause all sorts of issues. Note that this function is "dangerous" in that it can have unintended interactions with other actions. Please only use this action if you understand what you're doing. */ - public void ParentObject(string parentId, string childId) { - if (parentId == childId) { + public void ParentObject(string parentId, string childId) + { + if (parentId == childId) + { errorMessage = $"Parent id ({parentId}) must not equal child id."; actionFinished(false); return; } - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(parentId)) { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(parentId)) + { errorMessage = $"No parent object with ID {parentId}"; actionFinished(false); return; } - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(childId)) { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(childId)) + { errorMessage = $"No parent object with ID {childId}"; actionFinished(false); return; @@ -4260,8 +4884,10 @@ still be changed in such a case. Note that this function is "dangerous" in that it can have unintended interactions with other actions. Please only use this action if you understand what you're doing. */ - public void UnparentObject(string objectId, bool kinematic) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void UnparentObject(string objectId, bool kinematic) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"No object with ID {objectId}"; actionFinished(false); return; @@ -4274,52 +4900,76 @@ public void UnparentObject(string objectId, bool kinematic) { actionFinished(true); } - protected bool hasAncestor(GameObject child, GameObject potentialAncestor) { - if (child == potentialAncestor) { + protected bool hasAncestor(GameObject child, GameObject potentialAncestor) + { + if (child == potentialAncestor) + { return true; - } else if (child.transform.parent != null) { + } + else if (child.transform.parent != null) + { return hasAncestor(child.transform.parent.gameObject, potentialAncestor); - } else { + } + else + { return false; } } - protected bool ancestorHasName(GameObject go, string name) { - if (go.name == name) { + protected bool ancestorHasName(GameObject go, string name) + { + if (go.name == name) + { return true; - } else if (go.transform.parent != null) { + } + else if (go.transform.parent != null) + { return ancestorHasName(go.transform.parent.gameObject, name); - } else { + } + else + { return false; } } - protected static SimObjPhysics ancestorSimObjPhysics(GameObject go) { - if (go == null) { + protected static SimObjPhysics ancestorSimObjPhysics(GameObject go) + { + if (go == null) + { return null; } SimObjPhysics so = go.GetComponent(); - if (so != null) { + if (so != null) + { return so; - } else if (go.transform.parent != null) { + } + else if (go.transform.parent != null) + { return ancestorSimObjPhysics(go.transform.parent.gameObject); - } else { + } + else + { return null; } } - public void VisibleRange() { + public void VisibleRange() + { actionFinished(true, visibleRange()); } - public float TimeSinceStart() { + public float TimeSinceStart() + { return Time.time; } - protected bool objectIsWithinViewport(SimObjPhysics sop) { - if (sop.VisibilityPoints.Length > 0) { + protected bool objectIsWithinViewport(SimObjPhysics sop) + { + if (sop.VisibilityPoints.Length > 0) + { Transform[] visPoints = sop.VisibilityPoints; - foreach (Transform point in visPoints) { + foreach (Transform point in visPoints) + { Vector3 viewPoint = m_Camera.WorldToViewportPoint(point.position); float ViewPointRangeHigh = 1.0f; float ViewPointRangeLow = 0.0f; @@ -4331,11 +4981,14 @@ protected bool objectIsWithinViewport(SimObjPhysics sop) { && // within x bounds of viewport viewPoint.y < ViewPointRangeHigh && viewPoint.y > ViewPointRangeLow // within y bounds of viewport - ) { + ) + { return true; } } - } else { + } + else + { #if UNITY_EDITOR Debug.Log("Error! Set at least 1 visibility point on SimObjPhysics prefab!"); #endif @@ -4343,32 +4996,39 @@ protected bool objectIsWithinViewport(SimObjPhysics sop) { return false; } - public VisibilityCheck isSimObjVisible(Camera camera, SimObjPhysics sop, float maxDistance) { + public VisibilityCheck isSimObjVisible(Camera camera, SimObjPhysics sop, float maxDistance) + { VisibilityCheck visCheck = new VisibilityCheck(); // check against all visibility points, accumulate count. If at least one point is visible, set object to visible - if (sop.VisibilityPoints != null && sop.VisibilityPoints.Length > 0) { + if (sop.VisibilityPoints != null && sop.VisibilityPoints.Length > 0) + { Transform[] visPoints = sop.VisibilityPoints; float maxDistanceSquared = maxDistance * maxDistance; - foreach (Transform point in visPoints) { + foreach (Transform point in visPoints) + { float xdelta = Math.Abs(camera.transform.position.x - point.position.x); - if (xdelta > maxDistance) { + if (xdelta > maxDistance) + { continue; } float zdelta = Math.Abs(camera.transform.position.z - point.position.z); - if (zdelta > maxDistance) { + if (zdelta > maxDistance) + { continue; } // if the object is too far above the camera, skip float ydelta = point.position.y - camera.transform.position.y; - if (ydelta > maxDistance) { + if (ydelta > maxDistance) + { continue; } double distanceSquared = (xdelta * xdelta) + (zdelta * zdelta); - if (distanceSquared > maxDistanceSquared) { + if (distanceSquared > maxDistanceSquared) + { continue; } @@ -4379,7 +5039,8 @@ public VisibilityCheck isSimObjVisible(Camera camera, SimObjPhysics sop, float m camera, sop.IsReceptacle ); - if (visCheck.visible && visCheck.interactable) { + 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. @@ -4393,7 +5054,9 @@ public VisibilityCheck isSimObjVisible(Camera camera, SimObjPhysics sop, float m sop.debugIsVisible = visCheck.visible; sop.debugIsInteractable = visCheck.interactable; #endif - } else { + } + else + { Debug.Log("Error! Set at least 1 visibility point on SimObjPhysics " + sop + "."); } return visCheck; @@ -4404,53 +5067,64 @@ public VisibilityCheck isSimObjVisible( 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) ) - ) { + ) + { return visCheck; } Transform[] visPoints = sop.VisibilityPoints; float maxDistanceSquared = maxDistance * maxDistance; - foreach (Transform point in visPoints) { + foreach (Transform point in visPoints) + { bool outsidePlane = false; - for (int i = 0; i < planes.Length; i++) { - if (!planes[i].GetSide(point.position)) { + for (int i = 0; i < planes.Length; i++) + { + if (!planes[i].GetSide(point.position)) + { outsidePlane = true; break; } } - if (outsidePlane) { + if (outsidePlane) + { continue; } float xdelta = Math.Abs(camera.transform.position.x - point.position.x); - if (xdelta > maxDistance) { + if (xdelta > maxDistance) + { continue; } float zdelta = Math.Abs(camera.transform.position.z - point.position.z); - if (zdelta > maxDistance) { + if (zdelta > maxDistance) + { continue; } // if the object is too far above the Agent, skip float ydelta = point.position.y - this.transform.position.y; - if (ydelta > maxDistance) { + if (ydelta > maxDistance) + { continue; } double distanceSquared = (xdelta * xdelta) + (zdelta * zdelta); - if (distanceSquared > maxDistanceSquared) { + if (distanceSquared > maxDistanceSquared) + { continue; } @@ -4459,7 +5133,8 @@ Plane[] planes CheckIfVisibilityPointRaycast(sop, point, camera, false) | CheckIfVisibilityPointRaycast(sop, point, camera, true) ); - if (visCheck.visible && visCheck.interactable) { + 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. @@ -4473,7 +5148,9 @@ Plane[] planes sop.debugIsVisible = visCheck.visible; sop.debugIsInteractable = visCheck.interactable; #endif - } else { + } + else + { Debug.Log("Error! Set at least 1 visibility point on SimObjPhysics " + sop + "."); } return visCheck; @@ -4481,10 +5158,14 @@ Plane[] planes // pass in forceVisible bool to force grab all objects of type sim obj // if not, gather all visible sim objects maxVisibleDistance away from camera view - public SimObjPhysics[] VisibleSimObjs(bool forceVisible = false) { - if (forceVisible) { + public SimObjPhysics[] VisibleSimObjs(bool forceVisible = false) + { + if (forceVisible) + { return GameObject.FindObjectsOfType(typeof(SimObjPhysics)) as SimObjPhysics[]; - } else { + } + else + { return GetAllVisibleSimObjPhysics(m_Camera, maxVisibleDistance); } } @@ -4493,17 +5174,21 @@ protected SimObjPhysics[] GetAllVisibleSimObjPhysics( Camera camera, float maxDistance, IEnumerable filterSimObjs = null - ) { + ) + { SimObjPhysics[] interactable; - if (this.visibilityScheme == VisibilityScheme.Collider) { + if (this.visibilityScheme == VisibilityScheme.Collider) + { return GetAllVisibleSimObjPhysicsCollider( camera, maxDistance, filterSimObjs, out interactable ); - } else { + } + else + { return GetAllVisibleSimObjPhysicsDistance( camera, maxDistance, @@ -4518,15 +5203,19 @@ protected SimObjPhysics[] GetAllVisibleSimObjPhysics( float maxDistance, out SimObjPhysics[] interactable, IEnumerable filterSimObjs = null - ) { - if (this.visibilityScheme == VisibilityScheme.Collider) { + ) + { + if (this.visibilityScheme == VisibilityScheme.Collider) + { return GetAllVisibleSimObjPhysicsCollider( camera, maxDistance, filterSimObjs, out interactable ); - } else { + } + else + { return GetAllVisibleSimObjPhysicsDistance( camera, maxDistance, @@ -4536,27 +5225,36 @@ out interactable } } - protected VisibilityScheme getVisibilityScheme(string visibilityScheme = null) { + protected VisibilityScheme getVisibilityScheme(string visibilityScheme = null) + { VisibilityScheme visSchemeEnum; - if (visibilityScheme != null) { + if (visibilityScheme != null) + { visibilityScheme = visibilityScheme.ToLower(); if ( visibilityScheme == Enum.GetName(typeof(VisibilityScheme), VisibilityScheme.Collider).ToLower() - ) { + ) + { visSchemeEnum = VisibilityScheme.Collider; - } else if ( - visibilityScheme - == Enum.GetName(typeof(VisibilityScheme), VisibilityScheme.Distance).ToLower() - ) { + } + else if ( + visibilityScheme + == Enum.GetName(typeof(VisibilityScheme), VisibilityScheme.Distance).ToLower() + ) + { visSchemeEnum = VisibilityScheme.Distance; - } else { + } + else + { throw new System.NotImplementedException( $"Visibility scheme {visibilityScheme} is not implemented. Must be 'distance' or 'collider'." ); } - } else { + } + else + { visSchemeEnum = this.visibilityScheme; } return visSchemeEnum; @@ -4567,25 +5265,33 @@ public void GetVisibleObjects( string visibilityScheme = null, int? thirdPartyCameraIndex = null, List objectIds = null - ) { + ) + { VisibilityScheme visSchemeEnum = getVisibilityScheme(visibilityScheme); Camera camera; - if (thirdPartyCameraIndex.HasValue) { + if (thirdPartyCameraIndex.HasValue) + { camera = agentManager.thirdPartyCameras[thirdPartyCameraIndex.Value]; - if (visSchemeEnum != VisibilityScheme.Distance) { + if (visSchemeEnum != VisibilityScheme.Distance) + { throw new System.NotImplementedException( $"Visibility scheme {visSchemeEnum} is not implemented for third party cameras. Must be 'distance'." ); } - } else { + } + else + { camera = m_Camera; } List filterSimObjs = null; - if (objectIds != null) { - foreach (string objectId in objectIds) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + 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." ); @@ -4598,27 +5304,33 @@ public void GetVisibleObjects( SimObjPhysics[] interactable; SimObjPhysics[] visible; - if (visSchemeEnum == VisibilityScheme.Collider) { + if (visSchemeEnum == VisibilityScheme.Collider) + { visible = GetAllVisibleSimObjPhysicsCollider( camera: camera, maxDistance: maxDistance.GetValueOrDefault(this.maxVisibleDistance), // lgtm [cs/dereferenced-value-may-be-null] filterSimObjs: filterSimObjs, interactable: out interactable ); - } else if (visSchemeEnum == VisibilityScheme.Distance) { + } + else if (visSchemeEnum == VisibilityScheme.Distance) + { visible = GetAllVisibleSimObjPhysicsDistance( camera: camera, maxDistance: maxDistance.GetValueOrDefault(this.maxVisibleDistance), // lgtm [cs/dereferenced-value-may-be-null] filterSimObjs: filterSimObjs, interactable: out interactable ); - } else { + } + else + { throw new System.NotImplementedException( $"Visibility scheme {visSchemeEnum} is not implemented. Must be 'distance' or 'collider'." ); } #if UNITY_EDITOR - foreach (SimObjPhysics sop in visible) { + foreach (SimObjPhysics sop in visible) + { Debug.Log("Visible: " + sop.name); } #endif @@ -4627,13 +5339,15 @@ public void GetVisibleObjects( actionFinishedEmit(true, visible.Select(sop => sop.ObjectID).ToList()); } - public void GetObjaverseAnnotations() { + public void GetObjaverseAnnotations() + { Dictionary> annotations = new Dictionary>(); foreach ( Thor.Objaverse.ObjaverseAnnotation oa in GameObject.FindObjectsOfType() - ) { + ) + { SimObjPhysics sop = oa.gameObject.GetComponent(); annotations[sop.ObjectID] = new Dictionary(); @@ -4656,7 +5370,8 @@ public void ObjectsVisibleFromThirdPartyCamera( int thirdPartyCameraIndex, float? maxDistance = null, string visibilityScheme = null - ) { + ) + { GetVisibleObjects( maxDistance: maxDistance, visibilityScheme: visibilityScheme, @@ -4674,21 +5389,26 @@ protected SimObjPhysics[] GetAllVisibleSimObjPhysicsDistance( float maxDistance, IEnumerable filterSimObjs, out SimObjPhysics[] interactable - ) { - if (filterSimObjs == null) { + ) + { + if (filterSimObjs == null) + { filterSimObjs = physicsSceneManager.ObjectIdToSimObjPhysics.Values; } List visible = new List(); List interactableItems = new List(); Plane[] planes = GeometryUtility.CalculateFrustumPlanes(camera); - foreach (var sop in filterSimObjs) { + foreach (var sop in filterSimObjs) + { VisibilityCheck visCheck = isSimObjVisible(camera, sop, maxDistance, planes); - if (visCheck.visible) { + if (visCheck.visible) + { visible.Add(sop); } - if (visCheck.interactable) { + if (visCheck.interactable) + { interactableItems.Add(sop); } } @@ -4702,7 +5422,8 @@ private SimObjPhysics[] GetAllVisibleSimObjPhysicsCollider( float maxDistance, IEnumerable filterSimObjs, out SimObjPhysics[] interactable - ) { + ) + { HashSet currentlyVisibleItems = new HashSet(); HashSet interactableItems = new HashSet(); @@ -4712,7 +5433,8 @@ out SimObjPhysics[] interactable string, SimObjPhysics > pair in physicsSceneManager.ObjectIdToSimObjPhysics - ) { + ) + { // Set all objects to not be visible pair.Value.debugIsVisible = false; pair.Value.debugIsInteractable = false; @@ -4720,9 +5442,11 @@ out SimObjPhysics[] interactable #endif HashSet filter = null; - if (filterSimObjs != null) { + if (filterSimObjs != null) + { filter = new HashSet(filterSimObjs); - if (filter.Count == 0) { + if (filter.Count == 0) + { interactable = interactableItems.ToArray(); return currentlyVisibleItems.ToArray(); } @@ -4737,9 +5461,12 @@ out SimObjPhysics[] interactable point1; float radius; agentCapsuleCollider.ToWorldSpaceCapsule(out point0, out point1, out radius); - if (point0.y <= point1.y) { + if (point0.y <= point1.y) + { point1.y += maxDistance; - } else { + } + else + { point0.y += maxDistance; } @@ -4765,10 +5492,13 @@ out SimObjPhysics[] interactable ), QueryTriggerInteraction.Collide ); - if (collidersInView != null) { - foreach (Collider c in collidersInView) { + if (collidersInView != null) + { + foreach (Collider c in collidersInView) + { SimObjPhysics sop = ancestorSimObjPhysics(c.gameObject); - if (sop != null) { + if (sop != null) + { sopAndIncInvisibleTuples.Add((sop, false)); } } @@ -4785,11 +5515,15 @@ out SimObjPhysics[] interactable LayerMask.GetMask("SimObjInvisible"), QueryTriggerInteraction.Collide ); - if (invisibleCollidersInView != null) { - foreach (Collider c in invisibleCollidersInView) { - if (c.tag == "Receptacle") { + if (invisibleCollidersInView != null) + { + foreach (Collider c in invisibleCollidersInView) + { + if (c.tag == "Receptacle") + { SimObjPhysics sop = c.GetComponentInParent(); - if (sop != null) { + if (sop != null) + { sopAndIncInvisibleTuples.Add((sop, true)); } } @@ -4798,29 +5532,39 @@ out SimObjPhysics[] interactable // We have to explicitly add the items held by the arm as their // rigidbodies are set to not detect collisions - if (Arm != null && Arm.gameObject.activeSelf) { - foreach (SimObjPhysics sop in Arm.heldObjects.Keys) { + if (Arm != null && Arm.gameObject.activeSelf) + { + foreach (SimObjPhysics sop in Arm.heldObjects.Keys) + { sopAndIncInvisibleTuples.Add((sop, false)); } - } else if (SArm != null && SArm.gameObject.activeSelf) { - foreach (SimObjPhysics sop in SArm.heldObjects.Keys) { + } + else if (SArm != null && SArm.gameObject.activeSelf) + { + foreach (SimObjPhysics sop in SArm.heldObjects.Keys) + { sopAndIncInvisibleTuples.Add((sop, false)); } } - if (sopAndIncInvisibleTuples.Count != 0) { - foreach ((SimObjPhysics, bool) sopAndIncInvisible in sopAndIncInvisibleTuples) { + if (sopAndIncInvisibleTuples.Count != 0) + { + foreach ((SimObjPhysics, bool) sopAndIncInvisible in sopAndIncInvisibleTuples) + { SimObjPhysics sop = sopAndIncInvisible.Item1; bool includeInvisible = sopAndIncInvisible.Item2; // now we have a reference to our sim object - if (sop != null && (filter == null || filter.Contains(sop))) { + if (sop != null && (filter == null || filter.Contains(sop))) + { // check against all visibility points, accumulate count. If at least one point is visible, set object to visible - if (sop.VisibilityPoints != null && sop.VisibilityPoints.Length > 0) { + if (sop.VisibilityPoints != null && sop.VisibilityPoints.Length > 0) + { Transform[] visPoints = sop.VisibilityPoints; VisibilityCheck visCheck = new VisibilityCheck(); - foreach (Transform point in visPoints) { + 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( @@ -4829,7 +5573,8 @@ out SimObjPhysics[] interactable camera, includeInvisible ); - if (visCheck.visible && visCheck.interactable) { + 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. @@ -4842,14 +5587,18 @@ out SimObjPhysics[] interactable sop.debugIsVisible = visCheck.visible; sop.debugIsInteractable = visCheck.interactable; #endif - if (visCheck.visible && !currentlyVisibleItems.Contains(sop)) { + if (visCheck.visible && !currentlyVisibleItems.Contains(sop)) + { currentlyVisibleItems.Add(sop); } - if (visCheck.interactable && !interactableItems.Contains(sop)) { + if (visCheck.interactable && !interactableItems.Contains(sop)) + { interactableItems.Add(sop); } - } else { + } + else + { Debug.Log( "Error! Set at least 1 visibility point on SimObjPhysics " + sop @@ -4884,7 +5633,8 @@ out SimObjPhysics[] interactable return currentlyVisibleItemsToList.ToArray(); } - protected virtual LayerMask GetVisibilityRaycastLayerMask(bool withSimObjInvisible = false) { + protected virtual LayerMask GetVisibilityRaycastLayerMask(bool withSimObjInvisible = false) + { string[] layers = new string[] { "SimObjVisible", @@ -4894,7 +5644,8 @@ protected virtual LayerMask GetVisibilityRaycastLayerMask(bool withSimObjInvisib "Procedural0", "Agent" }; - if (withSimObjInvisible) { + if (withSimObjInvisible) + { layers = layers.Append("SimObjInvisible").ToArray(); } return LayerMask.GetMask(layers); @@ -4907,7 +5658,8 @@ protected VisibilityCheck CheckIfVisibilityPointRaycast( Vector3 position, Camera camera, bool includeInvisible - ) { + ) + { VisibilityCheck visCheck = new VisibilityCheck(); // now cast a ray out toward the point, if anything occludes this point, that point is not visible RaycastHit hit; @@ -4937,7 +5689,8 @@ bool includeInvisible // check raycast against both visible and invisible layers, to check against ReceptacleTriggerBoxes which are normally // ignored by the other raycast - if (includeInvisible) { + if (includeInvisible) + { if ( Physics.Raycast( camera.transform.position, @@ -4946,7 +5699,8 @@ bool includeInvisible raycastDistance, mask ) - ) { + ) + { if ( hit.transform == sop.transform || ( @@ -4956,7 +5710,8 @@ bool includeInvisible || (SArm != null && SArm.heldObjects[sop].Contains(hit.collider)) ) ) - ) { + ) + { visCheck.visible = true; visCheck.interactable = true; #if UNITY_EDITOR @@ -4982,7 +5737,8 @@ bool includeInvisible "Agent" ) ) - ) { + ) + { if ( hit.transform == sop.transform || ( @@ -4992,12 +5748,15 @@ bool includeInvisible || (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.... visCheck.visible = true; visCheck.interactable = true; - } else { + } + else + { // we didn't directly hit the sop we are checking for with this cast, // check if it's because we hit something see-through SimObjPhysics hitSop = hit.transform.GetComponent(); @@ -5007,7 +5766,8 @@ bool includeInvisible && 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; @@ -5026,13 +5786,15 @@ bool includeInvisible ); float[] hitDistances = new float[hits.Length]; - for (int i = 0; i < hitDistances.Length; i++) { + for (int i = 0; i < hitDistances.Length; i++) + { hitDistances[i] = hits[i].distance; // Vector3.Distance(hits[i].transform.position, camera.transform.position); } Array.Sort(hitDistances, hits); - foreach (RaycastHit h in hits) { + foreach (RaycastHit h in hits) + { if ( h.transform == sop.transform || ( @@ -5045,13 +5807,16 @@ bool includeInvisible && 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 visCheck.visible = true; visCheck.interactable = false; break; - } else { + } + else + { // Didn't find it, continue on only if the hit object was translucent SimObjPhysics sopHitOnPath = null; sopHitOnPath = h.transform.GetComponentInParent(); @@ -5060,7 +5825,8 @@ bool includeInvisible || !sopHitOnPath.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.CanSeeThrough ) - ) { + ) + { break; } } @@ -5069,7 +5835,8 @@ bool includeInvisible } #if UNITY_EDITOR - if (visCheck.visible) { + if (visCheck.visible) + { Debug.DrawLine(camera.transform.position, hit.point, Color.cyan, 0f); } #endif @@ -5083,7 +5850,8 @@ protected VisibilityCheck CheckIfVisibilityPointRaycast( Transform point, Camera camera, bool includeInvisible - ) { + ) + { VisibilityCheck visCheck = new VisibilityCheck(); // now cast a ray out toward the point, if anything occludes this point, that point is not visible RaycastHit hit; @@ -5106,7 +5874,8 @@ protected VisibilityCheck CheckIfVisibilityPointInViewport( Transform point, Camera camera, bool includeInvisible - ) { + ) + { VisibilityCheck visCheck = new VisibilityCheck(); Vector3 viewPoint = camera.WorldToViewportPoint(point.position); @@ -5126,7 +5895,8 @@ bool includeInvisible } #if UNITY_EDITOR - if (visCheck.visible) { + if (visCheck.visible) + { Debug.DrawLine(camera.transform.position, point.position, Color.cyan); } #endif @@ -5134,31 +5904,38 @@ bool includeInvisible return visCheck; } - public void DefaultAgentHand() { + public void DefaultAgentHand() + { ResetAgentHandPosition(); ResetAgentHandRotation(); IsHandDefault = true; } - public void ResetAgentHandPosition() { + public void ResetAgentHandPosition() + { AgentHand.transform.position = DefaultHandPosition.transform.position; } - public void ResetAgentHandRotation() { + public void ResetAgentHandRotation() + { AgentHand.transform.rotation = this.transform.rotation; } - public void ApproximateAgentRadius(int n = 12) { + public void ApproximateAgentRadius(int n = 12) + { Quaternion oldRot = this.transform.rotation; float radius = 0.0f; - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { this.transform.Rotate(0.0f, 360.0f / n, 0.0f); Physics.SyncTransforms(); Bounds b = UtilityFunctions.CreateEmptyBounds(); - foreach (Collider c in this.GetComponentsInChildren()) { - if (c.enabled && !c.isTrigger) { + foreach (Collider c in this.GetComponentsInChildren()) + { + if (c.enabled && !c.isTrigger) + { b.Encapsulate(c.bounds); } } @@ -5177,8 +5954,10 @@ public void ApproximateAgentRadius(int n = 12) { actionFinishedEmit(true, radius); } - public void SetAgentCapsuleRadius(float radius) { - if (radius < 0.0f) { + public void SetAgentCapsuleRadius(float radius) + { + if (radius < 0.0f) + { errorMessage = "Radius must be greater than 0.0"; actionFinishedEmit(false); return; @@ -5191,7 +5970,8 @@ public void SetAgentCapsuleRadius(float radius) { } // set random seed used by unity - public void SetRandomSeed(int seed) { + public void SetRandomSeed(int seed) + { UnityEngine.Random.InitState(seed); systemRandom = new System.Random(seed); actionFinishedEmit(true); @@ -5210,15 +5990,18 @@ public void InitialRandomSpawn( int numPlacementAttempts = 5, bool allowFloor = false, bool allowMoveable = false - ) { - if (numPlacementAttempts <= 0) { + ) + { + if (numPlacementAttempts <= 0) + { errorMessage = "numPlacementAttempts must be a positive integer."; actionFinished(false); return; } // something is in our hand AND we are trying to spawn it. Quick drop the object - if (ItemInHand != null) { + if (ItemInHand != null) + { Rigidbody rb = ItemInHand.GetComponent(); rb.isKinematic = false; rb.constraints = RigidbodyConstraints.None; @@ -5226,9 +6009,12 @@ public void InitialRandomSpawn( rb.collisionDetectionMode = CollisionDetectionMode.ContinuousDynamic; GameObject topObject = GameObject.Find("Objects"); - if (topObject != null) { + if (topObject != null) + { ItemInHand.transform.parent = topObject.transform; - } else { + } + else + { ItemInHand.transform.parent = null; } @@ -5238,36 +6024,45 @@ public void InitialRandomSpawn( } // default excludedReceptacles if null - if (excludedReceptacles == null) { + if (excludedReceptacles == null) + { excludedReceptacles = new String[0]; } List listOfExcludedReceptacleTypes = new List(); // check if strings used for excludedReceptacles are valid object types - foreach (string receptacleType in excludedReceptacles) { - try { + foreach (string receptacleType in excludedReceptacles) + { + try + { SimObjType objType = (SimObjType) System.Enum.Parse(typeof(SimObjType), receptacleType); listOfExcludedReceptacleTypes.Add(objType); - } catch (Exception) { + } + catch (Exception) + { errorMessage = "invalid Object Type used in excludedReceptacles array: " + receptacleType; actionFinished(false); return; } } - if (!allowFloor) { + if (!allowFloor) + { listOfExcludedReceptacleTypes.Add(SimObjType.Floor); } - if (excludedObjectIds == null) { + if (excludedObjectIds == null) + { excludedObjectIds = new String[0]; } HashSet excludedSimObjects = new HashSet(); - foreach (String objectId in excludedObjectIds) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + foreach (String objectId in excludedObjectIds) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = "Cannot find sim object with id '" + objectId + "'"; actionFinished(false); return; @@ -5288,11 +6083,13 @@ public void InitialRandomSpawn( allowMoveable: allowMoveable ); - if (success && !placeStationary) { + if (success && !placeStationary) + { // Let things come to rest for 2 seconds. bool autoSim = Physics.autoSimulation; Physics.autoSimulation = false; - for (int i = 0; i < 100; i++) { + for (int i = 0; i < 100; i++) + { PhysicsSceneManager.PhysicsSimulateTHOR(0.02f); } Physics.autoSimulation = autoSim; @@ -5300,7 +6097,8 @@ public void InitialRandomSpawn( physicsSceneManager.ResetObjectIdToSimObjPhysics(); //update image synthesis since scene has changed - if (this.imageSynthesis && this.imageSynthesis.enabled) { + if (this.imageSynthesis && this.imageSynthesis.enabled) + { this.imageSynthesis.OnSceneChange(); } @@ -5308,13 +6106,15 @@ public void InitialRandomSpawn( } // On demand public function for getting what sim objects are visible at that moment - public List GetAllVisibleSimObjPhysics(float maxDistance) { + public List GetAllVisibleSimObjPhysics(float maxDistance) + { var camera = this.GetComponentInChildren(); return new List(GetAllVisibleSimObjPhysics(camera, maxDistance)); } // not sure what this does, maybe delete? - public void SetTopLevelView(bool topView = false) { + public void SetTopLevelView(bool topView = false) + { inTopLevelView = topView; actionFinished(true); } @@ -5323,15 +6123,18 @@ public void SetTopLevelView(bool topView = false) { message: "This action is deprecated. Use GetMapViewCameraProperties with a third party camera instead.", error: false )] - public void ToggleMapView() { + public void ToggleMapView() + { SyncTransform[] syncInChildren; List structureObjsList = new List(); StructureObject[] structureObjs = GameObject.FindObjectsOfType(typeof(StructureObject)) as StructureObject[]; - foreach (StructureObject structure in structureObjs) { - switch (structure.WhatIsMyStructureObjectTag) { + foreach (StructureObject structure in structureObjs) + { + switch (structure.WhatIsMyStructureObjectTag) + { case StructureObjectTag.Ceiling: case StructureObjectTag.LightFixture: case StructureObjectTag.CeilingLight: @@ -5340,7 +6143,8 @@ public void ToggleMapView() { } } - if (inTopLevelView) { + if (inTopLevelView) + { inTopLevelView = false; m_Camera.orthographic = false; m_Camera.transform.localPosition = lastLocalCameraPosition; @@ -5351,20 +6155,25 @@ public void ToggleMapView() { .transform.GetComponent() .StopCullingThingsForASecond = false; syncInChildren = gameObject.GetComponentsInChildren(); - foreach (SyncTransform sync in syncInChildren) { + foreach (SyncTransform sync in syncInChildren) + { sync.StopSyncingForASecond = false; } - foreach (StructureObject so in structureObjsList) { + foreach (StructureObject so in structureObjsList) + { UpdateDisplayGameObject(so.gameObject, true); } - } else { + } + else + { // stop culling the agent's body so it's visible from the top? m_Camera .transform.GetComponent() .StopCullingThingsForASecond = true; syncInChildren = gameObject.GetComponentsInChildren(); - foreach (SyncTransform sync in syncInChildren) { + foreach (SyncTransform sync in syncInChildren) + { sync.StopSyncingForASecond = true; } @@ -5379,28 +6188,36 @@ public void ToggleMapView() { m_Camera.orthographicSize = (float)cameraProps["orthographicSize"]; cameraOrthSize = m_Camera.orthographicSize; - foreach (StructureObject so in structureObjsList) { + foreach (StructureObject so in structureObjsList) + { UpdateDisplayGameObject(so.gameObject, false); } } actionFinished(true); } - protected Dictionary getMapViewCameraProperties() { + protected Dictionary getMapViewCameraProperties() + { StructureObject[] structureObjs = GameObject.FindObjectsOfType(typeof(StructureObject)) as StructureObject[]; Bounds bounds = new Bounds(); bool boundsDidUpdate = false; - if (structureObjs != null) { - foreach (StructureObject structure in structureObjs) { + if (structureObjs != null) + { + foreach (StructureObject structure in structureObjs) + { if ( structure.WhatIsMyStructureObjectTag == StructureObjectTag.Ceiling && structure.gameObject.name.ToLower().Contains("ceiling") - ) { - if (!boundsDidUpdate) { + ) + { + if (!boundsDidUpdate) + { bounds = structure.GetComponent().bounds; - } else { + } + else + { Bounds b = structure.GetComponent().bounds; bounds.Encapsulate(b); } @@ -5410,11 +6227,14 @@ protected Dictionary getMapViewCameraProperties() { } float yValue; - if (boundsDidUpdate) { + if (boundsDidUpdate) + { // There's a ceiling component in the room! // Let's use it's bounds. (Likely iTHOR.) yValue = bounds.min.y; - } else { + } + else + { // There's no component in the room! // Let's use the bounds from every object. (Likely RoboTHOR.) bounds = new Bounds(); @@ -5428,11 +6248,13 @@ protected Dictionary getMapViewCameraProperties() { // solves an edge case where the lowest point of the ceiling // is actually below the floor :0 var sceneName = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; - if (sceneName == "FloorPlan309_physics") { + if (sceneName == "FloorPlan309_physics") + { yValue = 2f; } - return new Dictionary() { + return new Dictionary() + { ["position"] = new Vector3(midX, yValue, midZ), ["rotation"] = new Vector3(90, 0, 0), ["orthographicSize"] = Math.Max( @@ -5443,12 +6265,15 @@ protected Dictionary getMapViewCameraProperties() { }; } - public void GetMapViewCameraProperties() { + public void GetMapViewCameraProperties() + { actionFinishedEmit(success: true, actionReturn: getMapViewCameraProperties()); } - protected IEnumerable pointsOnSurfaceOfBoxCollider(BoxCollider bc, int divisions) { - if (divisions < 2) { + protected IEnumerable pointsOnSurfaceOfBoxCollider(BoxCollider bc, int divisions) + { + if (divisions < 2) + { throw new ArgumentException( $"divisions must be >= 2 (currently equals {divisions})." ); @@ -5462,32 +6287,40 @@ protected IEnumerable pointsOnSurfaceOfBoxCollider(BoxCollider bc, int List xCenterVals = new List(); List yCenterVals = new List(); List zCenterVals = new List(); - for (int i = 1; i < divisions - 1; i++) { + for (int i = 1; i < divisions - 1; i++) + { float alpha = (2f * i / (divisions - 1f)); xCenterVals.Add(-halfSize.x + halfSize.x * alpha); yCenterVals.Add(-halfSize.y + halfSize.y * alpha); zCenterVals.Add(-halfSize.z + halfSize.z * alpha); } - for (int whichX = 0; whichX < 2; whichX++) { + for (int whichX = 0; whichX < 2; whichX++) + { List xVals = whichX == 1 ? xMinMax : xCenterVals; - for (int whichY = 0; whichY < 2; whichY++) { + for (int whichY = 0; whichY < 2; whichY++) + { List yVals = whichY == 1 ? yMinMax : yCenterVals; - for (int whichZ = 0; whichZ < 2; whichZ++) { + for (int whichZ = 0; whichZ < 2; whichZ++) + { List zVals = whichZ == 1 ? zMinMax : zCenterVals; - if (whichX + whichY + whichZ == 0) { + if (whichX + whichY + whichZ == 0) + { continue; } # if UNITY_EDITOR Vector3? lastPoint = null; # endif - foreach (float x in xVals) { - foreach (float y in yVals) { - foreach (float z in zVals) { + 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) ); @@ -5509,10 +6342,12 @@ 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) { + if (sop0 == null || sop1 == null) + { actionFinishedEmit(false); // Error message set already by getSimObjectFromId return; } @@ -5527,7 +6362,8 @@ public void BBoxDistance(string objectId0, string objectId1, int divisions = 3) // Must temporarily enable the box collider c1 as otherwise the call to `ClosestPoint` will return subtly // incorrect results. c1.enabled = true; - foreach (Vector3 p in pointsOnSurfaceOfBoxCollider(c0, divisions)) { + foreach (Vector3 p in pointsOnSurfaceOfBoxCollider(c0, divisions)) + { Vector3 pLocal = c1.transform.InverseTransformPoint(p) - c1.center; Vector3 size = c1.size; // 0.5 used below because `size` corresponds to full box extents, not half extents @@ -5536,7 +6372,8 @@ public void BBoxDistance(string objectId0, string objectId1, int divisions = 3) (-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"); # endif @@ -5555,14 +6392,16 @@ public void BBoxDistance(string objectId0, string objectId1, int divisions = 3) // Must temporarily enable the box collider c1 as otherwise the call to `ClosestPoint` will return subtly // incorrect results. c0.enabled = true; - foreach (Vector3 p in pointsOnSurfaceOfBoxCollider(c1, divisions)) { + foreach (Vector3 p in pointsOnSurfaceOfBoxCollider(c1, divisions)) + { 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) - ) { + ) + { # if UNITY_EDITOR Debug.Log($"{objectId1} is inside {objectId0}, distance is 0"); # endif @@ -5584,10 +6423,12 @@ public void BBoxDistance(string objectId0, string objectId1, int divisions = 3) actionFinishedEmit(true, actionReturn: dist); } - public void CheckUnobstructedPathBetweenObjectCenters(string objectId0, string objectId1) { + public void CheckUnobstructedPathBetweenObjectCenters(string objectId0, string objectId1) + { SimObjPhysics sop0 = getSimObjectFromId(objectId0); SimObjPhysics sop1 = getSimObjectFromId(objectId1); - if (sop0 == null || sop1 == null) { + if (sop0 == null || sop1 == null) + { actionFinishedEmit(false); // Error message set already by getSimObjectFromId return; } @@ -5602,10 +6443,12 @@ public void CheckUnobstructedPathBetweenObjectCenters(string objectId0, string o Vector3 p1 = c1.transform.TransformPoint(c1.center); HashSet okColliders = new HashSet(); - foreach (Collider c in sop0.GetComponentsInChildren()) { + foreach (Collider c in sop0.GetComponentsInChildren()) + { okColliders.Add(c); } - foreach (Collider c in sop1.GetComponentsInChildren()) { + foreach (Collider c in sop1.GetComponentsInChildren()) + { okColliders.Add(c); } @@ -5623,8 +6466,10 @@ RaycastHit hit in Physics.RaycastAll( LayerMask.GetMask("SimObjVisible"), QueryTriggerInteraction.Ignore ) - ) { - if (!okColliders.Contains(hit.collider)) { + ) + { + if (!okColliders.Contains(hit.collider)) + { SimObjPhysics hitSop = ancestorSimObjPhysics(hit.collider.gameObject); string hitId = (hitSop != null) ? hitSop.ObjectID : hit.collider.gameObject.name; @@ -5658,7 +6503,8 @@ protected HashSet whatObjectOn( int divisions, float belowDistance, bool returnOnFirstHit - ) { + ) + { sop.syncBoundingBoxes(forceCreateObjectOrientedBoundingBox: true); // Ensures the sop has an object oriented bounding box attached List points = pointsOnSurfaceOfBoxCollider( @@ -5672,12 +6518,15 @@ bool returnOnFirstHit List collidersToDisable = sop.GetComponentsInChildren() .Where(c => c.enabled) .ToList(); - try { - foreach (Collider c in collidersToDisable) { + try + { + foreach (Collider c in collidersToDisable) + { c.enabled = false; } - for (int i = 0; i < divisions * divisions; i++) { // divisions**2 as this is the number of points on a single face + for (int i = 0; i < divisions * divisions; i++) + { // divisions**2 as this is the number of points on a single face Vector3 point = points[i]; # if UNITY_EDITOR @@ -5697,11 +6546,14 @@ bool returnOnFirstHit belowDistance + 1e-3f, LayerMask.GetMask("SimObjVisible") ) - ) { + ) + { SimObjPhysics onSop = ancestorSimObjPhysics(hit.collider.gameObject); - if (onSop != null) { + if (onSop != null) + { # if UNITY_EDITOR - if (!onObjectIds.Contains(onSop.ObjectID)) { + if (!onObjectIds.Contains(onSop.ObjectID)) + { Debug.Log($"{sop.ObjectID} is on {onSop.ObjectID}"); } # endif @@ -5716,8 +6568,11 @@ bool returnOnFirstHit } } } - } finally { - foreach (Collider c in collidersToDisable) { + } + finally + { + foreach (Collider c in collidersToDisable) + { c.enabled = true; } } @@ -5728,9 +6583,11 @@ public void CheckWhatObjectOn( string objectId, int divisions = 3, float belowDistance = 1e-2f - ) { + ) + { SimObjPhysics sop = getSimObjectFromId(objectId); - if (sop == null) { + if (sop == null) + { actionFinishedEmit(false); // Error message set already by getSimObjectFromId return; } @@ -5750,12 +6607,15 @@ public void CheckWhatObjectsOn( List objectIds, int divisions = 3, float belowDistance = 1e-2f - ) { + ) + { Dictionary> objectIdToOnObjectId = new Dictionary>(); - foreach (string objectId in objectIds) { + foreach (string objectId in objectIds) + { SimObjPhysics sop = getSimObjectFromId(objectId); - if (sop == null) { + if (sop == null) + { actionFinishedEmit(false); // Error message set already by getSimObjectFromId return; } @@ -5776,12 +6636,15 @@ Get the 2D (x, z) convex hull of a GameObject. See the Get2DSemanticHulls Will return null if the input game object has no mesh vertices. */ - protected List> Get2DSemanticHull(GameObject go) { + protected List> Get2DSemanticHull(GameObject go) + { List vertices = new List(); float maxY = -float.PositiveInfinity; - foreach (MeshFilter meshFilter in go.GetComponentsInChildren()) { - foreach (Vector3 localVertex in meshFilter.mesh.vertices) { + 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) @@ -5790,7 +6653,8 @@ protected List> Get2DSemanticHull(GameObject go) { } } - if (vertices.Count == 0) { + if (vertices.Count == 0) + { return null; } @@ -5800,7 +6664,8 @@ protected List> Get2DSemanticHull(GameObject go) { #if UNITY_EDITOR DefaultVertex2D[] pointsOnHullArray = miconvexHull.Result.ToArray(); - for (int i = 0; i < pointsOnHullArray.Length; i++) { + for (int i = 0; i < pointsOnHullArray.Length; i++) + { DefaultVertex2D p0 = pointsOnHullArray[i]; DefaultVertex2D p1 = pointsOnHullArray[(i + 1) % pointsOnHullArray.Length]; Debug.DrawLine( @@ -5813,7 +6678,8 @@ protected List> Get2DSemanticHull(GameObject go) { #endif List> toReturn = new List>(); - foreach (DefaultVertex2D v in miconvexHull.Result) { + foreach (DefaultVertex2D v in miconvexHull.Result) + { List tuple = new List(); tuple.Add((float)v.X); tuple.Add((float)v.Y); @@ -5839,36 +6705,44 @@ to the convex hull of the corresponding object. public void Get2DSemanticHulls( List objectIds = null, List objectTypes = null - ) { - if (objectIds != null && objectTypes != null) { + ) + { + if (objectIds != null && objectTypes != null) + { throw new ArgumentException( "Only one of objectIds and objectTypes can have a non-null value." ); } HashSet allowedObjectTypesSet = null; - if (objectTypes != null) { + if (objectTypes != null) + { allowedObjectTypesSet = new HashSet(objectTypes); } // Only consider sim objects which correspond to objectIds if given. SimObjPhysics[] sopsFilteredByObjectIds = null; - if (objectIds != null) { + if (objectIds != null) + { sopsFilteredByObjectIds = objectIds .Select(key => physicsSceneManager.ObjectIdToSimObjPhysics[key]) .ToArray(); - } else { + } + else + { sopsFilteredByObjectIds = GameObject.FindObjectsOfType(); } Dictionary>> objectIdToConvexHull = new Dictionary>>(); - foreach (SimObjPhysics sop in sopsFilteredByObjectIds) { + foreach (SimObjPhysics sop in sopsFilteredByObjectIds) + { // Skip objects that don't have one of the required types (if given) if ( allowedObjectTypesSet != null && !allowedObjectTypesSet.Contains(sop.Type.ToString()) - ) { + ) + { continue; } @@ -5877,18 +6751,23 @@ public void Get2DSemanticHulls( #endif List> hullPoints = Get2DSemanticHull(sop.gameObject); - if (hullPoints != null) { + if (hullPoints != null) + { objectIdToConvexHull[sop.ObjectID] = Get2DSemanticHull(sop.gameObject); } } actionFinishedEmit(true, objectIdToConvexHull); } - public void Get2DSemanticHull(string objectId) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void Get2DSemanticHull(string objectId) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"No object with ID {objectId}"; actionFinishedEmit(false); - } else { + } + else + { actionFinishedEmit( true, Get2DSemanticHull( @@ -5898,19 +6777,24 @@ public void Get2DSemanticHull(string objectId) { } } - public void UpdateDisplayGameObject(GameObject go, bool display) { - if (go != null) { + public void UpdateDisplayGameObject(GameObject go, bool display) + { + if (go != null) + { foreach ( MeshRenderer mr in go.GetComponentsInChildren() as MeshRenderer[] - ) { - if (!initiallyDisabledRenderers.Contains(mr.GetInstanceID())) { + ) + { + if (!initiallyDisabledRenderers.Contains(mr.GetInstanceID())) + { mr.enabled = 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; @@ -5918,7 +6802,8 @@ public void HighlightObject(string objectId, float lineWidth = 0.095f, float? he float minZ = bbox.center.z - bbox.size.z / 2; float maxZ = bbox.center.z + bbox.size.z / 2; - if (height == null) { + if (height == null) + { height = bbox.center.y + bbox.size.y / 2; } @@ -5942,9 +6827,11 @@ public void HighlightObject(string objectId, float lineWidth = 0.095f, float? he } // Hide a previously visualized path. - public void HideVisualizedPath(string pathName = "PathVisualization") { + public void HideVisualizedPath(string pathName = "PathVisualization") + { GameObject parent = GameObject.Find(pathName); - if (parent != null) { + if (parent != null) + { // using SetActive(false) instead of Destroy // since Destroy has hung the controller on // occassion. @@ -5964,25 +6851,29 @@ public void VisualizePath( float gridWidth = 0.045f, bool displayCount = false, string pathName = "PathVisualization" - ) { + ) + { // We do not have multiple path visualizations at the same time // by default. This is because we often want to override it // instead of have multiple of them. You can have multiple of them // by changing the pathName parameter. var path = positions; - if (path == null || path.Count() == 0) { + if (path == null || path.Count() == 0) + { throw new ArgumentException("Path cannot be null or empty."); } - if (grid) { + if (grid) + { getReachablePositions(visualize: grid, gridColor: gridColor, gridWidth: gridWidth); } GameObject parent = GameObject.Find(pathName); GameObject go; GameObject endGo; - if (parent == null) { + if (parent == null) + { parent = new GameObject(pathName); endGo = Instantiate( DebugTargetPointPrefab, @@ -5991,34 +6882,41 @@ public void VisualizePath( ); endGo.name = "End"; endGo.transform.parent = parent.transform; - if (endText != null) { + if (endText != null) + { endGo.GetComponentInChildren().text = endText; } go = Instantiate(DebugPointPrefab, path[0], Quaternion.identity); go.name = "Start"; go.transform.parent = parent.transform; - if (startText != null) { + if (startText != null) + { go.GetComponentInChildren().text = startText; } - } else { + } + else + { parent.SetActive(true); endGo = parent.transform.Find("End").gameObject; endGo.transform.position = path[path.Count() - 1]; - if (endText != null) { + if (endText != null) + { endGo.GetComponentInChildren().text = endText; } go = parent.transform.Find("Start").gameObject; go.transform.position = path[0]; - if (startText != null) { + if (startText != null) + { go.GetComponentInChildren().text = startText; } } var lineRenderer = go.GetComponentInChildren(); - if (pathGradient != null && pathGradient.colorKeys.Length > 0) { + if (pathGradient != null && pathGradient.colorKeys.Length > 0) + { lineRenderer.colorGradient = pathGradient; } @@ -6030,12 +6928,14 @@ 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) { + private void VisualizePath(Vector3 startPosition, NavMeshPath path) + { var pathDistance = 0.0; #if UNITY_EDITOR Debug.Log($"Visualize Path, corner lenght: {path.corners.Length}"); #endif - for (int i = 0; i < path.corners.Length - 1; i++) { + 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( @@ -6045,7 +6945,8 @@ private void VisualizePath(Vector3 startPosition, NavMeshPath path) { pathDistance += Vector3.Distance(path.corners[i], path.corners[i + 1]); } - if (pathDistance > 0.0001) { + if (pathDistance > 0.0001) + { // Better way to draw spheres var go = GameObject.CreatePrimitive(PrimitiveType.Sphere); go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); @@ -6054,38 +6955,50 @@ private void VisualizePath(Vector3 startPosition, NavMeshPath path) { } } - private string[] objectTypeToObjectIds(string objectTypeString) { + private string[] objectTypeToObjectIds(string objectTypeString) + { List objectIds = new List(); - try { + try + { SimObjType objectType = (SimObjType) Enum.Parse( typeof(SimObjType), objectTypeString.Replace(" ", String.Empty), true ); - foreach (var s in physicsSceneManager.ObjectIdToSimObjPhysics) { - if (s.Value.ObjType == objectType) { + foreach (var s in physicsSceneManager.ObjectIdToSimObjPhysics) + { + if (s.Value.ObjType == objectType) + { objectIds.Add(s.Value.objectID); } } - } catch (ArgumentException exception) { + } + catch (ArgumentException exception) + { Debug.Log(exception); } return objectIds.ToArray(); } - public void ObjectTypeToObjectIds(string objectType) { - try { + public void ObjectTypeToObjectIds(string objectType) + { + try + { var objectIds = objectTypeToObjectIds(objectType); actionFinished(true, objectIds.ToArray()); - } catch (ArgumentException exception) { + } + catch (ArgumentException exception) + { errorMessage = "Invalid object type '" + objectType + "'. " + exception.Message; actionFinished(false); } } - protected SimObjPhysics getSimObjectFromId(string objectId) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + protected SimObjPhysics getSimObjectFromId(string objectId) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = "Cannot find sim object with id '" + objectId + "'"; return null; } @@ -6095,14 +7008,19 @@ protected SimObjPhysics getSimObjectFromId(string objectId) { return sop; } - private SimObjPhysics getSimObjectFromTypeOrId(string objectType, string objectId) { - if (!String.IsNullOrEmpty(objectType) && String.IsNullOrEmpty(objectId)) { + private SimObjPhysics getSimObjectFromTypeOrId(string objectType, string objectId) + { + if (!String.IsNullOrEmpty(objectType) && String.IsNullOrEmpty(objectId)) + { var ids = objectTypeToObjectIds(objectType); - if (ids.Length == 0) { + if (ids.Length == 0) + { throw new ArgumentException( $"Object type {objectType} was not found in the scene." ); - } else if (ids.Length > 1) { + } + else if (ids.Length > 1) + { throw new ArgumentException( $"Multiple objects of type {objectType} were found in the scene, cannot disambiguate." ); @@ -6111,25 +7029,29 @@ private SimObjPhysics getSimObjectFromTypeOrId(string objectType, string objectI objectId = ids[0]; } - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { throw new ArgumentException($"Cannot find sim object with id {objectId}"); } SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; - if (sop == null) { + if (sop == null) + { throw new ArgumentException($"Object with id {objectId} is null"); } return sop; } - private SimObjPhysics getSimObjectFromTypeOrId(ServerAction action) { + private SimObjPhysics getSimObjectFromTypeOrId(ServerAction action) + { var objectId = action.objectId; var objectType = action.objectType; return getSimObjectFromTypeOrId(objectType, objectId); } - public void VisualizeGrid() { + public void VisualizeGrid() + { var reachablePositions = getReachablePositions(1.0f, 10000, true); actionFinished(true, reachablePositions); } @@ -6140,14 +7062,18 @@ public string objectNavExpertAction( Vector3? position = null, IEnumerable navMeshIds = null, bool sampleFromNavmesh = true - ) { + ) + { NavMeshPath path = new UnityEngine.AI.NavMeshPath(); Func visibilityTest; - if (!String.IsNullOrEmpty(objectType) || !String.IsNullOrEmpty(objectId)) { + if (!String.IsNullOrEmpty(objectType) || !String.IsNullOrEmpty(objectId)) + { 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( @@ -6161,9 +7087,11 @@ public string objectNavExpertAction( visibilityTest = () => true; } - if (path.status == UnityEngine.AI.NavMeshPathStatus.PathComplete) { + if (path.status == UnityEngine.AI.NavMeshPathStatus.PathComplete) + { int parts = (int)Math.Round(360f / rotateStepDegrees); - if (Math.Abs((parts * 1.0f) - 360f / rotateStepDegrees) > 1e-5) { + if (Math.Abs((parts * 1.0f) - 360f / rotateStepDegrees) > 1e-5) + { errorMessage = "Invalid rotate step degrees for agent, must divide 360 without a remainder."; return null; @@ -6174,26 +7102,32 @@ public string objectNavExpertAction( Quaternion startRotation = this.transform.rotation; Vector3 startCameraRot = m_Camera.transform.localEulerAngles; - if (path.corners.Length <= 1) { - if (visibilityTest()) { + if (path.corners.Length <= 1) + { + if (visibilityTest()) + { return null; } int relRotate = 0; int relHorizon = 0; int bestNumActions = 1000000; - for (int i = -numLeft; i <= numRight; i++) { + for (int i = -numLeft; i <= numRight; i++) + { transform.Rotate(0.0f, i * rotateStepDegrees, 0.0f); - for (int horizon = -1; horizon <= 2; horizon++) { + for (int horizon = -1; horizon <= 2; horizon++) + { m_Camera.transform.localEulerAngles = new Vector3( 30f * horizon, 0.0f, 0.0f ); - if (visibilityTest()) { + if (visibilityTest()) + { int numActions = Math.Abs(i) + Math.Abs(horizon - (int)(startCameraRot.x / 30f)); - if (numActions < bestNumActions) { + if (numActions < bestNumActions) + { bestNumActions = numActions; relRotate = i; relHorizon = horizon - (int)(startCameraRot.x / 30f); @@ -6213,19 +7147,30 @@ public string objectNavExpertAction( //transform.Rotate(0.0f, relRotate * rotateStepDegrees, 0.0f); #endif - if (relRotate != 0) { - if (relRotate < 0) { + if (relRotate != 0) + { + if (relRotate < 0) + { return "RotateLeft"; - } else { + } + else + { return "RotateRight"; } - } else if (relHorizon != 0) { - if (relHorizon < 0) { + } + else if (relHorizon != 0) + { + if (relHorizon < 0) + { return "LookUp"; - } else { + } + else + { return "LookDown"; } - } else { + } + else + { errorMessage = "Object doesn't seem visible from any rotation/horizon."; } return null; @@ -6236,27 +7181,33 @@ public string objectNavExpertAction( int whichBest = 0; float bestDistance = 1000f; string errorMessages = ""; - for (int i = -numLeft; i <= numRight; i++) { + for (int i = -numLeft; i <= numRight; i++) + { transform.Rotate(0.0f, i * rotateStepDegrees, 0.0f); Physics.SyncTransforms(); bool couldMove = moveInDirection(this.transform.forward * gridSize); - if (couldMove) { + if (couldMove) + { float newDistance = Math.Abs(nextCorner.x - transform.position.x) + Math.Abs(nextCorner.z - transform.position.z); - if (newDistance + 1e-6 < bestDistance) { + if (newDistance + 1e-6 < bestDistance) + { bestDistance = newDistance; whichBest = i; } - } else { + } + else + { errorMessages = errorMessages + " " + errorMessage; } transform.position = startPosition; transform.rotation = startRotation; } - if (bestDistance >= 1000f) { + if (bestDistance >= 1000f) + { errorMessage = "Can't seem to move in any direction. Error messages: " + errorMessages; return null; @@ -6270,14 +7221,21 @@ public string objectNavExpertAction( Debug.Log(whichBest); #endif - if (whichBest < 0) { + if (whichBest < 0) + { return "RotateLeft"; - } else if (whichBest > 0) { + } + else if (whichBest > 0) + { return "RotateRight"; - } else { + } + else + { return "MoveAhead"; } - } else { + } + else + { errorMessage = "Path to target could not be found"; return null; } @@ -6288,7 +7246,8 @@ public void ObjectNavExpertAction( string objectType = null, Vector3? position = null, IEnumerable navMeshIds = null - ) { + ) + { string action = objectNavExpertAction( objectId, objectType, @@ -6296,10 +7255,13 @@ public void ObjectNavExpertAction( navMeshIds: navMeshIds ); - if (action != null) { + if (action != null) + { actionFinished(true, action); return; - } else { + } + else + { actionFinished(false); return; } @@ -6311,10 +7273,12 @@ public UnityEngine.AI.NavMeshPath getShortestPath( ServerAction action = null, IEnumerable navMeshIds = null, bool sampleFromNavmesh = true - ) { + ) + { var startPosition = this.transform.position; var startRotation = this.transform.rotation; - if (!useAgentTransform) { + if (!useAgentTransform) + { startPosition = action.position; startRotation = Quaternion.Euler(action.rotation); } @@ -6337,7 +7301,8 @@ private void getShortestPath( float allowedError, IEnumerable navMeshIds = null, bool sampleFromNavmesh = true - ) { + ) + { SimObjPhysics sop = getSimObjectFromTypeOrId(objectType, objectId); var path = GetSimObjectNavMeshTarget( sop, @@ -6359,7 +7324,8 @@ public void GetShortestPath( float allowedError = DefaultAllowedErrorInShortestPath, IEnumerable navMeshIds = null, bool sampleFromNavmesh = true - ) { + ) + { getShortestPath( objectType: objectType, objectId: objectId, @@ -6399,7 +7365,8 @@ public void GetShortestPath( float allowedError = DefaultAllowedErrorInShortestPath, IEnumerable navMeshIds = null, bool sampleFromNavmesh = true - ) { + ) + { // this.transform.position = new Vector3(this.transform.position.x, 0.01f, this.transform.position.z); getShortestPath( objectType, @@ -6418,7 +7385,8 @@ public void GetShortestPath( float allowedError = DefaultAllowedErrorInShortestPath, IEnumerable navMeshIds = null, bool sampleFromNavmesh = true - ) { + ) + { getShortestPath( objectType, objectId, @@ -6436,16 +7404,19 @@ private bool GetPathFromReachablePositions( Transform agentTransform, string targetSimObjectId, UnityEngine.AI.NavMeshPath path - ) { + ) + { Vector3 fixedPosition = new Vector3(float.MinValue, float.MinValue, float.MinValue); // bool success = false; var PhysicsController = this; var targetSOP = getSimObjectFromId(targetSimObjectId); - foreach (var pos in sortedPositions) { + foreach (var pos in sortedPositions) + { agentTransform.position = pos; agentTransform.LookAt(targetPosition); - if (IsInteractable(targetSOP)) { + if (IsInteractable(targetSOP)) + { fixedPosition = pos; // success = true; break; @@ -6466,7 +7437,8 @@ protected Collider[] overlapCollider( Vector3 newCenter, float rotateBy, int layerMask - ) { + ) + { Vector3 center, halfExtents; Quaternion orientation; @@ -6486,7 +7458,8 @@ protected Collider[] overlapCollider( SphereCollider sphere, Vector3 newCenter, int layerMask - ) { + ) + { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); @@ -6503,7 +7476,8 @@ protected Collider[] overlapCollider( Vector3 newCenter, float rotateBy, int layerMask - ) { + ) + { Vector3 point0, point1; float radius; @@ -6528,8 +7502,10 @@ int layerMask ); } - protected bool handObjectCanFitInPosition(Vector3 newAgentPosition, float rotation) { - if (ItemInHand == null) { + protected bool handObjectCanFitInPosition(Vector3 newAgentPosition, float rotation) + { + if (ItemInHand == null) + { return true; } @@ -6548,25 +7524,34 @@ protected bool handObjectCanFitInPosition(Vector3 newAgentPosition, float rotati "Procedural3", "Procedural0" ); - foreach (CapsuleCollider cc in soInHand.GetComponentsInChildren()) { - foreach (Collider c in overlapCollider(cc, newHandPosition, rotation, layerMask)) { - if (!hasAncestor(c.transform.gameObject, gameObject)) { + foreach (CapsuleCollider cc in soInHand.GetComponentsInChildren()) + { + foreach (Collider c in overlapCollider(cc, newHandPosition, rotation, layerMask)) + { + if (!hasAncestor(c.transform.gameObject, gameObject)) + { return false; } } } - foreach (BoxCollider bc in soInHand.GetComponentsInChildren()) { - foreach (Collider c in overlapCollider(bc, newHandPosition, rotation, layerMask)) { - if (!hasAncestor(c.transform.gameObject, gameObject)) { + foreach (BoxCollider bc in soInHand.GetComponentsInChildren()) + { + foreach (Collider c in overlapCollider(bc, newHandPosition, rotation, layerMask)) + { + if (!hasAncestor(c.transform.gameObject, gameObject)) + { return false; } } } - foreach (SphereCollider sc in soInHand.GetComponentsInChildren()) { - foreach (Collider c in overlapCollider(sc, newHandPosition, layerMask)) { - if (!hasAncestor(c.transform.gameObject, gameObject)) { + foreach (SphereCollider sc in soInHand.GetComponentsInChildren()) + { + foreach (Collider c in overlapCollider(sc, newHandPosition, layerMask)) + { + if (!hasAncestor(c.transform.gameObject, gameObject)) + { return false; } } @@ -6584,7 +7569,8 @@ public RaycastHit[] capsuleCastAllForAgent( Vector3 dir, float moveMagnitude, 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); @@ -6609,7 +7595,8 @@ int layerMask protected bool isAgentCapsuleColliding( HashSet collidersToIgnore = null, bool includeErrorMessage = false - ) { + ) + { int layerMask = LayerMask.GetMask( "SimObjVisible", "Procedural1", @@ -6623,17 +7610,23 @@ Collider c in PhysicsExtensions.OverlapCapsule( layerMask, QueryTriggerInteraction.Ignore ) - ) { + ) + { if ( (!hasAncestor(c.transform.gameObject, gameObject)) && (collidersToIgnore == null || !collidersToIgnoreDuringMovement.Contains(c)) - ) { - if (includeErrorMessage) { + ) + { + if (includeErrorMessage) + { SimObjPhysics sop = ancestorSimObjPhysics(c.gameObject); String collidedWithName; - if (sop != null) { + if (sop != null) + { collidedWithName = sop.ObjectID; - } else { + } + else + { collidedWithName = c.gameObject.name; } errorMessage = $"Collided with: {collidedWithName}."; @@ -6653,7 +7646,8 @@ protected bool isAgentBoxColliding( Transform transformWithBoxCollider, HashSet collidersToIgnore = null, bool includeErrorMessage = false - ) { + ) + { int layerMask = LayerMask.GetMask( "SimObjVisible", "Procedural1", @@ -6667,17 +7661,23 @@ Collider c in PhysicsExtensions.OverlapBox( layerMask, QueryTriggerInteraction.Ignore ) - ) { + ) + { if ( (!hasAncestor(c.transform.gameObject, gameObject)) && (collidersToIgnore == null || !collidersToIgnoreDuringMovement.Contains(c)) - ) { - if (includeErrorMessage) { + ) + { + if (includeErrorMessage) + { SimObjPhysics sop = ancestorSimObjPhysics(c.gameObject); String collidedWithName; - if (sop != null) { + if (sop != null) + { collidedWithName = sop.ObjectID; - } else { + } + else + { collidedWithName = c.gameObject.name; } errorMessage = $"Collided with: {collidedWithName}."; @@ -6693,7 +7693,8 @@ Collider c in PhysicsExtensions.OverlapBox( return false; } - protected Collider[] objectsCollidingWithAgent() { + protected Collider[] objectsCollidingWithAgent() + { int layerMask = LayerMask.GetMask( "SimObjVisible", "Procedural1", @@ -6715,7 +7716,8 @@ public virtual RaycastHit[] CastBodyTrayectory( float moveMagnitude, int layerMask, CapsuleData cachedCapsule - ) { + ) + { return capsuleCastAllForAgent( capsule: cachedCapsule, skinWidth: skinWidth, @@ -6731,7 +7733,8 @@ public bool getReachablePositionToObjectVisible( out Vector3 pos, float gridMultiplier = 1.0f, int maxStepCount = 10000 - ) { + ) + { var capsule = GetAgentCapsule(); float sw = m_CharacterController.skinWidth; Queue pointsQueue = new Queue(); @@ -6756,10 +7759,12 @@ public bool getReachablePositionToObjectVisible( ); int stepsTaken = 0; pos = Vector3.negativeInfinity; - while (pointsQueue.Count != 0) { + while (pointsQueue.Count != 0) + { stepsTaken += 1; Vector3 p = pointsQueue.Dequeue(); - if (!goodPoints.Contains(p)) { + if (!goodPoints.Contains(p)) + { goodPoints.Add(p); transform.position = p; var rot = transform.rotation; @@ -6770,7 +7775,8 @@ public bool getReachablePositionToObjectVisible( transform.rotation = rot; - if (isVisible) { + if (isVisible) + { pos = p; return true; } @@ -6778,9 +7784,11 @@ public bool getReachablePositionToObjectVisible( HashSet objectsAlreadyColliding = new HashSet( objectsCollidingWithAgent() ); - foreach (Vector3 d in directions) { + foreach (Vector3 d in directions) + { Vector3 newPosition = p + d * gridSize * gridMultiplier; - if (seenPoints.Contains(newPosition)) { + if (seenPoints.Contains(newPosition)) + { continue; } seenPoints.Add(newPosition); @@ -6795,25 +7803,29 @@ public bool getReachablePositionToObjectVisible( ); bool shouldEnqueue = true; - foreach (RaycastHit hit in hits) { + foreach (RaycastHit hit in hits) + { 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) - ) { + ) + { shouldEnqueue = false; break; } } - if (!shouldEnqueue) { + if (!shouldEnqueue) + { continue; } bool inBounds = agentManager.SceneBounds.Contains(newPosition); - if (errorMessage == "" && !inBounds) { + if (errorMessage == "" && !inBounds) + { errorMessage = "In " + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name @@ -6831,7 +7843,8 @@ public bool getReachablePositionToObjectVisible( || handObjectCanFitInPosition(newPosition, 180.0f) || handObjectCanFitInPosition(newPosition, 270.0f) ); - if (shouldEnqueue) { + if (shouldEnqueue) + { pointsQueue.Enqueue(newPosition); #if UNITY_EDITOR Debug.DrawLine(p, newPosition, Color.cyan, 100000f); @@ -6842,7 +7855,8 @@ public bool getReachablePositionToObjectVisible( } } } - if (stepsTaken > Math.Floor(maxStepCount / (gridSize * gridSize))) { + if (stepsTaken > Math.Floor(maxStepCount / (gridSize * gridSize))) + { throw new InvalidOperationException( "Too many steps taken in GetReachablePositions!" ); @@ -6865,7 +7879,8 @@ private UnityEngine.AI.NavMeshPath GetSimObjectNavMeshTarget( bool visualize = false, IEnumerable navMeshIds = null, bool sampleFromNavmesh = true - ) { + ) + { var targetTransform = targetSOP.transform; var targetSimObject = targetTransform.GetComponentInChildren(); var agentTransform = this.transform; @@ -6888,7 +7903,8 @@ out fixedPosition 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})" ); @@ -6907,7 +7923,8 @@ out fixedPosition ); var pathDistance = 0.0f; - for (int i = 0; i < path.corners.Length - 1; i++) { + for (int i = 0; i < path.corners.Length - 1; i++) + { #if UNITY_EDITOR Debug.DrawLine(path.corners[i], path.corners[i + 1], Color.red, 10.0f); Debug.Log("Corner " + i + ": " + path.corners[i]); @@ -6917,13 +7934,15 @@ out fixedPosition return path; } - protected float getFloorY(float x, float start_y, float z) { + protected float getFloorY(float x, float start_y, float z) + { int layerMask = ~LayerMask.GetMask("Agent", "SimObjInvisible"); float y = start_y; RaycastHit hit; Ray ray = new Ray(new Vector3(x, y, z), -transform.up); - if (!Physics.Raycast(ray, out hit, 100f, layerMask)) { + if (!Physics.Raycast(ray, out hit, 100f, layerMask)) + { throw new InvalidOperationException( $"Raycast could not find the floor from position: {x},{start_y},{z}" ); @@ -6931,12 +7950,14 @@ protected float getFloorY(float x, float start_y, float z) { return hit.point.y; } - protected float getFloorY(float x, float z) { + protected float getFloorY(float x, float z) + { int layerMask = ~LayerMask.GetMask("Agent"); Ray ray = new Ray(transform.position, -transform.up); RaycastHit hit; - if (!Physics.Raycast(ray, out hit, 10f, layerMask)) { + if (!Physics.Raycast(ray, out hit, 10f, layerMask)) + { errorMessage = "Could not find the floor"; return float.NegativeInfinity; } @@ -6951,13 +7972,15 @@ protected void SafelyComputeFirstNavMeshPath( IEnumerable navMeshIds, 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) { + if (navmeshSurfaces.Count() > 0) + { defaultNavmeshIds = new List() { NavMeshSurfaceExtended.activeSurfaces[0].agentTypeID @@ -6967,7 +7990,8 @@ protected void SafelyComputeFirstNavMeshPath( IEnumerable navMeshIdsWIthDefault = navMeshIds != null ? navMeshIds.Select(x => (int?)x) : defaultNavmeshIds; - foreach (var navmeshId in navMeshIdsWIthDefault) { + foreach (var navmeshId in navMeshIdsWIthDefault) + { SafelyComputeNavMeshPath( start: start, target: target, @@ -6979,7 +8003,8 @@ protected void SafelyComputeFirstNavMeshPath( navmehsAgent: navMeshAgent, navmeshSurfaces: navmeshSurfaces ); - if (path.status == UnityEngine.AI.NavMeshPathStatus.PathComplete) { + if (path.status == UnityEngine.AI.NavMeshPathStatus.PathComplete) + { return; } } @@ -6995,7 +8020,8 @@ protected void SafelyComputeNavMeshPath( bool sampleFromNavmesh = true, UnityEngine.AI.NavMeshAgent navmehsAgent = null, // for speedup NavMeshSurfaceExtended[] navmeshSurfaces = null - ) { + ) + { var navMeshAgent = navmehsAgent ?? this.GetComponentInChildren(); navMeshAgent.enabled = true; @@ -7012,7 +8038,8 @@ protected void SafelyComputeNavMeshPath( var pathStartPosition = new Vector3(start.x, start.y, start.z); var pathTargetPosition = new Vector3(target.x, start.y, target.z); - if (sampleFromNavmesh) { + if (sampleFromNavmesh) + { float floorY = Math.Min( getFloorY(start.x, start.y, start.z), getFloorY(target.x, target.y, target.z) @@ -7041,14 +8068,17 @@ protected void SafelyComputeNavMeshPath( pathStartPosition = startHit.position; pathTargetPosition = targetHit.position; - if (!startWasHit || !targetWasHit) { + if (!startWasHit || !targetWasHit) + { this.GetComponentInChildren().enabled = false; - if (!startWasHit) { + if (!startWasHit) + { throw new InvalidOperationException( $"No point on NavMesh near startPosition {startPositionWithFloorY}." ); } - if (!targetWasHit) { + if (!targetWasHit) + { throw new InvalidOperationException( $"No point on NavMesh near targetPosition {targetPositionWithFloorY}." ); @@ -7071,7 +8101,8 @@ protected void SafelyComputeNavMeshPath( targetPositionWithFloorY.z ) ); - if (startOffset > allowedError && targetOffset > allowedError) { + if (startOffset > allowedError && targetOffset > allowedError) + { this.GetComponentInChildren().enabled = false; var extraDebug = !string.IsNullOrEmpty(debugTargetObjectId) ? $" For objectId: '{debugTargetObjectId}'" @@ -7127,7 +8158,8 @@ protected void SafelyComputeNavMeshPath( // bool pathSuccess = UnityEngine.AI.NavMesh.CalculatePath( // startHit.position, targetHit.position, UnityEngine.AI.NavMesh.AllAreas, path // ); - if (path.status != UnityEngine.AI.NavMeshPathStatus.PathComplete) { + if (path.status != UnityEngine.AI.NavMeshPathStatus.PathComplete) + { var extraDebug = !string.IsNullOrEmpty(debugTargetObjectId) ? $" For objectId: '{debugTargetObjectId}'" : ""; @@ -7144,39 +8176,49 @@ protected void SafelyComputeNavMeshPath( this.GetComponentInChildren().enabled = false; } - private void randomizeSmoothness(string objectId) { + private void randomizeSmoothness(string objectId) + { SimObjPhysics sop = getSimObjectFromId(objectId: objectId); - if (sop == null) { + if (sop == null) + { throw new ArgumentException($"No object with id {objectId} found."); } Renderer[] renderers = sop.GetComponentsInChildren(); - foreach (Renderer renderer in renderers) { - foreach (Material material in renderer.materials) { + foreach (Renderer renderer in renderers) + { + foreach (Material material in renderer.materials) + { material.SetFloat("_Metallic", Random.Range(0.0f, 1.0f)); material.SetFloat("_GlossMapScale", Random.Range(0.0f, 1.0f)); } } } - public void MakeAllObjectsUnbreakable() { + public void MakeAllObjectsUnbreakable() + { UpdateBreakabilityOfAllObjects(true); } - public void MakeAllObjectsBreakable() { + public void MakeAllObjectsBreakable() + { UpdateBreakabilityOfAllObjects(false); } - private void UpdateBreakabilityOfAllObjects(bool isUnbreakable) { + private void UpdateBreakabilityOfAllObjects(bool isUnbreakable) + { SimObjPhysics[] simObjs = GameObject.FindObjectsOfType(typeof(SimObjPhysics)) as SimObjPhysics[]; - if (simObjs != null) { - foreach (SimObjPhysics sop in simObjs) { + if (simObjs != null) + { + foreach (SimObjPhysics sop in simObjs) + { if ( sop.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.CanBreak ) - ) { + ) + { sop.GetComponentInChildren().Unbreakable = isUnbreakable; } } @@ -7184,16 +8226,20 @@ private void UpdateBreakabilityOfAllObjects(bool isUnbreakable) { actionFinished(true); } - public void RandomizeSmoothness(string objectId) { + public void RandomizeSmoothness(string objectId) + { randomizeSmoothness(objectId: objectId); actionFinished(success: true); } - public void RandomizeSmoothness(string[] objectIds) { - if (objectIds == null) { + public void RandomizeSmoothness(string[] objectIds) + { + if (objectIds == null) + { throw new ArgumentNullException(nameof(objectIds)); } - foreach (string objectId in objectIds) { + foreach (string objectId in objectIds) + { randomizeSmoothness(objectId: objectId); } actionFinished(success: true); @@ -7205,7 +8251,8 @@ public void GetShortestPathToPoint( float allowedError = DefaultAllowedErrorInShortestPath, IEnumerable navMeshIds = null, bool sampleFromNavmesh = true - ) { + ) + { var path = new UnityEngine.AI.NavMeshPath(); SafelyComputeFirstNavMeshPath( position, @@ -7223,7 +8270,8 @@ public void GetShortestPathToPoint( float allowedError = DefaultAllowedErrorInShortestPath, IEnumerable navMeshIds = null, bool sampleFromNavmesh = true - ) { + ) + { var startPosition = this.transform.position; GetShortestPathToPoint( startPosition, @@ -7234,9 +8282,11 @@ public void GetShortestPathToPoint( ); } - public void VisualizeShortestPaths(ServerAction action) { + public void VisualizeShortestPaths(ServerAction action) + { SimObjPhysics sop = getSimObjectFromTypeOrId(action.objectType, action.objectId); - if (sop == null) { + if (sop == null) + { actionFinished(false); return; } @@ -7245,7 +8295,8 @@ public void VisualizeShortestPaths(ServerAction action) { Instantiate(DebugTargetPointPrefab, sop.transform.position, Quaternion.identity); var results = new List(); - for (var i = 0; i < action.positions.Count; i++) { + for (var i = 0; i < action.positions.Count; i++) + { var pos = action.positions[i]; var go = Instantiate(DebugPointPrefab, pos, Quaternion.identity); var textMesh = go.GetComponentInChildren(); @@ -7261,7 +8312,8 @@ public void VisualizeShortestPaths(ServerAction action) { var lineRenderer = go.GetComponentInChildren(); - if (action.pathGradient != null && action.pathGradient.colorKeys.Length > 0) { + if (action.pathGradient != null && action.pathGradient.colorKeys.Length > 0) + { lineRenderer.colorGradient = action.pathGradient; } lineRenderer.startWidth = 0.015f; @@ -7269,7 +8321,8 @@ public void VisualizeShortestPaths(ServerAction action) { results.Add(path.status == UnityEngine.AI.NavMeshPathStatus.PathComplete); - if (path.status == UnityEngine.AI.NavMeshPathStatus.PathComplete) { + 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)) @@ -7284,10 +8337,12 @@ 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++) { + for (var i = 0; i < waypoints.Count; i++) + { var waypoint = waypoints[i]; var pos = waypoint.position; var go = Instantiate(DebugPointPrefab, pos, Quaternion.identity); @@ -7303,7 +8358,8 @@ public void VisualizeWaypoints( actionFinished(true); } - public void CameraCrack(int randomSeed = 0) { + public void CameraCrack(int randomSeed = 0) + { GameObject canvas = Instantiate(CrackedCameraCanvas); CrackedCameraManager camMan = canvas.GetComponent(); @@ -7311,7 +8367,8 @@ public void CameraCrack(int randomSeed = 0) { actionFinished(true); } - public void SimObjPhysicsTypeIsReceptacle(float receptacleRatioTolerance = 0.001f) { + public void SimObjPhysicsTypeIsReceptacle(float receptacleRatioTolerance = 0.001f) + { var sops = GameObject .FindObjectOfType() .GetPrefabs() @@ -7325,7 +8382,8 @@ public void SimObjPhysicsTypeIsReceptacle(float receptacleRatioTolerance = 0.001 sop.SecondaryProperties.Contains(SimObjSecondaryProperty.Receptacle) ) .GroupBy(sop => sop.ObjType) - .Select(g => new { + .Select(g => new + { simObjType = g.Key.ToString(), totalInCategory = categoriesCount[g.Key], totalIsReceptacle = categoriesCount[g.Key] @@ -7343,8 +8401,10 @@ public static void TryToAddReceptacleTriggerBox( SimObjPhysics sop, float yThresMax = 0.075f, float worldOffset = -100f - ) { - if (sop == null) { + ) + { + if (sop == null) + { throw new NotImplementedException( $"Adding receptacle trigger box is only possible the active game object, has an associated SimObjPhysics script." ); @@ -7355,19 +8415,23 @@ public static void TryToAddReceptacleTriggerBox( 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; @@ -7406,12 +8470,14 @@ public static void TryToAddReceptacleTriggerBox( 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})"); @@ -7426,16 +8492,22 @@ public static void TryToAddReceptacleTriggerBox( 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); - } else { + } + else + { yVals.Add(dummyY); } - } else { + } + else + { yVals.Add(dummyY); } } @@ -7449,20 +8521,24 @@ public static void TryToAddReceptacleTriggerBox( 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]; @@ -7470,7 +8546,8 @@ public static void TryToAddReceptacleTriggerBox( if ( 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); @@ -7479,7 +8556,8 @@ public static void TryToAddReceptacleTriggerBox( } } - if (iZ > 0) { + if (iZ > 0) + { int group = posToGroup[(iX, iZ - 1)]; float otherMaxYVal = groupToMaxYVal[group]; float otherMinYVal = groupToMinYVal[group]; @@ -7487,7 +8565,8 @@ public static void TryToAddReceptacleTriggerBox( if ( 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); @@ -7507,43 +8586,52 @@ public static void TryToAddReceptacleTriggerBox( // TODO: Improve this logic so that we get rectangles more intelligently 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)); } } @@ -7565,10 +8653,12 @@ public static void TryToAddReceptacleTriggerBox( 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; @@ -7584,7 +8674,8 @@ public static void TryToAddReceptacleTriggerBox( Math.Abs(start.Item1 - end.Item1), Math.Abs(start.Item2 - end.Item2) ) <= 1 - ) { + ) + { continue; } @@ -7607,10 +8698,12 @@ public static void TryToAddReceptacleTriggerBox( Transform t = sop.transform.Find("ReceptacleTriggerBoxes"); GameObject go = null; - if (t != null) { + if (t != null) + { GameObject.DestroyImmediate(t.gameObject); } - if (t == null) { + if (t == null) + { go = new GameObject("ReceptacleTriggerBoxes"); go.transform.position = sop.transform.position; go.transform.parent = sop.transform; @@ -7619,7 +8712,8 @@ public static void TryToAddReceptacleTriggerBox( 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]; @@ -7640,15 +8734,19 @@ public static void TryToAddReceptacleTriggerBox( 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) + { GameObject.DestroyImmediate(tmc.gameObject); } - foreach (Collider c in enabledColliders) { + foreach (Collider c in enabledColliders) + { c.enabled = true; } Physics.SyncTransforms(); @@ -7665,7 +8763,8 @@ public void CreateSkybox( string rightTexturePath, string frontTexturePath, string backTexturePath - ) { + ) + { Texture2D upTexture = new Texture2D(2, 2); upTexture.LoadImage(File.ReadAllBytes(upTexturePath)); Texture2D downTexture = new Texture2D(2, 2); @@ -7692,9 +8791,11 @@ string backTexturePath actionFinished(true); } - public ActionFinished CreateRuntimeAsset(ProceduralAsset asset) { + public ActionFinished CreateRuntimeAsset(ProceduralAsset asset) + { var assetDb = GameObject.FindObjectOfType(); - if (assetDb.ContainsAssetKey(asset.name)) { + if (assetDb.ContainsAssetKey(asset.name)) + { return new ActionFinished( success: false, errorMessage: $"'{asset.name}' already exists in ProceduralAssetDatabase, trying to create procedural object twice, call `SpawnAsset` instead.", @@ -7729,9 +8830,11 @@ public ActionFinished CreateRuntimeAsset( string extension = ".msgpack.gz", ObjectAnnotations annotations = null, bool serializable = false - ) { + ) + { var assetDb = GameObject.FindObjectOfType(); - if (assetDb.ContainsAssetKey(id)) { + if (assetDb.ContainsAssetKey(id)) + { return new ActionFinished( success: false, errorMessage: $"'{id}' already exists in ProceduralAssetDatabase, trying to create procedural object twice, call `SpawnAsset` instead.", @@ -7752,7 +8855,8 @@ public ActionFinished CreateRuntimeAsset( }; extension = !extension.StartsWith(".") ? $".{extension}" : extension; extension = extension.Trim(); - if (!supportedExtensions.Contains(extension)) { + if (!supportedExtensions.Contains(extension)) + { return new ActionFinished( success: false, errorMessage: $"Unsupported extension `{extension}`. Only supported: {string.Join(", ", supportedExtensions)}", @@ -7761,7 +8865,8 @@ public ActionFinished CreateRuntimeAsset( } var filename = $"{id}{extension}"; var filepath = Path.GetFullPath(Path.Combine(dir, id, filename)); - if (!File.Exists(filepath)) { + if (!File.Exists(filepath)) + { return new ActionFinished( success: false, actionReturn: null, @@ -7779,28 +8884,35 @@ public ActionFinished CreateRuntimeAsset( using FileStream rawFileStream = File.Open(filepath, FileMode.Open); using var resultStream = new MemoryStream(); var stageIndex = 0; - if ("gz" == presentStages[stageIndex]) { + if ("gz" == presentStages[stageIndex]) + { using var decompressor = new GZipStream(rawFileStream, CompressionMode.Decompress); decompressor.CopyTo(resultStream); stageIndex++; - } else { + } + else + { rawFileStream.CopyTo(resultStream); } ProceduralAsset procAsset = null; var debug = stageIndex < presentStages.Length ? presentStages[stageIndex] : "null"; - if (stageIndex < presentStages.Length && presentStages[stageIndex] == "msgpack") { + if (stageIndex < presentStages.Length && presentStages[stageIndex] == "msgpack") + { procAsset = MessagePack.MessagePackSerializer.Deserialize( resultStream.ToArray(), MessagePack.Resolvers.ThorContractlessStandardResolver.Options ); - } else if (presentStages.Length == 1) { + } + 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() { + var serializer = new Newtonsoft.Json.JsonSerializerSettings() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver, ObjectCreationHandling = ObjectCreationHandling.Replace @@ -7808,7 +8920,9 @@ public ActionFinished CreateRuntimeAsset( var json = reader.ReadToEnd(); // procAsset = Newtonsoft.Json.JsonConvert.DeserializeObject(reader.ReadToEnd(), serializer); procAsset = JsonConvert.DeserializeObject(json); - } else { + } + else + { return new ActionFinished( success: false, errorMessage: $"Unexpected error with extension `{extension}`, filepath: `{filepath}`, compression stages: {string.Join(".", presentStages)}. Only supported: {string.Join(", ", supportedExtensions)}", @@ -7845,15 +8959,18 @@ public ActionFinished CreateRuntimeAsset( return new ActionFinished(success: true, actionReturn: assetData); } - public void GetStreamingAssetsPath() { + public void GetStreamingAssetsPath() + { actionFinished(success: true, actionReturn: Application.streamingAssetsPath); } - public void GetPersistentDataPath() { + public void GetPersistentDataPath() + { actionFinished(success: true, actionReturn: Application.persistentDataPath); } - public void CreateHouse(ProceduralHouse house) { + public void CreateHouse(ProceduralHouse house) + { var rooms = house.rooms.SelectMany(room => house.rooms); var materials = ProceduralTools.GetMaterials(); @@ -7867,7 +8984,8 @@ public void CreateHouse(ProceduralHouse house) { .Concat(new List() { house.proceduralParameters.ceilingMaterial.name }) ); var missingIds = materialIds.Where(id => id != null && !materials.ContainsKey(id)); - if (missingIds.Count() > 0) { + if (missingIds.Count() > 0) + { actionFinished( success: false, errorMessage: ( @@ -7877,9 +8995,12 @@ public void CreateHouse(ProceduralHouse house) { ); } - try { + 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); @@ -7889,7 +9010,8 @@ public void CreateHouse(ProceduralHouse house) { actionFinished(true); } - public void GetHouseFromTemplate(HouseTemplate template) { + public void GetHouseFromTemplate(HouseTemplate template) + { var rooms = template.rooms.Select(room => room.Value); // TODO: Bring back for validation and add tests when making this API public @@ -7939,45 +9061,54 @@ public void GetHouseFromTemplate(HouseTemplate template) { actionFinished(true, house); } - protected Dictionary getAssetMetadata(GameObject asset) { - if (asset.GetComponent() == null) { + protected Dictionary getAssetMetadata(GameObject asset) + { + if (asset.GetComponent() == null) + { return null; } var simObj = asset.GetComponent(); var bb = simObj.AxisAlignedBoundingBox; - return new Dictionary() { + return new Dictionary() + { ["name"] = simObj.gameObject.name, ["objectType"] = simObj.Type.ToString(), ["primaryProperty"] = simObj.PrimaryProperty.ToString(), ["secondaryProperties"] = simObj .SecondaryProperties.Select(s => s.ToString()) .ToList(), - ["boundingBox"] = new BoundingBox() { + ["boundingBox"] = new BoundingBox() + { min = bb.center - bb.size / 2.0f, max = bb.center + bb.size / 2.0f } }; } - public void GetAssetDatabase() { + public void GetAssetDatabase() + { var assetDb = GameObject.FindObjectOfType(); - if (assetDb == null) { + if (assetDb == null) + { errorMessage = "ProceduralAssetDatabase not in scene."; actionFinishedEmit(false); return; } var metadata = new Dictionary>(); - foreach (GameObject p in assetDb.GetPrefabs()) { + foreach (GameObject p in assetDb.GetPrefabs()) + { var meta = getAssetMetadata(p); - if (meta == null) { + if (meta == null) + { continue; } var name = meta["name"].ToString(); - if (metadata.ContainsKey(name)) { + if (metadata.ContainsKey(name)) + { throw new InvalidOperationException( $"There are duplicate assets with the name '{name}'." ); @@ -7989,21 +9120,25 @@ public void GetAssetDatabase() { actionFinishedEmit(true, metadata); } - public void AssetInDatabase(string assetId) { + public void AssetInDatabase(string assetId) + { var assetMap = ProceduralTools.getAssetMap(); actionFinishedEmit(success: true, actionReturn: assetMap.ContainsKey(assetId)); } - public void TouchProceduralLRUCache(List assetIds) { + public void TouchProceduralLRUCache(List assetIds) + { var assetDB = GameObject.FindObjectOfType(); assetDB.touchProceduralLRUCache(assetIds); actionFinishedEmit(success: true); } - public void DeleteLRUFromProceduralCache(int assetLimit) { + public void DeleteLRUFromProceduralCache(int assetLimit) + { var assetDB = GameObject.FindObjectOfType(); - if (assetDB == null) { + if (assetDB == null) + { errorMessage = "No ProceduralAssetDatabase seems to exist."; // Debug.Log(errorMessage); actionFinishedEmit(success: false); @@ -8015,7 +9150,8 @@ public void DeleteLRUFromProceduralCache(int assetLimit) { actionFinishedEmit(success: true); } - public void GetLRUCacheKeys() { + public void GetLRUCacheKeys() + { var assetDB = GameObject.FindObjectOfType(); actionFinishedEmit( success: true, @@ -8023,10 +9159,12 @@ public void GetLRUCacheKeys() { ); } - public void AssetsInDatabase(List assetIds, bool updateProceduralLRUCache = false) { + public void AssetsInDatabase(List assetIds, bool updateProceduralLRUCache = false) + { var assetDB = GameObject.FindObjectOfType(); - if (updateProceduralLRUCache) { + if (updateProceduralLRUCache) + { assetDB.touchProceduralLRUCache(assetIds); } var assetMap = assetDB.assetMap; @@ -8040,9 +9178,11 @@ public void AssetsInDatabase(List assetIds, bool updateProceduralLRUCach // 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) { + public void GetAssetHoleMetadata(string assetId) + { var assetDb = GameObject.FindObjectOfType(); - if (assetDb == null) { + if (assetDb == null) + { actionFinishedEmit( success: false, errorMessage: "ProceduralAssetDatabase not in scene." @@ -8050,7 +9190,8 @@ public void GetAssetHoleMetadata(string assetId) { } var assetMap = ProceduralTools.getAssetMap(); - if (!assetMap.ContainsKey(assetId)) { + if (!assetMap.ContainsKey(assetId)) + { actionFinishedEmit( success: false, errorMessage: $"Asset '{assetId}' is not contained in asset database, you may need to rebuild asset database." @@ -8061,12 +9202,15 @@ public void GetAssetHoleMetadata(string assetId) { var result = ProceduralTools.getHoleAssetBoundingBox(assetId); - if (result == null) { + if (result == null) + { actionFinishedEmit( 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 { + } + else + { actionFinishedEmit(success: false, actionReturn: result); } } @@ -8077,7 +9221,8 @@ public void GetInSceneAssetGeometry( bool triangles = false, bool uv = false, bool normals = false - ) { + ) + { SimObjPhysics asset = getInteractableSimObjectFromId( objectId: objectId, forceAction: true @@ -8085,26 +9230,31 @@ public void GetInSceneAssetGeometry( MeshFilter[] meshFilters = asset.GetComponentsInChildren(); var geometries = new List(); - foreach (MeshFilter meshFilter in meshFilters) { + foreach (MeshFilter meshFilter in meshFilters) + { var geo = new Dictionary(); Mesh mesh = meshFilter.mesh; Matrix4x4 localToWorld = meshFilter.gameObject.transform.localToWorldMatrix; var globalVertices = new List(); - foreach (Vector3 vertex in mesh.vertices) { + foreach (Vector3 vertex in mesh.vertices) + { // converts from local space to world space. Vector3 worldCoordinate = localToWorld.MultiplyPoint3x4(vertex); globalVertices.Add(worldCoordinate); } geo["vertices"] = globalVertices; - if (triangles) { + if (triangles) + { geo["triangles"] = mesh.triangles; } - if (uv) { + if (uv) + { geo["uv"] = mesh.uv; } - if (normals) { + if (normals) + { geo["normals"] = mesh.normals; } geometries.Add(geo); @@ -8112,7 +9262,8 @@ public void GetInSceneAssetGeometry( actionFinishedEmit(success: true, actionReturn: geometries); } - public void DestroyHouse() { + public void DestroyHouse() + { Destroy(GameObject.Find("Objects")); Destroy(GameObject.Find("Structure")); Destroy(GameObject.Find("ProceduralLighting")); @@ -8131,16 +9282,19 @@ public void GetAsset3DGeometry( bool triangleIndices = true, bool uvs = false, bool normals = false - ) { + ) + { var assetDb = GameObject.FindObjectOfType(); - if (assetDb == null) { + if (assetDb == null) + { errorMessage = "ProceduralAssetDatabase not in scene."; actionFinishedEmit(false); return; } var assetMap = ProceduralTools.getAssetMap(); - if (!assetMap.ContainsKey(assetId)) { + if (!assetMap.ContainsKey(assetId)) + { errorMessage = $"Object '{assetId}' is not contained in asset database, you may need to rebuild asset database."; actionFinishedEmit(false); @@ -8152,7 +9306,8 @@ public void GetAsset3DGeometry( var meshFilters = asset.GetComponentsInChildren(); var geoList = meshFilters - .Select(meshFilter => { + .Select(meshFilter => + { var mesh = meshFilter.sharedMesh; var geo = new Geometry3D() { vertices = mesh.vertices }; geo.triangleIndices = triangleIndices ? mesh.triangles : null; @@ -8169,10 +9324,13 @@ public ActionFinished SpawnAsset( string generatedId, Vector3? position = null, Vector3? rotation = null - ) { + ) + { var assetDb = GameObject.FindObjectOfType(); - if (assetDb == null) { - return new ActionFinished() { + if (assetDb == null) + { + return new ActionFinished() + { toEmitState = true, success = false, errorMessage = "ProceduralAssetDatabase not in scene." @@ -8180,8 +9338,10 @@ public ActionFinished SpawnAsset( } var assetMap = ProceduralTools.getAssetMap(); - if (!assetMap.ContainsKey(assetId)) { - return new ActionFinished() { + if (!assetMap.ContainsKey(assetId)) + { + return new ActionFinished() + { toEmitState = true, success = false, errorMessage = @@ -8202,7 +9362,8 @@ public ActionFinished SpawnAsset( ); spawned.isStatic = true; - foreach (var rigidBody in spawned.GetComponentsInChildren()) { + foreach (var rigidBody in spawned.GetComponentsInChildren()) + { rigidBody.useGravity = false; rigidBody.isKinematic = true; } @@ -8210,9 +9371,11 @@ public ActionFinished SpawnAsset( physicsSceneManager.SetupScene(generateObjectIds: false); var bounds = GetObjectSphereBounds(spawned); - return new ActionFinished() { + return new ActionFinished() + { success = true, - actionReturn = new ObjectSphereBounds() { + actionReturn = new ObjectSphereBounds() + { id = spawned.name, worldSpaceCenter = bounds.center, radius = bounds.extents.magnitude @@ -8220,15 +9383,18 @@ public ActionFinished SpawnAsset( }; } - public void GetAssetSphereBounds(string assetId) { + public void GetAssetSphereBounds(string assetId) + { var assetDb = GameObject.FindObjectOfType(); - if (assetDb == null) { + if (assetDb == null) + { errorMessage = "ProceduralAssetDatabase not in scene."; actionFinishedEmit(false); return; } var assetMap = ProceduralTools.getAssetMap(); - if (!assetMap.ContainsKey(assetId)) { + if (!assetMap.ContainsKey(assetId)) + { errorMessage = $"Asset '{assetId}' is not contained in asset database, you may need to rebuild asset database."; actionFinishedEmit(false); @@ -8241,7 +9407,8 @@ public void GetAssetSphereBounds(string assetId) { actionFinishedEmit( true, - new ObjectSphereBounds() { + new ObjectSphereBounds() + { id = assetId, worldSpaceCenter = bounds.center, radius = bounds.extents.magnitude @@ -8249,9 +9416,11 @@ public void GetAssetSphereBounds(string assetId) { ); } - public void LookAtObjectCenter(string objectId = "asset_0", Vector3? position = null) { + public void LookAtObjectCenter(string objectId = "asset_0", Vector3? position = null) + { var obj = GameObject.Find(objectId); - if (obj == null) { + if (obj == null) + { errorMessage = $"Object does not exist in scene."; actionFinishedEmit(false); return; @@ -8261,9 +9430,11 @@ public void LookAtObjectCenter(string objectId = "asset_0", Vector3? position = actionFinished(true, obj.name); } - public void SetSkybox(string materialId) { + public void SetSkybox(string materialId) + { var materialDb = ProceduralTools.GetMaterials(); - if (materialDb == null) { + if (materialDb == null) + { errorMessage = "ProceduralAssetDatabase not in scene."; actionFinishedEmit(false); return; @@ -8271,13 +9442,15 @@ public void SetSkybox(string materialId) { RenderSettings.skybox = materialDb.getAsset(materialId); } - public void SetSkybox(Color color) { + public void SetSkybox(Color color) + { m_Camera.clearFlags = CameraClearFlags.SolidColor; m_Camera.backgroundColor = color; actionFinished(true); } - private void LookAtObjectCenter(GameObject gameObject) { + private void LookAtObjectCenter(GameObject gameObject) + { var bounds = GetObjectSphereBounds(gameObject); // objectBounds = bounds; // var size = 2.0f * Mathf.Tan(m_Camera.fieldOfView / 2.0f) * bounds.extents.magnitude; @@ -8289,7 +9462,8 @@ private void LookAtObjectCenter(GameObject gameObject) { bounds.center + Vector3.forward * (radius + dist); #if UNITY_EDITOR debugSpheres.Add( - new DebugSphere() { + new DebugSphere() + { color = Color.yellow, radius = radius, worldSpaceCenter = bounds.center @@ -8301,23 +9475,27 @@ private void LookAtObjectCenter(GameObject gameObject) { m_Camera.transform.LookAt(bounds.center, Vector3.up); } - private Bounds GetObjectSphereBounds(GameObject gameObject) { + private Bounds GetObjectSphereBounds(GameObject gameObject) + { return gameObject .GetComponentsInChildren() .Select(renderer => renderer.bounds) .Aggregate( new Bounds(), - (allBounds, partBounds) => { + (allBounds, partBounds) => + { allBounds.Encapsulate(partBounds); return allBounds; } ); } - protected static Vector3[] GetBoundsCorners(Bounds bounds) { + protected static Vector3[] GetBoundsCorners(Bounds bounds) + { Vector3[] corners = new Vector3[8]; - for (int i = 0; i < 8; i++) { + for (int i = 0; i < 8; i++) + { corners[i] = new Vector3( (i & 1) == 0 ? bounds.min.x : bounds.max.x, (i & 2) == 0 ? bounds.min.y : bounds.max.y, @@ -8328,7 +9506,8 @@ protected static Vector3[] GetBoundsCorners(Bounds bounds) { return corners; } - protected static bool IsPointInView(Camera camera, Vector3 point, float minSlack) { + protected static bool IsPointInView(Camera camera, Vector3 point, float minSlack) + { Vector3 viewportPoint = camera.WorldToViewportPoint(point); return ( viewportPoint.z > 0 @@ -8344,7 +9523,8 @@ private static bool AreBoundsInViewAtDistance( 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; @@ -8357,8 +9537,10 @@ float minSlack // Check each corner of the bounds to see if it's visible bool allCornersInView = true; Vector3[] corners = GetBoundsCorners(bounds); - foreach (Vector3 corner in corners) { - if (!IsPointInView(camera, corner, minSlack: minSlack)) { + foreach (Vector3 corner in corners) + { + if (!IsPointInView(camera, corner, minSlack: minSlack)) + { allCornersInView = false; break; } @@ -8371,12 +9553,14 @@ float minSlack return allCornersInView; } - public float FindClosestDistance(Camera camera, Bounds objectBounds, float minSlack = 0.01f) { + 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++) { + for (int i = 0; i < 10; i++) + { if ( !AreBoundsInViewAtDistance( camera, @@ -8384,25 +9568,33 @@ public float FindClosestDistance(Camera camera, Bounds objectBounds, float minSl maxDistance, minSlack: minSlack ) - ) { + ) + { maxDistance *= 2; - } else { + } + else + { break; } } - if (!AreBoundsInViewAtDistance(camera, objectBounds, maxDistance, minSlack: minSlack)) { + if (!AreBoundsInViewAtDistance(camera, objectBounds, maxDistance, minSlack: minSlack)) + { return -1.0f; } float targetAccuracy = 0.01f; // How close we need to get to the answer - while (minDistance < maxDistance - targetAccuracy) { + while (minDistance < maxDistance - targetAccuracy) + { float midDistance = (minDistance + maxDistance) / 2; Debug.Log(midDistance); if ( AreBoundsInViewAtDistance(camera, objectBounds, midDistance, minSlack: minSlack) - ) { + ) + { maxDistance = midDistance; - } else { + } + else + { minDistance = midDistance; } } @@ -8417,7 +9609,8 @@ protected IEnumerator renderObjectFromAngles( Vector2 renderResolution, float[] angles, float cameraHeightMultiplier - ) { + ) + { // Save the original camera settings Vector3 originalPosition = renderCamera.transform.position; Quaternion originalRotation = renderCamera.transform.rotation; @@ -8426,10 +9619,12 @@ float cameraHeightMultiplier // Calculate bounds of the target object Renderer[] renderers = targetObject.GetComponentsInChildren(); Bounds bounds = new Bounds(targetObject.transform.position, Vector3.zero); - foreach (Renderer renderer in renderers) { + foreach (Renderer renderer in renderers) + { bounds.Encapsulate(renderer.bounds); } - foreach (Collider c in targetObject.GetComponentsInChildren()) { + foreach (Collider c in targetObject.GetComponentsInChildren()) + { bounds.Encapsulate(c.bounds); } @@ -8447,7 +9642,8 @@ float cameraHeightMultiplier renderCamera.targetTexture = renderTexture; List byte_arrays = new List(); - foreach (float angle in angles) { + foreach (float angle in angles) + { // Calculate camera position for 3/4 view float radians = (90f - angle) * Mathf.Deg2Rad; Vector3 cameraPosition = new Vector3( @@ -8461,7 +9657,8 @@ float cameraHeightMultiplier float dist = FindClosestDistance(renderCamera, bounds, minSlack: 0.025f); - if (dist < 0) { + if (dist < 0) + { errorMessage = "Could not find a suitable distance to render the object."; byte_arrays = null; break; @@ -8510,11 +9707,15 @@ public void RenderObjectFromAngles( Vector2 renderResolution, float[] angles, float cameraHeightMultiplier = 0.5f - ) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + ) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = "No object with ID " + objectId; actionFinished(false, errorMessage: errorMessage); - } else { + } + else + { StartCoroutine( renderObjectFromAngles( renderCamera: m_Camera, @@ -8529,9 +9730,11 @@ public void RenderObjectFromAngles( } } - public void RemoveObject(string objectId) { + public void RemoveObject(string objectId) + { var obj = GameObject.Find(objectId); - if (obj == null) { + if (obj == null) + { errorMessage = $"Object does not exist in scene."; actionFinishedEmit(false); return; @@ -8545,9 +9748,11 @@ public void RotateObject( FlexibleRotation angleAxisRotation, string objectId = "asset_0", bool absolute = true - ) { + ) + { var obj = GameObject.Find(objectId); - if (obj == null) { + if (obj == null) + { errorMessage = $"Object does not exist in scene."; actionFinishedEmit(false); return; @@ -8555,7 +9760,8 @@ public void RotateObject( var bounds = GetObjectSphereBounds(obj); //obj.transform.RotateAround() var rot = Quaternion.AngleAxis(angleAxisRotation.degrees, angleAxisRotation.axis); - if (absolute) { + if (absolute) + { obj.transform.position = Vector3.zero; obj.transform.rotation = Quaternion.identity; obj.transform.RotateAround( @@ -8563,7 +9769,9 @@ public void RotateObject( angleAxisRotation.axis, angleAxisRotation.degrees ); - } else { + } + else + { obj.transform.RotateAround( bounds.center, angleAxisRotation.axis, @@ -8575,9 +9783,11 @@ public void RotateObject( actionFinished(true); } - public void BakeNavMesh() { + public void BakeNavMesh() + { var navmesh = GameObject.FindObjectOfType(); - if (navmesh == null) { + if (navmesh == null) + { actionFinishedEmit( false, null, @@ -8590,12 +9800,15 @@ public void BakeNavMesh() { actionFinishedEmit(true); } - public void OverwriteNavMeshes(List navMeshConfigs) { + 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) { + if (go == null) + { actionFinishedEmit( false, null, @@ -8604,12 +9817,15 @@ public void OverwriteNavMeshes(List navMeshConfigs) { 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(); @@ -8621,9 +9837,11 @@ public void OverwriteNavMeshes(List navMeshConfigs) { actionFinishedEmit(success: true); } - public void ReBakeNavMeshes(List navMeshConfigs = null) { + public void ReBakeNavMeshes(List navMeshConfigs = null) + { var navmeshes = GameObject.FindObjectsOfType(); - if (navmeshes == null || navmeshes.Count() == 0) { + if (navmeshes == null || navmeshes.Count() == 0) + { actionFinishedEmit( false, null, @@ -8631,29 +9849,38 @@ public void ReBakeNavMeshes(List navMeshConfigs = null) { ); return; } - if (navMeshConfigs != null && navMeshConfigs.Count != navmeshes.Count()) { + 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) { - for (var i = 0; i < navmeshes.Count(); i++) { + } + else if (navMeshConfigs != null) + { + for (var i = 0; i < navmeshes.Count(); i++) + { navmeshes[i] .BuildNavMesh( ProceduralTools.navMeshConfigToBuildSettings(navMeshConfigs[i]) ); } - } else { - foreach (var navmesh in navmeshes) { + } + else + { + foreach (var navmesh in navmeshes) + { navmesh.BuildNavMesh(navmesh.buildSettings); } } actionFinishedEmit(success: true); } - public void GetNavMeshConfigs() { + public void GetNavMeshConfigs() + { var navmeshes = GameObject.FindObjectsOfType(); - if (navmeshes == null || navmeshes.Count() == 0) { + if (navmeshes == null || navmeshes.Count() == 0) + { actionFinishedEmit( false, null, @@ -8669,9 +9896,11 @@ public void GetNavMeshConfigs() { ); } - public void CreateNewNavMesh(NavMeshConfig navMeshConfig) { + public void CreateNewNavMesh(NavMeshConfig navMeshConfig) + { var navmesh = GameObject.FindObjectOfType(); - if (navmesh == null) { + if (navmesh == null) + { actionFinishedEmit( false, null, @@ -8691,16 +9920,21 @@ public void CreateNewNavMesh(NavMeshConfig navMeshConfig) { actionFinishedEmit(true); } - public void OnTriggerStay(Collider other) { - if (other.CompareTag("HighFriction")) { + public void OnTriggerStay(Collider other) + { + if (other.CompareTag("HighFriction")) + { inHighFrictionArea = true; - } else { + } + else + { inHighFrictionArea = false; } } // use this to check if any given Vector3 coordinate is within the agent's viewport and also not obstructed - public bool CheckIfPointIsInViewport(Vector3 point) { + public bool CheckIfPointIsInViewport(Vector3 point) + { Vector3 viewPoint = m_Camera.WorldToViewportPoint(point); float ViewPointRangeHigh = 1.0f; @@ -8734,10 +9968,13 @@ public bool CheckIfPointIsInViewport(Vector3 point) { "Agent" ) ) - ) { + ) + { updateAllAgentCollidersForVisibilityCheck(true); return false; - } else { + } + else + { updateAllAgentCollidersForVisibilityCheck(true); return true; } @@ -8749,19 +9986,23 @@ protected List approxObjectMask( SimObjPhysics sop, int divisions, int? thirdPartyCameraIndex = null - ) { - if (divisions <= 2) { + ) + { + if (divisions <= 2) + { throw new ArgumentException("divisions must be >=3"); } ObjectOrientedBoundingBox oobb = sop.ObjectOrientedBoundingBox; - if (oobb == null) { + if (oobb == null) + { sop.syncBoundingBoxes( forceCacheReset: true, forceCreateObjectOrientedBoundingBox: true ); oobb = sop.ObjectOrientedBoundingBox; - if (oobb == null) { + if (oobb == null) + { throw new ArgumentException( $"{sop.objectID} does not have an object oriented bounding box" ); @@ -8770,7 +10011,8 @@ protected List approxObjectMask( float[][] oobbPoints = oobb.cornerPoints; Camera camera = m_Camera; - if (thirdPartyCameraIndex.HasValue) { + if (thirdPartyCameraIndex.HasValue) + { camera = agentManager.thirdPartyCameras[thirdPartyCameraIndex.Value]; } @@ -8780,7 +10022,8 @@ protected List approxObjectMask( float minY = 1.0f; float maxY = 0.0f; float maxDist = 0.0f; - for (int i = 0; i < 8; i++) { + for (int i = 0; i < 8; i++) + { Vector3 worldSpaceCornerPoint = new Vector3( oobbPoints[i][0], oobbPoints[i][1], @@ -8804,7 +10047,8 @@ protected List approxObjectMask( maxY = Math.Min(maxY, 1f); List points = new List(); - if (maxX - minX < 1e-3f || maxY - minY < 1e-3f) { + if (maxX - minX < 1e-3f || maxY - minY < 1e-3f) + { return points; } @@ -8818,8 +10062,10 @@ protected List approxObjectMask( 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++) { + for (int i = 0; i < divisions; i++) + { + for (int j = 0; j < divisions; j++) + { float x = shrunkMinX + (shrunkMaxX - shrunkMinX) * i / (divisions - 1); float y = shrunkMinY + (shrunkMaxY - shrunkMinY) * j / (divisions - 1); @@ -8833,7 +10079,8 @@ protected List approxObjectMask( camera: camera, includeInvisible: false ).visible - ) { + ) + { points.Add(new Vector2(x, y)); } } @@ -8845,7 +10092,8 @@ public void GetApproxObjectMask( string objectId, int divisions = 10, int? thirdPartyCameraIndex = null - ) { + ) + { SimObjPhysics sop = getInteractableSimObjectFromId( objectId: objectId, forceAction: true @@ -8858,11 +10106,13 @@ public void GetApproxObjectMask( actionFinishedEmit(success: true, actionReturn: points); } - public void unrollSimulatePhysics(IEnumerator enumerator, float fixedDeltaTime) { + public void unrollSimulatePhysics(IEnumerator enumerator, float fixedDeltaTime) + { ContinuousMovement.unrollSimulatePhysics(enumerator, fixedDeltaTime); } - public void GetSceneBounds() { + public void GetSceneBounds() + { Vector3[] positions = new Vector3[2]; positions[0] = agentManager.SceneBounds.min; positions[1] = agentManager.SceneBounds.max; @@ -8874,7 +10124,8 @@ public void GetSceneBounds() { actionFinishedEmit(true, positions); } - public void GetLights() { + public void GetLights() + { print("GetLights in BASE happening now"); //debug #if UNITY_EDITOR @@ -8885,29 +10136,34 @@ public void GetLights() { actionFinishedEmit(true, UtilityFunctions.GetLightPropertiesOfScene()); } - public void SetLights() { + public void SetLights() + { //check that name of light specified exists in scene, if not throw exception actionFinished(true); } - public void GetPhysicsSimulateCount() { + public void GetPhysicsSimulateCount() + { actionFinished( success: true, actionReturn: PhysicsSceneManager.PhysicsSimulateCallCount ); } - public void GetLastPhysicsSimulateCount() { + public void GetLastPhysicsSimulateCount() + { actionFinished( success: true, actionReturn: PhysicsSceneManager.LastPhysicsSimulateCallCount ); } - public void SetObjectsCollisionMode(string collisionDetectionMode) { + public void SetObjectsCollisionMode(string collisionDetectionMode) + { var rootObject = GameObject.Find(ProceduralTools.DefaultObjectsRootName); - if (rootObject == null) { + if (rootObject == null) + { actionFinished( success: false, errorMessage: $"No root object '{ProceduralTools.DefaultObjectsRootName}', make sure it's a procedural scene and house created when running this action." @@ -8916,10 +10172,12 @@ public void SetObjectsCollisionMode(string collisionDetectionMode) { CollisionDetectionMode collDet = CollisionDetectionMode.ContinuousSpeculative; Enum.TryParse(collisionDetectionMode, true, out collDet); - for (var i = 0; i < rootObject.transform.childCount; i++) { + for (var i = 0; i < rootObject.transform.childCount; i++) + { var obj = rootObject.transform.GetChild(i); var rb = obj.GetComponent(); - if (!rb.isKinematic) { + if (!rb.isKinematic) + { rb.collisionDetectionMode = collDet; } } @@ -8927,7 +10185,8 @@ public void SetObjectsCollisionMode(string collisionDetectionMode) { } #if UNITY_EDITOR - void OnDrawGizmos() { + void OnDrawGizmos() + { //// check for valid spawn points in GetSpawnCoordinatesAboveObject action // Gizmos.color = Color.magenta; // if(validpointlist.Count > 0) @@ -8958,27 +10217,33 @@ void OnDrawGizmos() { } #endif - public void TestActionDispatchSAAmbig2(float foo, bool def = false) { + public void TestActionDispatchSAAmbig2(float foo, bool def = false) + { actionFinished(true); } - public void TestActionDispatchSAAmbig2(float foo) { + public void TestActionDispatchSAAmbig2(float foo) + { actionFinished(true); } - public void TestActionDispatchSAAmbig(ServerAction action) { + public void TestActionDispatchSAAmbig(ServerAction action) + { actionFinished(true); } - public void TestActionDispatchSAAmbig(float foo) { + public void TestActionDispatchSAAmbig(float foo) + { actionFinished(true); } - public void TestActionDispatchNoopServerAction(ServerAction action) { + public void TestActionDispatchNoopServerAction(ServerAction action) + { actionFinished(true, "serveraction"); } - public void TestFastEmit(string rvalue) { + public void TestFastEmit(string rvalue) + { actionFinishedEmit(true, rvalue); } @@ -8986,105 +10251,129 @@ public void TestActionDispatchNoopAllDefault2( float param12, float param10 = 0.0f, float param11 = 1.0f - ) { + ) + { actionFinished(true, "somedefault"); } - public void TestActionDispatchNoopAllDefault(float param10 = 0.0f, float param11 = 1.0f) { + public void TestActionDispatchNoopAllDefault(float param10 = 0.0f, float param11 = 1.0f) + { actionFinished(true, "alldefault"); } - public void TestActionDispatchNoop2(bool param3, string param4 = "foo") { + public void TestActionDispatchNoop2(bool param3, string param4 = "foo") + { actionFinished(true, "param3 param4/default " + param4); } - public void TestActionReflectParam(string rvalue) { + public void TestActionReflectParam(string rvalue) + { actionFinished(true, rvalue); } - public void TestActionDispatchNoop(string param6, string param7) { + public void TestActionDispatchNoop(string param6, string param7) + { actionFinished(true, "param6 param7"); } - public void TestActionDispatchNoop(bool param1, bool param2) { + public void TestActionDispatchNoop(bool param1, bool param2) + { actionFinished(true, "param1 param2"); } - public void TestActionDispatchConflict(string param22) { + public void TestActionDispatchConflict(string param22) + { actionFinished(true); } - public void TestActionDispatchConflict(bool param22) { + public void TestActionDispatchConflict(bool param22) + { actionFinished(true); } - public void TestActionDispatchNoop(bool param1) { + public void TestActionDispatchNoop(bool param1) + { actionFinished(true, "param1"); } - public void TestActionDispatchNoop() { + public void TestActionDispatchNoop() + { actionFinished(true, "emptyargs"); } - public void TestActionDispatchFindAmbiguous(string typeName) { + public void TestActionDispatchFindAmbiguous(string typeName) + { List actions = ActionDispatcher.FindAmbiguousActions(Type.GetType(typeName)); actionFinished(true, actions); } - public void TestActionDispatchFindConflicts(string typeName) { + public void TestActionDispatchFindConflicts(string typeName) + { Dictionary> conflicts = ActionDispatcher.FindMethodVariableNameConflicts(Type.GetType(typeName)); string[] ignore = new string[] { "GetComponent", "StopCoroutine" }; - foreach (var methodName in ignore) { - if (conflicts.ContainsKey(methodName)) { + foreach (var methodName in ignore) + { + if (conflicts.ContainsKey(methodName)) + { conflicts.Remove(methodName); } } actionFinished(true, conflicts); } - public void print(string message) { + public void print(string message) + { MonoBehaviour.print(message); } public T GetComponent() - where T : Component { + where T : Component + { return this.baseAgentComponent.GetComponent(); } public T GetComponentInParent() - where T : Component { + where T : Component + { return this.baseAgentComponent.GetComponentInParent(); } public T GetComponentInChildren() - where T : Component { + where T : Component + { return this.baseAgentComponent.GetComponentInChildren(); } public T[] GetComponentsInChildren() - where T : Component { + where T : Component + { return this.baseAgentComponent.GetComponentsInChildren(); } - public GameObject Instantiate(GameObject original) { + public GameObject Instantiate(GameObject original) + { return UnityEngine.Object.Instantiate(original); } - public GameObject Instantiate(GameObject original, Vector3 position, Quaternion rotation) { + public GameObject Instantiate(GameObject original, Vector3 position, Quaternion rotation) + { return UnityEngine.Object.Instantiate(original, position, rotation); } - public void Destroy(GameObject targetObject) { + public void Destroy(GameObject targetObject) + { MonoBehaviour.Destroy(targetObject); } } - public class VisibilityCheck { + public class VisibilityCheck + { public bool visible; public bool interactable; - public static VisibilityCheck operator |(VisibilityCheck a, VisibilityCheck b) { + public static VisibilityCheck operator |(VisibilityCheck a, VisibilityCheck b) + { VisibilityCheck c = new VisibilityCheck(); c.interactable = a.interactable || b.interactable; c.visible = a.visible || b.visible; diff --git a/unity/Assets/Scripts/BatchRename.cs b/unity/Assets/Scripts/BatchRename.cs index 2339dc1ca0..185676e429 100644 --- a/unity/Assets/Scripts/BatchRename.cs +++ b/unity/Assets/Scripts/BatchRename.cs @@ -5,7 +5,8 @@ using UnityEditor; using System.Collections; -public class BatchRename : ScriptableWizard { +public class BatchRename : ScriptableWizard +{ /// /// Base name /// @@ -22,31 +23,36 @@ public class BatchRename : ScriptableWizard { public int Increment = 1; [MenuItem("Edit/Batch Rename...")] - static void CreateWizard() { + static void CreateWizard() + { ScriptableWizard.DisplayWizard("Batch Rename", typeof(BatchRename), "Rename"); } /// /// Called when the window first appears /// - void OnEnable() { + void OnEnable() + { UpdateSelectionHelper(); } /// /// Function called when selection changes in scene /// - void OnSelectionChange() { + void OnSelectionChange() + { UpdateSelectionHelper(); } /// /// Update selection counter /// - void UpdateSelectionHelper() { + void UpdateSelectionHelper() + { helpString = ""; - if (Selection.objects != null) { + if (Selection.objects != null) + { helpString = "Number of objects selected: " + Selection.objects.Length; } } @@ -54,9 +60,11 @@ void UpdateSelectionHelper() { /// /// Rename /// - void OnWizardCreate() { + void OnWizardCreate() + { // If selection is empty, then exit - if (Selection.objects == null) { + if (Selection.objects == null) + { return; } @@ -64,7 +72,8 @@ void OnWizardCreate() { int PostFix = StartNumber; // Cycle and rename - foreach (Object O in Selection.objects) { + foreach (Object O in Selection.objects) + { O.name = BaseName + PostFix; PostFix += Increment; } diff --git a/unity/Assets/Scripts/Bathtub.cs b/unity/Assets/Scripts/Bathtub.cs index 9d5df6b326..c794545cae 100644 --- a/unity/Assets/Scripts/Bathtub.cs +++ b/unity/Assets/Scripts/Bathtub.cs @@ -3,21 +3,26 @@ using UnityEngine; [ExecuteInEditMode] -public class Bathtub : MonoBehaviour { +public class Bathtub : MonoBehaviour +{ public SimObj ParentObj; public bool EditorFilled = false; public GameObject FilledObject; - void OnEnable() { + void OnEnable() + { ParentObj = gameObject.GetComponent(); - if (ParentObj == null) { + if (ParentObj == null) + { ParentObj = gameObject.AddComponent(); } ParentObj.Type = SimObjType.Bathtub; - if (!Application.isPlaying) { + if (!Application.isPlaying) + { Animator a = ParentObj.gameObject.GetComponent(); - if (a == null) { + if (a == null) + { a = ParentObj.gameObject.AddComponent(); a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; @@ -25,13 +30,16 @@ void OnEnable() { } } - void Update() { + void Update() + { bool filled = EditorFilled; - if (Application.isPlaying) { + if (Application.isPlaying) + { filled = ParentObj.Animator.GetBool("AnimState1"); } - if (FilledObject == null) { + if (FilledObject == null) + { Debug.LogError("Filled object is null in bathtub"); return; } diff --git a/unity/Assets/Scripts/Bed.cs b/unity/Assets/Scripts/Bed.cs index b58881b5a4..774dc2d89a 100644 --- a/unity/Assets/Scripts/Bed.cs +++ b/unity/Assets/Scripts/Bed.cs @@ -3,7 +3,8 @@ using UnityEngine; [ExecuteInEditMode] -public class Bed : MonoBehaviour { +public class Bed : MonoBehaviour +{ public SimObj ParentObj; // public GameObject FittedSheet; @@ -13,16 +14,20 @@ public class Bed : MonoBehaviour { [Range(0, 2)] public int EditorState = 0; - void OnEnable() { + void OnEnable() + { ParentObj = gameObject.GetComponent(); - if (ParentObj == null) { + if (ParentObj == null) + { ParentObj = gameObject.AddComponent(); } ParentObj.Type = SimObjType.Bed; - if (!Application.isPlaying) { + if (!Application.isPlaying) + { Animator a = ParentObj.gameObject.GetComponent(); - if (a == null) { + if (a == null) + { a = ParentObj.gameObject.AddComponent(); a.runtimeAnimatorController = Resources.Load("StateAnimController") as RuntimeAnimatorController; @@ -30,9 +35,11 @@ void OnEnable() { } } - void Update() { + void Update() + { int state = EditorState; - if (Application.isPlaying) { + if (Application.isPlaying) + { state = ParentObj.Animator.GetInteger("AnimState1"); } @@ -40,7 +47,8 @@ void Update() { // 1 - clean, no sheet // 2 - clean, sheet - switch (state) { + switch (state) + { case 0: default: MessyBlanket.SetActive(true); diff --git a/unity/Assets/Scripts/Blinds.cs b/unity/Assets/Scripts/Blinds.cs index 6728a8de77..f7dee207d7 100644 --- a/unity/Assets/Scripts/Blinds.cs +++ b/unity/Assets/Scripts/Blinds.cs @@ -3,42 +3,53 @@ using UnityEngine; [ExecuteInEditMode] -public class Blinds : MonoBehaviour { +public class Blinds : MonoBehaviour +{ public SimObj ParentObj; public bool EditorOpen = false; public bool OpenByDefault = true; public GameObject OpenObject; public GameObject ClosedObject; - void OnEnable() { + void OnEnable() + { EditorOpen = OpenByDefault; ParentObj = gameObject.GetComponent(); - if (ParentObj == null) { + if (ParentObj == null) + { ParentObj = gameObject.AddComponent(); } ParentObj.Type = SimObjType.Blinds; - if (!Application.isPlaying) { + if (!Application.isPlaying) + { Animator a = ParentObj.gameObject.GetComponent(); - if (a == null) { + if (a == null) + { a = ParentObj.gameObject.AddComponent(); a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; } - } else { - if (OpenByDefault) { + } + else + { + if (OpenByDefault) + { ParentObj.Animator.SetBool("AnimState1", true); } } } - void Update() { + void Update() + { bool open = EditorOpen; - if (Application.isPlaying) { + if (Application.isPlaying) + { open = ParentObj.Animator.GetBool("AnimState1"); } - if (OpenObject == null || ClosedObject == null) { + if (OpenObject == null || ClosedObject == null) + { Debug.LogError("Open or closed object is null in blinds"); return; } diff --git a/unity/Assets/Scripts/Box.cs b/unity/Assets/Scripts/Box.cs index d8a4dc27d4..0036d71031 100644 --- a/unity/Assets/Scripts/Box.cs +++ b/unity/Assets/Scripts/Box.cs @@ -3,17 +3,22 @@ using UnityEngine; [ExecuteInEditMode] -public class Box : MonoBehaviour { +public class Box : MonoBehaviour +{ public SimObj ParentSimObj; public GameObject[] Lids; public bool EditorClosed = true; - void OnEnable() { - if (Application.isPlaying) { + void OnEnable() + { + if (Application.isPlaying) + { ParentSimObj.Animator.SetBool("AnimState1", false); - foreach (GameObject lid in Lids) { + foreach (GameObject lid in Lids) + { Renderer r = lid.GetComponent(); - if (r != null) { + if (r != null) + { bool lighten = SceneManager.Current.SceneNumber % 2 == 0; Material darkerMat = r.material; darkerMat.color = Color.Lerp( @@ -26,15 +31,20 @@ void OnEnable() { } } - void Update() { + void Update() + { bool closed = false; - if (Application.isPlaying) { + if (Application.isPlaying) + { closed = !ParentSimObj.Animator.GetBool("AnimState1"); - } else { + } + else + { closed = EditorClosed; } - foreach (GameObject lid in Lids) { + foreach (GameObject lid in Lids) + { lid.SetActive(closed); } } diff --git a/unity/Assets/Scripts/Break.cs b/unity/Assets/Scripts/Break.cs index 478a947659..8a95ec2c7d 100644 --- a/unity/Assets/Scripts/Break.cs +++ b/unity/Assets/Scripts/Break.cs @@ -3,7 +3,8 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public class Break : MonoBehaviour { +public class Break : MonoBehaviour +{ [SerializeField] private GameObject PrefabToSwapTo = null; @@ -29,7 +30,8 @@ public class Break : MonoBehaviour { // 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 { + protected enum BreakType + { PrefabSwap, MaterialSwap, Decal @@ -72,12 +74,14 @@ protected enum BreakType { SimObjType.HandTowel }; - public bool isBroken() { + public bool isBroken() + { return broken; } // Start is called before the first frame update - void Start() { + void Start() + { #if UNITY_EDITOR // TODO refactor Break logic as separate from DecalCollision.cs to avoid error, and remove last part of AND if ( @@ -87,12 +91,15 @@ void Start() { .GetComponentInParent() .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBreak) ) && !gameObject.GetComponentInParent().IsReceptacle - ) { + ) + { Debug.LogError(gameObject.name + " is missing the CanBreak secondary property!"); } - if (gameObject.GetComponent()) { - if (DirtyPrefabToSwapTo == null) { + if (gameObject.GetComponent()) + { + if (DirtyPrefabToSwapTo == null) + { Debug.LogError(gameObject.name + " is missing a DirtyPrefabToSpawnTo!"); } } @@ -101,9 +108,11 @@ void Start() { CurrentImpulseThreshold = ImpulseThreshold; } - public void BreakObject(Collision collision) { + public void BreakObject(Collision collision) + { // prefab swap will switch the entire object out with a new prefab object entirely - if (breakType == BreakType.PrefabSwap) { + if (breakType == BreakType.PrefabSwap) + { // Disable this game object and spawn in the broken pieces Rigidbody rb = gameObject.GetComponent(); @@ -111,14 +120,18 @@ public void BreakObject(Collision collision) { Transform objectsTransform = GameObject.Find("Objects").transform; //before disabling things, if this object is a receptacle, unparent all objects contained - if (gameObject.GetComponent().IsReceptacle) { + if (gameObject.GetComponent().IsReceptacle) + { foreach ( GameObject go in gameObject.GetComponent().ContainedGameObjects() - ) { + ) + { //only reset rigidbody properties if contained object was pickupable/moveable - if (go.GetComponentInParent()) { + if (go.GetComponentInParent()) + { SimObjPhysics containedSOP = go.GetComponentInParent(); - if (containedSOP.IsMoveable || containedSOP.IsPickupable) { + if (containedSOP.IsMoveable || containedSOP.IsPickupable) + { go.transform.SetParent(objectsTransform); Rigidbody childrb = go.GetComponent(); childrb.isKinematic = false; @@ -132,7 +145,8 @@ GameObject go in gameObject.GetComponent().ContainedGameObjects() } // turn off everything except the top object - foreach (Transform t in gameObject.transform) { + foreach (Transform t in gameObject.transform) + { t.gameObject.SetActive(false); } @@ -142,9 +156,11 @@ GameObject go in gameObject.GetComponent().ContainedGameObjects() // if gameObject.GetComponent() - first check to make sure if this object can become dirty // if object is dirty - probably get this from the "Dirty" component to keep everything nice and self contained // PrefabToSwapTo = DirtyPrefabToSwapTo - if (gameObject.GetComponent()) { + if (gameObject.GetComponent()) + { // if the object is not clean, swap to the dirty prefab - if (gameObject.GetComponent().IsDirty()) { + if (gameObject.GetComponent().IsDirty()) + { PrefabToSwapTo = DirtyPrefabToSwapTo; } } @@ -158,7 +174,8 @@ GameObject go in gameObject.GetComponent().ContainedGameObjects() broken = true; // ContactPoint cp = collision.GetContact(0); - foreach (Rigidbody subRb in resultObject.GetComponentsInChildren()) { + foreach (Rigidbody subRb in resultObject.GetComponentsInChildren()) + { subRb.velocity = rb.velocity * 0.4f; subRb.angularVelocity = rb.angularVelocity * 0.4f; } @@ -168,8 +185,10 @@ GameObject go in gameObject.GetComponent().ContainedGameObjects() // if this object breaking is an egg, set rotation for the EggCracked object // 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 - if (resultObject.GetComponent()) { - if (resultObject.GetComponent().Type == SimObjType.EggCracked) { + if (resultObject.GetComponent()) + { + if (resultObject.GetComponent().Type == SimObjType.EggCracked) + { resultObject.transform.rotation = Quaternion.Euler(Vector3.zero); PhysicsSceneManager psm = GameObject .Find("PhysicsSceneManager") @@ -191,17 +210,21 @@ GameObject go in gameObject.GetComponent().ContainedGameObjects() } // if decal type, do not switch out the object but instead swap materials to show cracked/broken parts - if (breakType == BreakType.MaterialSwap) { + if (breakType == BreakType.MaterialSwap) + { // decal logic here - if (MaterialSwapObjects.Length > 0) { - for (int i = 0; i < MaterialSwapObjects.Length; i++) { + if (MaterialSwapObjects.Length > 0) + { + for (int i = 0; i < MaterialSwapObjects.Length; i++) + { MaterialSwapObjects[i].MyObject.GetComponent().materials = MaterialSwapObjects[i].OnMaterials; } } // if the object can be toggled on/off, if it is on, turn it off since it is now broken - if (gameObject.GetComponent()) { + if (gameObject.GetComponent()) + { gameObject.GetComponent().isOn = false; } @@ -210,7 +233,8 @@ GameObject go in gameObject.GetComponent().ContainedGameObjects() readytobreak = false; } - if (breakType == BreakType.Decal) { + if (breakType == BreakType.Decal) + { // move shattered decal to location of the collision, or if there was no collision and this is being called // directly from the Break() action, create a default decal i guess? BreakForDecalType(collision); @@ -220,8 +244,10 @@ GameObject go in gameObject.GetComponent().ContainedGameObjects() .Find("PhysicsSceneManager") .GetComponent() .PrimaryAgent; - if (primaryAgent.imageSynthesis) { - if (primaryAgent.imageSynthesis.enabled) { + if (primaryAgent.imageSynthesis) + { + if (primaryAgent.imageSynthesis.enabled) + { primaryAgent.imageSynthesis.OnSceneChange(); } } @@ -230,9 +256,11 @@ GameObject go in gameObject.GetComponent().ContainedGameObjects() // Override for Decal behavior protected virtual void BreakForDecalType(Collision collision) { } - void OnCollisionEnter(Collision col) { + void OnCollisionEnter(Collision col) + { // do nothing if this specific breakable sim objects has been set to unbreakable - if (Unbreakable) { + if (Unbreakable) + { return; } @@ -243,12 +271,14 @@ 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 (col.transform.GetComponentInParent()) + { if ( TooSmalOrSoftToBreakOtherObjects.Contains( col.transform.GetComponentInParent().Type ) - ) { + ) + { return; } } @@ -257,8 +287,10 @@ void OnCollisionEnter(Collision col) { if ( col.impulse.magnitude > CurrentImpulseThreshold && !col.transform.GetComponentInParent() - ) { - if (readytobreak) { + ) + { + if (readytobreak) + { readytobreak = false; BreakObject(col); } @@ -267,14 +299,18 @@ void OnCollisionEnter(Collision col) { // change the ImpulseThreshold to higher if we are in a high friction zone, to simulate throwing an object at a "soft" object requiring // more force to break - ie: dropping mug on floor vs on a rug - public void OnTriggerEnter(Collider other) { - if (other.CompareTag("HighFriction")) { + public void OnTriggerEnter(Collider other) + { + if (other.CompareTag("HighFriction")) + { CurrentImpulseThreshold = ImpulseThreshold + HighFrictionImpulseOffset; } } - public void OnTriggerExit(Collider other) { - if (other.CompareTag("HighFriction")) { + public void OnTriggerExit(Collider other) + { + if (other.CompareTag("HighFriction")) + { CurrentImpulseThreshold = ImpulseThreshold; } } diff --git a/unity/Assets/Scripts/Breakdown.cs b/unity/Assets/Scripts/Breakdown.cs index 8efdf7ca5b..08f2c13b87 100644 --- a/unity/Assets/Scripts/Breakdown.cs +++ b/unity/Assets/Scripts/Breakdown.cs @@ -5,17 +5,21 @@ // this logic is for controlling how pieces shatter after spawning in a broken version of a sim object (mug, plate, etc) // this should be placed on the gameobject transform that is holding all of the shattered pieces // the pieces should only have rigidbodies and colliders -public class Breakdown : MonoBehaviour { +public class Breakdown : MonoBehaviour +{ public float power = 10.0f; protected float explosionRadius = 0.25f; // Start is called before the first frame update - void Start() { + void Start() + { Vector3 explosionPos = transform.position; Collider[] colliders = Physics.OverlapSphere(explosionPos, explosionRadius); - foreach (Collider col in colliders) { - if (col.GetComponent()) { + foreach (Collider col in colliders) + { + if (col.GetComponent()) + { Rigidbody rb = col.GetComponent(); rb.AddExplosionForce(power, gameObject.transform.position, explosionRadius, 0.005f); rb.AddTorque(new Vector3(Random.value, Random.value, Random.value)); diff --git a/unity/Assets/Scripts/Cabinet.cs b/unity/Assets/Scripts/Cabinet.cs index f7a1be722a..8678825080 100644 --- a/unity/Assets/Scripts/Cabinet.cs +++ b/unity/Assets/Scripts/Cabinet.cs @@ -2,7 +2,8 @@ using System.Collections; using UnityEngine; -public enum CabinetOpenStyle { +public enum CabinetOpenStyle +{ SingleDoorLeft, SingleDoorRight, DoubleDoors, @@ -10,7 +11,8 @@ public enum CabinetOpenStyle { } [ExecuteInEditMode] -public class Cabinet : MonoBehaviour { +public class Cabinet : MonoBehaviour +{ public bool Animate = false; public bool Open; public SimObj ParentObj; @@ -66,11 +68,14 @@ center and expands so that the Agent can see what is inside the drawer. // bool lastOpen = false; float animatingDistance; - public void OnEnable() { + public void OnEnable() + { ParentObj.Manipulation = SimObjManipType.StaticNoPlacement; - if (!Application.isPlaying) { + if (!Application.isPlaying) + { Animator a = ParentObj.gameObject.GetComponent(); - if (a == null) { + if (a == null) + { a = ParentObj.gameObject.AddComponent(); a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; @@ -78,39 +83,47 @@ public void OnEnable() { } } - public void Update() { + public void Update() + { bool open = Open; - if (Application.isPlaying) { + if (Application.isPlaying) + { // get whether we're open from our animation state - if (!ParentObj.IsAnimated) { + if (!ParentObj.IsAnimated) + { return; } open = ParentObj.Animator.GetBool("AnimState1"); } - if (!Application.isPlaying && !Animate) { + if (!Application.isPlaying && !Animate) + { return; } - switch (SceneManager.Current.AnimationMode) { + switch (SceneManager.Current.AnimationMode) + { case SceneAnimationMode.Instant: default: UpdateAnimationInstant(open); break; case SceneAnimationMode.Smooth: - if (Application.isPlaying) { + if (Application.isPlaying) + { UpdateAnimationSmooth(open); } break; } } - void UpdateAnimationSmooth(bool open) { + void UpdateAnimationSmooth(bool open) + { Quaternion rightDoorStartRotation = Quaternion.identity; Quaternion leftDoorStartRotation = Quaternion.identity; - switch (OpenStyle) { + switch (OpenStyle) + { case CabinetOpenStyle.DoubleDoors: rightDoorStartRotation = RightDoor.rotation; leftDoorStartRotation = LeftDoor.rotation; @@ -190,22 +203,28 @@ void UpdateAnimationSmooth(bool open) { break; } - if (animatingDistance >= 360f) { + if (animatingDistance >= 360f) + { animatingDistance -= 360f; } ParentObj.IsAnimating = (animatingDistance > 0.0025f); } - void UpdateAnimationInstant(bool open) { - if (VisCollider) { + void UpdateAnimationInstant(bool open) + { + if (VisCollider) + { VisCollider.gameObject.SetActive(open); - } else { + } + else + { // this handles Cabinets ParentObj.Receptacle.VisibilityCollider.gameObject.SetActive(open); } - switch (OpenStyle) { + switch (OpenStyle) + { case CabinetOpenStyle.DoubleDoors: RightDoor.transform.localEulerAngles = open ? OpenAngleRight : ClosedAngleRight; LeftDoor.transform.localEulerAngles = open ? OpenAngleLeft : ClosedAngleLeft; diff --git a/unity/Assets/Scripts/CameraControls.cs b/unity/Assets/Scripts/CameraControls.cs index 43b474df43..35076659c3 100644 --- a/unity/Assets/Scripts/CameraControls.cs +++ b/unity/Assets/Scripts/CameraControls.cs @@ -2,16 +2,20 @@ using System.Collections; using UnityEngine; -public class CameraControls : MonoBehaviour { +public class CameraControls : MonoBehaviour +{ Camera cam; - void Start() { + void Start() + { cam = GetComponent(); cam.enabled = false; } - void Update() { - if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter)) { + void Update() + { + if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter)) + { cam.enabled = !cam.enabled; } } diff --git a/unity/Assets/Scripts/CameraDepthSetup.cs b/unity/Assets/Scripts/CameraDepthSetup.cs index b27b3920db..013b3b19c3 100644 --- a/unity/Assets/Scripts/CameraDepthSetup.cs +++ b/unity/Assets/Scripts/CameraDepthSetup.cs @@ -3,8 +3,10 @@ using UnityEngine; [ExecuteInEditMode] -public class CameraDepthSetup : MonoBehaviour { - void Start() { +public class CameraDepthSetup : MonoBehaviour +{ + void Start() + { Camera.main.depthTextureMode = DepthTextureMode.Depth; // GetComponent().depthTextureMode = DepthTextureMode.Depth; Camera.main.transparencySortMode = TransparencySortMode.Perspective; diff --git a/unity/Assets/Scripts/CanOpen_Object.cs b/unity/Assets/Scripts/CanOpen_Object.cs index f515bec84d..1b332c3d15 100644 --- a/unity/Assets/Scripts/CanOpen_Object.cs +++ b/unity/Assets/Scripts/CanOpen_Object.cs @@ -4,7 +4,8 @@ using UnityStandardAssets.Characters.FirstPerson; // Allows for openable objects to be opened. -public class CanOpen_Object : MonoBehaviour { +public class CanOpen_Object : MonoBehaviour +{ [Header("Moving Parts for this Object")] [SerializeField] public GameObject[] MovingParts; @@ -28,7 +29,8 @@ public class CanOpen_Object : MonoBehaviour { private float startOpenness; private float lastSuccessfulOpenness; - public enum failState { + public enum failState + { none, collision, hyperextension @@ -60,7 +62,8 @@ public enum failState { //public bool isCurrentlyResetting = false; // private bool isCurrentlyResetting = false; - public enum MovementType { + public enum MovementType + { Slide, Rotate, Scale @@ -81,22 +84,26 @@ public enum MovementType { //[SerializeField] // protected GameObject ClosedBoundingBox; - public List WhatReceptaclesMustBeOffToOpen() { + public List WhatReceptaclesMustBeOffToOpen() + { return MustBeOffToOpen; } // Use this for initialization - void Start() { + void Start() + { #if UNITY_EDITOR if ( !this.GetComponent() .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanOpen) - ) { + ) + { Debug.LogError(this.name + "is missing the CanOpen Secondary Property! Please set it!"); } #endif - if (!isOpen) { + if (!isOpen) + { currentOpenness = 0.0f; } @@ -106,10 +113,12 @@ void Start() { } // Update is called once per frame - void Update() { + void Update() + { // test if it can open without Agent Command - Debug Purposes #if UNITY_EDITOR - if (Input.GetKeyDown(KeyCode.Equals)) { + if (Input.GetKeyDown(KeyCode.Equals)) + { Interact(); } #endif @@ -117,36 +126,43 @@ void Update() { // Helper functions for setting up scenes, only for use in Editor #if UNITY_EDITOR - void OnEnable() { + 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!" ); } } - public void SetMovementToSlide() { + public void SetMovementToSlide() + { movementType = MovementType.Slide; } - public void SetMovementToRotate() { + public void SetMovementToRotate() + { movementType = MovementType.Rotate; } - public void SetMovementToScale() { + 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++) { + 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; MovingParts[i].transform.localRotation = Quaternion.Euler(newRot); @@ -163,18 +179,21 @@ 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(); - if (sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup && sop.isInAgentHand == false) { + if (sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup && sop.isInAgentHand == false) + { gameObject.GetComponent().isKinematic = false; } // set physicsInterval to default of 0.02 if no value has yet been given physicsInterval = physicsInterval.GetValueOrDefault(Time.fixedDeltaTime); - if (failure == failState.none) { + if (failure == failState.none) + { // storing initial opennness-state case there's a failure, and we want to revert back to it startOpenness = currentOpenness; // storing lastSuccessfulOpenness in case opening fails on very first physics-step, and returnToStart is false @@ -182,8 +201,10 @@ public void Interact( } // okay let's open / reset the object! - if (movementType == MovementType.Slide) { - if (failure == failState.none || returnToStart == true) { + if (movementType == MovementType.Slide) + { + if (failure == failState.none || returnToStart == true) + { StartCoroutine( LerpPosition( movingParts: MovingParts, @@ -199,9 +220,12 @@ public void Interact( posRotRef: posRotRef ) ); - } else { + } + else + { currentOpenness = lastSuccessfulOpenness; - for (int i = 0; i < MovingParts.Length; i++) { + for (int i = 0; i < MovingParts.Length; i++) + { MovingParts[i].transform.localPosition = Vector3.Lerp( closedPositions[i], openPositions[i], @@ -213,8 +237,11 @@ public void Interact( setIsOpen(currentOpenness); isCurrentlyLerping = false; } - } else if (movementType == MovementType.Rotate) { - if (failure == failState.none || returnToStart == true) { + } + else if (movementType == MovementType.Rotate) + { + if (failure == failState.none || returnToStart == true) + { StartCoroutine( LerpRotation( movingParts: MovingParts, @@ -230,9 +257,12 @@ public void Interact( posRotRef: posRotRef ) ); - } else { + } + else + { currentOpenness = lastSuccessfulOpenness; - for (int i = 0; i < MovingParts.Length; i++) { + for (int i = 0; i < MovingParts.Length; i++) + { MovingParts[i].transform.localRotation = Quaternion.Lerp( Quaternion.Euler(closedPositions[i]), Quaternion.Euler(openPositions[i]), @@ -244,8 +274,11 @@ public void Interact( setIsOpen(currentOpenness); isCurrentlyLerping = false; } - } else if (movementType == MovementType.Scale) { - if (failure == failState.none || returnToStart == true) { + } + else if (movementType == MovementType.Scale) + { + if (failure == failState.none || returnToStart == true) + { StartCoroutine( LerpScale( movingParts: MovingParts, @@ -261,9 +294,12 @@ public void Interact( posRotRef: posRotRef ) ); - } else { + } + else + { currentOpenness = lastSuccessfulOpenness; - for (int i = 0; i < MovingParts.Length; i++) { + for (int i = 0; i < MovingParts.Length; i++) + { MovingParts[i].transform.localScale = Vector3.Lerp( closedPositions[i], openPositions[i], @@ -290,11 +326,13 @@ private protected IEnumerator LerpPosition( bool returnToStartMode, GameObject posRotManip, GameObject posRotRef - ) { + ) + { float elapsedTime = 0f; while ( elapsedTime < animationTime && (failure == failState.none || returnToStartMode == true) - ) { + ) + { lastSuccessfulOpenness = currentOpenness; elapsedTime += physicsInterval; currentOpenness = Mathf.Clamp( @@ -304,7 +342,8 @@ GameObject posRotRef Mathf.Max(initialOpenness, desiredOpenness) ); - for (int i = 0; i < movingParts.Length; i++) { + for (int i = 0; i < movingParts.Length; i++) + { movingParts[i].transform.localPosition = Vector3.Lerp( closedLocalPositions[i], openLocalPositions[i], @@ -312,7 +351,8 @@ GameObject posRotRef ); } - if (useGripper == true) { + if (useGripper == true) + { SyncPosRot(posRotManip, posRotRef); } @@ -339,11 +379,13 @@ private protected IEnumerator LerpRotation( bool returnToStartMode, GameObject posRotManip, GameObject posRotRef - ) { + ) + { float elapsedTime = 0f; while ( elapsedTime < animationTime && (failure == failState.none || returnToStartMode == true) - ) { + ) + { lastSuccessfulOpenness = currentOpenness; elapsedTime += physicsInterval; currentOpenness = Mathf.Clamp( @@ -353,7 +395,8 @@ GameObject posRotRef Mathf.Max(initialOpenness, desiredOpenness) ); - for (int i = 0; i < movingParts.Length; i++) { + for (int i = 0; i < movingParts.Length; i++) + { movingParts[i].transform.localRotation = Quaternion.Lerp( Quaternion.Euler(closedLocalRotations[i]), Quaternion.Euler(openLocalRotations[i]), @@ -361,7 +404,8 @@ GameObject posRotRef ); } - if (useGripper == true) { + if (useGripper == true) + { SyncPosRot(posRotManip, posRotRef); } @@ -388,12 +432,14 @@ private protected IEnumerator LerpScale( bool returnToStartMode, GameObject posRotManip, GameObject posRotRef - ) { + ) + { float elapsedTime = 0f; while ( elapsedTime < animationTime && (failure == failState.none || returnToStartMode == true) - ) { + ) + { lastSuccessfulOpenness = currentOpenness; elapsedTime += physicsInterval; currentOpenness = Mathf.Clamp( @@ -403,7 +449,8 @@ GameObject posRotRef Mathf.Max(initialOpenness, desiredOpenness) ); - for (int i = 0; i < movingParts.Length; i++) { + for (int i = 0; i < movingParts.Length; i++) + { movingParts[i].transform.localScale = Vector3.Lerp( closedLocalScales[i], openLocalScales[i], @@ -411,7 +458,8 @@ GameObject posRotRef ); } - if (useGripper == true) { + if (useGripper == true) + { SyncPosRot(posRotManip, posRotRef); } @@ -426,24 +474,29 @@ GameObject posRotRef yield break; } - private void setIsOpen(float openness) { + private void setIsOpen(float openness) + { isOpen = openness != 0; currentOpenness = openness; } - public bool GetisOpen() { + public bool GetisOpen() + { return isOpen; } - public void stepOpen(float physicsInterval, bool useGripper, float elapsedTime) { - if (Physics.autoSimulation != true) { + public void stepOpen(float physicsInterval, bool useGripper, float elapsedTime) + { + if (Physics.autoSimulation != true) + { PhysicsSceneManager.PhysicsSimulateTHOR(physicsInterval); Physics.SyncTransforms(); } // failure check (The OnTriggerEnter collision check is listening at all times, // but this hyperextension check must be called manually) - if (useGripper == true && forceAction == false) { + if (useGripper == true && forceAction == false) + { FK_IK_Solver armBase = GameObject .Find("FPSController") .GetComponent() @@ -453,7 +506,8 @@ public void stepOpen(float physicsInterval, bool useGripper, float elapsedTime) 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."); @@ -462,46 +516,54 @@ public void stepOpen(float physicsInterval, bool useGripper, float elapsedTime) } } - public void OnTriggerEnter(Collider other) { + public void OnTriggerEnter(Collider other) + { // If the openable object is meant to ignore trigger collisions entirely, then ignore - if (!triggerEnabled) { + if (!triggerEnabled) + { // Debug.Log("I'm supposed to ignore triggers!, Bye, " + other); return; } // If the openable object is not opening or closing, then ignore - if (!isCurrentlyLerping) { + if (!isCurrentlyLerping) + { // Debug.Log("I'm not currently lerping! Bye, " + other); return; } // If forceAction is enabled, then ignore - if (forceAction == true) { + if (forceAction == true) + { // Debug.Log("All checks are off when forceAction is true!"); return; } // If the overlapping collider is a (non-physical) trigger collider, then ignore - if (other.isTrigger == true) { + if (other.isTrigger == true) + { // Debug.Log(other + "is a trigger, so bye!"); return; } // If the overlapping collider is a child of one of the gameobjects // that it's been explicitly told to disregard, then ignore - if (IsInIgnoreArray(other, IgnoreTheseObjects)) { + if (IsInIgnoreArray(other, IgnoreTheseObjects)) + { // Debug.Log(other + " is in ignore array"); return; } // 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; } // If the overlapping collider is a descendant of the openable GameObject itself (or its parent), then ignore - if (hasAncestor(other.transform.gameObject, gameObject)) { + if (hasAncestor(other.transform.gameObject, gameObject)) + { // Debug.Log(other + " belongs to me!"); return; } @@ -510,7 +572,8 @@ public void OnTriggerEnter(Collider other) { if ( ignoreAgentInTransition == true && hasAncestor(other.transform.gameObject, GameObject.Find("FPSController")) - ) { + ) + { // Debug.Log(other + " belongs to agent, and ignoreAgentInTransition is active!"); return; } @@ -522,16 +585,20 @@ public void OnTriggerEnter(Collider other) { && ancestorSimObjPhysics(other.gameObject).PrimaryProperty != SimObjPrimaryProperty.Static && stopAtNonStaticCol == false - ) { + ) + { // Debug.Log("Ignore nonstatics " + other); return; } // All right, so it was a legit collision? RESET! failure = failState.collision; - if (ancestorSimObjPhysics(other.gameObject) != null) { + if (ancestorSimObjPhysics(other.gameObject) != null) + { failureCollision = other.GetComponentInParent().gameObject; - } else { + } + else + { failureCollision = other.gameObject; } #if UNITY_EDITOR @@ -541,10 +608,14 @@ public void OnTriggerEnter(Collider other) { // for use in OnTriggerEnter ignore check // 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()) { - if (other == ignoredCollider) { + public bool IsInIgnoreArray(Collider other, GameObject[] ignoredObjects) + { + foreach (GameObject ignoredObject in ignoredObjects) + { + foreach (Collider ignoredCollider in ignoredObject.GetComponentsInChildren()) + { + if (other == ignoredCollider) + { return true; } } @@ -552,79 +623,107 @@ public bool IsInIgnoreArray(Collider other, GameObject[] ignoredObjects) { return false; } - private bool hasAncestor(GameObject child, GameObject potentialAncestor) { - if (child == potentialAncestor) { + private bool hasAncestor(GameObject child, GameObject potentialAncestor) + { + if (child == potentialAncestor) + { return true; - } else if (child.transform.parent != null) { + } + else if (child.transform.parent != null) + { return hasAncestor(child.transform.parent.gameObject, potentialAncestor); - } else { + } + else + { return false; } } - private static SimObjPhysics ancestorSimObjPhysics(GameObject go) { - if (go == null) { + private static SimObjPhysics ancestorSimObjPhysics(GameObject go) + { + if (go == null) + { return null; } SimObjPhysics so = go.GetComponent(); - if (so != null) { + if (so != null) + { return so; - } else if (go.transform.parent != null) { + } + else if (go.transform.parent != null) + { return ancestorSimObjPhysics(go.transform.parent.gameObject); - } else { + } + else + { return null; } } - public MovementType GetMovementType() { + public MovementType GetMovementType() + { return movementType; } - public float GetStartOpenness() { + public float GetStartOpenness() + { return startOpenness; } - public void SetFailState(failState failState) { + public void SetFailState(failState failState) + { failure = failState; } - public failState GetFailState() { + public failState GetFailState() + { return failure; } - public void SetFailureCollision(GameObject collision) { + public void SetFailureCollision(GameObject collision) + { failureCollision = collision; } - public GameObject GetFailureCollision() { + public GameObject GetFailureCollision() + { return failureCollision; } - public void SetForceAction(bool forceAction) { + public void SetForceAction(bool forceAction) + { this.forceAction = forceAction; } - public void SetIgnoreAgentInTransition(bool ignoreAgentInTransition) { + public void SetIgnoreAgentInTransition(bool ignoreAgentInTransition) + { this.ignoreAgentInTransition = ignoreAgentInTransition; } - public void SetStopAtNonStaticCol(bool stopAtNonStaticCol) { + public void SetStopAtNonStaticCol(bool stopAtNonStaticCol) + { this.stopAtNonStaticCol = stopAtNonStaticCol; } - public bool GetIsCurrentlyLerping() { - if (this.isCurrentlyLerping) { + public bool GetIsCurrentlyLerping() + { + if (this.isCurrentlyLerping) + { return true; - } else { + } + else + { return false; } } - public void SetIsCurrentlyLerping(bool isCurrentlyLerping) { + public void SetIsCurrentlyLerping(bool isCurrentlyLerping) + { this.isCurrentlyLerping = isCurrentlyLerping; } - public void SyncPosRot(GameObject child, GameObject parent) { + public void SyncPosRot(GameObject child, GameObject parent) + { child.transform.position = parent.transform.position; child.transform.rotation = parent.transform.rotation; } diff --git a/unity/Assets/Scripts/CanToggleOnOff.cs b/unity/Assets/Scripts/CanToggleOnOff.cs index db42f092e4..660c9328e4 100644 --- a/unity/Assets/Scripts/CanToggleOnOff.cs +++ b/unity/Assets/Scripts/CanToggleOnOff.cs @@ -4,7 +4,8 @@ // serialized class so it can show up in Inspector Window [System.Serializable] -public class SwapObjList { +public class SwapObjList +{ // reference to game object that needs to have materials changed [Header("Object That Needs Mat Swaps")] [SerializeField] @@ -21,7 +22,8 @@ public class SwapObjList { public Material[] OffMaterials; } -public class CanToggleOnOff : MonoBehaviour { +public class CanToggleOnOff : MonoBehaviour +{ // the array of moving parts and lightsources will correspond with each other based on their // position in the array @@ -64,7 +66,8 @@ public class CanToggleOnOff : MonoBehaviour { private bool isCurrentlyLerping = false; - protected enum MovementType { + protected enum MovementType + { Slide, Rotate }; @@ -92,43 +95,51 @@ protected enum MovementType { // another sim object, the stove knob. // stove knob: returns toggleable, returns istoggled // stove burner: only returns istoggled - public bool ReturnSelfControlled() { + public bool ReturnSelfControlled() + { return SelfControlled; } // returns references to all sim objects this object toggles the on/off state of. For example all stove knobs can // return which burner they control with this - public SimObjPhysics[] ReturnControlledSimObjects() { + public SimObjPhysics[] ReturnControlledSimObjects() + { return ControlledSimObjects; } - public List ReturnMustBeClosedToTurnOn() { + public List ReturnMustBeClosedToTurnOn() + { return MustBeClosedToTurnOn; } - public bool isTurnedOnOrOff() { + public bool isTurnedOnOrOff() + { return isOn; } // Helper functions for setting up scenes, only for use in Editor #if UNITY_EDITOR - public void SetMovementToSlide() { + public void SetMovementToSlide() + { movementType = MovementType.Slide; } - public void SetMovementToRotate() { + public void SetMovementToRotate() + { movementType = MovementType.Rotate; } #endif // Use this for initialization - void Start() { + 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!" ); @@ -147,28 +158,36 @@ void Start() { // } // Update is called once per frame - void Update() { + void Update() + { // // test if it can open without Agent Command - Debug Purposes #if UNITY_EDITOR - if (Input.GetKeyDown(KeyCode.Minus)) { + if (Input.GetKeyDown(KeyCode.Minus)) + { Toggle(); } #endif } - public void Toggle() { + public void Toggle() + { // if this object is controlled by another object, do nothing and report failure? - if (!SelfControlled) { + if (!SelfControlled) + { return; } isCurrentlyLerping = true; // check if there are moving parts // check if there are lights/materials etc to swap out - if (!isOn) { - if (MovingParts.Length > 0) { - for (int i = 0; i < MovingParts.Length; i++) { - if (movementType == MovementType.Slide) { + if (!isOn) + { + if (MovingParts.Length > 0) + { + for (int i = 0; i < MovingParts.Length; i++) + { + if (movementType == MovementType.Slide) + { StartCoroutine( LerpPosition( movingParts: MovingParts, @@ -179,7 +198,9 @@ public void Toggle() { animationTime: animationTime ) ); - } else if (movementType == MovementType.Rotate) { + } + else if (movementType == MovementType.Rotate) + { StartCoroutine( LerpRotation( movingParts: MovingParts, @@ -195,10 +216,15 @@ public void Toggle() { } setisOn(); - } else { - if (MovingParts.Length > 0) { - for (int i = 0; i < MovingParts.Length; i++) { - if (movementType == MovementType.Slide) { + } + else + { + if (MovingParts.Length > 0) + { + for (int i = 0; i < MovingParts.Length; i++) + { + if (movementType == MovementType.Slide) + { StartCoroutine( LerpPosition( movingParts: MovingParts, @@ -209,7 +235,9 @@ public void Toggle() { animationTime: animationTime ) ); - } else if (movementType == MovementType.Rotate) { + } + else if (movementType == MovementType.Rotate) + { StartCoroutine( LerpRotation( movingParts: MovingParts, @@ -230,31 +258,41 @@ public void Toggle() { } // toggle isOn variable, swap Materials and enable/disable Light sources - private void setisOn() { + private void setisOn() + { // if isOn true, set it to false and also turn off all lights/deactivate materials - if (isOn) { - if (LightSources.Length > 0) { - for (int i = 0; i < LightSources.Length; i++) { + if (isOn) + { + if (LightSources.Length > 0) + { + for (int i = 0; i < LightSources.Length; i++) + { LightSources[i].transform.gameObject.SetActive(false); } } - 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); } } - if (MaterialSwapObjects.Length > 0) { - for (int i = 0; i < MaterialSwapObjects.Length; i++) { + if (MaterialSwapObjects.Length > 0) + { + for (int i = 0; i < MaterialSwapObjects.Length; i++) + { MaterialSwapObjects[i].MyObject.GetComponent().materials = MaterialSwapObjects[i].OffMaterials; } } // also set any objects this object controlls to the off state - if (ControlledSimObjects.Length > 0) { - foreach (SimObjPhysics sop in ControlledSimObjects) { + if (ControlledSimObjects.Length > 0) + { + foreach (SimObjPhysics sop in ControlledSimObjects) + { sop.GetComponent().isOn = false; } } @@ -262,29 +300,38 @@ 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) { - for (int i = 0; i < LightSources.Length; i++) { + else + { + if (LightSources.Length > 0) + { + for (int i = 0; i < LightSources.Length; i++) + { LightSources[i].transform.gameObject.SetActive(true); } } - 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); } } - if (MaterialSwapObjects.Length > 0) { - for (int i = 0; i < MaterialSwapObjects.Length; i++) { + if (MaterialSwapObjects.Length > 0) + { + for (int i = 0; i < MaterialSwapObjects.Length; i++) + { MaterialSwapObjects[i].MyObject.GetComponent().materials = MaterialSwapObjects[i].OnMaterials; } } // also set any objects this object controlls to the on state - if (ControlledSimObjects.Length > 0) { - foreach (SimObjPhysics sop in ControlledSimObjects) { + if (ControlledSimObjects.Length > 0) + { + foreach (SimObjPhysics sop in ControlledSimObjects) + { sop.GetComponent().isOn = true; } } @@ -300,9 +347,11 @@ private protected IEnumerator LerpPosition( float initialOpenness, float desiredOpenness, float animationTime - ) { + ) + { float elapsedTime = 0f; - while (elapsedTime < animationTime) { + while (elapsedTime < animationTime) + { elapsedTime += Time.fixedDeltaTime; float currentOpenness = Mathf.Clamp( initialOpenness @@ -310,7 +359,8 @@ float animationTime Mathf.Min(initialOpenness, desiredOpenness), Mathf.Max(initialOpenness, desiredOpenness) ); - for (int i = 0; i < movingParts.Length; i++) { + for (int i = 0; i < movingParts.Length; i++) + { movingParts[i].transform.localPosition = Vector3.Lerp( offLocalPositions[i], onLocalPositions[i], @@ -328,9 +378,11 @@ private protected IEnumerator LerpRotation( float initialOpenness, float desiredOpenness, float animationTime - ) { + ) + { float elapsedTime = 0f; - while (elapsedTime < animationTime) { + while (elapsedTime < animationTime) + { elapsedTime += Time.fixedDeltaTime; float currentOpenness = Mathf.Clamp( initialOpenness @@ -338,7 +390,8 @@ float animationTime Mathf.Min(initialOpenness, desiredOpenness), Mathf.Max(initialOpenness, desiredOpenness) ); - for (int i = 0; i < MovingParts.Length; i++) { + for (int i = 0; i < MovingParts.Length; i++) + { MovingParts[i].transform.localRotation = Quaternion.Lerp( Quaternion.Euler(offLocalRotations[i]), Quaternion.Euler(onLocalRotations[i]), @@ -349,10 +402,14 @@ float animationTime yield break; } - public bool GetIsCurrentlyLerping() { - if (this.isCurrentlyLerping) { + public bool GetIsCurrentlyLerping() + { + if (this.isCurrentlyLerping) + { return true; - } else { + } + else + { return false; } } diff --git a/unity/Assets/Scripts/ChangeLighting.cs b/unity/Assets/Scripts/ChangeLighting.cs index da85e4c7ad..bdac9b774b 100644 --- a/unity/Assets/Scripts/ChangeLighting.cs +++ b/unity/Assets/Scripts/ChangeLighting.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class ChangeLighting : MonoBehaviour { +public class ChangeLighting : MonoBehaviour +{ // 9 elements right now public GameObject[] Lights; @@ -12,8 +13,10 @@ void Start() { } // Update is called once per frame void Update() { } - public void SetLights(int lightset) { - foreach (GameObject go in Lights) { + public void SetLights(int lightset) + { + foreach (GameObject go in Lights) + { go.SetActive(false); } diff --git a/unity/Assets/Scripts/ColdZone.cs b/unity/Assets/Scripts/ColdZone.cs index a432165da0..59e07f4bfb 100644 --- a/unity/Assets/Scripts/ColdZone.cs +++ b/unity/Assets/Scripts/ColdZone.cs @@ -2,20 +2,24 @@ using System.Collections.Generic; using UnityEngine; -public class ColdZone : MonoBehaviour { +public class ColdZone : MonoBehaviour +{ // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } - public void OnTriggerStay(Collider other) { + public void OnTriggerStay(Collider other) + { // if any simobjphys are touching this zone, set their temperature values to Cold - if (other.GetComponentInParent()) { + if (other.GetComponentInParent()) + { SimObjPhysics sop = other.GetComponentInParent(); sop.CurrentTemperature = Temperature.Cold; - if (sop.HowManySecondsUntilRoomTemp != sop.GetTimerResetValue()) { + if (sop.HowManySecondsUntilRoomTemp != sop.GetTimerResetValue()) + { sop.HowManySecondsUntilRoomTemp = sop.GetTimerResetValue(); } diff --git a/unity/Assets/Scripts/CollisionEventResolver.cs b/unity/Assets/Scripts/CollisionEventResolver.cs index 6debb01d8f..febc7fa215 100644 --- a/unity/Assets/Scripts/CollisionEventResolver.cs +++ b/unity/Assets/Scripts/CollisionEventResolver.cs @@ -2,10 +2,13 @@ using System.Collections.Generic; using UnityEngine; -public abstract class CollisionEventResolver : MonoBehaviour { - protected void Start() { +public abstract class CollisionEventResolver : MonoBehaviour +{ + protected void Start() + { var listener = this.transform.GetComponentInParent(); - if (listener != null) { + if (listener != null) + { listener.setCollisionEventResolver(this); } } @@ -17,21 +20,28 @@ HashSet internalColliders } // Class to track what was hit while arm was moving -public class StaticCollision { +public class StaticCollision +{ public GameObject gameObject; public SimObjPhysics simObjPhysics; // indicates if gameObject a simObject - public bool isSimObj { + public bool isSimObj + { get { return simObjPhysics != null; } } - public string name { - get { - if (this.isSimObj) { + public string name + { + get + { + if (this.isSimObj) + { return this.simObjPhysics.name; - } else { + } + else + { return this.gameObject.name; } } diff --git a/unity/Assets/Scripts/CollisionListener.cs b/unity/Assets/Scripts/CollisionListener.cs index ba544a72c6..400d4d43b4 100644 --- a/unity/Assets/Scripts/CollisionListener.cs +++ b/unity/Assets/Scripts/CollisionListener.cs @@ -5,7 +5,8 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public class CollisionListener : MonoBehaviour { +public class CollisionListener : MonoBehaviour +{ public Dictionary> externalColliderToInternalCollisions = new Dictionary>(); public List doNotRegisterChildrenWithin = new List(); @@ -18,10 +19,13 @@ public class CollisionListener : MonoBehaviour { private HashSet collisionListenerChildren = new HashSet(); - void Start() { + void Start() + { registerAllChildColliders(); - foreach (CollisionListener cl in this.GetComponentsInChildren()) { - if (cl.gameObject != this.gameObject) { + 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}" @@ -34,74 +38,94 @@ void Start() { } } - public void setCollisionEventResolver(CollisionEventResolver collisionEventResolver) { + public void setCollisionEventResolver(CollisionEventResolver collisionEventResolver) + { this.collisionEventResolver = collisionEventResolver; } - public void registerAllChildColliders() { + public void registerAllChildColliders() + { HashSet ignoredColliders = new HashSet(); - foreach (GameObject go in doNotRegisterChildrenWithin) { - foreach (Collider c in go.GetComponentsInChildren()) { + foreach (GameObject go in doNotRegisterChildrenWithin) + { + foreach (Collider c in go.GetComponentsInChildren()) + { ignoredColliders.Add(c); } } - foreach (CollisionListenerChild clc in collisionListenerChildren) { + foreach (CollisionListenerChild clc in collisionListenerChildren) + { clc.parent = null; } collisionListenerChildren.Clear(); - foreach (Collider c in this.GetComponentsInChildren()) { - if (!ignoredColliders.Contains(c)) { + foreach (Collider c in this.GetComponentsInChildren()) + { + if (!ignoredColliders.Contains(c)) + { registerChild(c); } } } - public void registerChild(Collider c) { - if (c.enabled && c.isTrigger) { + public void registerChild(Collider c) + { + if (c.enabled && c.isTrigger) + { CollisionListenerChild clc = c.gameObject.GetComponent(); - if (clc == null) { + if (clc == null) + { clc = c.gameObject.AddComponent(); } registerChild(clc); } } - public void registerChild(CollisionListenerChild clc) { + public void registerChild(CollisionListenerChild clc) + { clc.parent = this; collisionListenerChildren.Add(clc); } - public void deregisterChild(Collider c) { + public void deregisterChild(Collider c) + { deregisterChild(c.gameObject.GetComponent()); } - public void deregisterChild(CollisionListenerChild clc) { - if (clc != null) { + public void deregisterChild(CollisionListenerChild clc) + { + if (clc != null) + { clc.parent = null; collisionListenerChildren.Remove(clc); } } - public void RegisterCollision(Collider internalCollider, Collider externalCollider) { - if (!externalColliderToInternalCollisions.ContainsKey(externalCollider)) { + public void RegisterCollision(Collider internalCollider, Collider externalCollider) + { + if (!externalColliderToInternalCollisions.ContainsKey(externalCollider)) + { externalColliderToInternalCollisions[externalCollider] = new HashSet(); } externalColliderToInternalCollisions[externalCollider].Add(internalCollider); } - public void DeregisterCollision(Collider internalCollider, Collider externalCollider) { - if (externalColliderToInternalCollisions.ContainsKey(externalCollider)) { + public void DeregisterCollision(Collider internalCollider, Collider externalCollider) + { + if (externalColliderToInternalCollisions.ContainsKey(externalCollider)) + { externalColliderToInternalCollisions[externalCollider].Remove(internalCollider); - if (externalColliderToInternalCollisions[externalCollider].Count == 0) { + if (externalColliderToInternalCollisions[externalCollider].Count == 0) + { externalColliderToInternalCollisions.Remove(externalCollider); } } } - public void Reset() { + public void Reset() + { externalColliderToInternalCollisions.Clear(); deadZoneCheck = false; } @@ -109,7 +133,8 @@ public void Reset() { private static bool debugCheckIfCollisionIsNonTrivial( Collider internalCollider, Collider externalCollider - ) { + ) + { Vector3 direction; float distance = 0f; Physics.ComputePenetration( @@ -129,35 +154,46 @@ out distance return distance > 0.001f; } - private StaticCollision ColliderToStaticCollision(Collider collider) { + private StaticCollision ColliderToStaticCollision(Collider collider) + { StaticCollision sc = null; - if (!collider.isTrigger) { // only detect collisions with non-trigger colliders detected - if (collider.GetComponentInParent()) { + if (!collider.isTrigger) + { // only detect collisions with non-trigger colliders detected + 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 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) { + } + 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 - if (sop.Mass > massThreshold) { + if (sop.Mass > massThreshold) + { sc = new StaticCollision(); sc.simObjPhysics = sop; sc.gameObject = collider.gameObject; } } - } else if (collider.gameObject.CompareTag("Structure")) { + } + else if (collider.gameObject.CompareTag("Structure")) + { sc = new StaticCollision(); sc.gameObject = collider.gameObject; - } else if (collisionEventResolver != null) { + } + else if (collisionEventResolver != null) + { sc = collisionEventResolver.resolveToStaticCollision( collider, externalColliderToInternalCollisions[collider] @@ -167,26 +203,33 @@ private StaticCollision ColliderToStaticCollision(Collider collider) { return sc; } - public IEnumerable StaticCollisions(IEnumerable colliders) { - foreach (Collider c in colliders) { + public IEnumerable StaticCollisions(IEnumerable colliders) + { + foreach (Collider c in colliders) + { var staticCollision = ColliderToStaticCollision(collider: c); - if (staticCollision != null) { + if (staticCollision != null) + { yield return staticCollision; } } } - public IEnumerable StaticCollisions() { + public IEnumerable StaticCollisions() + { return StaticCollisions(this.externalColliderToInternalCollisions.Keys); } - public void enableDeadZoneCheck() { + public void enableDeadZoneCheck() + { deadZoneCheck = true; } - public bool TransformChecks(PhysicsRemoteFPSAgentController controller, Transform objectTarget) { + public bool TransformChecks(PhysicsRemoteFPSAgentController controller, Transform objectTarget) + { // this action is specifically for a stretch wrist-rotation with limits - if (deadZoneCheck) { + if (deadZoneCheck) + { float currentYaw = objectTarget.rotation.eulerAngles.y; float cLimit = controller .gameObject.GetComponentInChildren() @@ -197,24 +240,32 @@ public bool TransformChecks(PhysicsRemoteFPSAgentController controller, Transfor // 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) { + if (cLimit < ccLimit) + { cLimit += 360; - if (currentYaw < ccLimit) { + if (currentYaw < ccLimit) + { currentYaw += 360; } } - if (currentYaw < ccLimit || currentYaw > cLimit) { + if (currentYaw < ccLimit || currentYaw > cLimit) + { return true; - } else { + } + else + { return false; } - } else { + } + else + { return false; } } - public virtual bool ShouldHalt() { + public virtual bool ShouldHalt() + { return StaticCollisions().GetEnumerator().MoveNext(); } } diff --git a/unity/Assets/Scripts/CollisionListenerAB.cs b/unity/Assets/Scripts/CollisionListenerAB.cs index b521bf4c50..350878f512 100644 --- a/unity/Assets/Scripts/CollisionListenerAB.cs +++ b/unity/Assets/Scripts/CollisionListenerAB.cs @@ -1,7 +1,9 @@ -public class CollisionListenerAB : CollisionListener { +public class CollisionListenerAB : CollisionListener +{ // public ArticulatedArmController armController; - public override bool ShouldHalt() { + 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 236906846e..dea2885a12 100644 --- a/unity/Assets/Scripts/CollisionListenerChild.cs +++ b/unity/Assets/Scripts/CollisionListenerChild.cs @@ -3,32 +3,41 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public class CollisionListenerChild : MonoBehaviour { +public class CollisionListenerChild : MonoBehaviour +{ // references to the joints of the mid level arm public CollisionListener parent; public Collider us; - public void Start() { + public void Start() + { us = this.gameObject.GetComponent(); } - public void OnDestroy() { - if (parent != null) { + public void OnDestroy() + { + if (parent != null) + { parent.deregisterChild(this.GetComponent()); } } - public void OnTriggerExit(Collider col) { - if (parent) { + public void OnTriggerExit(Collider col) + { + if (parent) + { parent.DeregisterCollision(this.us, col); } } - public void OnTriggerStay(Collider col) { + public void OnTriggerStay(Collider col) + { #if UNITY_EDITOR - if (!parent.externalColliderToInternalCollisions.ContainsKey(col)) { - if (col.gameObject.name == "StandardIslandHeight" || col.gameObject.name == "Sphere") { + if (!parent.externalColliderToInternalCollisions.ContainsKey(col)) + { + if (col.gameObject.name == "StandardIslandHeight" || col.gameObject.name == "Sphere") + { Debug.Log( "got collision stay with " + col.gameObject.name @@ -38,15 +47,19 @@ public void OnTriggerStay(Collider col) { } } #endif - if (parent) { + if (parent) + { parent.RegisterCollision(this.us, col); } } - public void OnTriggerEnter(Collider col) { + public void OnTriggerEnter(Collider col) + { #if UNITY_EDITOR - if (!parent.externalColliderToInternalCollisions.ContainsKey(col)) { - if (col.gameObject.name == "StandardIslandHeight" || col.gameObject.name == "Sphere") { + if (!parent.externalColliderToInternalCollisions.ContainsKey(col)) + { + if (col.gameObject.name == "StandardIslandHeight" || col.gameObject.name == "Sphere") + { Debug.Log( "got collision enter with " + col.gameObject.name @@ -57,7 +70,8 @@ public void OnTriggerEnter(Collider col) { } #endif // Debug.Log("got collision with " + col.gameObject.name + " this" + this.gameObject.name); - if (parent) { + if (parent) + { parent.RegisterCollision(this.us, col); } } diff --git a/unity/Assets/Scripts/ColorChanger.cs b/unity/Assets/Scripts/ColorChanger.cs index 7ea2e4e137..111d0ddec2 100644 --- a/unity/Assets/Scripts/ColorChanger.cs +++ b/unity/Assets/Scripts/ColorChanger.cs @@ -2,7 +2,8 @@ using UnityEngine; using Random = UnityEngine.Random; -public class ColorChanger : MonoBehaviour { +public class ColorChanger : MonoBehaviour +{ // These will eventually be turned into sets, such that they are // easily checkable at runtime. @@ -11,7 +12,8 @@ public class ColorChanger : MonoBehaviour { Dictionary> materialGroupPaths; private ResourceAssetManager assetManager; - protected void cacheMaterials() { + protected void cacheMaterials() + { var objectMaterialLabels = new string[] { "AlarmClockMaterials", @@ -82,18 +84,21 @@ protected void cacheMaterials() { this.assetManager = new ResourceAssetManager(); objectMaterials = new Dictionary>>(); - foreach (var label in objectMaterialLabels) { + foreach (var label in objectMaterialLabels) + { objectMaterials[label] = this.assetManager.FindResourceAssetReferences(label); } materialGroupPaths = new Dictionary>(); - foreach (var label in materialGroupLabels) { + foreach (var label in materialGroupLabels) + { HashSet paths = new HashSet(); foreach ( var resourceAssetRef in this.assetManager.FindResourceAssetReferences( label ) - ) { + ) + { paths.Add(resourceAssetRef.ResourcePath); } @@ -101,23 +106,28 @@ var resourceAssetRef in this.assetManager.FindResourceAssetReferences( } } - private void storeOriginal(Material mat) { - if (!origMaterials.ContainsKey(mat)) { + private void storeOriginal(Material mat) + { + if (!origMaterials.ContainsKey(mat)) + { origMaterials[mat] = new Material(mat); } } - private void swapMaterial(Material mat1, Material mat2) { + private void swapMaterial(Material mat1, Material mat2) + { storeOriginal(mat1); storeOriginal(mat2); - if (mat1.HasProperty("_MainTex") && mat2.HasProperty("_MainTex")) { + if (mat1.HasProperty("_MainTex") && mat2.HasProperty("_MainTex")) + { Texture tempTexture = mat1.mainTexture; mat1.mainTexture = mat2.mainTexture; mat2.mainTexture = tempTexture; } - if (mat1.HasProperty("_Color") && mat2.HasProperty("_Color")) { + if (mat1.HasProperty("_Color") && mat2.HasProperty("_Color")) + { Color tempColor = mat1.color; mat1.color = mat2.color; mat2.color = tempColor; @@ -127,15 +137,20 @@ private void swapMaterial(Material mat1, Material mat2) { private void shuffleMaterials( HashSet activeMaterialNames, List> materialGroup - ) { - for (int n = materialGroup.Count - 1; n >= 0; n--) { + ) + { + for (int n = materialGroup.Count - 1; n >= 0; n--) + { int i = Random.Range(0, n + 1); ResourceAssetReference refA = materialGroup[n]; ResourceAssetReference refB = materialGroup[i]; - if (activeMaterialNames.Contains(refA.Name) || activeMaterialNames.Contains(refB.Name)) { + if (activeMaterialNames.Contains(refA.Name) || activeMaterialNames.Contains(refB.Name)) + { swapMaterial(refA.Load(), refB.Load()); - } else { + } + else + { // just swap the references if neither material is actively being used in the scene materialGroup[n] = refB; materialGroup[i] = refA; @@ -150,16 +165,20 @@ public int RandomizeMaterials( bool useExternalMaterials, HashSet inRoomTypes, HashSet excludedMaterialNames = null - ) { - if (objectMaterials == null) { + ) + { + if (objectMaterials == null) + { cacheMaterials(); } - if (excludedMaterialNames == null) { + if (excludedMaterialNames == null) + { excludedMaterialNames = new HashSet(); } - Dictionary roomTypeLabelMap = new Dictionary() { + Dictionary roomTypeLabelMap = new Dictionary() + { ["kitchen"] = "RawKitchenMaterials", ["livingroom"] = "RawLivingRoomMaterials", ["bedroom"] = "RawBedroomMaterials", @@ -174,9 +193,12 @@ public int RandomizeMaterials( // need to get loaded and shuffled, using this the shuffle step // can limit what materials actually get loaded through Resources.Load() HashSet activeMaterialNames = new HashSet(); - foreach (var renderer in GameObject.FindObjectsOfType()) { - foreach (var mat in renderer.sharedMaterials) { - if (mat != null && mat.name != null && !excludedMaterialNames.Contains(mat.name)) { + foreach (var renderer in GameObject.FindObjectsOfType()) + { + foreach (var mat in renderer.sharedMaterials) + { + if (mat != null && mat.name != null && !excludedMaterialNames.Contains(mat.name)) + { #if UNITY_EDITOR Debug.Log("Found material: " + mat.name); #endif @@ -190,10 +212,12 @@ public int RandomizeMaterials( string, List> > materialGroup in objectMaterials - ) { + ) + { List> validMaterials = new List>(); - foreach (ResourceAssetReference resourceAssetReference in materialGroup.Value) { + foreach (ResourceAssetReference resourceAssetReference in materialGroup.Value) + { if ( useTrainMaterials && materialGroupPaths["RawTrainMaterials"] @@ -204,17 +228,23 @@ public int RandomizeMaterials( || useTestMaterials && materialGroupPaths["RawTestMaterials"] .Contains(resourceAssetReference.ResourcePath) - ) { - if (inRoomTypes == null) { + ) + { + if (inRoomTypes == null) + { validMaterials.Add(resourceAssetReference); numTotalMaterials++; - } else { - foreach (string roomType in inRoomTypes) { + } + else + { + foreach (string roomType in inRoomTypes) + { string roomLabel = roomTypeLabelMap[roomType]; if ( materialGroupPaths[roomLabel] .Contains(resourceAssetReference.ResourcePath) - ) { + ) + { validMaterials.Add(resourceAssetReference); numTotalMaterials++; break; @@ -230,53 +260,69 @@ public int RandomizeMaterials( return numTotalMaterials; } - public void ResetMaterials() { - foreach (KeyValuePair matPair in origMaterials) { + public void ResetMaterials() + { + foreach (KeyValuePair matPair in origMaterials) + { Material mat = matPair.Key; - if (mat.HasProperty("_Color")) { + if (mat.HasProperty("_Color")) + { mat.color = matPair.Value.color; } - if (mat.HasProperty("_MainTex")) { + if (mat.HasProperty("_MainTex")) + { mat.mainTexture = matPair.Value.mainTexture; } } } - public void RandomizeColor() { - if (objectMaterials == null) { + public void RandomizeColor() + { + if (objectMaterials == null) + { cacheMaterials(); } - foreach (var renderer in GameObject.FindObjectsOfType()) { - foreach (var mat in renderer.sharedMaterials) { + foreach (var renderer in GameObject.FindObjectsOfType()) + { + foreach (var mat in renderer.sharedMaterials) + { storeOriginal(mat); - if (mat.HasProperty("_Color")) { + if (mat.HasProperty("_Color")) + { mat.color = Random.ColorHSV(0f, 1f, 0.5f, 1f, 0.5f, 1f); } } } } - public void ResetColors() { - foreach (KeyValuePair matPair in origMaterials) { + public void ResetColors() + { + foreach (KeyValuePair matPair in origMaterials) + { Material mat = matPair.Key; - if (mat.HasProperty("_Color")) { + if (mat.HasProperty("_Color")) + { mat.color = matPair.Value.color; } } } - public Dictionary GetMaterials() { + public Dictionary GetMaterials() + { Dictionary orSomething = new Dictionary(); - if (objectMaterials == null) { + if (objectMaterials == null) + { cacheMaterials(); } - foreach (KeyValuePair>> sm in objectMaterials) { + foreach (KeyValuePair>> sm in objectMaterials) + { List materialNames = new List(); - foreach (ResourceAssetReference resourceAssetReference in sm.Value) { + foreach (ResourceAssetReference resourceAssetReference in sm.Value) + { materialNames.Add(resourceAssetReference.Name); } diff --git a/unity/Assets/Scripts/ConnectionProperties.cs b/unity/Assets/Scripts/ConnectionProperties.cs index f73a0de346..87e21588f7 100644 --- a/unity/Assets/Scripts/ConnectionProperties.cs +++ b/unity/Assets/Scripts/ConnectionProperties.cs @@ -3,14 +3,16 @@ using EasyButtons; using UnityEngine; -public enum ConnectionType { +public enum ConnectionType +{ Unknown = 0, DoubleDoor, SignleDoor, Window } -public class ConnectionProperties : MonoBehaviour { +public class ConnectionProperties : MonoBehaviour +{ public bool IsOpen = false; public string OpenFromRoomId; public string OpenToRoomId; @@ -18,9 +20,11 @@ public class ConnectionProperties : MonoBehaviour { //public Material WallMaterialId [Button] - public void ToggleOpen() { + public void ToggleOpen() + { var canOpen = this.gameObject.GetComponentInChildren(); - if (canOpen != null) { + if (canOpen != null) + { canOpen.SetOpennessImmediate(!this.IsOpen ? 1.0f : 0.0f); } this.IsOpen = !this.IsOpen; diff --git a/unity/Assets/Scripts/Contains.cs b/unity/Assets/Scripts/Contains.cs index 75a3b0d87e..df196a077b 100644 --- a/unity/Assets/Scripts/Contains.cs +++ b/unity/Assets/Scripts/Contains.cs @@ -9,14 +9,16 @@ // of the Receptacle Trigger Box, which gets confusing if an Object has multiple ReceptacleTriggerBoxes // with multiple Contains.cs scripts [System.Serializable] -public class ReceptacleSpawnPoint { +public class ReceptacleSpawnPoint +{ public BoxCollider ReceptacleBox; // the box the point is in public Vector3 Point; // Vector3 coordinate in world space, possible spawn location public Contains Script; public SimObjPhysics ParentSimObjPhys; - public ReceptacleSpawnPoint(Vector3 p, BoxCollider box, Contains c, SimObjPhysics parentsop) { + public ReceptacleSpawnPoint(Vector3 p, BoxCollider box, Contains c, SimObjPhysics parentsop) + { ReceptacleBox = box; Point = p; Script = c; @@ -24,7 +26,8 @@ public ReceptacleSpawnPoint(Vector3 p, BoxCollider box, Contains c, SimObjPhysic } } -public class Contains : MonoBehaviour { +public class Contains : MonoBehaviour +{ [SerializeField] protected List CurrentlyContains = new List(); @@ -42,20 +45,25 @@ public class Contains : MonoBehaviour { // Use this for initialization - void OnEnable() { + void OnEnable() + { // if the parent of this object has a SimObjPhysics component, grab a reference to it - if (myParent == null) { - if (gameObject.GetComponentInParent().transform.gameObject) { + if (myParent == null) + { + if (gameObject.GetComponentInParent().transform.gameObject) + { myParent = gameObject.GetComponentInParent().transform.gameObject; } } } - void Start() { + 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)) { + if (!go.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) + { Debug.LogError( go.transform.name + " is missing Receptacle Secondary Property! please hook them up" ); @@ -64,7 +72,8 @@ void Start() { } // Update is called once per frame - void Update() { + void Update() + { // turn this on for debugging spawnpoints in editor // GetValidSpawnPoints(true); @@ -80,12 +89,18 @@ void Update() { // } } - protected bool hasAncestor(GameObject child, GameObject potentialAncestor) { - if (child == potentialAncestor) { + protected bool hasAncestor(GameObject child, GameObject potentialAncestor) + { + if (child == potentialAncestor) + { return true; - } else if (child.transform.parent != null) { + } + else if (child.transform.parent != null) + { return hasAncestor(child.transform.parent.gameObject, potentialAncestor); - } else { + } + else + { return false; } } @@ -93,7 +108,8 @@ protected bool hasAncestor(GameObject child, GameObject potentialAncestor) { // public BoxCollider coll; // return a list of sim objects currently inside this trigger box as GameObjects - public List CurrentlyContainedGameObjects() { + public List CurrentlyContainedGameObjects() + { List objs = new List(); BoxCollider b = this.GetComponent(); @@ -122,19 +138,23 @@ public List CurrentlyContainedGameObjects() { // 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) - ) { + ) + { // ignore triggers - if (col.GetComponentInParent() && !col.isTrigger) { + 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 // 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)) { + if (!hasAncestor(this.transform.gameObject, sop.transform.gameObject)) + { // don't add repeat objects in case there were multiple // colliders from the same object - if (!objs.Contains(sop.transform.gameObject)) { + if (!objs.Contains(sop.transform.gameObject)) + { objs.Add(sop.transform.gameObject); } } @@ -146,9 +166,11 @@ Collider col in Physics.OverlapBox(worldCenter, worldHalfExtents, b.transform.ro // return if this container object is occupied by any object(s) inside the trigger collider // used by ObjectSpecificReceptacle, so objects like stove burners, coffee machine, etc. - public bool isOccupied() { + public bool isOccupied() + { bool result = false; - if (CurrentlyContainedGameObjects().Count > 0) { + if (CurrentlyContainedGameObjects().Count > 0) + { result = true; } @@ -156,10 +178,12 @@ public bool isOccupied() { } // report back what is currently inside this receptacle as list of SimObjPhysics - public List CurrentlyContainedObjects() { + public List CurrentlyContainedObjects() + { List toSimObjPhysics = new List(); - foreach (GameObject g in CurrentlyContainedGameObjects()) { + foreach (GameObject g in CurrentlyContainedGameObjects()) + { toSimObjPhysics.Add(g.GetComponent()); } @@ -167,10 +191,12 @@ public List CurrentlyContainedObjects() { } // report back a list of object ids of objects currently inside this receptacle - public List CurrentlyContainedObjectIDs() { + public List CurrentlyContainedObjectIDs() + { List ids = new List(); - foreach (GameObject g in CurrentlyContainedGameObjects()) { + foreach (GameObject g in CurrentlyContainedGameObjects()) + { ids.Add(g.GetComponent().ObjectID); } @@ -178,7 +204,8 @@ 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) { + public List GetValidSpawnPointsFromTriggerBoxLocalSpace(bool top = true) + { Vector3 p1, p2, p4; // in case we need all the corners later for something... @@ -208,21 +235,24 @@ public List GetValidSpawnPointsFromTriggerBoxLocalSpace(bool top = true Vector3 zdir = (p4 - p1).normalized; // direction in the -z direction to finish drawing grid float zdist = Vector3.Distance(p4, p1); - for (int i = 0; i < linepoints; i++) { + for (int i = 0; i < linepoints; i++) + { float x = p1.x + (p2.x - p1.x) * (lineincrement * i); float y = p1.y + (p2.y - p1.y) * (lineincrement * i); float z = p1.z + (p2.z - p1.z) * (lineincrement * i); PointsOnLineXdir[i] = new Vector3(x, y, z); - for (int j = 0; j < linepoints; j++) { + for (int j = 0; j < linepoints; j++) + { gridpoints.Add(PointsOnLineXdir[i] + zdir * (zdist * (j * lineincrement))); } } //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)); } @@ -230,7 +260,8 @@ public List GetValidSpawnPointsFromTriggerBoxLocalSpace(bool top = true } // returns a grid of points above the target receptacle - public List GetValidSpawnPointsFromTriggerBox(bool top = true) { + public List GetValidSpawnPointsFromTriggerBox(bool top = true) + { Vector3 p1, p2, p4; // in case we need all the corners later for something... @@ -260,19 +291,22 @@ public List GetValidSpawnPointsFromTriggerBox(bool top = true) { Vector3 zdir = (p4 - p1).normalized; // direction in the -z direction to finish drawing grid float zdist = Vector3.Distance(p4, p1); - for (int i = 0; i < linepoints; i++) { + for (int i = 0; i < linepoints; i++) + { float x = p1.x + (p2.x - p1.x) * (lineincrement * i); float y = p1.y + (p2.y - p1.y) * (lineincrement * i); float z = p1.z + (p2.z - p1.z) * (lineincrement * i); PointsOnLineXdir[i] = new Vector3(x, y, z); - for (int j = 0; j < linepoints; j++) { + for (int j = 0; j < linepoints; j++) + { gridpoints.Add(PointsOnLineXdir[i] + zdir * (zdist * (j * lineincrement))); } } #if UNITY_EDITOR - foreach (Vector3 point in gridpoints) { + 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); } @@ -284,7 +318,8 @@ public List GetValidSpawnPointsFromTriggerBox(bool top = true) { // generate a grid of potential spawn points, set ReturnPointsClosestToAgent to true if // the list of points should be filtered closest to agent, if false // it will return all points on the receptacle regardless of agent proximity - public List GetValidSpawnPoints(BaseFPSAgentController agent = null) { + public List GetValidSpawnPoints(BaseFPSAgentController agent = null) + { List PossibleSpawnPoints = new List(); Vector3 p1, @@ -321,19 +356,22 @@ public List GetValidSpawnPoints(BaseFPSAgentController age float zdist = Vector3.Distance(p4, p1); float ydist = Vector3.Distance(p1, p5); - for (int i = 0; i < linepoints; i++) { + for (int i = 0; i < linepoints; i++) + { float x = p1.x + (p2.x - p1.x) * (lineincrement * i); float y = p1.y + (p2.y - p1.y) * (lineincrement * i); float z = p1.z + (p2.z - p1.z) * (lineincrement * i); PointsOnLineXdir[i] = new Vector3(x, y, z); - for (int j = 0; j < linepoints; j++) { + for (int j = 0; j < linepoints; j++) + { gridpoints.Add(PointsOnLineXdir[i] + zdir * (zdist * (j * lineincrement))); } } - foreach (Vector3 point in gridpoints) { + foreach (Vector3 point in gridpoints) + { // // quick test to see if this point on the grid is blocked by anything by raycasting down // // toward it @@ -360,12 +398,15 @@ public List GetValidSpawnPoints(BaseFPSAgentController age ), 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) { + if (hit.transform == myParent.transform) + { // print("raycast hit: " + hit.transform.name); - if (agent == null) { + if (agent == null) + { PossibleSpawnPoints.Add( new ReceptacleSpawnPoint( hit.point, @@ -374,7 +415,9 @@ public List GetValidSpawnPoints(BaseFPSAgentController age myParent.GetComponent() ) ); - } else if (narrowDownValidSpawnPoints(agent, hit.point)) { + } + else if (narrowDownValidSpawnPoints(agent, hit.point)) + { PossibleSpawnPoints.Add( new ReceptacleSpawnPoint( hit.point, @@ -389,7 +432,8 @@ 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) { + if (agent == null) + { PossibleSpawnPoints.Add( new ReceptacleSpawnPoint( BottomPoint, @@ -398,7 +442,9 @@ public List GetValidSpawnPoints(BaseFPSAgentController age myParent.GetComponent() ) ); - } else if (narrowDownValidSpawnPoints(agent, BottomPoint)) { + } + else if (narrowDownValidSpawnPoints(agent, BottomPoint)) + { PossibleSpawnPoints.Add( new ReceptacleSpawnPoint( BottomPoint, @@ -425,7 +471,8 @@ 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) { + 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 @@ -433,7 +480,8 @@ private bool narrowDownValidSpawnPoints(BaseFPSAgentController agent, Vector3 po tmpForCamera.y = point.y; // automatically rule out a point if it's beyond our max distance of visibility - if (Vector3.Distance(point, tmpForCamera) >= agent.maxVisibleDistance) { + if (Vector3.Distance(point, tmpForCamera) >= agent.maxVisibleDistance) + { return false; } @@ -443,20 +491,25 @@ private bool narrowDownValidSpawnPoints(BaseFPSAgentController agent, Vector3 po Camera agentCam = agent.m_Camera; // no offset if the object is below the camera position - a slight offset to account for objects equal in y distance to the camera - if (point.y < agentCam.transform.position.y - 0.05f) { + if (point.y < agentCam.transform.position.y - 0.05f) + { // do this check if the point's y value is below the camera's y value // this check will be a raycast vision check from the camera to the point exactly - if (agent.CheckIfPointIsInViewport(point)) { + if (agent.CheckIfPointIsInViewport(point)) + { return true; } - } else { + } + else + { // do this check if the point's y value is above the agent camera. This means we are // trying to place an object on a shelf or something high up that we can't quite reach // in this case, modify the point that is checked for visibility by adding a little bit to the y // might want to adjust this offset amount, or even move this check to ensure object visibility after the // checkspawnarea corners are generated? - if (agent.CheckIfPointIsInViewport(point + new Vector3(0, 0.05f, 0))) { + if (agent.CheckIfPointIsInViewport(point + new Vector3(0, 0.05f, 0))) + { return true; } } @@ -466,7 +519,8 @@ private bool narrowDownValidSpawnPoints(BaseFPSAgentController agent, Vector3 po // used to check if a given Vector3 is inside this receptacle box in world space // use this to check if a SimObjectPhysics's corners are contained within this receptacle, if not then it doesn't fit - public bool CheckIfPointIsInsideReceptacleTriggerBox(Vector3 point) { + public bool CheckIfPointIsInsideReceptacleTriggerBox(Vector3 point) + { BoxCollider myBox = gameObject.GetComponent(); point = myBox.transform.InverseTransformPoint(point) - myBox.center; @@ -481,14 +535,18 @@ public bool CheckIfPointIsInsideReceptacleTriggerBox(Vector3 point) { && point.y > -halfY && point.z < halfZ && point.z > -halfZ - ) { + ) + { return true; - } else { + } + else + { return false; } } - public bool CheckIfPointIsAboveReceptacleTriggerBox(Vector3 point) { + public bool CheckIfPointIsAboveReceptacleTriggerBox(Vector3 point) + { BoxCollider myBox = gameObject.GetComponent(); point = myBox.transform.InverseTransformPoint(point) - myBox.center; @@ -503,15 +561,19 @@ public bool CheckIfPointIsAboveReceptacleTriggerBox(Vector3 point) { && point.y > -BIGY && point.z < halfZ && point.z > -halfZ - ) { + ) + { return true; - } else { + } + else + { return false; } } #if UNITY_EDITOR - void OnDrawGizmos() { + void OnDrawGizmos() + { BoxCollider b = GetComponent(); // these are the 8 points making up the corner of the box. If ANY parents of this object have non uniform scales, diff --git a/unity/Assets/Scripts/ContinuousMovement.cs b/unity/Assets/Scripts/ContinuousMovement.cs index e64e37b1be..74f15a693c 100644 --- a/unity/Assets/Scripts/ContinuousMovement.cs +++ b/unity/Assets/Scripts/ContinuousMovement.cs @@ -4,7 +4,8 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public interface MovableContinuous { +public interface MovableContinuous +{ public bool ShouldHalt(); public void ContinuousUpdate(float fixedDeltaTime); public ActionFinished FinishContinuousMove(BaseFPSAgentController controller); @@ -12,14 +13,18 @@ public interface MovableContinuous { // public string GetHaltMessage(); } -namespace UnityStandardAssets.Characters.FirstPerson { - public class ContinuousMovement { - public static int unrollSimulatePhysics(IEnumerator enumerator, float fixedDeltaTime) { +namespace UnityStandardAssets.Characters.FirstPerson +{ + public class ContinuousMovement + { + public static int unrollSimulatePhysics(IEnumerator enumerator, float fixedDeltaTime) + { int count = 0; PhysicsSceneManager.PhysicsSimulateCallCount = 0; var previousAutoSimulate = Physics.autoSimulation; Physics.autoSimulation = false; - while (enumerator.MoveNext()) { + while (enumerator.MoveNext()) + { // physics simulate happens in updateTransformPropertyFixedUpdate as long // as autoSimulation is off count++; @@ -37,7 +42,8 @@ public static IEnumerator rotate( float radiansPerSecond, bool returnToStartPropIfFailed = false, Quaternion? secTargetRotation = null - ) { + ) + { bool teleport = (radiansPerSecond == float.PositiveInfinity) && fixedDeltaTime == 0f; float degreesPerSecond = radiansPerSecond * 180.0f / Mathf.PI; @@ -47,7 +53,8 @@ public static IEnumerator rotate( Func nextRotFunc = (t, target) => Quaternion.RotateTowards(t.rotation, target, fixedDeltaTime * degreesPerSecond); - if (teleport) { + if (teleport) + { nextRotFunc = (t, target) => target; } @@ -79,7 +86,8 @@ public static IEnumerator move( float unitsPerSecond, bool returnToStartPropIfFailed = false, bool localPosition = false - ) { + ) + { bool teleport = (unitsPerSecond == float.PositiveInfinity) && fixedDeltaTime == 0f; Func< @@ -106,19 +114,23 @@ public static IEnumerator move( Func getPosFunc; Action setPosFunc; Func nextPosFunc; - if (localPosition) { + if (localPosition) + { getPosFunc = (t) => t.localPosition; setPosFunc = (t, pos) => t.localPosition = pos; nextPosFunc = (t, direction) => t.localPosition + direction * unitsPerSecond * fixedDeltaTime; - } else { + } + else + { getPosFunc = (t) => t.position; setPosFunc = (t, pos) => t.position = pos; nextPosFunc = (t, direction) => t.position + direction * unitsPerSecond * fixedDeltaTime; } - if (teleport) { + if (teleport) + { nextPosFunc = (t, direction) => targetPosition; } @@ -129,7 +141,8 @@ public static IEnumerator moveAB( MovableContinuous movable, ArticulatedAgentController controller, float fixedDeltaTime - ) { + ) + { return continuousUpdateAB( movable: movable, controller: controller, @@ -140,12 +153,15 @@ float fixedDeltaTime protected static IEnumerator finallyDestroyGameObjects( List gameObjectsToDestroy, IEnumerator steps - ) { - while (steps.MoveNext()) { + ) + { + while (steps.MoveNext()) + { yield return steps.Current; } - foreach (GameObject go in gameObjectsToDestroy) { + foreach (GameObject go in gameObjectsToDestroy) + { GameObject.Destroy(go); } } @@ -159,7 +175,8 @@ public static IEnumerator rotateAroundPoint( float fixedDeltaTime, float degreesPerSecond, bool returnToStartPropIfFailed = false - ) { + ) + { bool teleport = (degreesPerSecond == float.PositiveInfinity) && fixedDeltaTime == 0f; // To figure out how to translate/rotate the undateTransform @@ -190,12 +207,14 @@ public static IEnumerator rotateAroundPoint( Quaternion.Angle(current, target); Func getRotFunc = (t) => t.rotation; - Action setRotFunc = (t, newRotation) => { + Action setRotFunc = (t, newRotation) => + { t.rotation = newRotation; updateTransform.position = wristProxy.transform.position; updateTransform.rotation = newRotation; }; - Func nextRotFunc = (t, target) => { + Func nextRotFunc = (t, target) => + { return Quaternion.RotateTowards( t.rotation, target, @@ -203,7 +222,8 @@ public static IEnumerator rotateAroundPoint( ); }; - if (teleport) { + if (teleport) + { nextRotFunc = (t, direction) => targetRotation; } @@ -230,11 +250,14 @@ 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) { + if (!Physics.autoSimulation) + { //Debug.Log("manual simulate from PhysicsManager"); PhysicsSceneManager.PhysicsSimulateTHOR(fixedDeltaTime); } @@ -266,7 +289,8 @@ public static IEnumerator updateTransformPropertyFixedUpdate( double epsilon, T? secTarget = null ) - where T : struct { + where T : struct + { T originalProperty = getProp(moveTransform); var previousProperty = originalProperty; @@ -279,7 +303,8 @@ public static IEnumerator updateTransformPropertyFixedUpdate( // yield return yieldInstruction; int transformIterations = 1; - if (secTarget != null) { + if (secTarget != null) + { transformIterations = 2; } @@ -290,12 +315,16 @@ public static IEnumerator updateTransformPropertyFixedUpdate( float currentDistance = 0; bool haveGottenWithinEpsilon = currentDistance <= epsilon; - for (int i = 0; i < transformIterations; i++) { + for (int i = 0; i < transformIterations; i++) + { // This syntax is a new method of pattern-matching that was introduced in C# 7.0, where the type check and // variable assignment are performed in a single step - if (i == 0) { + if (i == 0) + { currentTarget = target; - } else { + } + else + { currentTarget = (T)secTarget; } @@ -307,7 +336,8 @@ public static IEnumerator updateTransformPropertyFixedUpdate( // Debug.Log("Oh, currentTarget is " + printTarget.eulerAngles.y); // } - while (!movable.ShouldHalt()) { + while (!movable.ShouldHalt()) + { // TODO: put in movable && !collisionListener.TransformChecks(controller, moveTransform)) { previousProperty = getProp(moveTransform); @@ -321,9 +351,12 @@ public static IEnumerator updateTransformPropertyFixedUpdate( if ( nextDistance <= epsilon || nextDistance > distanceMetric((T)currentTarget, getProp(moveTransform)) - ) { + ) + { setProp(moveTransform, (T)currentTarget); - } else { + } + else + { setProp(moveTransform, next); } @@ -346,12 +379,16 @@ public static IEnumerator updateTransformPropertyFixedUpdate( currentDistance = distanceMetric((T)currentTarget, getProp(moveTransform)); - if (currentDistance <= epsilon) { + if (currentDistance <= epsilon) + { // This logic is a bit unintuitive but it ensures we run the // `setProp(moveTransform, currentTarget);` line above once we get within epsilon - if (haveGottenWithinEpsilon) { + if (haveGottenWithinEpsilon) + { break; - } else { + } + else + { haveGottenWithinEpsilon = true; } } @@ -360,7 +397,8 @@ public static IEnumerator updateTransformPropertyFixedUpdate( //Debug.Log("4"); T resetProp = previousProperty; - if (returnToStartPropIfFailed) { + if (returnToStartPropIfFailed) + { resetProp = originalProperty; } //Debug.Log("about to continuousMoveFinish"); @@ -373,7 +411,8 @@ public static IEnumerator updateTransformPropertyFixedUpdate( // resetProp // ); var actionFinished = movable.FinishContinuousMove(controller); - if (!actionFinished.success) { + if (!actionFinished.success) + { setProp(moveTransform, resetProp); } diff --git a/unity/Assets/Scripts/Convertable.cs b/unity/Assets/Scripts/Convertable.cs index c5ee20f281..f8c3a2b793 100644 --- a/unity/Assets/Scripts/Convertable.cs +++ b/unity/Assets/Scripts/Convertable.cs @@ -4,16 +4,19 @@ using UnityEngine; [Serializable] -public class SimObjState { +public class SimObjState +{ public GameObject Obj; public SimObjType Type; } [ExecuteInEditMode] -public class Convertable : MonoBehaviour { +public class Convertable : MonoBehaviour +{ public SimObjState[] States; public int DefaultState = 0; - public int CurrentState { + public int CurrentState + { get { return currentState; } } #if UNITY_EDITOR @@ -23,43 +26,57 @@ public int CurrentState { int currentState = -1; SimObj parentObj; - void OnEnable() { - if (Application.isPlaying) { + void OnEnable() + { + if (Application.isPlaying) + { currentState = DefaultState; } } - void Update() { - if (parentObj == null) { + void Update() + { + if (parentObj == null) + { parentObj = gameObject.GetComponent(); } // anim state is 1-4 int animState = -1; - if (Application.isPlaying) { + if (Application.isPlaying) + { animState = parentObj.Animator.GetInteger("AnimState1"); } #if UNITY_EDITOR - else { + else + { animState = EditorState + 1; } #endif - if (animState > States.Length) { + if (animState > States.Length) + { animState = -1; } // stateIndex is 0-3 int stateIndex = animState - 1; - if (currentState != stateIndex && stateIndex >= 0) { + if (currentState != stateIndex && stateIndex >= 0) + { currentState = stateIndex; - for (int i = 0; i < States.Length; i++) { - if (i == currentState) { + for (int i = 0; i < States.Length; i++) + { + if (i == currentState) + { parentObj.Type = States[i].Type; - if (States[i].Obj != null) { + if (States[i].Obj != null) + { States[i].Obj.SetActive(true); } - } else { - if (States[i].Obj != null) { + } + else + { + if (States[i].Obj != null) + { States[i].Obj.SetActive(false); } } diff --git a/unity/Assets/Scripts/CookObject.cs b/unity/Assets/Scripts/CookObject.cs index bf46dc2a9c..de8523604e 100644 --- a/unity/Assets/Scripts/CookObject.cs +++ b/unity/Assets/Scripts/CookObject.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class CookObject : MonoBehaviour { +public class CookObject : MonoBehaviour +{ // Meshes that require different materials when in on/off state [Header("Objects that need Mat Swaps")] [SerializeField] @@ -11,37 +12,45 @@ public class CookObject : MonoBehaviour { [SerializeField] private bool isCooked = false; - void Start() { + void Start() + { #if UNITY_EDITOR if ( !gameObject .GetComponent() .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeCooked) - ) { + ) + { Debug.LogError(gameObject.name + " is missing the CanBeCooked secondary property!"); } #endif } // Update is called once per frame - void Update() { + void Update() + { #if UNITY_EDITOR - if (Input.GetKeyDown(KeyCode.Minus)) { + if (Input.GetKeyDown(KeyCode.Minus)) + { Cook(); } #endif } // use this to return info on if this object is toasted or not - public bool IsCooked() { + public bool IsCooked() + { return isCooked; } // this will swap the material of this object to toasted. There is no // un-toast function because uh... you can't un toast bread? - public void Cook() { - if (MaterialSwapObjects.Length > 0) { - for (int i = 0; i < MaterialSwapObjects.Length; i++) { + public void Cook() + { + if (MaterialSwapObjects.Length > 0) + { + for (int i = 0; i < MaterialSwapObjects.Length; i++) + { MaterialSwapObjects[i].MyObject.GetComponent().materials = MaterialSwapObjects[i].OnMaterials; } diff --git a/unity/Assets/Scripts/CopyLightingSettings.cs b/unity/Assets/Scripts/CopyLightingSettings.cs index a68a1fb7ae..0966364a12 100644 --- a/unity/Assets/Scripts/CopyLightingSettings.cs +++ b/unity/Assets/Scripts/CopyLightingSettings.cs @@ -4,7 +4,8 @@ using System.Reflection; // Latest version at https://bitbucket.org/snippets/pschraut/LeykeL -static class CopyLightingSettings { +static class CopyLightingSettings +{ // // Written by Peter Schraut // http://www.console-dev.de @@ -31,7 +32,8 @@ static class CopyLightingSettings { #endif [MenuItem(k_CopySettingsMenuPath, priority = 200)] - static void CopySettings() { + static void CopySettings() + { UnityEngine.Object lightmapSettings; if ( !TryGetSettings( @@ -39,12 +41,14 @@ static void CopySettings() { "GetLightmapSettings", out lightmapSettings ) - ) { + ) + { return; } UnityEngine.Object renderSettings; - if (!TryGetSettings(typeof(RenderSettings), "GetRenderSettings", out renderSettings)) { + if (!TryGetSettings(typeof(RenderSettings), "GetRenderSettings", out renderSettings)) + { return; } @@ -53,7 +57,8 @@ out lightmapSettings } [MenuItem(k_PasteSettingsMenuPath, priority = 201)] - static void PasteSettings() { + static void PasteSettings() + { UnityEngine.Object lightmapSettings; if ( !TryGetSettings( @@ -61,12 +66,14 @@ static void PasteSettings() { "GetLightmapSettings", out lightmapSettings ) - ) { + ) + { return; } UnityEngine.Object renderSettings; - if (!TryGetSettings(typeof(RenderSettings), "GetRenderSettings", out renderSettings)) { + if (!TryGetSettings(typeof(RenderSettings), "GetRenderSettings", out renderSettings)) + { return; } @@ -77,24 +84,30 @@ out lightmapSettings } [MenuItem(k_PasteSettingsMenuPath, validate = true)] - static bool PasteValidate() { + static bool PasteValidate() + { return s_SourceLightmapSettings != null && s_SourceRenderSettings != null; } - static void CopyInternal(SerializedObject source, SerializedObject dest) { + static void CopyInternal(SerializedObject source, SerializedObject dest) + { var prop = source.GetIterator(); - while (prop.Next(true)) { + while (prop.Next(true)) + { var copyProperty = true; foreach ( var propertyName in new[] { "m_Sun", "m_FileID", "m_PathID", "m_ObjectHideFlags" } - ) { - if (string.Equals(prop.name, propertyName, System.StringComparison.Ordinal)) { + ) + { + if (string.Equals(prop.name, propertyName, System.StringComparison.Ordinal)) + { copyProperty = false; break; } } - if (copyProperty) { + if (copyProperty) + { dest.CopyFromSerializedProperty(prop); } } @@ -102,11 +115,13 @@ static void CopyInternal(SerializedObject source, SerializedObject dest) { dest.ApplyModifiedProperties(); } - static bool TryGetSettings(System.Type type, string methodName, out UnityEngine.Object settings) { + static bool TryGetSettings(System.Type type, string methodName, out UnityEngine.Object settings) + { settings = null; var method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic); - if (method == null) { + if (method == null) + { Debug.LogErrorFormat( "CopyLightingSettings: Could not find {0}.{1}", type.Name, @@ -116,7 +131,8 @@ static bool TryGetSettings(System.Type type, string methodName, out UnityEngine. } var value = method.Invoke(null, null) as UnityEngine.Object; - if (value == null) { + if (value == null) + { Debug.LogErrorFormat( "CopyLightingSettings: Could get data from {0}.{1}", type.Name, diff --git a/unity/Assets/Scripts/CrackedCameraManager.cs b/unity/Assets/Scripts/CrackedCameraManager.cs index 747c0587eb..83377b7506 100644 --- a/unity/Assets/Scripts/CrackedCameraManager.cs +++ b/unity/Assets/Scripts/CrackedCameraManager.cs @@ -2,10 +2,12 @@ using System.Collections.Generic; using UnityEngine; -public class CrackedCameraManager : MonoBehaviour { +public class CrackedCameraManager : MonoBehaviour +{ public List cracks; - public void SpawnCrack(int seed = 0) { + public void SpawnCrack(int seed = 0) + { UnityEngine.Random.InitState(seed); GameObject whichCrack = cracks[Random.Range(0, cracks.Count)]; diff --git a/unity/Assets/Scripts/CreatePrefab.cs b/unity/Assets/Scripts/CreatePrefab.cs index 80b9b0346d..6d5484d81a 100644 --- a/unity/Assets/Scripts/CreatePrefab.cs +++ b/unity/Assets/Scripts/CreatePrefab.cs @@ -4,11 +4,14 @@ using System.Collections; using UnityEditor; -public class CreatePrefab : MonoBehaviour { +public class CreatePrefab : MonoBehaviour +{ [MenuItem("Extras/Create Prefab From Selection")] - static void DoCreatePrefab() { + static void DoCreatePrefab() + { Transform[] transforms = Selection.transforms; - foreach (Transform t in transforms) { + foreach (Transform t in transforms) + { PrefabUtility.SaveAsPrefabAsset( t.gameObject, "Assets/Prefabs/" + t.gameObject.name + ".prefab" diff --git a/unity/Assets/Scripts/DebugDiscreteAgentController.cs b/unity/Assets/Scripts/DebugDiscreteAgentController.cs index 5ab2aa575b..8e74af63fe 100644 --- a/unity/Assets/Scripts/DebugDiscreteAgentController.cs +++ b/unity/Assets/Scripts/DebugDiscreteAgentController.cs @@ -4,8 +4,10 @@ using UnityEngine; using UnityEngine.UI; -namespace UnityStandardAssets.Characters.FirstPerson { - public class DebugDiscreteAgentController : MonoBehaviour { +namespace UnityStandardAssets.Characters.FirstPerson +{ + public class DebugDiscreteAgentController : MonoBehaviour + { public GameObject InputFieldObj = null; public AgentManager AManager = null; private InputField inputField; @@ -14,7 +16,8 @@ public class DebugDiscreteAgentController : MonoBehaviour { private GameObject InputMode_Text = null; // Start is called before the first frame update - void Start() { + void Start() + { InputFieldObj = GameObject.Find("DebugCanvasPhysics/InputField"); var Debug_Canvas = GameObject.Find("DebugCanvasPhysics"); inputField = InputFieldObj.GetComponent(); @@ -26,27 +29,32 @@ void Start() { Cursor.visible = true; Cursor.lockState = CursorLockMode.None; - if (this.isActiveAndEnabled) { + if (this.isActiveAndEnabled) + { Debug_Canvas.GetComponent().enabled = true; Cursor.visible = true; Cursor.lockState = CursorLockMode.None; } } - BaseFPSAgentController CurrentActiveController() { + BaseFPSAgentController CurrentActiveController() + { return AManager.PrimaryAgent; } - public void OnEnable() { + public void OnEnable() + { InputMode_Text = GameObject.Find("DebugCanvasPhysics/InputModeText"); - if (InputMode_Text) { + if (InputMode_Text) + { InputMode_Text.GetComponent().text = "Text Input Mode"; } } public void OnDisable() { } - void Update() { + void Update() + { // use these for the Breakable Window demo video // if(Input.GetKeyDown(KeyCode.P)) // { @@ -80,14 +88,17 @@ void Update() { // } // if we press enter, select the input field - if (CurrentActiveController().ReadyForCommand) { - if (Input.GetKeyDown(KeyCode.Return)) { + if (CurrentActiveController().ReadyForCommand) + { + if (Input.GetKeyDown(KeyCode.Return)) + { UnityEngine.EventSystems.EventSystem.current.SetSelectedGameObject( InputFieldObj ); } - if (!inputField.isFocused) { + if (!inputField.isFocused) + { bool shiftHeld = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); bool altHeld = Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt); @@ -98,164 +109,226 @@ void Update() { bool isArticulated = CurrentActiveController().GetType() == typeof(ArticulatedAgentController); Dictionary action = new Dictionary(); - var physicsSimulationParams = new PhysicsSimulationParams() { + var physicsSimulationParams = new PhysicsSimulationParams() + { autoSimulation = false }; bool useLimits = true; - if (noModifier) { + if (noModifier) + { float WalkMagnitude = 0.25f; action["action"] = ""; action["physicsSimulationParams"] = physicsSimulationParams; - if (isArticulated) { - if (Input.GetKeyDown(KeyCode.W)) { + if (isArticulated) + { + if (Input.GetKeyDown(KeyCode.W)) + { action["action"] = "MoveAgent"; action["moveMagnitude"] = WalkMagnitude; } - if (Input.GetKeyDown(KeyCode.S)) { + if (Input.GetKeyDown(KeyCode.S)) + { action["action"] = "MoveAgent"; action["moveMagnitude"] = -WalkMagnitude; } - if (Input.GetKeyDown(KeyCode.LeftArrow)) { + if (Input.GetKeyDown(KeyCode.LeftArrow)) + { action["action"] = "RotateLeft"; action["degrees"] = 30f; action["speed"] = 22.5f; action["acceleration"] = 22.5f; } - if (Input.GetKeyDown(KeyCode.RightArrow)) { + if (Input.GetKeyDown(KeyCode.RightArrow)) + { action["action"] = "RotateRight"; action["degrees"] = 30f; action["speed"] = 22.5f; action["acceleration"] = 22.5f; } - } else { - if (Input.GetKeyDown(KeyCode.W)) { + } + else + { + if (Input.GetKeyDown(KeyCode.W)) + { action["action"] = "MoveAhead"; action["moveMagnitude"] = WalkMagnitude; } - if (Input.GetKeyDown(KeyCode.S)) { + if (Input.GetKeyDown(KeyCode.S)) + { action["action"] = "MoveBack"; action["moveMagnitude"] = WalkMagnitude; } - if (Input.GetKeyDown(KeyCode.A)) { + if (Input.GetKeyDown(KeyCode.A)) + { action["action"] = "MoveLeft"; action["moveMagnitude"] = WalkMagnitude; } - if (Input.GetKeyDown(KeyCode.D)) { + if (Input.GetKeyDown(KeyCode.D)) + { action["action"] = "MoveRight"; action["moveMagnitude"] = WalkMagnitude; } - if (Input.GetKeyDown(KeyCode.UpArrow)) { + if (Input.GetKeyDown(KeyCode.UpArrow)) + { action["action"] = "LookUp"; } - if (Input.GetKeyDown(KeyCode.DownArrow)) { + if (Input.GetKeyDown(KeyCode.DownArrow)) + { action["action"] = "LookDown"; } - if (Input.GetKeyDown(KeyCode.LeftArrow)) { + if (Input.GetKeyDown(KeyCode.LeftArrow)) + { action["action"] = "RotateLeft"; } - if (Input.GetKeyDown(KeyCode.RightArrow)) { + if (Input.GetKeyDown(KeyCode.RightArrow)) + { action["action"] = "RotateRight"; } } - if ((string)action["action"] != "") { + if ((string)action["action"] != "") + { if ( ((string)action["action"]).Contains("Move") && CurrentActiveController().GetType() == typeof(KinovaArmAgentController) - ) { + ) + { action["returnToStart"] = false; } this.CurrentActiveController().ProcessControlCommand(action); } - } else if (armMoveMode) { + } + else if (armMoveMode) + { var actionName = "MoveArmRelative"; var localPos = new Vector3(0, 0, 0); float ArmMoveMagnitude = 0.05f; - if (isArticulated) { + if (isArticulated) + { ArmMoveMagnitude = 0.1f; float speed = 0.5f; action["physicsSimulationParams"] = physicsSimulationParams; - if (Input.GetKeyDown(KeyCode.W)) { + if (Input.GetKeyDown(KeyCode.W)) + { action["action"] = "MoveArm"; action["position"] = new Vector3(0f, 0f, ArmMoveMagnitude); action["speed"] = speed; - } else if (Input.GetKeyDown(KeyCode.S)) { + } + else if (Input.GetKeyDown(KeyCode.S)) + { action["action"] = "MoveArm"; action["position"] = new Vector3(0f, 0f, -ArmMoveMagnitude); action["speed"] = speed; - } else if (Input.GetKeyDown(KeyCode.UpArrow)) { + } + else if (Input.GetKeyDown(KeyCode.UpArrow)) + { action["action"] = "MoveArmBaseUp"; action["distance"] = 0.2f; action["speed"] = speed; - } else if (Input.GetKeyDown(KeyCode.DownArrow)) { + } + else if (Input.GetKeyDown(KeyCode.DownArrow)) + { action["action"] = "MoveArmBaseDown"; action["distance"] = 0.2f; action["speed"] = speed; - } else if (Input.GetKeyDown(KeyCode.Q)) { + } + else if (Input.GetKeyDown(KeyCode.Q)) + { action["action"] = "RotateWristRelative"; action["yaw"] = -30f; action["speed"] = 1000f; - } else if (Input.GetKeyDown(KeyCode.E)) { + } + else if (Input.GetKeyDown(KeyCode.E)) + { action["action"] = "RotateWristRelative"; action["yaw"] = 30f; action["speed"] = 1000f; - } else if (Input.GetKeyDown(KeyCode.P)) { + } + else if (Input.GetKeyDown(KeyCode.P)) + { action["action"] = "PickupObject"; // Doesn't matter we can keep them action.Remove("physicsSimulationParams"); - } else if (Input.GetKeyDown(KeyCode.D)) { + } + else if (Input.GetKeyDown(KeyCode.D)) + { action["action"] = "ReleaseObject"; // Doesn't matter we can keep them action.Remove("physicsSimulationParams"); - } else { + } + else + { actionName = ""; } - if (actionName != "") { - if (((string)action["action"]).StartsWith("MoveArm")) { + if (actionName != "") + { + if (((string)action["action"]).StartsWith("MoveArm")) + { action["useLimits"] = useLimits; } this.CurrentActiveController().ProcessControlCommand(action); } - } else { - if (Input.GetKeyDown(KeyCode.W)) { + } + else + { + if (Input.GetKeyDown(KeyCode.W)) + { localPos.y += ArmMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.S)) { + } + else if (Input.GetKeyDown(KeyCode.S)) + { localPos.y -= ArmMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.UpArrow)) { + } + else if (Input.GetKeyDown(KeyCode.UpArrow)) + { localPos.z += ArmMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.DownArrow)) { + } + else if (Input.GetKeyDown(KeyCode.DownArrow)) + { localPos.z -= ArmMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.LeftArrow)) { + } + else if (Input.GetKeyDown(KeyCode.LeftArrow)) + { localPos.x -= ArmMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.RightArrow)) { + } + else if (Input.GetKeyDown(KeyCode.RightArrow)) + { localPos.x += ArmMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.P)) { + } + else if (Input.GetKeyDown(KeyCode.P)) + { actionName = "PickupObject"; - } else if (Input.GetKeyDown(KeyCode.D)) { + } + else if (Input.GetKeyDown(KeyCode.D)) + { actionName = "ReleaseObject"; - } else { + } + else + { actionName = ""; } - if (actionName != "") { + if (actionName != "") + { action["action"] = actionName; - if (localPos.magnitude != 0) { + if (localPos.magnitude != 0) + { action["offset"] = localPos; //action["fixedDeltaTime"] = fixedDeltaTime; action["speed"] = 0.1; @@ -264,7 +337,9 @@ void Update() { this.CurrentActiveController().ProcessControlCommand(action); } } - } else if (armRotateMode) { + } + else if (armRotateMode) + { var actionName = "RotateWristRelative"; float rotateMag = 30f; float pitch = 0f; @@ -272,39 +347,60 @@ void Update() { float roll = 0f; float degrees = 0f; - if (Input.GetKeyDown(KeyCode.W)) { + if (Input.GetKeyDown(KeyCode.W)) + { roll += rotateMag; - } else if (Input.GetKeyDown(KeyCode.S)) { + } + else if (Input.GetKeyDown(KeyCode.S)) + { roll -= rotateMag; - } else if (Input.GetKeyDown(KeyCode.UpArrow)) { + } + else if (Input.GetKeyDown(KeyCode.UpArrow)) + { pitch += rotateMag; - } else if (Input.GetKeyDown(KeyCode.DownArrow)) { + } + else if (Input.GetKeyDown(KeyCode.DownArrow)) + { pitch -= rotateMag; - } else if (Input.GetKeyDown(KeyCode.LeftArrow)) { + } + else if (Input.GetKeyDown(KeyCode.LeftArrow)) + { yaw -= rotateMag; - } else if (Input.GetKeyDown(KeyCode.RightArrow)) { + } + else if (Input.GetKeyDown(KeyCode.RightArrow)) + { yaw += rotateMag; - } else if (Input.GetKeyDown(KeyCode.E)) { + } + else if (Input.GetKeyDown(KeyCode.E)) + { actionName = "RotateElbowRelative"; degrees += rotateMag; - } else if (Input.GetKeyDown(KeyCode.Q)) { + } + else if (Input.GetKeyDown(KeyCode.Q)) + { // Why Q/E rather than A/D? Because apparently // shift+alt+A is a Unity shortcut and Unity // doesn't provide the ability to disable shortcuts in // play mode despite this being a feature request since 2013. actionName = "RotateElbowRelative"; degrees -= rotateMag; - } else { + } + else + { actionName = ""; } - if (actionName != "") { + if (actionName != "") + { action["action"] = actionName; - if (actionName == "RotateWristRelative") { + if (actionName == "RotateWristRelative") + { action["pitch"] = pitch; action["yaw"] = yaw; action["roll"] = roll; - } else if (actionName == "RotateElbowRelative") { + } + else if (actionName == "RotateElbowRelative") + { action["degrees"] = degrees; } this.CurrentActiveController().ProcessControlCommand(action); diff --git a/unity/Assets/Scripts/DebugFPSAgentController.cs b/unity/Assets/Scripts/DebugFPSAgentController.cs index b2044fafcf..b41b6c79a3 100644 --- a/unity/Assets/Scripts/DebugFPSAgentController.cs +++ b/unity/Assets/Scripts/DebugFPSAgentController.cs @@ -12,9 +12,11 @@ using UnityStandardAssets.Utility; using Random = UnityEngine.Random; -namespace UnityStandardAssets.Characters.FirstPerson { +namespace UnityStandardAssets.Characters.FirstPerson +{ [RequireComponent(typeof(CharacterController))] - public class DebugFPSAgentController : MonoBehaviour { + public class DebugFPSAgentController : MonoBehaviour + { // for use with mouse/keyboard input [SerializeField] protected bool m_IsWalking; @@ -65,7 +67,8 @@ public class DebugFPSAgentController : MonoBehaviour { protected bool enableHighlightShader = true; - private void Start() { + private void Start() + { m_CharacterController = GetComponent(); m_Camera = Camera.main; m_MouseLook.Init(transform, m_Camera.transform); @@ -91,7 +94,8 @@ private void Start() { ); // if this component is enabled, turn on the targeting reticle and target text - if (this.isActiveAndEnabled) { + if (this.isActiveAndEnabled) + { Debug_Canvas.GetComponent().enabled = true; Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; @@ -107,7 +111,8 @@ private void Start() { #endif } - public Vector3 ScreenPointMoveHand(float yOffset) { + public Vector3 ScreenPointMoveHand(float yOffset) + { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // shoot a ray out based on mouse position @@ -115,24 +120,30 @@ public Vector3 ScreenPointMoveHand(float yOffset) { return hit.point + new Vector3(0, yOffset, 0); } - public void HideHUD() { - if (InputMode_Text != null) { + public void HideHUD() + { + if (InputMode_Text != null) + { InputMode_Text.SetActive(false); } - if (InputFieldObj != null) { + if (InputFieldObj != null) + { InputFieldObj.SetActive(false); } var background = GameObject.Find("DebugCanvasPhysics/InputModeText_Background"); - if (background != null) { + if (background != null) + { background.SetActive(false); } } - public void SetScroll2DEnabled(bool enabled) { + public void SetScroll2DEnabled(bool enabled) + { this.scroll2DEnabled = enabled; } - public void OnEnable() { + public void OnEnable() + { FPSEnabled = true; originalPhysicsAutosimulation = Physics.autoSimulation; Physics.autoSimulation = true; @@ -141,7 +152,8 @@ public void OnEnable() { InputMode_Text = GameObject.Find("DebugCanvasPhysics/InputModeText"); InputFieldObj = GameObject.Find("DebugCanvasPhysics/InputField"); - if (InputMode_Text) { + if (InputMode_Text) + { InputMode_Text.GetComponent().text = "FPS Mode"; } @@ -150,15 +162,18 @@ public void OnEnable() { Debug_Canvas.GetComponent().enabled = true; } - public void OnDisable() { + public void OnDisable() + { DisableMouseControl(); // if (InputFieldObj) { // InputFieldObj.SetActive(true); // } } - public void EnableMouseControl() { - if (InputMode_Text) { + public void EnableMouseControl() + { + if (InputMode_Text) + { InputMode_Text.GetComponent().text = "FPS Mode (mouse free)"; } FPSEnabled = true; @@ -168,8 +183,10 @@ public void EnableMouseControl() { Physics.autoSimulation = true; } - public void DisableMouseControl() { - if (InputMode_Text) { + public void DisableMouseControl() + { + if (InputMode_Text) + { InputMode_Text.GetComponent().text = "FPS Mode"; } FPSEnabled = false; @@ -178,14 +195,20 @@ public void DisableMouseControl() { Physics.autoSimulation = originalPhysicsAutosimulation; } - private void DebugKeyboardControls() { - if (InputFieldObj != null) { + private void DebugKeyboardControls() + { + if (InputFieldObj != null) + { InputField inField = InputFieldObj.GetComponentInChildren(); - if (inField != null) { - if (inField.isFocused) { + if (inField != null) + { + if (inField.isFocused) + { highlightController.ThrowEnabled = false; return; - } else { + } + else + { highlightController.ThrowEnabled = true; } } @@ -193,12 +216,16 @@ 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) { + if (FPSEnabled) + { DisableMouseControl(); return; - } else { + } + else + { EnableMouseControl(); return; } @@ -206,11 +233,13 @@ private void DebugKeyboardControls() { #endif // 1D Scroll for hand movement - if (!scroll2DEnabled && this.PhysicsController.WhatAmIHolding() != null) { + if (!scroll2DEnabled && this.PhysicsController.WhatAmIHolding() != null) + { var scrollAmount = Input.GetAxis("Mouse ScrollWheel"); var eps = 1e-6; - if (Mathf.Abs(scrollAmount) > eps) { + if (Mathf.Abs(scrollAmount) > eps) + { // webGL action var action = new Dictionary() { @@ -222,7 +251,8 @@ private void DebugKeyboardControls() { } } - private void Update() { + private void Update() + { highlightController.UpdateHighlightedObject( new Vector3(Screen.width / 2, Screen.height / 2) ); @@ -232,21 +262,27 @@ private void Update() { /////////////////////////////////////////////////////////////////////////// // we are not in focus mode, so use WASD and mouse to move around - if (FPSEnabled) { + if (FPSEnabled) + { FPSInput(); - if (Cursor.visible == false) { + if (Cursor.visible == false) + { // accept input to update view based on mouse input MouseRotateView(); } } } - public void OnGUI() { - if (Event.current.type == EventType.ScrollWheel && scroll2DEnabled) { - if (this.PhysicsController.WhatAmIHolding() != null) { + public void OnGUI() + { + if (Event.current.type == EventType.ScrollWheel && scroll2DEnabled) + { + if (this.PhysicsController.WhatAmIHolding() != null) + { var scrollAmount = Event.current.delta; var eps = 1e-6; - if (Mathf.Abs(scrollAmount.x) > eps || Mathf.Abs(scrollAmount.y) > eps) { + 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() { @@ -261,7 +297,8 @@ public void OnGUI() { } } - private void GetInput(out float speed) { + private void GetInput(out float speed) + { // Read input float horizontal = CrossPlatformInputManager.GetAxis("Horizontal"); float vertical = CrossPlatformInputManager.GetAxis("Vertical"); @@ -278,20 +315,24 @@ private void GetInput(out float speed) { m_Input = new Vector2(horizontal, vertical); // normalize input if it exceeds 1 in combined length: - if (m_Input.sqrMagnitude > 1) { + if (m_Input.sqrMagnitude > 1) + { m_Input.Normalize(); } } - public MouseLook GetMouseLook() { + public MouseLook GetMouseLook() + { return m_MouseLook; } - private void MouseRotateView() { + private void MouseRotateView() + { m_MouseLook.LookRotation(transform, m_Camera.transform); } - private void FPSInput() { + private void FPSInput() + { // take WASD input and do magic, turning it into movement! float speed; GetInput(out speed); @@ -318,7 +359,8 @@ private void FPSInput() { m_MoveDir += Physics.gravity * m_GravityMultiplier * Time.deltaTime; // added this check so that move is not called if/when the Character Controller's capsule is disabled. Right now the capsule is being disabled when open/close animations are in progress so yeah there's that - if (m_CharacterController.enabled == true) { + if (m_CharacterController.enabled == true) + { m_CharacterController.Move(m_MoveDir * Time.deltaTime); } } diff --git a/unity/Assets/Scripts/DebugInputField.cs b/unity/Assets/Scripts/DebugInputField.cs index 0fc77e4c08..0eb115f664 100644 --- a/unity/Assets/Scripts/DebugInputField.cs +++ b/unity/Assets/Scripts/DebugInputField.cs @@ -13,8 +13,10 @@ using UnityEngine.AI; using UnityEngine.UI; -namespace UnityStandardAssets.Characters.FirstPerson { - public class DebugInputField : MonoBehaviour { +namespace UnityStandardAssets.Characters.FirstPerson +{ + public class DebugInputField : MonoBehaviour + { public GameObject Agent = null; public AgentManager AManager = null; @@ -34,15 +36,18 @@ public class DebugInputField : MonoBehaviour { }; #endif - private bool setEnabledControlComponent(ControlMode mode, bool enabled) { + private bool setEnabledControlComponent(ControlMode mode, bool enabled) + { Type componentType; var success = PlayerControllers.controlModeToComponent.TryGetValue( mode, out componentType ); - if (success) { + if (success) + { var previousComponent = Agent.GetComponent(componentType) as MonoBehaviour; - if (previousComponent == null) { + if (previousComponent == null) + { previousComponent = Agent.AddComponent(componentType) as MonoBehaviour; } previousComponent.enabled = enabled; @@ -50,7 +55,8 @@ out componentType return success; } - public IEnumerator moveArmHeightDebug(float height) { + public IEnumerator moveArmHeightDebug(float height) + { CapsuleCollider cc = CurrentActiveController().GetComponent(); var arm = CurrentActiveController().GetComponentInChildren(); Vector3 cc_center = cc.center; @@ -62,11 +68,13 @@ public IEnumerator moveArmHeightDebug(float height) { Vector3 target = new Vector3(0, targetY, 0); float currentDistance = Vector3.SqrMagnitude(target - arm.transform.localPosition); double epsilon = 1e-3; - while (currentDistance > epsilon && !arm.collisionListener.ShouldHalt()) { + while (currentDistance > epsilon && !arm.collisionListener.ShouldHalt()) + { Vector3 direction = (target - arm.transform.localPosition).normalized; arm.transform.localPosition += direction * 1.0f * Time.fixedDeltaTime; - if (!Physics.autoSimulation) { + if (!Physics.autoSimulation) + { PhysicsSceneManager.PhysicsSimulateTHOR(Time.fixedDeltaTime); } @@ -76,7 +84,8 @@ public IEnumerator moveArmHeightDebug(float height) { } } - public void dumpPosition(Transform to) { + public void dumpPosition(Transform to) + { Debug.Log("GameObject: " + to.gameObject.name); Debug.Log( to.position.x.ToString("0.####") @@ -88,7 +97,8 @@ public void dumpPosition(Transform to) { ); } - public IEnumerator moveArmDebug(Vector3 targetArmBase) { + 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(); @@ -104,7 +114,8 @@ public IEnumerator moveArmDebug(Vector3 targetArmBase) { float currentDistance = Vector3.SqrMagnitude(target - armTarget.transform.position); double epsilon = 1e-3; Debug.Log("Starting arm movement"); - while (currentDistance > epsilon && !arm.collisionListener.ShouldHalt()) { + while (currentDistance > epsilon && !arm.collisionListener.ShouldHalt()) + { Vector3 direction = (target - armTarget.transform.position).normalized; armTarget.transform.position += direction * 1.0f * Time.fixedDeltaTime; @@ -112,7 +123,8 @@ public IEnumerator moveArmDebug(Vector3 targetArmBase) { dumpPosition(wristCol); - if (!Physics.autoSimulation) { + if (!Physics.autoSimulation) + { PhysicsSceneManager.PhysicsSimulateTHOR(Time.fixedDeltaTime); } // animator.Update(Time.fixedDeltaTime); @@ -125,21 +137,24 @@ public IEnumerator moveArmDebug(Vector3 targetArmBase) { Debug.Log("Ending arm movement"); } - public void setControlMode(ControlMode mode) { + public void setControlMode(ControlMode mode) + { setEnabledControlComponent(controlMode, false); controlMode = mode; setEnabledControlComponent(controlMode, true); } // Use this for initialization - void Start() { + void Start() + { #if UNITY_EDITOR || UNITY_WEBGL Debug.Log("In Unity editor, init DebugInputField"); this.InitializeUserControl(); #endif } - void SelectPlayerControl() { + void SelectPlayerControl() + { #if UNITY_EDITOR Debug.Log("Player Control Set To: Editor control"); setControlMode(ControlMode.DEBUG_TEXT_INPUT); @@ -158,7 +173,8 @@ void SelectPlayerControl() { #endif } - void InitializeUserControl() { + void InitializeUserControl() + { GameObject fpsController = GameObject.FindObjectOfType().gameObject; Agent = fpsController.gameObject; AManager = GameObject @@ -174,20 +190,26 @@ void InitializeUserControl() { #endif } - BaseFPSAgentController CurrentActiveController() { + BaseFPSAgentController CurrentActiveController() + { return AManager.PrimaryAgent; } - private PhysicsRemoteFPSAgentController PhysicsController { + private PhysicsRemoteFPSAgentController PhysicsController + { get => (PhysicsRemoteFPSAgentController)this.CurrentActiveController(); } // Update is called once per frame - void Update() { + void Update() + { #if UNITY_EDITOR - foreach (KeyValuePair entry in debugKeyToController) { - if (Input.GetKeyDown(entry.Key)) { - if (controlMode != entry.Value) { + 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; @@ -198,9 +220,11 @@ void Update() { #endif } - public void HideHUD() { + public void HideHUD() + { var InputMode_Text = GameObject.Find("DebugCanvasPhysics/InputModeText"); - if (InputMode_Text != null) { + if (InputMode_Text != null) + { InputMode_Text.SetActive(false); } var InputFieldObj = GameObject.Find("DebugCanvasPhysics/InputField"); @@ -211,15 +235,19 @@ public void HideHUD() { #if UNITY_EDITOR - public string closestVisibleObjectId() { + public string closestVisibleObjectId() + { return ( (PhysicsRemoteFPSAgentController)AManager.PrimaryAgent ).ObjectIdOfClosestVisibleObject(); } - public IEnumerator ExecuteBatch(List commands) { - foreach (var command in commands) { - while (CurrentActiveController().IsProcessing) { + public IEnumerator ExecuteBatch(List commands) + { + foreach (var command in commands) + { + while (CurrentActiveController().IsProcessing) + { yield return new WaitForEndOfFrame(); } Debug.Log("Executing Batch command: " + command); @@ -228,14 +256,17 @@ public IEnumerator ExecuteBatch(List commands) { } // shortcut to execute no-parameter actions - private void ExecuteAction(string actionName) { + private void ExecuteAction(string actionName) + { Dictionary action = new Dictionary(); action["action"] = actionName; AManager.ProcessControlCommand(new DynamicServerAction(action)); } - public void Execute(string command) { - if (CurrentActiveController().IsProcessing) { + public void Execute(string command) + { + if (CurrentActiveController().IsProcessing) + { Debug.Log("Cannot execute command while last action has not completed."); } @@ -245,370 +276,407 @@ public void Execute(string command) { System.StringSplitOptions.None ); - switch (splitcommand[0]) { - case "init": { - Dictionary action = new Dictionary(); - // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here - // by default the gridsize is 0.25, so only moving in increments of .25 will work - // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default - // grid size! - if (splitcommand.Length == 2) { - action["gridSize"] = float.Parse(splitcommand[1]); - } else if (splitcommand.Length == 3) { - action["gridSize"] = float.Parse(splitcommand[1]); - action["agentCount"] = int.Parse(splitcommand[2]); - } else if (splitcommand.Length == 4) { - action["gridSize"] = float.Parse(splitcommand[1]); - action["agentCount"] = int.Parse(splitcommand[2]); - action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; - } - // action.renderNormalsImage = true; - // action.renderDepthImage = true; - // action.renderSemanticSegmentation = true; - // action.renderInstanceSegmentation = true; - // action.renderFlowImage = true; - // action.rotateStepDegrees = 30; - // action.ssao = "default"; - // action.snapToGrid = true; - // action.makeAgentsVisible = false; - // 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); - // AgentManager am = PhysicsController.gameObject.FindObjectsOfType()[0]; - // Debug.Log("Physics scene manager = ..."); - // Debug.Log(physicsSceneManager); - // AgentManager am = physicsSceneManager.GetComponent(); - // Debug.Log(am); - // am.Initialize(action); - break; - } - case "initb": { - Dictionary action = new Dictionary(); - // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here - // by default the gridsize is 0.25, so only moving in increments of .25 will work - // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default - // grid size! - // if (splitcommand.Length == 2) { - // action["gridSize"] = float.Parse(splitcommand[1]); - // } else if (splitcommand.Length == 3) { - // action["gridSize"] = float.Parse(splitcommand[1]); - // action["agentCount"] = int.Parse(splitcommand[2]); - // } else if (splitcommand.Length == 4) { - // action["gridSize"] = float.Parse(splitcommand[1]); - // action["agentCount"] = int.Parse(splitcommand[2]); - // action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; - // } + switch (splitcommand[0]) + { + case "init": + { + Dictionary action = new Dictionary(); + // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here + // by default the gridsize is 0.25, so only moving in increments of .25 will work + // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default + // grid size! + if (splitcommand.Length == 2) + { + action["gridSize"] = float.Parse(splitcommand[1]); + } + else if (splitcommand.Length == 3) + { + action["gridSize"] = float.Parse(splitcommand[1]); + action["agentCount"] = int.Parse(splitcommand[2]); + } + else if (splitcommand.Length == 4) + { + action["gridSize"] = float.Parse(splitcommand[1]); + action["agentCount"] = int.Parse(splitcommand[2]); + action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; + } + // action.renderNormalsImage = true; + // action.renderDepthImage = true; + // action.renderSemanticSegmentation = true; + // action.renderInstanceSegmentation = true; + // action.renderFlowImage = true; + // action.rotateStepDegrees = 30; + // action.ssao = "default"; + // action.snapToGrid = true; + // action.makeAgentsVisible = false; + // 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); + // AgentManager am = PhysicsController.gameObject.FindObjectsOfType()[0]; + // Debug.Log("Physics scene manager = ..."); + // Debug.Log(physicsSceneManager); + // AgentManager am = physicsSceneManager.GetComponent(); + // Debug.Log(am); + // am.Initialize(action); + break; + } + case "initb": + { + Dictionary action = new Dictionary(); + // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here + // by default the gridsize is 0.25, so only moving in increments of .25 will work + // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default + // grid size! + // if (splitcommand.Length == 2) { + // action["gridSize"] = float.Parse(splitcommand[1]); + // } else if (splitcommand.Length == 3) { + // action["gridSize"] = float.Parse(splitcommand[1]); + // action["agentCount"] = int.Parse(splitcommand[2]); + // } else if (splitcommand.Length == 4) { + // action["gridSize"] = float.Parse(splitcommand[1]); + // action["agentCount"] = int.Parse(splitcommand[2]); + // action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; + // } + + // action.renderNormalsImage = true; + // action.renderDepthImage = true; + // action.renderSemanticSegmentation = true; + // action.renderInstanceSegmentation = true; + // action.renderFlowImage = true; + + action["action"] = "Initialize"; + action["agentMode"] = "locobot"; + // action["gridSize"] = 0.25f; + action["visibilityDistance"] = 1.0f; + action["rotateStepDegrees"] = 30; + // action["agentControllerType"] = "stochastic"; + // action["applyActionNoise"] = true; + action["width"] = 400; + action["height"] = 300; + action["snapToGrid"] = false; + 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); + break; + } + case "initb1": + { + Dictionary action = new Dictionary(); + // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here + // by default the gridsize is 0.25, so only moving in increments of .25 will work + // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default + // grid size! + // if (splitcommand.Length == 2) { + // action["gridSize"] = float.Parse(splitcommand[1]); + // } else if (splitcommand.Length == 3) { + // action["gridSize"] = float.Parse(splitcommand[1]); + // action["agentCount"] = int.Parse(splitcommand[2]); + // } else if (splitcommand.Length == 4) { + // action["gridSize"] = float.Parse(splitcommand[1]); + // action["agentCount"] = int.Parse(splitcommand[2]); + // action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; + // } + + // action.renderNormalsImage = true; + // action.renderDepthImage = true; + // action.renderSemanticSegmentation = true; + // action.renderInstanceSegmentation = true; + // action.renderFlowImage = true; + + action["action"] = "Initialize"; + action["agentMode"] = "locobot"; + // action["gridSize"] = 0.25f; + action["visibilityDistance"] = 1.5f; + action["rotateStepDegrees"] = 30; + // action["agentControllerType"] = "stochastic"; + // action["applyActionNoise"] = true; + action["width"] = 400; + action["height"] = 300; + action["snapToGrid"] = false; + action["fieldOfView"] = 90; + 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); + break; + } + case "inita": + { + Dictionary action = new Dictionary(); + // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here + // by default the gridsize is 0.25, so only moving in increments of .25 will work + // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default + // grid size! + if (splitcommand.Length == 2) + { + action["gridSize"] = float.Parse(splitcommand[1]); + } + else if (splitcommand.Length == 3) + { + action["gridSize"] = float.Parse(splitcommand[1]); + action["agentCount"] = int.Parse(splitcommand[2]); + } + else if (splitcommand.Length == 4) + { + action["gridSize"] = float.Parse(splitcommand[1]); + action["agentCount"] = int.Parse(splitcommand[2]); + action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; + } + // action.renderNormalsImage = true; + // action.renderDepthImage = true; + // action.renderClassImage = true; + // action.renderObjectImage = true; + // action.renderFlowImage = true; + // PhysicsController.actionComplete = false; + // action.rotateStepDegrees = 30; + // action.ssao = "default"; + // action.snapToGrid = true; + // action.makeAgentsVisible = false; + // action.agentMode = "bot"; + // action.fieldOfView = 90f; + // action.cameraY = 2.0f; + // action.snapToGrid = true; + // action.rotateStepDegrees = 45; + action["action"] = "Initialize"; + + action["agentMode"] = "arm"; + action["agentControllerType"] = "arm"; + action["renderInstanceSegmentation"] = true; + + // action.useMassThreshold = true; + // action.massThreshold = 10f; - // action.renderNormalsImage = true; - // action.renderDepthImage = true; - // action.renderSemanticSegmentation = true; - // action.renderInstanceSegmentation = true; - // action.renderFlowImage = true; - - action["action"] = "Initialize"; - action["agentMode"] = "locobot"; - // action["gridSize"] = 0.25f; - action["visibilityDistance"] = 1.0f; - action["rotateStepDegrees"] = 30; - // action["agentControllerType"] = "stochastic"; - // action["applyActionNoise"] = true; - action["width"] = 400; - action["height"] = 300; - action["snapToGrid"] = false; - 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); - break; - } - case "initb1": { - Dictionary action = new Dictionary(); - // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here - // by default the gridsize is 0.25, so only moving in increments of .25 will work - // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default - // grid size! - // if (splitcommand.Length == 2) { - // action["gridSize"] = float.Parse(splitcommand[1]); - // } else if (splitcommand.Length == 3) { - // action["gridSize"] = float.Parse(splitcommand[1]); - // action["agentCount"] = int.Parse(splitcommand[2]); - // } else if (splitcommand.Length == 4) { - // action["gridSize"] = float.Parse(splitcommand[1]); - // action["agentCount"] = int.Parse(splitcommand[2]); - // action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; - // } - // action.renderNormalsImage = true; - // action.renderDepthImage = true; - // action.renderSemanticSegmentation = true; - // action.renderInstanceSegmentation = true; - // action.renderFlowImage = true; - - action["action"] = "Initialize"; - action["agentMode"] = "locobot"; - // action["gridSize"] = 0.25f; - action["visibilityDistance"] = 1.5f; - action["rotateStepDegrees"] = 30; - // action["agentControllerType"] = "stochastic"; - // action["applyActionNoise"] = true; - action["width"] = 400; - action["height"] = 300; - action["snapToGrid"] = false; - action["fieldOfView"] = 90; - 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); - break; - } - case "inita": { - Dictionary action = new Dictionary(); - // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here - // by default the gridsize is 0.25, so only moving in increments of .25 will work - // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default - // grid size! - if (splitcommand.Length == 2) { - action["gridSize"] = float.Parse(splitcommand[1]); - } else if (splitcommand.Length == 3) { - action["gridSize"] = float.Parse(splitcommand[1]); - action["agentCount"] = int.Parse(splitcommand[2]); - } else if (splitcommand.Length == 4) { - action["gridSize"] = float.Parse(splitcommand[1]); - action["agentCount"] = int.Parse(splitcommand[2]); - action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; - } - // action.renderNormalsImage = true; - // action.renderDepthImage = true; - // action.renderClassImage = true; - // action.renderObjectImage = true; - // action.renderFlowImage = true; - // PhysicsController.actionComplete = false; - // action.rotateStepDegrees = 30; - // action.ssao = "default"; - // action.snapToGrid = true; - // action.makeAgentsVisible = false; - // action.agentMode = "bot"; - // action.fieldOfView = 90f; - // action.cameraY = 2.0f; - // action.snapToGrid = true; - // action.rotateStepDegrees = 45; - action["action"] = "Initialize"; - - action["agentMode"] = "arm"; - action["agentControllerType"] = "arm"; - action["renderInstanceSegmentation"] = true; - - // action.useMassThreshold = true; - // action.massThreshold = 10f; - - - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action), AManager); - // AgentManager am = PhysicsController.gameObject.FindObjectsOfType()[0]; - // Debug.Log("Physics scene manager = ..."); - // Debug.Log(physicsSceneManager); - // AgentManager am = physicsSceneManager.GetComponent(); - // Debug.Log(am); - // am.Initialize(action); - break; - } - case "initab": { - Dictionary action = new Dictionary(); - // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here - // by default the gridsize is 0.25, so only moving in increments of .25 will work - // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default - // grid size! - if (splitcommand.Length == 2) { - action["gridSize"] = float.Parse(splitcommand[1]); - } else if (splitcommand.Length == 3) { - action["gridSize"] = float.Parse(splitcommand[1]); - action["agentCount"] = int.Parse(splitcommand[2]); - } else if (splitcommand.Length == 4) { - action["gridSize"] = float.Parse(splitcommand[1]); - action["agentCount"] = int.Parse(splitcommand[2]); - action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; - } - // action.renderNormalsImage = true; - // action.renderDepthImage = true; - // action.renderClassImage = true; - // action.renderObjectImage = true; - // action.renderFlowImage = true; - // PhysicsController.actionComplete = false; - // action.rotateStepDegrees = 30; - // action.ssao = "default"; - // action.snapToGrid = true; - // action.makeAgentsVisible = false; - // action.agentMode = "bot"; - // action.fieldOfView = 90f; - // action.cameraY = 2.0f; - // action.snapToGrid = true; - // action.rotateStepDegrees = 45; - action["action"] = "Initialize"; - - action["agentMode"] = "stretchab"; - // action["agentControllerType"] = "arm"; - action["renderInstanceSegmentation"] = true; - - // action.useMassThreshold = true; - // action.massThreshold = 10f; - - - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action), AManager); - // AgentManager am = PhysicsController.gameObject.FindObjectsOfType()[0]; - // Debug.Log("Physics scene manager = ..."); - // Debug.Log(physicsSceneManager); - // AgentManager am = physicsSceneManager.GetComponent(); - // Debug.Log(am); - // am.Initialize(action); - break; - } - case "initp": { - Dictionary action = new Dictionary(); - // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here - // by default the gridsize is 0.25, so only moving in increments of .25 will work - // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default - // grid size! - if (splitcommand.Length == 2) { - action["gridSize"] = float.Parse(splitcommand[1]); - } else if (splitcommand.Length == 3) { - action["gridSize"] = float.Parse(splitcommand[1]); - action["agentCount"] = int.Parse(splitcommand[2]); - } else if (splitcommand.Length == 4) { - action["gridSize"] = float.Parse(splitcommand[1]); - action["agentCount"] = int.Parse(splitcommand[2]); - action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; - } + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action), AManager); + // AgentManager am = PhysicsController.gameObject.FindObjectsOfType()[0]; + // Debug.Log("Physics scene manager = ..."); + // Debug.Log(physicsSceneManager); + // AgentManager am = physicsSceneManager.GetComponent(); + // Debug.Log(am); + // am.Initialize(action); + break; + } + case "initab": + { + Dictionary action = new Dictionary(); + // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here + // by default the gridsize is 0.25, so only moving in increments of .25 will work + // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default + // grid size! + if (splitcommand.Length == 2) + { + action["gridSize"] = float.Parse(splitcommand[1]); + } + else if (splitcommand.Length == 3) + { + action["gridSize"] = float.Parse(splitcommand[1]); + action["agentCount"] = int.Parse(splitcommand[2]); + } + else if (splitcommand.Length == 4) + { + action["gridSize"] = float.Parse(splitcommand[1]); + action["agentCount"] = int.Parse(splitcommand[2]); + action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; + } + // action.renderNormalsImage = true; + // action.renderDepthImage = true; + // action.renderClassImage = true; + // action.renderObjectImage = true; + // action.renderFlowImage = true; + // PhysicsController.actionComplete = false; + // action.rotateStepDegrees = 30; + // action.ssao = "default"; + // action.snapToGrid = true; + // action.makeAgentsVisible = false; + // action.agentMode = "bot"; + // action.fieldOfView = 90f; + // action.cameraY = 2.0f; + // action.snapToGrid = true; + // action.rotateStepDegrees = 45; + action["action"] = "Initialize"; + + action["agentMode"] = "stretchab"; + // action["agentControllerType"] = "arm"; + action["renderInstanceSegmentation"] = true; + + // action.useMassThreshold = true; + // action.massThreshold = 10f; - action["fieldOfView"] = 90f; - action["snapToGrid"] = true; - action["renderInstanceSegmentation"] = true; - action["renderSemanticSegmentation"] = true; - action["action"] = "Initialize"; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - break; - } - case "initpsynth": { - Dictionary action = new Dictionary(); - // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here - // by default the gridsize is 0.25, so only moving in increments of .25 will work - // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default - // grid size! - if (splitcommand.Length == 2) { - action["gridSize"] = float.Parse(splitcommand[1]); - } else if (splitcommand.Length == 3) { - action["gridSize"] = float.Parse(splitcommand[1]); - action["agentCount"] = int.Parse(splitcommand[2]); - } else if (splitcommand.Length == 4) { - action["gridSize"] = float.Parse(splitcommand[1]); - action["agentCount"] = int.Parse(splitcommand[2]); - action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; - } - action["renderNormalsImage"] = true; - action["renderDepthImage"] = true; - action["renderSemanticSegmentation"] = true; - action["renderInstanceSegmentation"] = true; - action["renderFlowImage"] = true; - - action["fieldOfView"] = 90f; - action["snapToGrid"] = true; - action["action"] = "Initialize"; - action["procedural"] = true; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - break; - } - case "inite": { - Dictionary action = new Dictionary - { + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action), AManager); + // AgentManager am = PhysicsController.gameObject.FindObjectsOfType()[0]; + // Debug.Log("Physics scene manager = ..."); + // Debug.Log(physicsSceneManager); + // AgentManager am = physicsSceneManager.GetComponent(); + // Debug.Log(am); + // am.Initialize(action); + break; + } + case "initp": + { + Dictionary action = new Dictionary(); + // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here + // by default the gridsize is 0.25, so only moving in increments of .25 will work + // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default + // grid size! + if (splitcommand.Length == 2) + { + action["gridSize"] = float.Parse(splitcommand[1]); + } + else if (splitcommand.Length == 3) + { + action["gridSize"] = float.Parse(splitcommand[1]); + action["agentCount"] = int.Parse(splitcommand[2]); + } + else if (splitcommand.Length == 4) + { + action["gridSize"] = float.Parse(splitcommand[1]); + action["agentCount"] = int.Parse(splitcommand[2]); + action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; + } + + action["fieldOfView"] = 90f; + action["snapToGrid"] = true; + action["renderInstanceSegmentation"] = true; + action["renderSemanticSegmentation"] = true; + action["action"] = "Initialize"; + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + break; + } + case "initpsynth": + { + Dictionary action = new Dictionary(); + // if you want to use smaller grid size step increments, initialize with a smaller/larger gridsize here + // by default the gridsize is 0.25, so only moving in increments of .25 will work + // so the MoveAhead action will only take, by default, 0.25, .5, .75 etc magnitude with the default + // grid size! + if (splitcommand.Length == 2) + { + action["gridSize"] = float.Parse(splitcommand[1]); + } + else if (splitcommand.Length == 3) + { + action["gridSize"] = float.Parse(splitcommand[1]); + action["agentCount"] = int.Parse(splitcommand[2]); + } + else if (splitcommand.Length == 4) + { + action["gridSize"] = float.Parse(splitcommand[1]); + action["agentCount"] = int.Parse(splitcommand[2]); + action["makeAgentsVisible"] = int.Parse(splitcommand[3]) == 1; + } + action["renderNormalsImage"] = true; + action["renderDepthImage"] = true; + action["renderSemanticSegmentation"] = true; + action["renderInstanceSegmentation"] = true; + action["renderFlowImage"] = true; + + action["fieldOfView"] = 90f; + action["snapToGrid"] = true; + action["action"] = "Initialize"; + action["procedural"] = true; + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + + break; + } + case "inite": + { + Dictionary action = new Dictionary + { { "action", "Initialize" }, { "agentMode", "arm" }, { "agentControllerType", "mid-level" } }; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - var arm = CurrentActiveController() - .GetComponentInChildren(); - var armTarget = GameObject.Find("IK_pos_rot_manipulator"); - armTarget.transform.Rotate(90f, 0f, 0f); + var arm = CurrentActiveController() + .GetComponentInChildren(); + var armTarget = GameObject.Find("IK_pos_rot_manipulator"); + armTarget.transform.Rotate(90f, 0f, 0f); - var armJointToRotate = GameObject.Find("IK_pole_manipulator"); - armJointToRotate.transform.Rotate(0f, 0f, 90f); - var armBase = GameObject.Find("robot_arm_rig_gripper"); - armBase.transform.Translate(0f, 0.27f, 0f); + var armJointToRotate = GameObject.Find("IK_pole_manipulator"); + armJointToRotate.transform.Rotate(0f, 0f, 90f); + 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; - } + break; + } - case "sim": { - var collisionListener = this.CurrentActiveController() - .GetComponent(); - Physics.Simulate(0.02f); - var l = collisionListener.StaticCollisions(); - Debug.Log("total collisions: " + l.ToArray().Length); - break; - } + case "sim": + { + 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(); + case "inits": + { + 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< - string, - object - >() - { + 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< + string, + object + >() + { { "originOffsetX", 0.2f }, { "originOffsetZ", 0.4f }, { "colliderScaleRatio", new Vector3(0.8f, 1.2f, 0.5f) }, @@ -616,28 +684,29 @@ public void Execute(string command) { { "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< - string, - object - >() - { + 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< + string, + object + >() + { { "bodyAsset", new BodyAsset() { assetId = "StretchBotSimObj" } @@ -648,27 +717,28 @@ public void Execute(string command) { { "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; - } - - case "initpinsabsolute": { - Dictionary action = new Dictionary(); - - action["action"] = "Initialize"; - action["agentMode"] = "fpin"; - //action["useAbsoluteSize"] = true; - action["visibilityScheme"] = "Distance"; - action["renderInstanceSegmentation"] = true; - action["renderDepth"] = true; + break; + } - action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< - string, - object - >() - { + 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< + string, + object + >() + { { "bodyAsset", new BodyAsset() { assetId = "StretchBotSimObj" } @@ -680,27 +750,28 @@ public void Execute(string command) { { "useVisibleColliderBase", true } }; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - - break; - } + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - case "initpinsratio": { - Dictionary action = new Dictionary(); - - action["action"] = "Initialize"; - action["agentMode"] = "fpin"; - //action["useAbsoluteSize"] = true; - action["visibilityScheme"] = "Distance"; - action["renderInstanceSegmentation"] = true; - action["renderDepth"] = true; + break; + } - action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< - string, - object - >() - { + 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< + string, + object + >() + { { "bodyAsset", new BodyAsset() { assetId = "StretchBotSimObj" } @@ -710,28 +781,29 @@ public void Execute(string command) { { "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< - string, - object - >() - { + 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< + string, + object + >() + { { "bodyAsset", new BodyAsset() { assetId = "LocoBotSimObj" } @@ -741,29 +813,30 @@ public void Execute(string command) { { "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< - string, - object - >() - { + 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< + string, + object + >() + { { "bodyAsset", new BodyAsset() { assetId = "Toaster_5" } @@ -773,31 +846,32 @@ public void Execute(string command) { { "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< - string, - object - >() - { + 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< + string, + object + >() + { { "bodyAsset", new BodyAsset() { assetId = "Toaster_5" } @@ -808,31 +882,32 @@ public void Execute(string command) { { "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< - string, - object - >() - { + 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< + string, + object + >() + { { "bodyAsset", new BodyAsset() { assetId = "Toaster_5" } @@ -843,231 +918,245 @@ public void Execute(string command) { { "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; - } - case "initpinobja": { - Dictionary action = new Dictionary(); - BodyAsset ba = null; + break; + } + case "initpinobja": + { + Dictionary action = new Dictionary(); + BodyAsset ba = null; - if (splitcommand.Length == 2) { - 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< - string, - object - >() - { + // 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(); + case "initbodynobody": + { + 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(); + case "initbodyt": + { + 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(); + case "initbodyorigint": + { + 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(); + case "initbodyratiot": + { + 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(); + case "initbodyabsolutet": + { + 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(); + case "initbodyl": + { + 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(); + case "initbodys": + { + 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(); + case "initbodya": + { + 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(); + 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; + 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; - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + break; + } //fpin using apple - case "initpina": { - Dictionary action = new Dictionary(); - - action["action"] = "Initialize"; - action["agentMode"] = "fpin"; - action["visibilityScheme"] = "Distance"; - - action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< - string, - object - >() - { + case "initpina": + { + Dictionary action = new Dictionary(); + + action["action"] = "Initialize"; + action["agentMode"] = "fpin"; + action["visibilityScheme"] = "Distance"; + + action[DynamicServerAction.agentInitializationParamsVariable] = new Dictionary< + string, + object + >() + { { "bodyAsset", new BodyAsset() { assetId = "Apple_1" } @@ -1077,22 +1166,23 @@ public void Execute(string command) { { "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(); + case "inits-cp": + { + 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() - { + action["thirdPartyCameraParameters"] = new Dictionary() + { { "SecondaryCamera", new CameraParameters() @@ -1103,40 +1193,44 @@ public void Execute(string command) { } }; - 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; - } - case "ftele": { - Dictionary action = new Dictionary(); - action["action"] = "TeleportFull"; - action["position"] = new Vector3(10.0f, 0.009f, 2.75f); - action["rotation"] = new Vector3(0f, 0f, 0f); - action["horizon"] = -20f; - action["standing"] = true; - CurrentActiveController().ProcessControlCommand(action); - break; + action["action"] = "RandomlyPlaceAgentOnNavMesh"; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "ftele": + { + Dictionary action = new Dictionary(); + action["action"] = "TeleportFull"; + action["position"] = new Vector3(10.0f, 0.009f, 2.75f); + action["rotation"] = new Vector3(0f, 0f, 0f); + action["horizon"] = -20f; + action["standing"] = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "obig": + { + Dictionary action = new Dictionary(); + + action["action"] = "PlaceObjectIntoGripper"; + action["objectId"] = "Apple|-00.47|+01.15|+00.48"; + if (splitcommand.Length > 1) + { + action["objectId"] = splitcommand[1]; } - case "obig": { - Dictionary action = new Dictionary(); - action["action"] = "PlaceObjectIntoGripper"; - action["objectId"] = "Apple|-00.47|+01.15|+00.48"; - if (splitcommand.Length > 1) { - action["objectId"] = splitcommand[1]; - } - - CurrentActiveController().ProcessControlCommand(action); - break; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } // case "telearm": { // Dictionary action = new Dictionary(); // action["action"] = "TeleportArm"; @@ -1145,408 +1239,463 @@ public void Execute(string command) { // break; // } - case "mcb": { - Dictionary action = new Dictionary(); + case "mcb": + { + 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(); + case "rcb": + { + 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]); - } - CurrentActiveController().ProcessControlCommand(action); - break; + 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; + } - case "rcm": { - Dictionary action = new Dictionary(); + case "rcm": + { + 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]); - } - CurrentActiveController().ProcessControlCommand(action); - break; + action["action"] = "RotateCameraMount"; + action["degrees"] = 20.0f; + if (splitcommand.Length > 1) + { + action["degrees"] = float.Parse(splitcommand[1]); } - case "render": { - Dictionary action = new Dictionary(); + if (splitcommand.Length == 3) + { + action["secondary"] = bool.Parse(splitcommand[2]); + } + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "render": + { + 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]); } + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "sgo": { - Dictionary action = new Dictionary(); + case "adbdol": + { + Dictionary action = new Dictionary(); - action["action"] = "SetGripperOpenness"; - action["openness"] = 0; - if (splitcommand.Length > 1) { - action["openness"] = float.Parse(splitcommand[1]); - } - CurrentActiveController().ProcessControlCommand(action); - break; + action["action"] = "SetAssetDatabaseCaching"; + + if (splitcommand.Length > 1) + { + action["enable"] = bool.Parse(splitcommand[1]); } - case "adbdol": { - Dictionary action = new Dictionary(); + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "mabd": + { + Dictionary action = new Dictionary(); - action["action"] = "SetAssetDatabaseCaching"; + action["action"] = "MoveArmBaseDown"; + action["distance"] = 0.4f; - if (splitcommand.Length > 1) { - action["enable"] = bool.Parse(splitcommand[1]); - } + CurrentActiveController().ProcessControlCommand(action); + break; + } - CurrentActiveController().ProcessControlCommand(action); - break; + case "gaom": + { + Dictionary action = new Dictionary(); + + action["action"] = "GetApproxObjectMask"; + action["objectId"] = splitcommand[1]; + if (splitcommand.Length > 2) + { + action["divisions"] = int.Parse(splitcommand[2]); } - case "mabd": { - Dictionary action = new Dictionary(); + CurrentActiveController().ProcessControlCommand(action); + break; + } - action["action"] = "MoveArmBaseDown"; - action["distance"] = 0.4f; + case "inits-camera": + { + Dictionary action = new Dictionary(); - CurrentActiveController().ProcessControlCommand(action); - break; + 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]); } - case "gaom": { - Dictionary action = new Dictionary(); + action["cameraFarPlane"] = 20.0f; + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - action["action"] = "GetApproxObjectMask"; - action["objectId"] = splitcommand[1]; - if (splitcommand.Length > 2) { - action["divisions"] = int.Parse(splitcommand[2]); - } - CurrentActiveController().ProcessControlCommand(action); - break; - } - - case "inits-camera": { - 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["cameraFarPlane"] = 20.0f; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - //CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action), AManager); - - break; - } + break; + } - case "getlights": { - Dictionary action = new Dictionary(); + case "getlights": + { + 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; - } + case "stretchtest1": + { + 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; - } + case "stretchtest2": + { + 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; - } + case "stretchtest3": + { + 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; - } + case "stretchtest4": + { + 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; - } + case "stretchtest5": + { + 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; - } + case "stretchtest6": + { + 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; - } + case "stretchtest7": + { + 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; - } + case "stretchtest8": + { + 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; - } + case "stretchtest9": + { + 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; - } + case "stretchtest10": + { + 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; - } + case "stretchtest11": + { + 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; - } + case "stretchtest12": + { + 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; - } + case "stretchtest13": + { + 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; - } + case "stretchtest14": + { + 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; - } + case "stretchtest15": + { + 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; - } + case "stretchtest16": + { + 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; - } + case "stretchtest17": + { + 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; - } + case "stretchtest18": + { + 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; - } + case "stretchtestu": + { + 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; - } + case "stretchtestd": + { + 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; - } + case "iktest1": + { + 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; - } + case "iktest2": + { + List commands = new List(); + commands.Add("run move_ik_arm_2"); + //commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } - case "parent": { - Dictionary action = new Dictionary - { + case "parent": + { + 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 - { + case "gohfr": + { + 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 - { + case "bboxdist": + { + 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 - { + case "adjacent": + { + 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(); + case "whaton": + { + List objectIds = new List(); - for (int i = 1; i < splitcommand.Length; i++) { - objectIds.Add(splitcommand[i]); - } - Dictionary action = new Dictionary - { + 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(); + case "expspawn": + { + ServerAction action = new ServerAction(); - if (splitcommand.Length == 2) { - if (splitcommand[1] == "s") { - action.objectType = "screen"; - } + if (splitcommand.Length == 2) + { + if (splitcommand[1] == "s") + { + action.objectType = "screen"; + } - if (splitcommand[1] == "r") { - action.objectType = "receptacle"; - } - } else { + if (splitcommand[1] == "r") + { action.objectType = "receptacle"; } - action.action = "ReturnValidSpawnsExpRoom"; - action.receptacleObjectId = "DiningTable|-00.59|+00.00|+00.33"; - action.objectVariation = 0; - action.y = 120f; // UnityEngine.Random.Range(0, 360); - CurrentActiveController().ProcessControlCommand(action); - break; } + else + { + action.objectType = "receptacle"; + } + action.action = "ReturnValidSpawnsExpRoom"; + action.receptacleObjectId = "DiningTable|-00.59|+00.00|+00.33"; + action.objectVariation = 0; + action.y = 120f; // UnityEngine.Random.Range(0, 360); + CurrentActiveController().ProcessControlCommand(action); + break; + } // Reads and executes each action from a JSON file. // Example: 'run', where a local file explorer will open, and you'll select a json file. @@ -1557,21 +1706,27 @@ public void Execute(string command) { const string BASE_PATH = "./debug/"; string file = ""; string path; - if (splitcommand.Length == 1) { + if (splitcommand.Length == 1) + { // opens up a file explorer in the background path = EditorUtility.OpenFilePanel( title: "Open JSON actions file.", directory: "debug", extension: "json" ); - } else if (splitcommand.Length == 2) { + } + else if (splitcommand.Length == 2) + { // uses ./debug/{splitcommand[1]}[.json] file = splitcommand[1].Trim(); - if (!file.EndsWith(".json")) { + if (!file.EndsWith(".json")) + { file += ".json"; } path = BASE_PATH + file; - } else { + } + else + { Debug.LogError( "Pass in a file name, like 'run simple' or open a file with 'run'." ); @@ -1584,22 +1739,29 @@ public void Execute(string command) { Debug.Log($"Running: {file}.json. It has {actions.Count} total actions."); // execute each action - IEnumerator executeBatch(JArray jActions) { + IEnumerator executeBatch(JArray jActions) + { int i = 0; - foreach (JObject action in jActions) { - if (!action.ContainsKey("action")) { + foreach (JObject action in jActions) + { + if (!action.ContainsKey("action")) + { continue; } - while (CurrentActiveController().IsProcessing) { + while (CurrentActiveController().IsProcessing) + { yield return new WaitForEndOfFrame(); } Debug.Log($"{++i} Executing: {action}"); - if (AManager.agentManagerActions.Contains((String)action["action"])) { + if (AManager.agentManagerActions.Contains((String)action["action"])) + { ActionDispatcher.Dispatch( AManager, new DynamicServerAction(action) ); - } else { + } + else + { CurrentActiveController() .ProcessControlCommand(new DynamicServerAction(action)); } @@ -1607,463 +1769,525 @@ IEnumerator executeBatch(JArray jActions) { } 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); - - break; - } - case "exp": { - ServerAction action = new ServerAction(); + 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); - action.action = "SpawnExperimentObjAtRandom"; - action.objectType = "receptacle"; - 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); - CurrentActiveController().ProcessControlCommand(action); - break; - } + break; + } + case "exp": + { + ServerAction action = new ServerAction(); + + action.action = "SpawnExperimentObjAtRandom"; + action.objectType = "receptacle"; + 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); + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "exps": { - ServerAction action = new ServerAction(); + case "exps": + { + ServerAction action = new ServerAction(); - action.action = "SpawnExperimentObjAtRandom"; - action.objectType = "screen"; - action.randomSeed = UnityEngine.Random.Range(0, 1000); - action.receptacleObjectId = "DiningTable|-00.59|+00.00|+00.33"; + action.action = "SpawnExperimentObjAtRandom"; + action.objectType = "screen"; + action.randomSeed = UnityEngine.Random.Range(0, 1000); + action.receptacleObjectId = "DiningTable|-00.59|+00.00|+00.33"; - if (splitcommand.Length == 2) { - action.objectVariation = int.Parse(splitcommand[1]); - } else { - action.objectVariation = 0; - } - action.y = 0f; // UnityEngine.Random.Range(0, 360); - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length == 2) + { + action.objectVariation = int.Parse(splitcommand[1]); } - - case "expp": { - ServerAction action = new ServerAction(); - - action.action = "SpawnExperimentObjAtPoint"; - 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); - CurrentActiveController().ProcessControlCommand(action); - break; + else + { + action.objectVariation = 0; } + action.y = 0f; // UnityEngine.Random.Range(0, 360); + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "wallcolor": { - ServerAction action = new ServerAction(); + case "expp": + { + ServerAction action = new ServerAction(); + + action.action = "SpawnExperimentObjAtPoint"; + 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); + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.action = "ChangeWallColorExpRoom"; - action.r = 100f; - action.g = 100f; - action.b = 100f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "wallcolor": + { + ServerAction action = new ServerAction(); - case "floorcolor": { - ServerAction action = new ServerAction(); + action.action = "ChangeWallColorExpRoom"; + action.r = 100f; + action.g = 100f; + action.b = 100f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.action = "ChangeFloorColorExpRoom"; - action.r = 100f; - action.g = 100f; - action.b = 100f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "floorcolor": + { + ServerAction action = new ServerAction(); - case "wallmaterial": { - Dictionary action = new Dictionary(); - action["action"] = "ChangeWallMaterialExpRoom"; - action["objectVariation"] = 1; - CurrentActiveController().ProcessControlCommand(action); - break; - } + action.action = "ChangeFloorColorExpRoom"; + action.r = 100f; + action.g = 100f; + action.b = 100f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "floormaterial": { - ServerAction action = new ServerAction(); + case "wallmaterial": + { + Dictionary action = new Dictionary(); + action["action"] = "ChangeWallMaterialExpRoom"; + action["objectVariation"] = 1; + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.action = "ChangeFloorMaterialExpRoom"; - action.objectVariation = 1; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "floormaterial": + { + ServerAction action = new ServerAction(); - case "lightc": { - ServerAction action = new ServerAction(); + action.action = "ChangeFloorMaterialExpRoom"; + action.objectVariation = 1; + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.action = "ChangeLightColorExpRoom"; - action.r = 20f; - action.g = 94f; - action.b = 10f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "lightc": + { + ServerAction action = new ServerAction(); - case "lighti": { - Dictionary action = new Dictionary(); - action["action"] = "ChangeLightIntensityExpRoom"; - action["intensity"] = 3; - CurrentActiveController().ProcessControlCommand(action); - break; - } + action.action = "ChangeLightColorExpRoom"; + action.r = 20f; + action.g = 94f; + action.b = 10f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "tabletopc": { - ServerAction action = new ServerAction(); + case "lighti": + { + Dictionary action = new Dictionary(); + action["action"] = "ChangeLightIntensityExpRoom"; + action["intensity"] = 3; + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.action = "ChangeTableTopColorExpRoom"; - action.r = 20f; - action.g = 94f; - action.b = 10f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "tabletopc": + { + ServerAction action = new ServerAction(); - case "tabletopm": { - ServerAction action = new ServerAction(); + action.action = "ChangeTableTopColorExpRoom"; + action.r = 20f; + action.g = 94f; + action.b = 10f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.action = "ChangeTableTopMaterialExpRoom"; - action.objectVariation = 3; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "tabletopm": + { + ServerAction action = new ServerAction(); - case "tablelegc": { - ServerAction action = new ServerAction(); + action.action = "ChangeTableTopMaterialExpRoom"; + action.objectVariation = 3; + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.action = "ChangeTableLegColorExpRoom"; - action.r = 20f; - action.g = 94f; - action.b = 10f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "tablelegc": + { + ServerAction action = new ServerAction(); - case "tablelegm": { - ServerAction action = new ServerAction(); + action.action = "ChangeTableLegColorExpRoom"; + action.r = 20f; + action.g = 94f; + action.b = 10f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.action = "ChangeTableLegMaterialExpRoom"; - action.objectVariation = 3; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "tablelegm": + { + ServerAction action = new ServerAction(); - case "screenm": { - Dictionary action = new Dictionary(); - action["action"] = "ChangeScreenMaterialExpRoom"; - action["objectVariation"] = 3; - action["objectId"] = "ScreenSheet|-00.18|+01.24|+00.23"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + action.action = "ChangeTableLegMaterialExpRoom"; + action.objectVariation = 3; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "screenc": { - Dictionary action = new Dictionary(); - action["action"] = "ChangeScreenColorExpRoom"; - action["r"] = 20f; - action["g"] = 94f; - action["b"] = 10f; - action["objectId"] = "ScreenSheet|-00.18|+01.24|+00.23"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "screenm": + { + Dictionary action = new Dictionary(); + action["action"] = "ChangeScreenMaterialExpRoom"; + action["objectVariation"] = 3; + action["objectId"] = "ScreenSheet|-00.18|+01.24|+00.23"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "grid": { - Dictionary action = new Dictionary(); - action["action"] = "GetReceptacleCoordinatesExpRoom"; - action["gridSize"] = 0.1f; - action["maxStepCount"] = 5; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "screenc": + { + Dictionary action = new Dictionary(); + action["action"] = "ChangeScreenColorExpRoom"; + action["r"] = 20f; + action["g"] = 94f; + action["b"] = 10f; + action["objectId"] = "ScreenSheet|-00.18|+01.24|+00.23"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "dirtcoords": { - Dictionary action = new Dictionary(); - action["action"] = "GetDirtCoordinateBounds"; + case "grid": + { + Dictionary action = new Dictionary(); + action["action"] = "GetReceptacleCoordinatesExpRoom"; + action["gridSize"] = 0.1f; + action["maxStepCount"] = 5; + CurrentActiveController().ProcessControlCommand(action); + break; + } - GameObject table = GameObject.FindObjectOfType().gameObject; + case "dirtcoords": + { + Dictionary action = new Dictionary(); + action["action"] = "GetDirtCoordinateBounds"; - if (table == null) { - break; - } + GameObject table = GameObject.FindObjectOfType().gameObject; - action["objectId"] = table.GetComponent().objectID; - CurrentActiveController().ProcessControlCommand(action); + if (table == null) + { break; } - case "spawndirt": { - Dictionary action = new Dictionary(); - action["action"] = "SpawnDirt"; + action["objectId"] = table.GetComponent().objectID; + CurrentActiveController().ProcessControlCommand(action); + break; + } - GameObject table = GameObject.FindObjectOfType().gameObject; + case "spawndirt": + { + Dictionary action = new Dictionary(); + action["action"] = "SpawnDirt"; - if (table == null) { - break; - } + GameObject table = GameObject.FindObjectOfType().gameObject; - action["objectId"] = table.GetComponent().objectID; - action["howManyDirt"] = 100; - action["randomSeed"] = 0; - CurrentActiveController().ProcessControlCommand(action); + if (table == null) + { break; } - case "spawndirtarray": { - Dictionary action = new Dictionary(); - action["action"] = "SpawnDirt"; + action["objectId"] = table.GetComponent().objectID; + action["howManyDirt"] = 100; + action["randomSeed"] = 0; + CurrentActiveController().ProcessControlCommand(action); + break; + } - GameObject table = GameObject.FindObjectOfType().gameObject; + case "spawndirtarray": + { + Dictionary action = new Dictionary(); + action["action"] = "SpawnDirt"; - if (table == null) { - break; - } + GameObject table = GameObject.FindObjectOfType().gameObject; - 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["randomSeed"] = 0; - CurrentActiveController().ProcessControlCommand(action); + if (table == null) + { break; } - case "cleardirt": { - Dictionary action = new Dictionary(); - action["action"] = "ClearAllDirt"; - CurrentActiveController().ProcessControlCommand(action); - 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["randomSeed"] = 0; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "sponge": { - Dictionary action = new Dictionary(); - action["action"] = "ActivateSponge"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "cleardirt": + { + Dictionary action = new Dictionary(); + action["action"] = "ClearAllDirt"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "getsponge": { - Dictionary action = new Dictionary(); - action["action"] = "GetSpongeScale"; - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "setsponge": { - Dictionary action = new Dictionary(); - action["action"] = "SetSpongeScale"; - action["x"] = 3.0f; - action["y"] = 3.0f; - action["z"] = 3.0f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "sponge": + { + Dictionary action = new Dictionary(); + action["action"] = "ActivateSponge"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "pen": { - Dictionary action = new Dictionary(); - action["action"] = "ActivatePen"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "getsponge": + { + Dictionary action = new Dictionary(); + action["action"] = "GetSpongeScale"; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "setsponge": + { + Dictionary action = new Dictionary(); + action["action"] = "SetSpongeScale"; + action["x"] = 3.0f; + action["y"] = 3.0f; + action["z"] = 3.0f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "getspongemeta": { - Dictionary action = new Dictionary(); - action["action"] = "GetSpongeMeta"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "pen": + { + Dictionary action = new Dictionary(); + action["action"] = "ActivatePen"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "getpenmeta": { - Dictionary action = new Dictionary(); - action["action"] = "GetPenMeta"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "getspongemeta": + { + Dictionary action = new Dictionary(); + action["action"] = "GetSpongeMeta"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "getdirtmeta": { - Dictionary action = new Dictionary(); - action["action"] = "GetDirtMeta"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "getpenmeta": + { + Dictionary action = new Dictionary(); + action["action"] = "GetPenMeta"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "getdoorhinge": { - Dictionary action = new Dictionary(); - action["action"] = "GetDoorHinge"; - action["objectId"] = "door|1|3"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "getdirtmeta": + { + Dictionary action = new Dictionary(); + action["action"] = "GetDirtMeta"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "getdoorhandle": { - Dictionary action = new Dictionary(); - action["action"] = "GetDoorHandle"; - action["objectId"] = "door|1|3"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "getdoorhinge": + { + Dictionary action = new Dictionary(); + action["action"] = "GetDoorHinge"; + action["objectId"] = "door|1|3"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "getpenmarkmeta": { - Dictionary action = new Dictionary(); - action["action"] = "GetPenMarkMeta"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "getdoorhandle": + { + Dictionary action = new Dictionary(); + action["action"] = "GetDoorHandle"; + 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": { - Dictionary action = new Dictionary(); - // action.renderNormalsImage = true; - // action.renderDepthImage = true; - // action.renderSemanticSegmentation = true; - // action.renderInstanceSegmentation = true; - // action.renderFlowImage = true; - - action["action"] = "Initialize"; - action["agentMode"] = "drone"; - action["agentControllerType"] = "drone"; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + case "initd": + { + Dictionary action = new Dictionary(); + // action.renderNormalsImage = true; + // action.renderDepthImage = true; + // action.renderSemanticSegmentation = true; + // action.renderInstanceSegmentation = true; + // action.renderFlowImage = true; + + action["action"] = "Initialize"; + action["agentMode"] = "drone"; + action["agentControllerType"] = "drone"; + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - break; - } + break; + } // activate cracked camera effect with random seed - case "cc": { - Dictionary action = new Dictionary(); - action["action"] = "CameraCrack"; - - // give me a seed - if (splitcommand.Length == 2) { - action["randomSeed"] = int.Parse(splitcommand[1]); - } else { - action["randomSeed"] = 0; - } + case "cc": + { + Dictionary action = new Dictionary(); + action["action"] = "CameraCrack"; + + // give me a seed + if (splitcommand.Length == 2) + { + action["randomSeed"] = int.Parse(splitcommand[1]); + } + else + { + action["randomSeed"] = 0; + } - CurrentActiveController().ProcessControlCommand(action); + CurrentActiveController().ProcessControlCommand(action); - break; - } + break; + } - case "geo": { - var action = new Dictionary() { - ["action"] = "GetInSceneAssetGeometry", - ["objectId"] = splitcommand[1], - ["triangles"] = true - }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "geo": + { + var action = new Dictionary() + { + ["action"] = "GetInSceneAssetGeometry", + ["objectId"] = splitcommand[1], + ["triangles"] = true + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "des": { - var action = new Dictionary() { ["action"] = "DestroyHouse" }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "des": + { + var action = new Dictionary() { ["action"] = "DestroyHouse" }; + CurrentActiveController().ProcessControlCommand(action); + break; + } // move ahead stochastic - case "mas": { - ServerAction action = new ServerAction(); - action.action = "MoveAhead"; + case "mas": + { + ServerAction action = new ServerAction(); + action.action = "MoveAhead"; - action.moveMagnitude = 0.25f; + action.moveMagnitude = 0.25f; - CurrentActiveController().ProcessControlCommand(action); + CurrentActiveController().ProcessControlCommand(action); - break; - } - case "rad": { - Dictionary action = new Dictionary(); - action["action"] = "SetAgentRadius"; - action["agentRadius"] = 0.35f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + break; + } + case "rad": + { + Dictionary action = new Dictionary(); + action["action"] = "SetAgentRadius"; + action["agentRadius"] = 0.35f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "sbc": { - var action = new Dictionary() { - ["action"] = "UpdateAgentBoxCollider", - ["colliderScaleRatio"] = new Vector3(1.0f, 1.0f, 1.0f), - ["useVisibleColliderBase"] = false - }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "sbc": + { + var action = new Dictionary() + { + ["action"] = "UpdateAgentBoxCollider", + ["colliderScaleRatio"] = new Vector3(1.0f, 1.0f, 1.0f), + ["useVisibleColliderBase"] = false + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "sbc2": { - var action = new Dictionary() { - ["action"] = "UpdateAgentBoxCollider", - ["colliderScaleRatio"] = new Vector3(1.1f, 1.0f, 1.3f), - ["useVisibleColliderBase"] = false - }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "sbc2": + { + var action = new Dictionary() + { + ["action"] = "UpdateAgentBoxCollider", + ["colliderScaleRatio"] = new Vector3(1.1f, 1.0f, 1.3f), + ["useVisibleColliderBase"] = false + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "sbcv": { - var action = new Dictionary() { - ["action"] = "UpdateAgentBoxCollider", - ["colliderScaleRatio"] = new Vector3(1.3f, 1.0f, 1.0f), - ["useVisibleColliderBase"] = true - }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "sbcv": + { + var action = new Dictionary() + { + ["action"] = "UpdateAgentBoxCollider", + ["colliderScaleRatio"] = new Vector3(1.3f, 1.0f, 1.0f), + ["useVisibleColliderBase"] = true + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "sbcv2": { - var action = new Dictionary() { - ["action"] = "UpdateAgentBoxCollider", - ["colliderScaleRatio"] = new Vector3(1.0f, 1.0f, 1.3f), - ["useVisibleColliderBase"] = true - }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "sbcv2": + { + var action = new Dictionary() + { + ["action"] = "UpdateAgentBoxCollider", + ["colliderScaleRatio"] = new Vector3(1.0f, 1.0f, 1.3f), + ["useVisibleColliderBase"] = true + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "sbca": { - var action = new Dictionary() { - ["action"] = "UpdateAgentBoxCollider", - ["colliderScaleRatio"] = new Vector3(0.5f, 1.0f, 0.3f), - ["useAbsoluteSize"] = true - }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "sbca": + { + var action = new Dictionary() + { + ["action"] = "UpdateAgentBoxCollider", + ["colliderScaleRatio"] = new Vector3(0.5f, 1.0f, 0.3f), + ["useAbsoluteSize"] = true + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "sbca2": { - var action = new Dictionary() { - ["action"] = "UpdateAgentBoxCollider", - ["colliderScaleRatio"] = new Vector3(0.3f, 1.0f, 0.5f), - ["useAbsoluteSize"] = true - }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "sbca2": + { + var action = new Dictionary() + { + ["action"] = "UpdateAgentBoxCollider", + ["colliderScaleRatio"] = new Vector3(0.3f, 1.0f, 0.5f), + ["useAbsoluteSize"] = true + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "dbc": { - var action = new Dictionary() { - ["action"] = "DestroyAgentBoxCollider", - }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "dbc": + { + var action = new Dictionary() + { + ["action"] = "DestroyAgentBoxCollider", + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } // This is dangerous because it will modify the underlying // materials, and you'll have to call "git restore *.mat *maT" @@ -2093,13 +2317,15 @@ IEnumerator executeBatch(JArray jActions) { case "dangerouslyChangeMaterial": List excludedObjectIds = new List(); - if (splitcommand.Length > 1) { + if (splitcommand.Length > 1) + { excludedObjectIds.Add(splitcommand[1]); } CurrentActiveController() .ProcessControlCommand( - new Dictionary() { + new Dictionary() + { ["action"] = "RandomizeMaterials", ["excludedObjectIds"] = excludedObjectIds } @@ -2112,2526 +2338,2859 @@ IEnumerator executeBatch(JArray jActions) { ); break; - case "light": { - Dictionary action = new Dictionary() { - ["action"] = "RandomizeLighting", - ["synchronized"] = false, - ["brightness"] = new float[] { 0.5f, 1.5f }, - ["hue"] = new float[] { 0, 1 }, - ["saturation"] = new float[] { 0, 1 } - }; - CurrentActiveController().ProcessControlCommand(action); - break; - } - - case "resetlight": { - Dictionary action = new Dictionary() { - ["action"] = "ResetLighting" - }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "light": + { + Dictionary action = new Dictionary() + { + ["action"] = "RandomizeLighting", + ["synchronized"] = false, + ["brightness"] = new float[] { 0.5f, 1.5f }, + ["hue"] = new float[] { 0, 1 }, + ["saturation"] = new float[] { 0, 1 } + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "spawnabove": { - ServerAction action = new ServerAction(); - action.action = "GetSpawnCoordinatesAboveReceptacle"; - action.objectId = "CounterTop|-01.94|+00.98|-03.67"; - action.anywhere = false; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "resetlight": + { + Dictionary action = new Dictionary() + { + ["action"] = "ResetLighting" + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "crazydiamond": { - Dictionary action = new Dictionary(); - action["action"] = "MakeObjectsOfTypeUnbreakable"; - action["objectType"] = "Egg"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "spawnabove": + { + ServerAction action = new ServerAction(); + action.action = "GetSpawnCoordinatesAboveReceptacle"; + action.objectId = "CounterTop|-01.94|+00.98|-03.67"; + action.anywhere = false; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "stc": { - ServerAction action = new ServerAction(); - action.action = "SpawnTargetCircle"; - if (splitcommand.Length > 1) { - if (int.Parse(splitcommand[1]) == 0) { - action.objectVariation = 0; - } + case "crazydiamond": + { + Dictionary action = new Dictionary(); + action["action"] = "MakeObjectsOfTypeUnbreakable"; + action["objectType"] = "Egg"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (int.Parse(splitcommand[1]) == 1) { - action.objectVariation = 1; - } + case "stc": + { + ServerAction action = new ServerAction(); + action.action = "SpawnTargetCircle"; + if (splitcommand.Length > 1) + { + if (int.Parse(splitcommand[1]) == 0) + { + action.objectVariation = 0; + } - if (int.Parse(splitcommand[1]) == 2) { - action.objectVariation = 2; - } + if (int.Parse(splitcommand[1]) == 1) + { + action.objectVariation = 1; } - 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; + if (int.Parse(splitcommand[1]) == 2) + { + action.objectVariation = 2; + } } - case "smp": { - Dictionary action = new Dictionary(); - action["action"] = "SetMassProperties"; - action["objectId"] = "Pot|+00.30|+00.96|+01.35"; - action["mass"] = 100; - action["drag"] = 100; - action["angularDrag"] = 100; - CurrentActiveController().ProcessControlCommand(action); - break; - } + 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; + } - case "pp": { - ExecuteAction("PausePhysicsAutoSim"); - break; - } + case "smp": + { + Dictionary action = new Dictionary(); + action["action"] = "SetMassProperties"; + action["objectId"] = "Pot|+00.30|+00.96|+01.35"; + action["mass"] = 100; + action["drag"] = 100; + action["angularDrag"] = 100; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "msa": { - GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere); - go.transform.position = new Vector3(-0.771f, 0.993f, 0.8023f); - go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); - SphereCollider sc = go.GetComponent(); - sc.isTrigger = true; - break; - } - case "msr": { - GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere); - go.transform.position = new Vector3(-0.771f, 0.87f, 0.6436f); - go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); - SphereCollider sc = go.GetComponent(); - sc.isTrigger = true; - break; - } + case "pp": + { + ExecuteAction("PausePhysicsAutoSim"); + break; + } - case "mach": { - var moveCall = moveArmHeightDebug(0.4f); - StartCoroutine(moveCall); - break; - } + case "msa": + { + GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere); + go.transform.position = new Vector3(-0.771f, 0.993f, 0.8023f); + go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); + SphereCollider sc = go.GetComponent(); + sc.isTrigger = true; + break; + } + case "msr": + { + GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere); + go.transform.position = new Vector3(-0.771f, 0.87f, 0.6436f); + go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); + SphereCollider sc = go.GetComponent(); + sc.isTrigger = true; + break; + } - case "mafh": { - var moveCall = moveArmHeightDebug(0.4f); - while (moveCall.MoveNext()) { - // physics simulate happens in updateTransformPropertyFixedUpdate as long - // as autoSimulation is off - } - break; - } - case "macr": { - var target = new Vector3(0.1f, 0.0f, 0.4f); - var moveCall = moveArmDebug(target); - StartCoroutine(moveCall); - break; - } - case "mafr": { - var target = new Vector3(0.1f, 0.0f, 0.4f); - var moveCall = moveArmDebug(target); - while (moveCall.MoveNext()) { - // physics simulate happens in updateTransformPropertyFixedUpdate as long - // as autoSimulation is off - } + case "mach": + { + var moveCall = moveArmHeightDebug(0.4f); + StartCoroutine(moveCall); + break; + } - break; + case "mafh": + { + var moveCall = moveArmHeightDebug(0.4f); + while (moveCall.MoveNext()) + { + // physics simulate happens in updateTransformPropertyFixedUpdate as long + // as autoSimulation is off } - case "dumpwrist": { - var wristCol = GameObject.Find("robot_wrist_1_tcol (11)").transform; - dumpPosition(wristCol); - break; + break; + } + case "macr": + { + var target = new Vector3(0.1f, 0.0f, 0.4f); + var moveCall = moveArmDebug(target); + StartCoroutine(moveCall); + break; + } + case "mafr": + { + var target = new Vector3(0.1f, 0.0f, 0.4f); + var moveCall = moveArmDebug(target); + while (moveCall.MoveNext()) + { + // physics simulate happens in updateTransformPropertyFixedUpdate as long + // as autoSimulation is off } - case "debugarm": { - var arm = CurrentActiveController() - .GetComponentInChildren(); - ArmMetadata armmeta = arm.GenerateMetadata(); - Debug.Log("last joint position"); - Vector3 rrpos = armmeta.joints[armmeta.joints.Length - 1].rootRelativePosition; + break; + } + case "dumpwrist": + { + var wristCol = GameObject.Find("robot_wrist_1_tcol (11)").transform; + dumpPosition(wristCol); + break; + } + + case "debugarm": + { + 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.###") + ); + break; + } + + case "debugstretcharmjoints": + { + var arm = CurrentActiveController() + .GetComponentInChildren(); + ArmMetadata armmeta = arm.GenerateMetadata(); + foreach (JointMetadata jm in armmeta.joints) + { Debug.Log( - "Root Relative Arm Position - x:" - + rrpos.x.ToString("0.###") - + " y:" - + rrpos.y.ToString("0.###") - + " z:" - + rrpos.z.ToString("0.###") + jm.name + + " position: (" + + jm.position.x + + ", " + + jm.position.y + + ", " + + jm.position.z + + ")" ); - break; + 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); } + break; + } - case "debugstretcharmjoints": { - 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 + " rotation: " + jm.rotation); - Debug.Log(jm.name + " root-relative rotation: " + jm.rootRelativeRotation); - Debug.Log(jm.name + " local rotation: " + jm.localRotation); - } - break; + case "debugarmjoints": + { + 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 + " rotation: " + jm.rotation); + Debug.Log(jm.name + " root-relative rotation: " + jm.rootRelativeRotation); + Debug.Log(jm.name + " local rotation: " + jm.localRotation); } + break; + } - case "debugarmjoints": { - 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 + " rotation: " + jm.rotation); - Debug.Log(jm.name + " root-relative rotation: " + jm.rootRelativeRotation); - Debug.Log(jm.name + " local rotation: " + jm.localRotation); - } - break; - } - - case "posarm1": { - 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; - } + case "posarm1": + { + 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; + } - case "slide1": { - List commands = new List(); - commands.Add("inita"); - commands.Add("run 02_04_2021_16_44_01"); - commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + case "slide1": + { + List commands = new List(); + commands.Add("inita"); + commands.Add("run 02_04_2021_16_44_01"); + commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } - case "slide2": { - List commands = new List(); - commands.Add("inita"); - commands.Add("run 02_04_2021_20_51_23"); - commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + case "slide2": + { + List commands = new List(); + commands.Add("inita"); + commands.Add("run 02_04_2021_20_51_23"); + commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } - case "slide3": { - List commands = new List(); - commands.Add("inita"); - commands.Add("run 02_04_2021_23_31_11"); - commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + case "slide3": + { + List commands = new List(); + commands.Add("inita"); + commands.Add("run 02_04_2021_23_31_11"); + commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } - case "slide4": { - List commands = new List(); - commands.Add("inita"); - commands.Add("run 02_05_2021_01_26_52"); - commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + case "slide4": + { + List commands = new List(); + commands.Add("inita"); + commands.Add("run 02_05_2021_01_26_52"); + commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } - case "slide5": { - List commands = new List(); - commands.Add("inita"); - commands.Add("run 02_05_2021_02_58_54"); - commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + case "slide5": + { + List commands = new List(); + commands.Add("inita"); + commands.Add("run 02_05_2021_02_58_54"); + commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } - case "slide6": { - List commands = new List(); - commands.Add("inita"); - commands.Add("run 02_05_2021_07_28_25"); - commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + case "slide6": + { + List commands = new List(); + commands.Add("inita"); + commands.Add("run 02_05_2021_07_28_25"); + commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } - case "slide7": { - List commands = new List(); - commands.Add("inita"); - commands.Add("run 02_05_2021_08_36_10"); - commands.Add("debugarmjoints"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + case "slide7": + { + List commands = new List(); + commands.Add("inita"); + commands.Add("run 02_05_2021_08_36_10"); + commands.Add("debugarmjoints"); + StartCoroutine(ExecuteBatch(commands)); + break; + } - case "ras1": { - List commands = new List(); - commands.Add("pp"); - commands.Add("rr"); - commands.Add("inita"); - commands.Add("telefull -1.0 0.9009995460510254 1 135"); - commands.Add("ld 20"); - commands.Add("posarm1"); - commands.Add("msr"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + case "ras1": + { + List commands = new List(); + commands.Add("pp"); + commands.Add("rr"); + commands.Add("inita"); + commands.Add("telefull -1.0 0.9009995460510254 1 135"); + commands.Add("ld 20"); + commands.Add("posarm1"); + commands.Add("msr"); + StartCoroutine(ExecuteBatch(commands)); + break; + } - case "ras2": { - List commands = new List(); - commands.Add("pp"); - commands.Add("inita"); - commands.Add("telefull -1.0 0.9009995460510254 1 135"); - commands.Add("ld 20"); - commands.Add("posarm1"); - commands.Add("msa"); - StartCoroutine(ExecuteBatch(commands)); - break; - } - case "reproarmrot1": { - List commands = new List(); - commands.Add("inita"); - commands.Add("telefull -1.0 0.9009995460510254 1.5 90"); - commands.Add("mmla 0.0 0.0 0.2 1.0"); - commands.Add("debugarm"); - StartCoroutine(ExecuteBatch(commands)); - break; - } + case "ras2": + { + List commands = new List(); + commands.Add("pp"); + commands.Add("inita"); + commands.Add("telefull -1.0 0.9009995460510254 1 135"); + commands.Add("ld 20"); + commands.Add("posarm1"); + commands.Add("msa"); + StartCoroutine(ExecuteBatch(commands)); + break; + } + case "reproarmrot1": + { + List commands = new List(); + commands.Add("inita"); + commands.Add("telefull -1.0 0.9009995460510254 1.5 90"); + commands.Add("mmla 0.0 0.0 0.2 1.0"); + commands.Add("debugarm"); + StartCoroutine(ExecuteBatch(commands)); + break; + } - case "reproarmrot2": { - List commands = new List(); - commands.Add("inita"); - commands.Add("telefull -1.0 0.9009995460510254 1.5 45"); - commands.Add("mmla 0.0 0.0 0.2 1.0"); - commands.Add("debugarm"); - StartCoroutine(ExecuteBatch(commands)); - break; - } - case "reproarmsphere3": { - GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere); - go.transform.position = new Vector3(-0.6648f, 1.701f, 1.421f); - go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); - go.GetComponent().enabled = false; - go.AddComponent(typeof(MeshCollider)); - MeshCollider mc = go.GetComponent(); - mc.convex = true; - mc.isTrigger = true; - List commands = new List(); - commands.Add("pp"); - commands.Add("rr"); - commands.Add("inita"); - commands.Add("mmlah 1 1 True True"); - StartCoroutine(ExecuteBatch(commands)); - break; - } - case "reproarmsphere2": { - GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere); - go.transform.position = new Vector3(-0.6648f, 1.701f, 1.421f); - go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); - go.GetComponent().enabled = false; - go.AddComponent(typeof(MeshCollider)); - List commands = new List(); - commands.Add("pp"); - commands.Add("rr"); - commands.Add("inita"); - commands.Add("mmlah 1 1 True True"); - StartCoroutine(ExecuteBatch(commands)); - break; - } - case "reproarmsphere1": { - GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere); - go.transform.position = new Vector3(-0.6648f, 1.701f, 1.421f); - go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); - SphereCollider sc = go.GetComponent(); - sc.isTrigger = true; - List commands = new List(); - commands.Add("pp"); - commands.Add("rr"); - commands.Add("inita"); - commands.Add("mmlah 1 1 True True"); - StartCoroutine(ExecuteBatch(commands)); - break; - } - case "reproarmstuck": { - List commands = new List(); - commands.Add("pp"); - commands.Add("rr"); - commands.Add("inita"); - 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" - ); - StartCoroutine(ExecuteBatch(commands)); - break; - } + case "reproarmrot2": + { + List commands = new List(); + commands.Add("inita"); + commands.Add("telefull -1.0 0.9009995460510254 1.5 45"); + commands.Add("mmla 0.0 0.0 0.2 1.0"); + commands.Add("debugarm"); + StartCoroutine(ExecuteBatch(commands)); + break; + } + case "reproarmsphere3": + { + GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere); + go.transform.position = new Vector3(-0.6648f, 1.701f, 1.421f); + go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); + go.GetComponent().enabled = false; + go.AddComponent(typeof(MeshCollider)); + MeshCollider mc = go.GetComponent(); + mc.convex = true; + mc.isTrigger = true; + List commands = new List(); + commands.Add("pp"); + commands.Add("rr"); + commands.Add("inita"); + commands.Add("mmlah 1 1 True True"); + StartCoroutine(ExecuteBatch(commands)); + break; + } + case "reproarmsphere2": + { + GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere); + go.transform.position = new Vector3(-0.6648f, 1.701f, 1.421f); + go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); + go.GetComponent().enabled = false; + go.AddComponent(typeof(MeshCollider)); + List commands = new List(); + commands.Add("pp"); + commands.Add("rr"); + commands.Add("inita"); + commands.Add("mmlah 1 1 True True"); + StartCoroutine(ExecuteBatch(commands)); + break; + } + case "reproarmsphere1": + { + GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere); + go.transform.position = new Vector3(-0.6648f, 1.701f, 1.421f); + go.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f); + SphereCollider sc = go.GetComponent(); + sc.isTrigger = true; + List commands = new List(); + commands.Add("pp"); + commands.Add("rr"); + commands.Add("inita"); + commands.Add("mmlah 1 1 True True"); + StartCoroutine(ExecuteBatch(commands)); + break; + } + case "reproarmstuck": + { + List commands = new List(); + commands.Add("pp"); + commands.Add("rr"); + commands.Add("inita"); + 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" + ); + StartCoroutine(ExecuteBatch(commands)); + break; + } - case "ap": { - Dictionary action = new Dictionary(); - action["action"] = "AdvancePhysicsStep"; - action["timeStep"] = 0.02f; // max 0.05, min 0.01 - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "ap": + { + Dictionary action = new Dictionary(); + action["action"] = "AdvancePhysicsStep"; + action["timeStep"] = 0.02f; // max 0.05, min 0.01 + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "up": { - Dictionary action = new Dictionary(); - action["action"] = "UnpausePhysicsAutoSim"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "up": + { + Dictionary action = new Dictionary(); + action["action"] = "UnpausePhysicsAutoSim"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "its": { - Dictionary action = new Dictionary(); - action["action"] = "InitializeTableSetting"; - if (splitcommand.Length > 1) { - action["objectVariation"] = int.Parse(splitcommand[1]); - } - CurrentActiveController().ProcessControlCommand(action); - break; + case "its": + { + Dictionary action = new Dictionary(); + action["action"] = "InitializeTableSetting"; + if (splitcommand.Length > 1) + { + action["objectVariation"] = int.Parse(splitcommand[1]); } + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "potwhcb": { - Dictionary action = new Dictionary(); - action["action"] = "PointsOverTableWhereHandCanBe"; - action["objectId"] = splitcommand[1]; - action["x"] = float.Parse(splitcommand[2]); - action["z"] = float.Parse(splitcommand[3]); + case "potwhcb": + { + Dictionary action = new Dictionary(); + action["action"] = "PointsOverTableWhereHandCanBe"; + action["objectId"] = splitcommand[1]; + action["x"] = float.Parse(splitcommand[2]); + action["z"] = float.Parse(splitcommand[3]); - CurrentActiveController().ProcessControlCommand(action); - break; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "pfrat": { - Dictionary action = new Dictionary(); + case "pfrat": + { + Dictionary action = new Dictionary(); - action["action"] = "PlaceFixedReceptacleAtLocation"; - if (splitcommand.Length > 1) { - action["objectVariation"] = int.Parse(splitcommand[1]); - action["x"] = float.Parse(splitcommand[2]); - action["y"] = float.Parse(splitcommand[3]); - action["z"] = float.Parse(splitcommand[4]); - } - CurrentActiveController().ProcessControlCommand(action); - break; + action["action"] = "PlaceFixedReceptacleAtLocation"; + if (splitcommand.Length > 1) + { + action["objectVariation"] = int.Parse(splitcommand[1]); + action["x"] = float.Parse(splitcommand[2]); + action["y"] = float.Parse(splitcommand[3]); + action["z"] = float.Parse(splitcommand[4]); } - case "pbwal": { - Dictionary action = new Dictionary(); - - action["action"] = "PlaceBookWallAtLocation"; - if (splitcommand.Length > 1) { - action["objectVariation"] = int.Parse(splitcommand[1]); - action["x"] = float.Parse(splitcommand[2]); - action["y"] = float.Parse(splitcommand[3]); - action["z"] = float.Parse(splitcommand[4]); - action["rotation"] = new Vector3(0f, float.Parse(splitcommand[5]), 0f); - } - CurrentActiveController().ProcessControlCommand(action); - break; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "pbwal": + { + Dictionary action = new Dictionary(); + + action["action"] = "PlaceBookWallAtLocation"; + if (splitcommand.Length > 1) + { + action["objectVariation"] = int.Parse(splitcommand[1]); + action["x"] = float.Parse(splitcommand[2]); + action["y"] = float.Parse(splitcommand[3]); + action["z"] = float.Parse(splitcommand[4]); + action["rotation"] = new Vector3(0f, float.Parse(splitcommand[5]), 0f); } + CurrentActiveController().ProcessControlCommand(action); + break; + } // random toggle state of all objects - case "rts": { - ServerAction action = new ServerAction(); + case "rts": + { + ServerAction action = new ServerAction(); - action.randomSeed = 0; - action.action = "RandomToggleStateOfAllObjects"; - CurrentActiveController().ProcessControlCommand(action); - break; - } - - case "rtss": { - ServerAction action = new ServerAction(); + action.randomSeed = 0; + action.action = "RandomToggleStateOfAllObjects"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.randomSeed = 0; - action.StateChange = "CanOpen"; - action.action = "RandomToggleSpecificState"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "rtss": + { + ServerAction action = new ServerAction(); - case "l": { - ServerAction action = new ServerAction(); - action.action = "ChangeLightSet"; - if (splitcommand.Length == 2) { - action.objectVariation = int.Parse(splitcommand[1]); - } + action.randomSeed = 0; + action.StateChange = "CanOpen"; + action.action = "RandomToggleSpecificState"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - CurrentActiveController().ProcessControlCommand(action); - break; + case "l": + { + ServerAction action = new ServerAction(); + action.action = "ChangeLightSet"; + if (splitcommand.Length == 2) + { + action.objectVariation = int.Parse(splitcommand[1]); } + CurrentActiveController().ProcessControlCommand(action); + break; + } + // set state of all objects that have a state - case "ssa": { - ServerAction action = new ServerAction(); + case "ssa": + { + ServerAction action = new ServerAction(); - action.StateChange = "CanBeDirty"; - action.forceAction = true; - action.action = "SetStateOfAllObjects"; + action.StateChange = "CanBeDirty"; + action.forceAction = true; + action.action = "SetStateOfAllObjects"; - if (splitcommand.Length > 1) { - if (splitcommand[1] == "t") { - action.forceAction = true; - } - - if (splitcommand[1] == "f") { - action.forceAction = false; - } + if (splitcommand.Length > 1) + { + if (splitcommand[1] == "t") + { + action.forceAction = true; } - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand[1] == "f") + { + action.forceAction = false; + } } + CurrentActiveController().ProcessControlCommand(action); - case "initsynth": { - Dictionary action = new Dictionary(); + break; + } - action["renderNormalsImage"] = true; - action["renderDepthImage"] = true; - action["renderSemanticSegmentation"] = true; - action["renderInstanceSegmentation"] = true; - action["renderFlowImage"] = true; + case "initsynth": + { + Dictionary action = new Dictionary(); - // action.ssao = "default"; + action["renderNormalsImage"] = true; + action["renderDepthImage"] = true; + action["renderSemanticSegmentation"] = true; + action["renderInstanceSegmentation"] = true; + action["renderFlowImage"] = true; - action["action"] = "Initialize"; - ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); - break; - } + // action.ssao = "default"; - case "atpc": { - Dictionary action = new Dictionary() { - ["action"] = "AddThirdPartyCamera", - ["position"] = new Vector3(1, 1, 1), - ["rotation"] = new Vector3(10, 20, 30), - ["parent"] = "agent", - ["agentPositionRelativeCoordinates"] = true - }; + action["action"] = "Initialize"; + ActionDispatcher.Dispatch(AManager, new DynamicServerAction(action)); + break; + } - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + case "atpc": + { + Dictionary action = new Dictionary() + { + ["action"] = "AddThirdPartyCamera", + ["position"] = new Vector3(1, 1, 1), + ["rotation"] = new Vector3(10, 20, 30), + ["parent"] = "agent", + ["agentPositionRelativeCoordinates"] = true + }; - case "utpc": { - Dictionary action = new Dictionary() { - ["action"] = "UpdateThirdPartyCamera", - ["position"] = new Vector3(2, 2, 2), - ["rotation"] = new Vector3(15, 25, 35), - ["thirdPartyCameraId"] = 1, - ["parent"] = "agent", - ["agentPositionRelativeCoordinates"] = true - }; + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action), AManager); + break; + } - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + case "utpc": + { + Dictionary action = new Dictionary() + { + ["action"] = "UpdateThirdPartyCamera", + ["position"] = new Vector3(2, 2, 2), + ["rotation"] = new Vector3(15, 25, 35), + ["thirdPartyCameraId"] = 1, + ["parent"] = "agent", + ["agentPositionRelativeCoordinates"] = true + }; - case "umc": { - Dictionary action = new Dictionary() { - ["action"] = "UpdateMainCamera", - ["position"] = new Vector3(0.5f, 0.5f, 0.5f), - ["rotation"] = new Vector3(15, 25, 35), - ["fieldOfView"] = 120f, - //["agentPositionRelativeCoordinates"] = false - }; + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action), AManager); + break; + } - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action), AManager); - break; - } + case "umc": + { + Dictionary action = new Dictionary() + { + ["action"] = "UpdateMainCamera", + ["position"] = new Vector3(0.5f, 0.5f, 0.5f), + ["rotation"] = new Vector3(15, 25, 35), + ["fieldOfView"] = 120f, + //["agentPositionRelativeCoordinates"] = false + }; - case "debugmaincamera": { - CurrentActiveController().generateMetadataWrapper(); - break; - } - case "to": { - ServerAction action = new ServerAction(); - action.action = "TeleportObject"; - action.objectId = splitcommand[1]; - action.x = float.Parse(splitcommand[2]); - action.y = float.Parse(splitcommand[3]); - action.z = float.Parse(splitcommand[4]); - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "daoot": { - ServerAction action = new ServerAction(); - action.action = "DisableAllObjectsOfType"; - action.objectId = splitcommand[1]; - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "ctlq": { - ServerAction action = new ServerAction(); - action.action = "ChangeQuality"; - action.quality = "Very Low"; - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "roco": { - Dictionary action = new Dictionary(); - action["action"] = "RandomlyOpenCloseObjects"; - action["randomSeed"] = (new System.Random()).Next(1, 1000000); - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "crouch": { - ExecuteAction("Crouch"); - break; - } - case "stand": { - ExecuteAction("Stand"); - break; - } + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action), AManager); + break; + } - case "remove": { - Dictionary action = new Dictionary(); - action["action"] = "RemoveFromScene"; + case "debugmaincamera": + { + CurrentActiveController().generateMetadataWrapper(); + break; + } + case "to": + { + ServerAction action = new ServerAction(); + action.action = "TeleportObject"; + action.objectId = splitcommand[1]; + action.x = float.Parse(splitcommand[2]); + action.y = float.Parse(splitcommand[3]); + action.z = float.Parse(splitcommand[4]); + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "daoot": + { + ServerAction action = new ServerAction(); + action.action = "DisableAllObjectsOfType"; + action.objectId = splitcommand[1]; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "ctlq": + { + ServerAction action = new ServerAction(); + action.action = "ChangeQuality"; + action.quality = "Very Low"; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "roco": + { + Dictionary action = new Dictionary(); + action["action"] = "RandomlyOpenCloseObjects"; + action["randomSeed"] = (new System.Random()).Next(1, 1000000); + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "crouch": + { + ExecuteAction("Crouch"); + break; + } + case "stand": + { + ExecuteAction("Stand"); + break; + } - if (splitcommand.Length == 2) { - action["objectId"] = splitcommand[1]; - } + case "remove": + { + Dictionary action = new Dictionary(); + action["action"] = "RemoveFromScene"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length == 2) + { + action["objectId"] = splitcommand[1]; } - case "putr": { - Dictionary action = new Dictionary(); - action["action"] = "PutObject"; - action["objectId"] = ( - (PhysicsRemoteFPSAgentController)CurrentActiveController() - ).ObjectIdOfClosestReceptacleObject(); - action["randomSeed"] = int.Parse(splitcommand[1]); + CurrentActiveController().ProcessControlCommand(action); + break; + } - // set this to false if we want to place it and let physics resolve by having it fall a short distance into position + case "putr": + { + Dictionary action = new Dictionary(); + action["action"] = "PutObject"; + action["objectId"] = ( + (PhysicsRemoteFPSAgentController)CurrentActiveController() + ).ObjectIdOfClosestReceptacleObject(); + action["randomSeed"] = int.Parse(splitcommand[1]); - // set true to place with kinematic = true so that it doesn't fall or roll in place - making placement more consistant and not physics engine reliant - this more closely mimics legacy pivot placement behavior - action["placeStationary"] = false; + // set this to false if we want to place it and let physics resolve by having it fall a short distance into position - // set this true to ignore Placement Restrictions - action["forceAction"] = true; + // set true to place with kinematic = true so that it doesn't fall or roll in place - making placement more consistant and not physics engine reliant - this more closely mimics legacy pivot placement behavior + action["placeStationary"] = false; - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "put": { - Dictionary action = new Dictionary(); - action["action"] = "PutObject"; + // set this true to ignore Placement Restrictions + action["forceAction"] = true; - if (splitcommand.Length == 2) { - action["objectId"] = splitcommand[1]; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "put": + { + Dictionary action = new Dictionary(); + action["action"] = "PutObject"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length == 2) + { + action["objectId"] = splitcommand[1]; } - case "putxy": { - Dictionary action = new Dictionary(); - action["action"] = "PutObject"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length == 2) { - action["putNearXY"] = bool.Parse(splitcommand[1]); - } - // set true to place with kinematic = true so that it doesn't fall or roll in place - making placement more consistant and not physics engine reliant - this more closely mimics legacy pivot placement behavior - // action["placeStationary"] = true; - action["x"] = 0.5f; - action["y"] = 0.5f; - // set this true to ignore Placement Restrictions - // action["forceAction"] = true; + case "putxy": + { + Dictionary action = new Dictionary(); + action["action"] = "PutObject"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length == 2) + { + action["putNearXY"] = bool.Parse(splitcommand[1]); } + // set true to place with kinematic = true so that it doesn't fall or roll in place - making placement more consistant and not physics engine reliant - this more closely mimics legacy pivot placement behavior + // action["placeStationary"] = true; + action["x"] = 0.5f; + action["y"] = 0.5f; + // set this true to ignore Placement Restrictions + // action["forceAction"] = true; - case "goif": { - Dictionary action = new Dictionary(); - action["action"] = "GetObjectInFrame"; - action["x"] = 0.5f; - action["y"] = 0.5f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } + + case "goif": + { + Dictionary action = new Dictionary(); + action["action"] = "GetObjectInFrame"; + action["x"] = 0.5f; + action["y"] = 0.5f; + CurrentActiveController().ProcessControlCommand(action); + break; + } // put an object down with stationary false - case "putf": { - Dictionary action = new Dictionary(); - action["action"] = "PutObject"; - - if (splitcommand.Length == 2) { - action["objectId"] = splitcommand[1]; - } else { - action["objectId"] = PhysicsController.ObjectIdOfClosestReceptacleObject(); - } + case "putf": + { + Dictionary action = new Dictionary(); + action["action"] = "PutObject"; - // set this to false if we want to place it and let physics resolve by having it fall a short distance into position + if (splitcommand.Length == 2) + { + action["objectId"] = splitcommand[1]; + } + else + { + action["objectId"] = PhysicsController.ObjectIdOfClosestReceptacleObject(); + } - // set true to place with kinematic = true so that it doesn't fall or roll in place - making placement more consistant and not physics engine reliant - this more closely mimics legacy pivot placement behavior - action["placeStationary"] = false; + // set this to false if we want to place it and let physics resolve by having it fall a short distance into position - // set this true to ignore Placement Restrictions - action["forceAction"] = true; + // set true to place with kinematic = true so that it doesn't fall or roll in place - making placement more consistant and not physics engine reliant - this more closely mimics legacy pivot placement behavior + action["placeStationary"] = false; - CurrentActiveController().ProcessControlCommand(action); - break; - } + // set this true to ignore Placement Restrictions + action["forceAction"] = true; + + CurrentActiveController().ProcessControlCommand(action); + break; + } // make all pickupable objects kinematic false so that they will react to collisions. Otherwise, some objects might be defaulted to kinematic true, or // if they were placed with placeStationary true, then they will not interact with outside collisions immediately. - case "maom": { - Dictionary action = new Dictionary(); - action["action"] = "MakeAllObjectsMoveable"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "maom": + { + Dictionary action = new Dictionary(); + action["action"] = "MakeAllObjectsMoveable"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "echoes": { - Dictionary action = new Dictionary(); - action["action"] = "MakeAllObjectsStationary"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "echoes": + { + Dictionary action = new Dictionary(); + action["action"] = "MakeAllObjectsStationary"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "gip": { - Dictionary action = new Dictionary(); - action["action"] = "GetInteractablePoses"; - if (splitcommand.Length == 2) { - action["objectId"] = splitcommand[1].ToString(); - } else { - action["objectId"] = "Fridge|-02.10|+00.00|+01.07"; - } - CurrentActiveController().ProcessControlCommand(action); - break; + case "gip": + { + Dictionary action = new Dictionary(); + action["action"] = "GetInteractablePoses"; + if (splitcommand.Length == 2) + { + action["objectId"] = splitcommand[1].ToString(); + } + else + { + action["objectId"] = "Fridge|-02.10|+00.00|+01.07"; } + CurrentActiveController().ProcessControlCommand(action); + break; + } // tests the Reset function on AgentManager.cs, adding a path to it from the PhysicsController - case "reset": { - ServerAction action = new ServerAction(); - action.action = "Reset"; - ExecuteAction("Reset"); - break; - } + case "reset": + { + ServerAction action = new ServerAction(); + action.action = "Reset"; + ExecuteAction("Reset"); + break; + } - case "poap": { - Dictionary action = new Dictionary(); - action["action"] = "PlaceObjectAtPoint"; + case "poap": + { + Dictionary action = new Dictionary(); + action["action"] = "PlaceObjectAtPoint"; - BaseFPSAgentController agent = AManager.agents[0]; + BaseFPSAgentController agent = AManager.agents[0]; - GameObject itemInHand = AManager.agents[0].ItemInHand; - if (itemInHand != null) { - itemInHand.SetActive(false); - } + GameObject itemInHand = AManager.agents[0].ItemInHand; + if (itemInHand != null) + { + itemInHand.SetActive(false); + } - RaycastHit hit; - Ray ray = agent.m_Camera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0.0f)); - bool raycastDidHit = Physics.Raycast(ray, out hit, 10f, (1 << 8) | (1 << 10)); + RaycastHit hit; + Ray ray = agent.m_Camera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0.0f)); + bool raycastDidHit = Physics.Raycast(ray, out hit, 10f, (1 << 8) | (1 << 10)); - print("where did the ray land? " + hit.point); - if (itemInHand != null) { - itemInHand.SetActive(true); - } + print("where did the ray land? " + hit.point); + if (itemInHand != null) + { + itemInHand.SetActive(true); + } - if (raycastDidHit) { - SimObjPhysics sop = null; - if (itemInHand != null) { - sop = itemInHand.GetComponent(); - } else { - SimObjPhysics[] allSops = GameObject.FindObjectsOfType(); - sop = allSops[UnityEngine.Random.Range(0, allSops.Length)]; - } - // adding y offset to position so that the downward raycast used in PlaceObjectAtPoint correctly collides with surface below point - action["position"] = hit.point + new Vector3(0, 0.5f, 0); - action["objectId"] = sop.ObjectID; - - Debug.Log(action); - CurrentActiveController().ProcessControlCommand(action); - } else { - agent.actionFinished(false); + if (raycastDidHit) + { + SimObjPhysics sop = null; + if (itemInHand != null) + { + sop = itemInHand.GetComponent(); + } + else + { + SimObjPhysics[] allSops = GameObject.FindObjectsOfType(); + sop = allSops[UnityEngine.Random.Range(0, allSops.Length)]; } + // adding y offset to position so that the downward raycast used in PlaceObjectAtPoint correctly collides with surface below point + action["position"] = hit.point + new Vector3(0, 0.5f, 0); + action["objectId"] = sop.ObjectID; - break; + Debug.Log(action); + CurrentActiveController().ProcessControlCommand(action); } + else + { + agent.actionFinished(false); + } + + break; + } // set forceVisible to true if you want objects to not spawn inside receptacles and only out in the open // set forceAction to true to spawn with kinematic = true to more closely resemble pivot functionality - case "irs": { - Dictionary action = new Dictionary(); - action["action"] = "InitialRandomSpawn"; + case "irs": + { + Dictionary action = new Dictionary(); + action["action"] = "InitialRandomSpawn"; + + // List excludedObjectIds = new List(); + // foreach (SimObjPhysics sop in AManager.agents[0].VisibleSimObjs(false)) { + // excludedObjectIds.Add(sop.ObjectID); + // } + // action["excludedObjectIds"] = excludedObjectIds.ToArray(); + + // give me a seed + if (splitcommand.Length == 2) + { + action["randomSeed"] = int.Parse(splitcommand[1]); + 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]); - // List excludedObjectIds = new List(); - // foreach (SimObjPhysics sop in AManager.agents[0].VisibleSimObjs(false)) { - // excludedObjectIds.Add(sop.ObjectID); - // } - // action["excludedObjectIds"] = excludedObjectIds.ToArray(); + if (splitcommand[2] == "t") + { + action["forceVisible"] = true; + } - // give me a seed - if (splitcommand.Length == 2) { - action["randomSeed"] = int.Parse(splitcommand[1]); + if (splitcommand[2] == "f") + { 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]); - - if (splitcommand[2] == "t") { - action["forceVisible"] = true; - } - - if (splitcommand[2] == "f") { - action["forceVisible"] = false; - } - } else if (splitcommand.Length == 4) { - action["randomSeed"] = int.Parse(splitcommand[1]); - - if (splitcommand[2] == "t") { - action["forceVisible"] = true; - } - - if (splitcommand[2] == "f") { - action["forceVisible"] = false; - } + } + else if (splitcommand.Length == 4) + { + action["randomSeed"] = int.Parse(splitcommand[1]); - action["numPlacementAttempts"] = int.Parse(splitcommand[3]); - } else { - action["randomSeed"] = 0; - action["forceVisible"] = false; // true; - action["numPlacementAttempts"] = 20; + if (splitcommand[2] == "t") + { + action["forceVisible"] = true; } - // ObjectTypeCount otc = new ObjectTypeCount(); - // otc.objectType = "Mug"; - // otc.count = 20; - // ObjectTypeCount[] count = new ObjectTypeCount[1]; - // count[0] = otc; - // action.numDuplicatesOfType = count; + if (splitcommand[2] == "f") + { + action["forceVisible"] = false; + } - String[] excludeThese = new String[1]; - excludeThese[0] = "CounterTop"; - action["excludedReceptacles"] = excludeThese; + action["numPlacementAttempts"] = int.Parse(splitcommand[3]); + } + else + { + action["randomSeed"] = 0; + action["forceVisible"] = false; // true; + action["numPlacementAttempts"] = 20; + } - 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); + // ObjectTypeCount otc = new ObjectTypeCount(); + // otc.objectType = "Mug"; + // otc.count = 20; + // ObjectTypeCount[] count = new ObjectTypeCount[1]; + // count[0] = otc; + // action.numDuplicatesOfType = count; - break; - } - case "spawn": { - ServerAction action = new ServerAction(); - // Debug.Log(action.objectVariation); - int objectVariation = 0; - if (splitcommand.Length == 2) { - action.objectType = splitcommand[1]; - } else if (splitcommand.Length == 3) { - action.objectType = splitcommand[1]; - objectVariation = int.Parse(splitcommand[2]); - } else { - 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) + String[] excludeThese = new String[1]; + excludeThese[0] = "CounterTop"; + action["excludedReceptacles"] = excludeThese; - CurrentActiveController().ProcessControlCommand(action); + 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; + break; + } + case "spawn": + { + ServerAction action = new ServerAction(); + // Debug.Log(action.objectVariation); + int objectVariation = 0; + if (splitcommand.Length == 2) + { + action.objectType = splitcommand[1]; } - - case "neutral": { - ExecuteAction("ChangeAgentFaceToNeutral"); - break; + else if (splitcommand.Length == 3) + { + action.objectType = splitcommand[1]; + objectVariation = int.Parse(splitcommand[2]); } - case "happy": { - ExecuteAction("ChangeAgentFaceToHappy"); - break; + else + { + 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) - case "mad": { - ExecuteAction("ChangeAgentFaceToMad"); - break; - } + CurrentActiveController().ProcessControlCommand(action); - case "supermad": { - ExecuteAction("ChangeAgentFaceToSuperMad"); - break; - } + break; + } - case "ruaa": { - ServerAction action = new ServerAction(); - action.action = "RotateUniverseAroundAgent"; + case "neutral": + { + ExecuteAction("ChangeAgentFaceToNeutral"); + break; + } + case "happy": + { + ExecuteAction("ChangeAgentFaceToHappy"); + break; + } - action.rotation = new Vector3(0f, float.Parse(splitcommand[1]), 0f); - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "thas": { - Dictionary action = new Dictionary(); - action["action"] = "ToggleHideAndSeekObjects"; + case "mad": + { + ExecuteAction("ChangeAgentFaceToMad"); + break; + } - if (splitcommand.Length == 2) { - if (splitcommand[1] == "t") { - action["forceVisible"] = true; - } + case "supermad": + { + ExecuteAction("ChangeAgentFaceToSuperMad"); + break; + } - if (splitcommand[1] == "f") { - action["forceVisible"] = false; - } - } else { - action["forceVisible"] = false; + case "ruaa": + { + ServerAction action = new ServerAction(); + action.action = "RotateUniverseAroundAgent"; + + action.rotation = new Vector3(0f, float.Parse(splitcommand[1]), 0f); + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "thas": + { + Dictionary action = new Dictionary(); + action["action"] = "ToggleHideAndSeekObjects"; + + if (splitcommand.Length == 2) + { + if (splitcommand[1] == "t") + { + action["forceVisible"] = true; } - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand[1] == "f") + { + action["forceVisible"] = false; + } + } + else + { + action["forceVisible"] = false; } - case "spawnat": { - ServerAction action = new ServerAction(); - - 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.rotation? - } - // default to zeroed out rotation tomato - else { - action.objectType = "Tomato"; // default to spawn debug tomato - action.position = Vector3.zero; - action.rotation = Vector3.zero; - } - action.action = "CreateObjectAtLocation"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - 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) + case "spawnat": + { + ServerAction action = new ServerAction(); - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "grpfo": { - ServerAction action = new ServerAction(); - action.action = "GetReachablePositionsForObject"; - action.objectId = splitcommand[1]; - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "rspawnlifted": { - ServerAction action = new ServerAction(); - action.action = "RandomlyCreateLiftedFurniture"; - action.objectType = "Television"; - action.objectVariation = 1; - action.y = 1.3f; - action.z = 1; - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "rspawnfloor": { - Dictionary action = new Dictionary(); - action["action"] = "RandomlyCreateAndPlaceObjectOnFloor"; - action["objectType"] = splitcommand[1]; - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "spawnfloor": { - ServerAction action = new ServerAction(); - int objectVariation = 1; + if (splitcommand.Length > 1) + { action.objectType = splitcommand[1]; - action.x = float.Parse(splitcommand[2]); - action.z = float.Parse(splitcommand[3]); - - action.action = "CreateObjectOnFloor"; - action.objectVariation = objectVariation; - CurrentActiveController().ProcessControlCommand(action); - break; + 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? } - case "gusfo": { - Dictionary action = new Dictionary(); - action["action"] = "GetUnreachableSilhouetteForObject"; - action["objectId"] = splitcommand[1]; - action["z"] = float.Parse(splitcommand[2]); - CurrentActiveController().ProcessControlCommand(action); - break; + // default to zeroed out rotation tomato + else + { + action.objectType = "Tomato"; // default to spawn debug tomato + action.position = Vector3.zero; + action.rotation = Vector3.zero; } + action.action = "CreateObjectAtLocation"; - case "rhs": { - Dictionary action = new Dictionary(); - action["action"] = "RandomizeHideSeekObjects"; - action["removeProb"] = float.Parse(splitcommand[1]); - action["randomSeed"] = int.Parse(splitcommand[2]); - CurrentActiveController().ProcessControlCommand(action); - break; - } + 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) - case "cts": { - ServerAction action = new ServerAction(); - action.action = "ChangeTimeScale"; - action.timeScale = float.Parse(splitcommand[1]); - CurrentActiveController().ProcessControlCommand(action); + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "grpfo": + { + ServerAction action = new ServerAction(); + action.action = "GetReachablePositionsForObject"; + action.objectId = splitcommand[1]; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "rspawnlifted": + { + ServerAction action = new ServerAction(); + action.action = "RandomlyCreateLiftedFurniture"; + action.objectType = "Television"; + action.objectVariation = 1; + action.y = 1.3f; + action.z = 1; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "rspawnfloor": + { + Dictionary action = new Dictionary(); + action["action"] = "RandomlyCreateAndPlaceObjectOnFloor"; + action["objectType"] = splitcommand[1]; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "spawnfloor": + { + ServerAction action = new ServerAction(); + int objectVariation = 1; + action.objectType = splitcommand[1]; + action.x = float.Parse(splitcommand[2]); + action.z = float.Parse(splitcommand[3]); + + action.action = "CreateObjectOnFloor"; + action.objectVariation = objectVariation; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "gusfo": + { + Dictionary action = new Dictionary(); + action["action"] = "GetUnreachableSilhouetteForObject"; + action["objectId"] = splitcommand[1]; + action["z"] = float.Parse(splitcommand[2]); + CurrentActiveController().ProcessControlCommand(action); + break; + } - // NOTE: reachablePositions has been removed as a public variable - // Debug.Log(PhysicsController.reachablePositions.Length); + case "rhs": + { + Dictionary action = new Dictionary(); + action["action"] = "RandomizeHideSeekObjects"; + action["removeProb"] = float.Parse(splitcommand[1]); + action["randomSeed"] = int.Parse(splitcommand[2]); + CurrentActiveController().ProcessControlCommand(action); + break; + } - break; - } + case "cts": + { + ServerAction action = new ServerAction(); + action.action = "ChangeTimeScale"; + action.timeScale = float.Parse(splitcommand[1]); + CurrentActiveController().ProcessControlCommand(action); - case "grp": { - Dictionary action = new Dictionary(); - action["action"] = "GetReachablePositions"; - // action.maxStepCount = 10; - if (splitcommand.Length == 2) { - action["directionsRelativeAgent"] = bool.Parse(splitcommand[1]); - } - CurrentActiveController().ProcessControlCommand(action); + // NOTE: reachablePositions has been removed as a public variable + // Debug.Log(PhysicsController.reachablePositions.Length); - // NOTE: reachablePositions has been removed as a public variable - // Debug.Log(PhysicsController.reachablePositions.Length); + break; + } - break; + case "grp": + { + Dictionary action = new Dictionary(); + action["action"] = "GetReachablePositions"; + // action.maxStepCount = 10; + if (splitcommand.Length == 2) + { + action["directionsRelativeAgent"] = bool.Parse(splitcommand[1]); } + CurrentActiveController().ProcessControlCommand(action); - case "grpb": { - Dictionary action = new Dictionary(); - action["action"] = "GetReachablePositions"; - // action.maxStepCount = 10; - CurrentActiveController().ProcessControlCommand(action); + // NOTE: reachablePositions has been removed as a public variable + // Debug.Log(PhysicsController.reachablePositions.Length); - // NOTE: reachablePositions has been removed as a public variable - // Debug.Log("stochastic grp " + StochasticController.reachablePositions.Length); + break; + } - break; - } + case "grpb": + { + Dictionary action = new Dictionary(); + action["action"] = "GetReachablePositions"; + // action.maxStepCount = 10; + CurrentActiveController().ProcessControlCommand(action); - case "csw": { - ServerAction action = new ServerAction(); - action.action = "CoverSurfacesWith"; - // int objectVariation = 1; - // action.objectVariation = objectVariation; + // NOTE: reachablePositions has been removed as a public variable + // Debug.Log("stochastic grp " + StochasticController.reachablePositions.Length); - if (splitcommand.Length == 2) { - action.objectType = splitcommand[1]; - } else if (splitcommand.Length == 3) { - action.objectType = splitcommand[1]; - action.objectVariation = int.Parse(splitcommand[2]); - } else { - action.objectType = "Tomato"; // default to spawn debug tomato - } - action.x = 0.3f; - action.z = 0.3f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + break; + } - case "fov": { - Dictionary comm = new Dictionary(); - comm["action"] = "ChangeFOV"; - comm["fieldOfView"] = float.Parse(splitcommand[1]); - if (splitcommand.Length > 2) { - comm["camera"] = splitcommand[2]; - } + case "csw": + { + ServerAction action = new ServerAction(); + action.action = "CoverSurfacesWith"; + // int objectVariation = 1; + // action.objectVariation = objectVariation; - CurrentActiveController().ProcessControlCommand(comm); - break; + if (splitcommand.Length == 2) + { + action.objectType = splitcommand[1]; } - case "teles": { - ServerAction action = new ServerAction(); - action.action = "TeleportFull"; - action.x = 4.42f; - action.y = 0.9009f; - action.z = -1.05f; - CurrentActiveController().ProcessControlCommand(action); - break; + else if (splitcommand.Length == 3) + { + action.objectType = splitcommand[1]; + action.objectVariation = int.Parse(splitcommand[2]); } - - case "map": { - ExecuteAction("ToggleMapView"); - break; + else + { + action.objectType = "Tomato"; // default to spawn debug tomato } - case "nopfwoiv": { - ServerAction action = new ServerAction(); - action.action = "NumberOfPositionsObjectsOfTypeAreVisibleFrom"; - action.objectType = splitcommand[1]; - CurrentActiveController().ProcessControlCommand(action); - break; + action.x = 0.3f; + action.z = 0.3f; + CurrentActiveController().ProcessControlCommand(action); + break; + } + + case "fov": + { + Dictionary comm = new Dictionary(); + comm["action"] = "ChangeFOV"; + comm["fieldOfView"] = float.Parse(splitcommand[1]); + if (splitcommand.Length > 2) + { + comm["camera"] = splitcommand[2]; } + CurrentActiveController().ProcessControlCommand(comm); + break; + } + case "teles": + { + ServerAction action = new ServerAction(); + action.action = "TeleportFull"; + action.x = 4.42f; + action.y = 0.9009f; + action.z = -1.05f; + CurrentActiveController().ProcessControlCommand(action); + break; + } + + case "map": + { + ExecuteAction("ToggleMapView"); + break; + } + case "nopfwoiv": + { + ServerAction action = new ServerAction(); + action.action = "NumberOfPositionsObjectsOfTypeAreVisibleFrom"; + action.objectType = splitcommand[1]; + CurrentActiveController().ProcessControlCommand(action); + break; + } + // Close visible objects - case "cvo": { - ExecuteAction("CloseVisibleObjects"); - break; - } + case "cvo": + { + ExecuteAction("CloseVisibleObjects"); + break; + } // Force open object at location - case "oal": { - ServerAction action = new ServerAction(); - action.action = "OpenObjectAtLocation"; - action.x = float.Parse(splitcommand[1]); - action.y = float.Parse(splitcommand[2]); - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "oal": + { + ServerAction action = new ServerAction(); + action.action = "OpenObjectAtLocation"; + action.x = float.Parse(splitcommand[1]); + action.y = float.Parse(splitcommand[2]); + CurrentActiveController().ProcessControlCommand(action); + break; + } // Get objects in box - case "oib": { - Dictionary action = new Dictionary(); - action["action"] = "ObjectsInBox"; - action["x"] = float.Parse(splitcommand[1]); - action["z"] = float.Parse(splitcommand[2]); - CurrentActiveController().ProcessControlCommand(action); - foreach (string s in PhysicsController.objectIdsInBox) { - Debug.Log(s); - } - break; + case "oib": + { + Dictionary action = new Dictionary(); + action["action"] = "ObjectsInBox"; + action["x"] = float.Parse(splitcommand[1]); + action["z"] = float.Parse(splitcommand[2]); + CurrentActiveController().ProcessControlCommand(action); + foreach (string s in PhysicsController.objectIdsInBox) + { + Debug.Log(s); } + break; + } // move ahead - case "mg": { - Dictionary action = new Dictionary(); - action["action"] = "MoveGlobal"; - action["x"] = float.Parse(splitcommand[1]); - action["z"] = float.Parse(splitcommand[2]); - - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "mg": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveGlobal"; + action["x"] = float.Parse(splitcommand[1]); + action["z"] = float.Parse(splitcommand[2]); + + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "move": { - Dictionary action = new Dictionary() { - ["action"] = "Move", - ["ahead"] = 0.25f - }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "move": + { + Dictionary action = new Dictionary() + { + ["action"] = "Move", + ["ahead"] = 0.25f + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "rotate": { - Dictionary action = new Dictionary() { - ["action"] = "Rotate", - ["degrees"] = 90 - }; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "rotate": + { + Dictionary action = new Dictionary() + { + ["action"] = "Rotate", + ["degrees"] = 90 + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "stretchmovebaseup": { - Dictionary action = new Dictionary(); - action["action"] = "MoveArmBaseUp"; - action["distance"] = 0.05f; - action["speed"] = 5.0f; - action["disableRendering"] = false; + case "stretchmovebaseup": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveArmBaseUp"; + action["distance"] = 0.05f; + action["speed"] = 5.0f; + action["disableRendering"] = false; - //action["fixedDeltaTime"] = 5.0f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + //action["fixedDeltaTime"] = 5.0f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "stretchmovebasedown": { - Dictionary action = new Dictionary(); - action["action"] = "MoveArmBaseUp"; - action["distance"] = -0.05f; - action["speed"] = 5.0f; - action["disableRendering"] = false; + case "stretchmovebasedown": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveArmBaseUp"; + action["distance"] = -0.05f; + action["speed"] = 5.0f; + action["disableRendering"] = false; - //action["fixedDeltaTime"] = 5.0f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + //action["fixedDeltaTime"] = 5.0f; + CurrentActiveController().ProcessControlCommand(action); + break; + } // move ahead - case "ma": { - Dictionary action = new Dictionary(); - action["action"] = "MoveAhead"; - action["speed"] = 0.14f; - action["acceleration"] = 0.14f; - - if (splitcommand.Length > 1) { - action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { - action["moveMagnitude"] = 0.25f; - } - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "ma": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveAhead"; + action["speed"] = 0.14f; + action["acceleration"] = 0.14f; + + if (splitcommand.Length > 1) + { + action["moveMagnitude"] = float.Parse(splitcommand[1]); + } + else + { + action["moveMagnitude"] = 0.25f; + } + CurrentActiveController().ProcessControlCommand(action); + break; + } // move backward - case "mb": { - Dictionary action = new Dictionary(); - action["action"] = "MoveBack"; - action["speed"] = 0.14f; - action["acceleration"] = 0.14f; - - if (splitcommand.Length > 1) { - action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { - action["moveMagnitude"] = 0.25f; - } - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "mb": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveBack"; + action["speed"] = 0.14f; + action["acceleration"] = 0.14f; + + if (splitcommand.Length > 1) + { + action["moveMagnitude"] = float.Parse(splitcommand[1]); + } + else + { + action["moveMagnitude"] = 0.25f; + } + CurrentActiveController().ProcessControlCommand(action); + break; + } // move left - case "ml": { - Dictionary action = new Dictionary(); - action["action"] = "MoveLeft"; - - if (splitcommand.Length > 1) { - action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { - action["moveMagnitude"] = 0.25f; - } - CurrentActiveController().ProcessControlCommand(action); - break; + case "ml": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveLeft"; + + if (splitcommand.Length > 1) + { + action["moveMagnitude"] = float.Parse(splitcommand[1]); + } + else + { + action["moveMagnitude"] = 0.25f; } + CurrentActiveController().ProcessControlCommand(action); + break; + } // move right - case "mr": { - Dictionary action = new Dictionary(); - action["action"] = "MoveRight"; - - if (splitcommand.Length > 1) { - action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { - action["moveMagnitude"] = 0.25f; - } - CurrentActiveController().ProcessControlCommand(action); - break; + case "mr": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveRight"; + + if (splitcommand.Length > 1) + { + action["moveMagnitude"] = float.Parse(splitcommand[1]); } + else + { + action["moveMagnitude"] = 0.25f; + } + CurrentActiveController().ProcessControlCommand(action); + break; + } // move ahead, force action true - case "maf": { - ServerAction action = new ServerAction(); - action.action = "MoveAhead"; - - if (splitcommand.Length > 1) { - action.moveMagnitude = float.Parse(splitcommand[1]); - } else { - action.moveMagnitude = 0.25f; - } + case "maf": + { + ServerAction action = new ServerAction(); + action.action = "MoveAhead"; - action.forceAction = true; + if (splitcommand.Length > 1) + { + action.moveMagnitude = float.Parse(splitcommand[1]); + } + else + { + action.moveMagnitude = 0.25f; + } - CurrentActiveController().ProcessControlCommand(action); + action.forceAction = true; - break; - } + CurrentActiveController().ProcessControlCommand(action); - // move backward, force action true - case "mbf": { - ServerAction action = new ServerAction(); - action.action = "MoveBack"; - - if (splitcommand.Length > 1) { - action.moveMagnitude = float.Parse(splitcommand[1]); - } else { - action.moveMagnitude = 0.25f; - } + break; + } - action.forceAction = true; + // move backward, force action true + case "mbf": + { + ServerAction action = new ServerAction(); + action.action = "MoveBack"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.moveMagnitude = float.Parse(splitcommand[1]); + } + else + { + action.moveMagnitude = 0.25f; } - // move left, force action true - case "mlf": { - ServerAction action = new ServerAction(); - action.action = "MoveLeft"; - - if (splitcommand.Length > 1) { - action.moveMagnitude = float.Parse(splitcommand[1]); - } else { - action.moveMagnitude = 0.25f; - } + action.forceAction = true; - action.forceAction = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } - CurrentActiveController().ProcessControlCommand(action); - break; + // move left, force action true + case "mlf": + { + ServerAction action = new ServerAction(); + action.action = "MoveLeft"; + + if (splitcommand.Length > 1) + { + action.moveMagnitude = float.Parse(splitcommand[1]); + } + else + { + action.moveMagnitude = 0.25f; } - // move right, force action true - case "mrf": { - ServerAction action = new ServerAction(); - action.action = "MoveRight"; - - if (splitcommand.Length > 1) { - action.moveMagnitude = float.Parse(splitcommand[1]); - } else { - action.moveMagnitude = 0.25f; - } + action.forceAction = true; - action.forceAction = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } - CurrentActiveController().ProcessControlCommand(action); - break; - } + // move right, force action true + case "mrf": + { + ServerAction action = new ServerAction(); + action.action = "MoveRight"; - case "fu": { - Dictionary action = new Dictionary(); - action["action"] = "FlyUp"; - action["moveMagnitude"] = 2f; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.moveMagnitude = float.Parse(splitcommand[1]); } - - case "fd": { - Dictionary action = new Dictionary(); - action["action"] = "FlyDown"; - action["moveMagnitude"] = 2f; - CurrentActiveController().ProcessControlCommand(action); - break; + else + { + action.moveMagnitude = 0.25f; } - case "fa": { - Dictionary action = new Dictionary(); - action["action"] = "FlyAhead"; - action["moveMagnitude"] = 2f; + action.forceAction = true; - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "fl": { - Dictionary action = new Dictionary(); - action["action"] = "FlyLeft"; - action["moveMagnitude"] = 2f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "fr": { - Dictionary action = new Dictionary(); - action["action"] = "FlyRight"; - action["moveMagnitude"] = 2f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "fu": + { + Dictionary action = new Dictionary(); + action["action"] = "FlyUp"; + action["moveMagnitude"] = 2f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "fb": { - Dictionary action = new Dictionary(); - action["action"] = "FlyBack"; - action["moveMagnitude"] = 2f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "fd": + { + Dictionary action = new Dictionary(); + action["action"] = "FlyDown"; + action["moveMagnitude"] = 2f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "ll": { - Dictionary action = new Dictionary(); - action["action"] = "LookLeft"; + case "fa": + { + Dictionary action = new Dictionary(); + action["action"] = "FlyAhead"; + action["moveMagnitude"] = 2f; - if (splitcommand.Length > 1) { - action["degrees"] = float.Parse(splitcommand[1]); - } + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "fl": + { + Dictionary action = new Dictionary(); + action["action"] = "FlyLeft"; + action["moveMagnitude"] = 2f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - // action.manualInteract = true; - CurrentActiveController().ProcessControlCommand(action); - break; + case "fr": + { + Dictionary action = new Dictionary(); + action["action"] = "FlyRight"; + action["moveMagnitude"] = 2f; + CurrentActiveController().ProcessControlCommand(action); + break; + } + + case "fb": + { + Dictionary action = new Dictionary(); + action["action"] = "FlyBack"; + action["moveMagnitude"] = 2f; + CurrentActiveController().ProcessControlCommand(action); + break; + } + + case "ll": + { + Dictionary action = new Dictionary(); + action["action"] = "LookLeft"; + + if (splitcommand.Length > 1) + { + action["degrees"] = float.Parse(splitcommand[1]); } - // look up - case "lu": { - Dictionary action = new Dictionary(); - action["action"] = "LookUp"; + // action.manualInteract = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action["degrees"] = float.Parse(splitcommand[1]); - } + // look up + case "lu": + { + Dictionary action = new Dictionary(); + action["action"] = "LookUp"; - // action.manualInteract = true; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action["degrees"] = float.Parse(splitcommand[1]); } - // stochastic look up - case "lus": { - ServerAction action = new ServerAction(); - action.action = "LookUp"; + // action.manualInteract = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action.degrees = float.Parse(splitcommand[1]); - } + // stochastic look up + case "lus": + { + ServerAction action = new ServerAction(); + action.action = "LookUp"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.degrees = float.Parse(splitcommand[1]); } - // look down - case "ld": { - ServerAction action = new ServerAction(); - action.action = "LookDown"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action.degrees = float.Parse(splitcommand[1]); - } + // look down + case "ld": + { + ServerAction action = new ServerAction(); + action.action = "LookDown"; - // action.manualInteract = true; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.degrees = float.Parse(splitcommand[1]); } - // stochastic look down - case "lds": { - ServerAction action = new ServerAction(); - action.action = "LookDown"; + // action.manualInteract = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action.degrees = float.Parse(splitcommand[1]); - } + // stochastic look down + case "lds": + { + ServerAction action = new ServerAction(); + action.action = "LookDown"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.degrees = float.Parse(splitcommand[1]); } - // rotate left - case "rl": { - Dictionary action = new Dictionary(); - action["action"] = "RotateLeft"; - action["speed"] = 22.5f; - action["acceleration"] = 22.5f; - - if (splitcommand.Length > 1) { - action["degrees"] = float.Parse(splitcommand[1]); - } + CurrentActiveController().ProcessControlCommand(action); + break; + } - // action.manualInteract = true; - CurrentActiveController().ProcessControlCommand(action); - break; + // rotate left + case "rl": + { + Dictionary action = new Dictionary(); + action["action"] = "RotateLeft"; + action["speed"] = 22.5f; + action["acceleration"] = 22.5f; + + if (splitcommand.Length > 1) + { + action["degrees"] = float.Parse(splitcommand[1]); } - // rotate left stochastic - case "rls": { - ServerAction action = new ServerAction(); - action.action = "RotateLeft"; + // action.manualInteract = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action.degrees = float.Parse(splitcommand[1]); - } + // rotate left stochastic + case "rls": + { + ServerAction action = new ServerAction(); + action.action = "RotateLeft"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.degrees = float.Parse(splitcommand[1]); } - // rotate right - case "rr": { - Dictionary action = new Dictionary(); - action["action"] = "RotateRight"; - action["speed"] = 22.5f; - action["acceleration"] = 22.5f; - - if (splitcommand.Length > 1) { - action["degrees"] = float.Parse(splitcommand[1]); - } + CurrentActiveController().ProcessControlCommand(action); + break; + } - // action.manualInteract = true; - CurrentActiveController().ProcessControlCommand(action); - break; + // rotate right + case "rr": + { + Dictionary action = new Dictionary(); + action["action"] = "RotateRight"; + action["speed"] = 22.5f; + action["acceleration"] = 22.5f; + + if (splitcommand.Length > 1) + { + action["degrees"] = float.Parse(splitcommand[1]); } - // rotate right stochastic - case "rrs": { - ServerAction action = new ServerAction(); - action.action = "RotateRight"; + // action.manualInteract = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action.degrees = float.Parse(splitcommand[1]); - } + // rotate right stochastic + case "rrs": + { + ServerAction action = new ServerAction(); + action.action = "RotateRight"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.degrees = float.Parse(splitcommand[1]); } - // rotate wrist absolute - case "rw": { - Dictionary action = new Dictionary(); - action["action"] = "RotateWrist"; - action["disableRendering"] = false; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action["yaw"] = float.Parse(splitcommand[1]); - } + // rotate wrist absolute + case "rw": + { + Dictionary action = new Dictionary(); + action["action"] = "RotateWrist"; + action["disableRendering"] = false; - // action.manualInteract = true; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action["yaw"] = float.Parse(splitcommand[1]); } + // action.manualInteract = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } + // pickup object - case "pu": { - Dictionary action = new Dictionary(); - action["action"] = "PickupObject"; - if (splitcommand.Length > 1) { - action["objectId"] = splitcommand[1]; - } - CurrentActiveController().ProcessControlCommand(action); - break; + case "pu": + { + Dictionary action = new Dictionary(); + action["action"] = "PickupObject"; + if (splitcommand.Length > 1) + { + action["objectId"] = splitcommand[1]; } + CurrentActiveController().ProcessControlCommand(action); + break; + } // Force pickup object - case "fpu": { - Dictionary action = new Dictionary(); - action["action"] = "PickupObject"; - if (splitcommand.Length > 1) { - action["objectId"] = splitcommand[1]; - } - action["forceAction"] = true; - CurrentActiveController().ProcessControlCommand(action); - break; + case "fpu": + { + Dictionary action = new Dictionary(); + action["action"] = "PickupObject"; + if (splitcommand.Length > 1) + { + action["objectId"] = splitcommand[1]; } + action["forceAction"] = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } // pickup using screen coordinates - case "puxy": { - Dictionary action = new Dictionary(); - action["action"] = "PickupObject"; - // action.forceAction = true; - action["x"] = 0.5f; - action["y"] = 0.5f; - CurrentActiveController().ProcessControlCommand(action); - break; - } - - case "slice": { - ServerAction action = new ServerAction(); - action.action = "SliceObject"; - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } - action.x = 0.5f; - action.y = 0.5f; - CurrentActiveController().ProcessControlCommand(action); - break; - } - - case "break": { - ServerAction action = new ServerAction(); - action.action = "BreakObject"; - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } - action.x = 0.5f; - action.y = 0.5f; + case "puxy": + { + Dictionary action = new Dictionary(); + action["action"] = "PickupObject"; + // action.forceAction = true; + action["x"] = 0.5f; + action["y"] = 0.5f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - CurrentActiveController().ProcessControlCommand(action); - break; + case "slice": + { + ServerAction action = new ServerAction(); + action.action = "SliceObject"; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; } + action.x = 0.5f; + action.y = 0.5f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "dirtyobject": { - ServerAction action = new ServerAction(); - action.action = "DirtyObject"; - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } - action.x = 0.5f; - action.y = 0.5f; - CurrentActiveController().ProcessControlCommand(action); - break; + case "break": + { + ServerAction action = new ServerAction(); + action.action = "BreakObject"; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; } - case "dirtyrec": { - Dictionary action = new Dictionary(); - action["action"] = "MakeReceptacleDirty"; - action["density"] = 0.1f; - action["scale"] = new Vector3(0.3f, 0.3f, 0.2f); - if (splitcommand.Length > 1) { - action["objectId"] = splitcommand[1]; - } - if (splitcommand.Length > 2) { - action["density"] = float.Parse(splitcommand[1]); - } + action.x = 0.5f; + action.y = 0.5f; - CurrentActiveController().ProcessControlCommand(action); - break; + CurrentActiveController().ProcessControlCommand(action); + break; + } + + case "dirtyobject": + { + ServerAction action = new ServerAction(); + action.action = "DirtyObject"; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; + } + action.x = 0.5f; + action.y = 0.5f; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "dirtyrec": + { + Dictionary action = new Dictionary(); + action["action"] = "MakeReceptacleDirty"; + action["density"] = 0.1f; + action["scale"] = new Vector3(0.3f, 0.3f, 0.2f); + if (splitcommand.Length > 1) + { + action["objectId"] = splitcommand[1]; + } + if (splitcommand.Length > 2) + { + action["density"] = float.Parse(splitcommand[1]); } - case "cleanobject": { - ServerAction action = new ServerAction(); - action.action = "CleanObject"; - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } else { - action.objectId = closestVisibleObjectId(); - } - CurrentActiveController().ProcessControlCommand(action); - break; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "cleanobject": + { + ServerAction action = new ServerAction(); + action.action = "CleanObject"; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; + } + else + { + action.objectId = closestVisibleObjectId(); } - case "fillwater": { - ServerAction action = new ServerAction(); - action.action = "FillObjectWithLiquid"; - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } else { - action.objectId = closestVisibleObjectId(); - } + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.fillLiquid = "water"; - CurrentActiveController().ProcessControlCommand(action); - break; + case "fillwater": + { + ServerAction action = new ServerAction(); + action.action = "FillObjectWithLiquid"; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; + } + else + { + action.objectId = closestVisibleObjectId(); } - case "fillcoffee": { - ServerAction action = new ServerAction(); - action.action = "FillObjectWithLiquid"; - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } else { - action.objectId = closestVisibleObjectId(); - } + action.fillLiquid = "water"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.fillLiquid = "coffee"; - CurrentActiveController().ProcessControlCommand(action); - break; + case "fillcoffee": + { + ServerAction action = new ServerAction(); + action.action = "FillObjectWithLiquid"; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; } - - // map view props - case "mvp": { - var action = new Dictionary() { - ["action"] = "GetMapViewCameraProperties" - }; - CurrentActiveController().ProcessControlCommand(action); - break; + else + { + action.objectId = closestVisibleObjectId(); } - case "fillwine": { - ServerAction action = new ServerAction(); - action.action = "FillObjectWithLiquid"; - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } else { - action.objectId = closestVisibleObjectId(); - } + action.fillLiquid = "coffee"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.fillLiquid = "wine"; - CurrentActiveController().ProcessControlCommand(action); - break; + // map view props + case "mvp": + { + var action = new Dictionary() + { + ["action"] = "GetMapViewCameraProperties" + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } + + case "fillwine": + { + ServerAction action = new ServerAction(); + action.action = "FillObjectWithLiquid"; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; + } + else + { + action.objectId = closestVisibleObjectId(); } - case "emptyliquid": { - ServerAction action = new ServerAction(); - action.action = "EmptyLiquidFromObject"; - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } else { - action.objectId = closestVisibleObjectId(); - } - CurrentActiveController().ProcessControlCommand(action); - break; + action.fillLiquid = "wine"; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "emptyliquid": + { + ServerAction action = new ServerAction(); + action.action = "EmptyLiquidFromObject"; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; + } + else + { + action.objectId = closestVisibleObjectId(); } - case "useup": { - ServerAction action = new ServerAction(); - action.action = "UseUpObject"; - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.x = 0.5f; - action.y = 0.5f; - CurrentActiveController().ProcessControlCommand(action); - break; + case "useup": + { + ServerAction action = new ServerAction(); + action.action = "UseUpObject"; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; } + action.x = 0.5f; + action.y = 0.5f; + CurrentActiveController().ProcessControlCommand(action); + break; + } + // drop object - case "dr": { - Dictionary action = new Dictionary(); - action["action"] = "DropHeldObject"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "dr": + { + Dictionary action = new Dictionary(); + action["action"] = "DropHeldObject"; + CurrentActiveController().ProcessControlCommand(action); + break; + } // force drop object - case "fdr": { - ServerAction action = new ServerAction(); - action.action = "DropHandObject"; - action.forceAction = true; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "fdr": + { + ServerAction action = new ServerAction(); + action.action = "DropHandObject"; + action.forceAction = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } // rotate object in hand, pass in desired x/y/z rotation - case "ro": { - ServerAction action = new ServerAction(); - action.action = "RotateHand"; - if (splitcommand.Length > 1) { - action.x = float.Parse(splitcommand[1]); - action.y = float.Parse(splitcommand[2]); - action.z = float.Parse(splitcommand[3]); - CurrentActiveController().ProcessControlCommand(action); - } - - break; + case "ro": + { + ServerAction action = new ServerAction(); + action.action = "RotateHand"; + if (splitcommand.Length > 1) + { + action.x = float.Parse(splitcommand[1]); + action.y = float.Parse(splitcommand[2]); + action.z = float.Parse(splitcommand[3]); + CurrentActiveController().ProcessControlCommand(action); } - case "ror": { - ServerAction action = new ServerAction(); - action.action = "RotateHandRelative"; - if (splitcommand.Length > 1) { - action.x = float.Parse(splitcommand[1]); - action.y = float.Parse(splitcommand[2]); - action.z = float.Parse(splitcommand[3]); - CurrentActiveController().ProcessControlCommand(action); - } - - break; - } + break; + } - // default the Hand's position and rotation to the starting position and rotation - case "dh": { - ServerAction action = new ServerAction(); - action.action = "DefaultAgentHand"; + case "ror": + { + ServerAction action = new ServerAction(); + action.action = "RotateHandRelative"; + if (splitcommand.Length > 1) + { + action.x = float.Parse(splitcommand[1]); + action.y = float.Parse(splitcommand[2]); + action.z = float.Parse(splitcommand[3]); CurrentActiveController().ProcessControlCommand(action); - break; } - case "tta": { - ServerAction action = new ServerAction(); - action.action = "TouchThenApplyForce"; - action.x = 0.5f; - action.y = 0.5f; - action.handDistance = 2.0f; - action.direction = new Vector3(0, 0, 1); - action.moveMagnitude = 800f; + break; + } - if (splitcommand.Length > 1) { - action.moveMagnitude = float.Parse(splitcommand[1]); - } - CurrentActiveController().ProcessControlCommand(action); - break; - } + // default the Hand's position and rotation to the starting position and rotation + case "dh": + { + ServerAction action = new ServerAction(); + action.action = "DefaultAgentHand"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - // rotate wrist right - case "rwr": { - Dictionary action = new Dictionary(); - action["action"] = "RotateWristRelative"; - action["yaw"] = 90f; - if (splitcommand.Length > 1) { - action["yaw"] = float.Parse(splitcommand[1]); - } + case "tta": + { + ServerAction action = new ServerAction(); + action.action = "TouchThenApplyForce"; + action.x = 0.5f; + action.y = 0.5f; + action.handDistance = 2.0f; + action.direction = new Vector3(0, 0, 1); + action.moveMagnitude = 800f; + + if (splitcommand.Length > 1) + { + action.moveMagnitude = float.Parse(splitcommand[1]); + } + CurrentActiveController().ProcessControlCommand(action); + break; + } - CurrentActiveController().ProcessControlCommand(action); - break; + // rotate wrist right + case "rwr": + { + Dictionary action = new Dictionary(); + action["action"] = "RotateWristRelative"; + action["yaw"] = 90f; + if (splitcommand.Length > 1) + { + action["yaw"] = float.Parse(splitcommand[1]); } + CurrentActiveController().ProcessControlCommand(action); + break; + } + // move hand ahead, forward relative to agent's facing // pass in move magnitude or default is 0.25 units - case "mha": { - Dictionary action = new Dictionary(); - action["action"] = "MoveHandAhead"; - - if (splitcommand.Length > 1) { - action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { - action["moveMagnitude"] = 0.1f; - } + case "mha": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveHandAhead"; - // action.x = 0f; - // action.y = 0f; - // action.z = 1f; - - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action["moveMagnitude"] = float.Parse(splitcommand[1]); + } + else + { + action["moveMagnitude"] = 0.1f; } + // action.x = 0f; + // action.y = 0f; + // action.z = 1f; + + CurrentActiveController().ProcessControlCommand(action); + break; + } + // move hand backward. relative to agent's facing // pass in move magnitude or default is 0.25 units - case "mhb": { - Dictionary action = new Dictionary(); - action["action"] = "MoveHandBack"; - - if (splitcommand.Length > 1) { - action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { - action["moveMagnitude"] = 0.1f; - } + case "mhb": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveHandBack"; - // action.x = 0f; - // action.y = 0f; - // action.z = -1f; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action["moveMagnitude"] = float.Parse(splitcommand[1]); + } + else + { + action["moveMagnitude"] = 0.1f; } + // action.x = 0f; + // action.y = 0f; + // action.z = -1f; + CurrentActiveController().ProcessControlCommand(action); + break; + } + // move hand left, relative to agent's facing // pass in move magnitude or default is 0.25 units - case "mhl": { - Dictionary action = new Dictionary(); - action["action"] = "MoveHandLeft"; - - if (splitcommand.Length > 1) { - action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { - action["moveMagnitude"] = 0.1f; - } + case "mhl": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveHandLeft"; - // action.x = -1f; - // action.y = 0f; - // action.z = 0f; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action["moveMagnitude"] = float.Parse(splitcommand[1]); } + else + { + action["moveMagnitude"] = 0.1f; + } + + // action.x = -1f; + // action.y = 0f; + // action.z = 0f; + CurrentActiveController().ProcessControlCommand(action); + break; + } // move hand right, relative to agent's facing // pass in move magnitude or default is 0.25 units - case "mhr": { - Dictionary action = new Dictionary(); - action["action"] = "MoveHandRight"; - - if (splitcommand.Length > 1) { - action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { - action["moveMagnitude"] = 0.1f; - } + case "mhr": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveHandRight"; - // action.x = 1f; - // action.y = 0f; - // action.z = 0f; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action["moveMagnitude"] = float.Parse(splitcommand[1]); + } + else + { + action["moveMagnitude"] = 0.1f; } + // action.x = 1f; + // action.y = 0f; + // action.z = 0f; + CurrentActiveController().ProcessControlCommand(action); + break; + } + // do nothing action case "pass": case "done": - case "noop": { - Dictionary action = new Dictionary(); - action["action"] = "NoOp"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "noop": + { + Dictionary action = new Dictionary(); + action["action"] = "NoOp"; + CurrentActiveController().ProcessControlCommand(action); + break; + } // Short circuiting exception test - case "sc": { - Dictionary action = new Dictionary(); - action["action"] = "OpenObject"; - action["x"] = 1.5; - action["y"] = 0.5; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "sc": + { + Dictionary action = new Dictionary(); + action["action"] = "OpenObject"; + action["x"] = 1.5; + action["y"] = 0.5; + CurrentActiveController().ProcessControlCommand(action); + break; + } // move hand up, relative to agent's facing // pass in move magnitude or default is 0.25 units - case "mhu": { - Dictionary action = new Dictionary(); - action["action"] = "MoveHandUp"; - - if (splitcommand.Length > 1) { - action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { - action["moveMagnitude"] = 0.1f; - } + case "mhu": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveHandUp"; - // action.x = 0f; - // action.y = 1f; - // action.z = 0f; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action["moveMagnitude"] = float.Parse(splitcommand[1]); } + else + { + action["moveMagnitude"] = 0.1f; + } + + // action.x = 0f; + // action.y = 1f; + // action.z = 0f; + CurrentActiveController().ProcessControlCommand(action); + break; + } // move hand down, relative to agent's facing // pass in move magnitude or default is 0.25 units - case "mhd": { - Dictionary action = new Dictionary(); - action["action"] = "MoveHandDown"; - - if (splitcommand.Length > 1) { - action["moveMagnitude"] = float.Parse(splitcommand[1]); - } else { - action["moveMagnitude"] = 0.1f; - } + case "mhd": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveHandDown"; - // action.x = 0f; - // action.y = -1f; - // action.z = 0f; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action["moveMagnitude"] = float.Parse(splitcommand[1]); + } + else + { + action["moveMagnitude"] = 0.1f; } + // action.x = 0f; + // action.y = -1f; + // action.z = 0f; + CurrentActiveController().ProcessControlCommand(action); + break; + } + // changes the time spent to decay to room temperature for all objects in this scene of given type - case "DecayTimeForType": { - Dictionary action = new Dictionary(); - action["action"] = "SetRoomTempDecayTimeForType"; + case "DecayTimeForType": + { + Dictionary action = new Dictionary(); + action["action"] = "SetRoomTempDecayTimeForType"; - action["TimeUntilRoomTemp"] = 20f; - action["objectType"] = "Bread"; - CurrentActiveController().ProcessControlCommand(action); + action["TimeUntilRoomTemp"] = 20f; + action["objectType"] = "Bread"; + CurrentActiveController().ProcessControlCommand(action); - break; - } + break; + } // changes the time spent to decay to room temperature for all objects globally in the scene - case "DecayTimeGlobal": { - ServerAction action = new ServerAction(); - action.action = "SetGlobalRoomTempDecayTime"; + case "DecayTimeGlobal": + { + ServerAction action = new ServerAction(); + action.action = "SetGlobalRoomTempDecayTime"; - action.TimeUntilRoomTemp = 20f; - CurrentActiveController().ProcessControlCommand(action); + action.TimeUntilRoomTemp = 20f; + CurrentActiveController().ProcessControlCommand(action); - break; - } + break; + } - case "SetTempDecayBool": { - Dictionary action = new Dictionary(); - action["action"] = "SetDecayTemperatureBool"; + case "SetTempDecayBool": + { + Dictionary action = new Dictionary(); + action["action"] = "SetDecayTemperatureBool"; - action["allowDecayTemperature"] = false; - CurrentActiveController().ProcessControlCommand(action); - break; - } + action["allowDecayTemperature"] = false; + CurrentActiveController().ProcessControlCommand(action); + break; + } // throw object by dropping it and applying force. // default is with strength of 120, can pass in custom magnitude of throw force - case "throw": { - ServerAction action = new ServerAction(); - action.action = "ThrowObject"; - - if (splitcommand.Length > 1) { - action.moveMagnitude = float.Parse(splitcommand[1]); - } else { - action.moveMagnitude = 120f; - } + case "throw": + { + ServerAction action = new ServerAction(); + action.action = "ThrowObject"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.moveMagnitude = float.Parse(splitcommand[1]); + } + else + { + action.moveMagnitude = 120f; } - case "push": { - ServerAction action = new ServerAction(); - action.action = "PushObject"; - - action.moveMagnitude = 2000f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1 && splitcommand.Length < 3) { - action.objectId = splitcommand[1]; - action.moveMagnitude = 200f; // 4000f; - } else if (splitcommand.Length > 2) { - action.objectId = splitcommand[1]; - action.moveMagnitude = float.Parse(splitcommand[2]); - } + case "push": + { + ServerAction action = new ServerAction(); + action.action = "PushObject"; - action.x = 0.5f; - action.y = 0.5f; + action.moveMagnitude = 2000f; - action.z = 1; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1 && splitcommand.Length < 3) + { + action.objectId = splitcommand[1]; + action.moveMagnitude = 200f; // 4000f; + } + else if (splitcommand.Length > 2) + { + action.objectId = splitcommand[1]; + action.moveMagnitude = float.Parse(splitcommand[2]); } - case "pull": { - ServerAction action = new ServerAction(); - action.action = "PullObject"; + action.x = 0.5f; + action.y = 0.5f; + + action.z = 1; + CurrentActiveController().ProcessControlCommand(action); + break; + } - action.moveMagnitude = 2000f; + case "pull": + { + ServerAction action = new ServerAction(); + action.action = "PullObject"; - if (splitcommand.Length > 1 && splitcommand.Length < 3) { - action.objectId = splitcommand[1]; - 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.moveMagnitude = 2000f; - // action.moveMagnitude = 200f;// 4000f; - action.z = -1; - action.x = 0.5f; - action.y = 0.5f; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1 && splitcommand.Length < 3) + { + action.objectId = splitcommand[1]; + 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(); } - case "dirpush": { - ServerAction action = new ServerAction(); - action.action = "DirectionalPush"; + // action.moveMagnitude = 200f;// 4000f; + action.z = -1; + action.x = 0.5f; + action.y = 0.5f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1 && splitcommand.Length < 3) { - action.objectId = splitcommand[1]; - action.moveMagnitude = 10f; // 4000f; - } else if (splitcommand.Length > 2) { - action.objectId = splitcommand[1]; - action.moveMagnitude = float.Parse(splitcommand[2]); - } + case "dirpush": + { + ServerAction action = new ServerAction(); + action.action = "DirectionalPush"; - action.pushAngle = 279f; - action.moveMagnitude = 159f; - action.x = 0.5f; - action.y = 0.5f; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1 && splitcommand.Length < 3) + { + action.objectId = splitcommand[1]; + action.moveMagnitude = 10f; // 4000f; + } + else if (splitcommand.Length > 2) + { + action.objectId = splitcommand[1]; + action.moveMagnitude = float.Parse(splitcommand[2]); } - case "toggleon": { - Dictionary action = new Dictionary(); - action["action"] = "ToggleObjectOn"; - if (splitcommand.Length > 1) { - action["objectId"] = splitcommand[1]; - } else { - action["x"] = 0.5f; - action["y"] = 0.5f; - } - - CurrentActiveController().ProcessControlCommand(action); + action.pushAngle = 279f; + action.moveMagnitude = 159f; + action.x = 0.5f; + action.y = 0.5f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - break; + case "toggleon": + { + Dictionary action = new Dictionary(); + action["action"] = "ToggleObjectOn"; + if (splitcommand.Length > 1) + { + action["objectId"] = splitcommand[1]; + } + else + { + action["x"] = 0.5f; + action["y"] = 0.5f; } - case "toggleoff": { - Dictionary action = new Dictionary(); - action["action"] = "ToggleObjectOff"; - if (splitcommand.Length > 1) { - action["objectId"] = splitcommand[1]; - } else { - action["x"] = 0.5f; - action["y"] = 0.5f; - } + CurrentActiveController().ProcessControlCommand(action); - // action.objectId = "DeskLamp|-01.32|+01.24|-00.99"; - action["forceVisible"] = true; - action["forceAction"] = true; - CurrentActiveController().ProcessControlCommand(action); + break; + } - break; + case "toggleoff": + { + Dictionary action = new Dictionary(); + action["action"] = "ToggleObjectOff"; + if (splitcommand.Length > 1) + { + action["objectId"] = splitcommand[1]; + } + else + { + action["x"] = 0.5f; + action["y"] = 0.5f; } - case "cook": { - ServerAction action = new ServerAction(); - action.action = "CookObject"; - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } + // action.objectId = "DeskLamp|-01.32|+01.24|-00.99"; + action["forceVisible"] = true; + action["forceAction"] = true; + CurrentActiveController().ProcessControlCommand(action); - action.x = 0.5f; - action.y = 0.5f; - CurrentActiveController().ProcessControlCommand(action); + break; + } - break; + case "cook": + { + ServerAction action = new ServerAction(); + action.action = "CookObject"; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; } - case "sos": { - ServerAction action = new ServerAction(); - action.action = "SetObjectStates"; - action.SetObjectStates = new SetObjectStates() { - stateChange = "toggleable", - objectType = "DeskLamp", - isToggled = false - }; + action.x = 0.5f; + action.y = 0.5f; + CurrentActiveController().ProcessControlCommand(action); - CurrentActiveController().ProcessControlCommand(action); + break; + } - break; - } + case "sos": + { + ServerAction action = new ServerAction(); + action.action = "SetObjectStates"; + action.SetObjectStates = new SetObjectStates() + { + stateChange = "toggleable", + objectType = "DeskLamp", + isToggled = false + }; - case "pose": { - ServerAction action = new ServerAction(); - action.action = "SetObjectPoses"; - action.objectPoses = new ObjectPose[1]; + CurrentActiveController().ProcessControlCommand(action); - action.objectPoses[0] = new ObjectPose(); + break; + } - action.objectPoses[0].objectName = "Book_3d15d052"; - action.objectPoses[0].position = new Vector3(0, 0, 0); - action.objectPoses[0].rotation = new Vector3(0, 0, 0); + case "pose": + { + ServerAction action = new ServerAction(); + action.action = "SetObjectPoses"; + action.objectPoses = new ObjectPose[1]; - CurrentActiveController().ProcessControlCommand(action); + action.objectPoses[0] = new ObjectPose(); - break; - } + action.objectPoses[0].objectName = "Book_3d15d052"; + action.objectPoses[0].position = new Vector3(0, 0, 0); + action.objectPoses[0].rotation = new Vector3(0, 0, 0); + + CurrentActiveController().ProcessControlCommand(action); + + break; + } // opens given object the given percent, default is 100% open // open percent - case "open": { - Dictionary action = new Dictionary(); - action["action"] = "OpenObject"; - action["forceAction"] = true; - - if (splitcommand.Length == 1) { - // try opening object in front of the agent - action["openness"] = 0.5f; - action["x"] = 0.5f; - action["y"] = 0.5f; - } else if (splitcommand.Length == 2) { - // default open 100% - action["objectId"] = splitcommand[1]; - } else if (splitcommand.Length == 3) { - // give the open percentage as 3rd param, from 0.0 to 1.0 - action["objectId"] = splitcommand[1]; - action["openness"] = float.Parse(splitcommand[2]); - } - - CurrentActiveController().ProcessControlCommand(action); - break; + case "open": + { + Dictionary action = new Dictionary(); + action["action"] = "OpenObject"; + action["forceAction"] = true; + + if (splitcommand.Length == 1) + { + // try opening object in front of the agent + action["openness"] = 0.5f; + action["x"] = 0.5f; + action["y"] = 0.5f; + } + else if (splitcommand.Length == 2) + { + // default open 100% + action["objectId"] = splitcommand[1]; + } + else if (splitcommand.Length == 3) + { + // give the open percentage as 3rd param, from 0.0 to 1.0 + action["objectId"] = splitcommand[1]; + action["openness"] = float.Parse(splitcommand[2]); } - case "openim": { - Dictionary action = new Dictionary(); - action["action"] = "OpenObjectImmediate"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - action["objectId"] = "Cabinet|-00.73|+02.02|-02.46"; + case "openim": + { + Dictionary action = new Dictionary(); + action["action"] = "OpenObjectImmediate"; - action["openness"] = 1f; + action["objectId"] = "Cabinet|-00.73|+02.02|-02.46"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + action["openness"] = 1f; - case "closeim": { - Dictionary action = new Dictionary(); - action["action"] = "OpenObjectImmediate"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - action["objectId"] = "Cabinet|-00.73|+02.02|-02.46"; + case "closeim": + { + Dictionary action = new Dictionary(); + action["action"] = "OpenObjectImmediate"; - action["openness"] = 0f; + action["objectId"] = "Cabinet|-00.73|+02.02|-02.46"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + action["openness"] = 0f; - case "close": { - Dictionary action = new Dictionary(); - action["action"] = "CloseObject"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action["objectId"] = splitcommand[1]; - } else { - action["x"] = 0.5f; - action["y"] = 0.5f; - } + case "close": + { + Dictionary action = new Dictionary(); + action["action"] = "CloseObject"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action["objectId"] = splitcommand[1]; } + else + { + action["x"] = 0.5f; + action["y"] = 0.5f; + } + + CurrentActiveController().ProcessControlCommand(action); + break; + } // pass in object id of a receptacle, and this will report any other sim objects inside of it // this works for cabinets, drawers, countertops, tabletops, etc. - case "contains": { - ServerAction action = new ServerAction(); - action.action = "Contains"; + case "contains": + { + ServerAction action = new ServerAction(); + action.action = "Contains"; - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; + } - CurrentActiveController().ProcessControlCommand(action); + CurrentActiveController().ProcessControlCommand(action); - break; - } + break; + } //***************************************************************************** // MASS SCALE ACTIONS HERE //***************************************************************************** // get total mass in right scale of MassScale sim obj - case "rscalemass": { - ServerAction action = new ServerAction(); - action.action = "MassInRightScale"; - - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } + case "rscalemass": + { + ServerAction action = new ServerAction(); + action.action = "MassInRightScale"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; } - // get total mass in left scale of MassScale sim obj - case "lscalemass": { - ServerAction action = new ServerAction(); - action.action = "MassInLeftScale"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } + // get total mass in left scale of MassScale sim obj + case "lscalemass": + { + ServerAction action = new ServerAction(); + action.action = "MassInLeftScale"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; } - // get total count of objects in right scale of MassScale sim obj - case "rscalecount": { - ServerAction action = new ServerAction(); - action.action = "CountInRightScale"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } + // get total count of objects in right scale of MassScale sim obj + case "rscalecount": + { + ServerAction action = new ServerAction(); + action.action = "CountInRightScale"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; } - // get total count of objects in the left scale of MassScale sim obj - case "lscalecount": { - ServerAction action = new ServerAction(); - action.action = "CountInLeftScale"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } + // get total count of objects in the left scale of MassScale sim obj + case "lscalecount": + { + ServerAction action = new ServerAction(); + action.action = "CountInLeftScale"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; } - // get list of all sim objects in the right scale of MassScale sim obj - case "rscaleobjs": { - ServerAction action = new ServerAction(); - action.action = "ObjectsInRightScale"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } + // get list of all sim objects in the right scale of MassScale sim obj + case "rscaleobjs": + { + ServerAction action = new ServerAction(); + action.action = "ObjectsInRightScale"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; } - // get list of all sim objects in the Left scale of MassScale sim obj - case "lscaleobjs": { - ServerAction action = new ServerAction(); - action.action = "ObjectsInLeftScale"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action.objectId = splitcommand[1]; - } + // get list of all sim objects in the Left scale of MassScale sim obj + case "lscaleobjs": + { + ServerAction action = new ServerAction(); + action.action = "ObjectsInLeftScale"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action.objectId = splitcommand[1]; } - // Will fail if navmeshes are not setup - case "expact": { - Dictionary action = new Dictionary(); - action["action"] = "ObjectNavExpertAction"; - - // pass in a min range, max range, delay - if (splitcommand.Length == 2) { - // ID of spawner - action["objectId"] = splitcommand[1]; - } else if (splitcommand.Length >= 4) { - // Target position - action["position"] = new Vector3( - float.Parse(splitcommand[1]), - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]) - ); - } - CurrentActiveController().ProcessControlCommand(action); - break; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } // Will fail if navmeshes are not setup - case "sp": { - Dictionary action = new Dictionary(); - action["action"] = "GetShortestPath"; - action["objectType"] = "Bowl"; - action["allowedError"] = 0.05f; - //for spraybottle on FloorPlan_Train9_5 - //action["position"] = new Vector3(7.149451732635498f, 0.9009996652603146f, -2.4680588245391846f); - - //for bowl on FloorPlan_Train1_3 + case "expact": + { + Dictionary action = new Dictionary(); + action["action"] = "ObjectNavExpertAction"; + + // pass in a min range, max range, delay + if (splitcommand.Length == 2) + { + // ID of spawner + action["objectId"] = splitcommand[1]; + } + else if (splitcommand.Length >= 4) + { + // Target position action["position"] = new Vector3( - 5.039496421813965f, - 0.9009997248649597f, - -3.127098560333252f + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]) ); + } + CurrentActiveController().ProcessControlCommand(action); + break; + } - // pass in a min range, max range, delay - if (splitcommand.Length > 1) { - // ID of spawner - action["objectId"] = splitcommand[1]; + // Will fail if navmeshes are not setup + case "sp": + { + Dictionary action = new Dictionary(); + action["action"] = "GetShortestPath"; + action["objectType"] = "Bowl"; + action["allowedError"] = 0.05f; + //for spraybottle on FloorPlan_Train9_5 + //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 + ); + + // pass in a min range, max range, delay + if (splitcommand.Length > 1) + { + // ID of spawner + action["objectId"] = splitcommand[1]; - if (splitcommand.Length == 5) { - action["position"] = new Vector3( - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]), - float.Parse(splitcommand[4]) - ); - } + if (splitcommand.Length == 5) + { + action["position"] = new Vector3( + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]), + float.Parse(splitcommand[4]) + ); } - - CurrentActiveController().ProcessControlCommand(action); - break; } - case "shortest_test": { - Dictionary action = new Dictionary(); - var agentId = 1; - if (splitcommand.Length == 2) { - // ID of spawner - agentId = int.Parse(splitcommand[1]); - } - 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["agentId"] = agentId; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "shortest_test": + { + Dictionary action = new Dictionary(); + var agentId = 1; + if (splitcommand.Length == 2) + { + // ID of spawner + agentId = int.Parse(splitcommand[1]); + } + action["action"] = "GetShortestPath"; - CurrentActiveController().ProcessControlCommand(action); + 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["agentId"] = agentId; - break; - } - case "shortest_path_type": { - Dictionary action = new Dictionary(); - action["action"] = "GetShortestPath"; + CurrentActiveController().ProcessControlCommand(action); - // pass in a min range, max range, delay - if (splitcommand.Length > 1) { - // ID of spawner - action["objectType"] = splitcommand[1]; + break; + } + case "shortest_path_type": + { + Dictionary action = new Dictionary(); + action["action"] = "GetShortestPath"; + + // pass in a min range, max range, delay + if (splitcommand.Length > 1) + { + // ID of spawner + action["objectType"] = splitcommand[1]; - if (splitcommand.Length == 5) { - action["position"] = new Vector3( - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]), - float.Parse(splitcommand[4]) - ); - } + if (splitcommand.Length == 5) + { + action["position"] = new Vector3( + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]), + float.Parse(splitcommand[4]) + ); } - - CurrentActiveController().ProcessControlCommand(action); - break; } - case "shortest_path_point": { - Dictionary action = new Dictionary(); - action["action"] = "GetShortestPathToPoint"; - // pass in a min range, max range, delay - if (splitcommand.Length > 1) { - // ID of spawner - // action.objectId = splitcommand[1]; - - if (splitcommand.Length == 4) { - action["x"] = float.Parse(splitcommand[1]); - action["y"] = float.Parse(splitcommand[2]); - action["z"] = float.Parse(splitcommand[3]); - } - if (splitcommand.Length >= 7) { - action["position"] = new Vector3( - float.Parse(splitcommand[1]), - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]) - ); - action["x"] = float.Parse(splitcommand[4]); - action["y"] = float.Parse(splitcommand[5]); - action["z"] = float.Parse(splitcommand[6]); - } - if (splitcommand.Length >= 8) { - action["allowedError"] = float.Parse(splitcommand[7]); - } + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "shortest_path_point": + { + Dictionary action = new Dictionary(); + action["action"] = "GetShortestPathToPoint"; + + // pass in a min range, max range, delay + if (splitcommand.Length > 1) + { + // ID of spawner + // action.objectId = splitcommand[1]; + + if (splitcommand.Length == 4) + { + action["x"] = float.Parse(splitcommand[1]); + action["y"] = float.Parse(splitcommand[2]); + action["z"] = float.Parse(splitcommand[3]); + } + if (splitcommand.Length >= 7) + { + action["position"] = new Vector3( + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]) + ); + action["x"] = float.Parse(splitcommand[4]); + action["y"] = float.Parse(splitcommand[5]); + action["z"] = float.Parse(splitcommand[6]); + } + if (splitcommand.Length >= 8) + { + 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" - ); - } - } else { + if (splitcommand.Length < 4) + { throw new ArgumentException( - "need to provide at least 3 floats for target position" + "need to provide 6 floats, first 3 source position second 3 target position" ); } - CurrentActiveController().ProcessControlCommand(action); - break; } - case "shortest_path_p": { - Dictionary action = new Dictionary(); - action["action"] = "GetShortestPathToPointN"; - - // pass in a min range, max range, delay - if (splitcommand.Length > 1) { - // ID of spawner - // action.objectId = splitcommand[1]; - - if (splitcommand.Length >= 4) { - var target = new Vector3( - float.Parse(splitcommand[1]), - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]) - ); - action["target"] = target; - } + else + { + throw new ArgumentException( + "need to provide at least 3 floats for target position" + ); + } + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "shortest_path_p": + { + Dictionary action = new Dictionary(); + action["action"] = "GetShortestPathToPointN"; + + // pass in a min range, max range, delay + if (splitcommand.Length > 1) + { + // ID of spawner + // action.objectId = splitcommand[1]; + + if (splitcommand.Length >= 4) + { + 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]); - } + if (splitcommand.Length > 4) + { + action["allowedError"] = float.Parse(splitcommand[4]); + } - if (splitcommand.Length > 5) { - action["agentId"] = int.Parse(splitcommand[5]); - } + if (splitcommand.Length > 5) + { + 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" - ); - } - } else { + if (splitcommand.Length < 4) + { throw new ArgumentException( - "need to provide at least 3 floats for target position" + "need to provide 6 floats, first 3 source position second 3 target position" ); } - CurrentActiveController().ProcessControlCommand(action); - break; } - case "visualize_path": { - Dictionary action = new Dictionary() { - ["action"] = "VisualizePath", - ["positions"] = new List() - { + else + { + throw new ArgumentException( + "need to provide at least 3 floats for target position" + ); + } + CurrentActiveController().ProcessControlCommand(action); + break; + } + 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) } - }; + }; - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "visualize_path2": { - Dictionary action = new Dictionary() { - ["action"] = "VisualizePath", - ["positions"] = new List() - { + CurrentActiveController().ProcessControlCommand(action); + break; + } + 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) } - }; - - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "hide_path": { - Dictionary action = new Dictionary() { - ["action"] = "HideVisualizedPath" - }; - - CurrentActiveController().ProcessControlCommand(action); - break; - } - - case "vp": { - ServerAction action = new ServerAction(); - action.action = "VisualizeShortestPaths"; + }; - // pass in a min range, max range, delay - if (splitcommand.Length > 1) { - // ID of spawner - action.objectType = splitcommand[1]; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "hide_path": + { + Dictionary action = new Dictionary() + { + ["action"] = "HideVisualizedPath" + }; - if (splitcommand.Length == 5) { - action.position = new Vector3( - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]), - float.Parse(splitcommand[4]) - ); - } else { - var pos = PhysicsController.getReachablePositions().Shuffle(); - action.positions = pos.Take(20).ToList(); - action.grid = true; - // action.pathGradient = new Gradient() { - // colorKeys = new GradientColorKey[]{ - // new GradientColorKey(Color.white, 0.0f), - // new GradientColorKey(Color.blue, 1.0f) - // }, - // alphaKeys = new GradientAlphaKey[]{ - // new GradientAlphaKey(1.0f, 0.0f), - // new GradientAlphaKey(1.0f, 1.0f) - // }, - // mode = GradientMode.Blend - // }; - // action.gridColor = new Color(1.0f, 0.0f, 0.0f, 1.0f); - // action.positions = new List() { - // new Vector3( 4.258f, 1.0f, -2.69f), - // new Vector3(4.3f, 1.0f, -3.452f) - // }; - } - } + CurrentActiveController().ProcessControlCommand(action); + break; + } - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "vpf": { - ServerAction action = new ServerAction(); - action.action = "VisualizeShortestPaths"; + case "vp": + { + ServerAction action = new ServerAction(); + action.action = "VisualizeShortestPaths"; - action.objectType = "Dog Bed"; + // pass in a min range, max range, delay + if (splitcommand.Length > 1) + { + // ID of spawner + action.objectType = splitcommand[1]; - if (splitcommand.Length > 1) { - // ID of spawner - action.objectType = splitcommand[1]; + if (splitcommand.Length == 5) + { + action.position = new Vector3( + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]), + float.Parse(splitcommand[4]) + ); } - - 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}" - ); - action.grid = true; - CurrentActiveController().ProcessControlCommand(action); - - break; - } - case "vw": { - Dictionary action = new Dictionary(); - action["action"] = "VisualizeWaypoints"; - - // pass in a min range, max range, delay - if (splitcommand.Length > 1) { - // ID of spawner - var num = int.Parse(splitcommand[1]); - + else + { 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.positions = pos.Take(20).ToList(); + action.grid = true; // action.pathGradient = new Gradient() { // colorKeys = new GradientColorKey[]{ // new GradientColorKey(Color.white, 0.0f), @@ -4647,1182 +5206,1379 @@ IEnumerator executeBatch(JArray jActions) { // action.positions = new List() { // new Vector3( 4.258f, 1.0f, -2.69f), // new Vector3(4.3f, 1.0f, -3.452f) - // };= + // }; } + } + + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "vpf": + { + ServerAction action = new ServerAction(); + action.action = "VisualizeShortestPaths"; + + action.objectType = "Dog Bed"; + + if (splitcommand.Length > 1) + { + // ID of spawner + action.objectType = splitcommand[1]; + } - CurrentActiveController().ProcessControlCommand(action); - break; + 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}" + ); + action.grid = true; + CurrentActiveController().ProcessControlCommand(action); + + break; + } + case "vw": + { + Dictionary action = new Dictionary(); + action["action"] = "VisualizeWaypoints"; + + // pass in a min range, max range, delay + if (splitcommand.Length > 1) + { + // ID of spawner + var num = int.Parse(splitcommand[1]); + + 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.pathGradient = new Gradient() { + // colorKeys = new GradientColorKey[]{ + // new GradientColorKey(Color.white, 0.0f), + // new GradientColorKey(Color.blue, 1.0f) + // }, + // alphaKeys = new GradientAlphaKey[]{ + // new GradientAlphaKey(1.0f, 0.0f), + // new GradientAlphaKey(1.0f, 1.0f) + // }, + // mode = GradientMode.Blend + // }; + // action.gridColor = new Color(1.0f, 0.0f, 0.0f, 1.0f); + // action.positions = new List() { + // new Vector3( 4.258f, 1.0f, -2.69f), + // new Vector3(4.3f, 1.0f, -3.452f) + // };= } - case "visualize_shortest_path": { - ServerAction action = new ServerAction(); - action.action = "VisualizeShortestPaths"; - // pass in a min range, max range, delay - if (splitcommand.Length > 1) { - // ID of spawner - action.objectType = splitcommand[1]; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "visualize_shortest_path": + { + ServerAction action = new ServerAction(); + action.action = "VisualizeShortestPaths"; + + // pass in a min range, max range, delay + if (splitcommand.Length > 1) + { + // ID of spawner + action.objectType = splitcommand[1]; - if (splitcommand.Length == 5) { - action.position = new Vector3( - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]), - float.Parse(splitcommand[4]) - ); - } else { - // var pos = PhysicsController.getReachablePositions().Shuffle(); - action.positions = new List() - { + if (splitcommand.Length == 5) + { + action.position = new Vector3( + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]), + float.Parse(splitcommand[4]) + ); + } + else + { + // var pos = PhysicsController.getReachablePositions().Shuffle(); + action.positions = new List() + { PhysicsController.transform.position }; - action.grid = true; - } + action.grid = true; } - - CurrentActiveController().ProcessControlCommand(action); - break; } - case "get_object_type_ids": { - Dictionary action = new Dictionary(); - action["action"] = "ObjectTypeToObjectIds"; - if (splitcommand.Length > 1) { - action["objectType"] = splitcommand[1]; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } - CurrentActiveController().ProcessControlCommand(action); - break; + case "get_object_type_ids": + { + Dictionary action = new Dictionary(); + action["action"] = "ObjectTypeToObjectIds"; + if (splitcommand.Length > 1) + { + action["objectType"] = splitcommand[1]; } + + CurrentActiveController().ProcessControlCommand(action); + break; + } case "move_mid_arm": - case "mmla": { - // Limit around -0.084 - //"mmla 0 0 0.08 0.1 false wrist true" - ServerAction action = new ServerAction(); - action.action = "MoveMidLevelArm"; - action.speed = 1.0f; - action.disableRendering = false; - // action.returnToStart = true; - if (splitcommand.Length > 4) { - action.position = new Vector3( - float.Parse(splitcommand[1]), - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]) - ); + case "mmla": + { + // Limit around -0.084 + //"mmla 0 0 0.08 0.1 false wrist true" + ServerAction action = new ServerAction(); + action.action = "MoveMidLevelArm"; + action.speed = 1.0f; + action.disableRendering = false; + // action.returnToStart = true; + if (splitcommand.Length > 4) + { + action.position = new Vector3( + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]) + ); - if (splitcommand.Length >= 5) { - action.speed = float.Parse(splitcommand[4]); - } + if (splitcommand.Length >= 5) + { + action.speed = float.Parse(splitcommand[4]); + } - if (splitcommand.Length >= 6) { - action.coordinateSpace = splitcommand[5]; - } + if (splitcommand.Length >= 6) + { + action.coordinateSpace = splitcommand[5]; + } - if (splitcommand.Length >= 7) { - action.returnToStart = bool.Parse(splitcommand[6]); - } + if (splitcommand.Length >= 7) + { + action.returnToStart = bool.Parse(splitcommand[6]); + } - if (splitcommand.Length >= 8) { - action.restrictMovement = bool.Parse(splitcommand[7]); - } + if (splitcommand.Length >= 8) + { + action.restrictMovement = bool.Parse(splitcommand[7]); + } - if (splitcommand.Length >= 9) { - action.disableRendering = bool.Parse(splitcommand[8]); - } - } else { - Debug.LogError("Target x y z args needed for command"); + if (splitcommand.Length >= 9) + { + action.disableRendering = bool.Parse(splitcommand[8]); } - // action.stopArmMovementOnContact = true; - CurrentActiveController().ProcessControlCommand(action); - break; } + else + { + Debug.LogError("Target x y z args needed for command"); + } + // action.stopArmMovementOnContact = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } // move mid level arm stop motion - case "mmlas": { - ServerAction action = new ServerAction(); - action.action = "MoveMidLevelArm"; - action.speed = 1.0f; - // action.returnToStart = true; - if (splitcommand.Length > 4) { - action.position = new Vector3( - float.Parse(splitcommand[1]), - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]) - ); + case "mmlas": + { + ServerAction action = new ServerAction(); + action.action = "MoveMidLevelArm"; + action.speed = 1.0f; + // action.returnToStart = true; + if (splitcommand.Length > 4) + { + action.position = new Vector3( + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]) + ); - if (splitcommand.Length >= 5) { - action.speed = float.Parse(splitcommand[4]); - } + if (splitcommand.Length >= 5) + { + action.speed = float.Parse(splitcommand[4]); + } - if (splitcommand.Length >= 6) { - action.returnToStart = bool.Parse(splitcommand[5]); - } + if (splitcommand.Length >= 6) + { + action.returnToStart = bool.Parse(splitcommand[5]); + } - if (splitcommand.Length >= 7) { - action.handCameraSpace = bool.Parse(splitcommand[6]); - } - } else { - Debug.LogError("Target x y z args needed for command"); + if (splitcommand.Length >= 7) + { + action.handCameraSpace = bool.Parse(splitcommand[6]); } - action.stopArmMovementOnContact = true; - // action.stopArmMovementOnContact = true; - CurrentActiveController().ProcessControlCommand(action); - break; } + else + { + Debug.LogError("Target x y z args needed for command"); + } + action.stopArmMovementOnContact = true; + // action.stopArmMovementOnContact = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } // move mid level arm stop motion - case "mar": { - // ServerAction action = new ServerAction(); - // action.action = "MoveArmRelative"; - // action.speed = 1.0f; - Dictionary action = new Dictionary(); - action["action"] = "MoveArmRelative"; - action["speed"] = 1.0f; - // action.returnToStart = true; - if (splitcommand.Length >= 4) { - Debug.Log("4 >"); - action["offset"] = new Vector3( - float.Parse(splitcommand[1]), - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]) - ); + case "mar": + { + // ServerAction action = new ServerAction(); + // action.action = "MoveArmRelative"; + // action.speed = 1.0f; + Dictionary action = new Dictionary(); + action["action"] = "MoveArmRelative"; + action["speed"] = 1.0f; + // action.returnToStart = true; + if (splitcommand.Length >= 4) + { + Debug.Log("4 >"); + action["offset"] = new Vector3( + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]) + ); - if (splitcommand.Length >= 5) { - action["speed"] = float.Parse(splitcommand[4]); - } + if (splitcommand.Length >= 5) + { + action["speed"] = float.Parse(splitcommand[4]); + } - if (splitcommand.Length >= 6) { - action["returnToStart"] = bool.Parse(splitcommand[5]); - } + if (splitcommand.Length >= 6) + { + action["returnToStart"] = bool.Parse(splitcommand[5]); + } - if (splitcommand.Length >= 7) { - action["coordinateSpace"] = bool.Parse(splitcommand[6]); - } - } else { - Debug.LogError("Target x y z args needed for command"); + if (splitcommand.Length >= 7) + { + action["coordinateSpace"] = bool.Parse(splitcommand[6]); } - // action.stopArmMovementOnContact = true; - // action.stopArmMovementOnContact = true; - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "pac": { - Dictionary action = new Dictionary(); - action["action"] = "DebugMidLevelArmCollisions"; - CurrentActiveController().ProcessControlCommand(action); - break; } - - case "mau": { - Dictionary action = new Dictionary(); - action["action"] = "MoveArmBaseUp"; - action["distance"] = 0.5f; - action["speed"] = 1.0f; - CurrentActiveController().ProcessControlCommand(action); - break; + else + { + Debug.LogError("Target x y z args needed for command"); } + // action.stopArmMovementOnContact = true; + // action.stopArmMovementOnContact = true; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "pac": + { + Dictionary action = new Dictionary(); + action["action"] = "DebugMidLevelArmCollisions"; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "abmovebaseup": { - Dictionary action = new Dictionary(); - action["action"] = "MoveArmBaseUp"; - action["distance"] = 0.05f; - action["speed"] = 5.0f; - action["disableRendering"] = false; + case "mau": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveArmBaseUp"; + action["distance"] = 0.5f; + action["speed"] = 1.0f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - //action["fixedDeltaTime"] = 5.0f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "abmovebaseup": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveArmBaseUp"; + action["distance"] = 0.05f; + action["speed"] = 5.0f; + action["disableRendering"] = false; - case "abmovebasedown": { - Dictionary action = new Dictionary(); - action["action"] = "MoveArmBaseDown"; - action["distance"] = 0.05f; - action["speed"] = 5.0f; - action["disableRendering"] = false; + //action["fixedDeltaTime"] = 5.0f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - //action["fixedDeltaTime"] = 5.0f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + case "abmovebasedown": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveArmBaseDown"; + action["distance"] = 0.05f; + action["speed"] = 5.0f; + action["disableRendering"] = false; - case "abextendarm": { - Dictionary action = new Dictionary(); - action["action"] = "MoveArm"; - action["position"] = new Vector3(0, 0, 0.5f); - action["speed"] = 5.0f; - action["disableRendering"] = false; - action["useLimits"] = true; + //action["fixedDeltaTime"] = 5.0f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action["position"] = new Vector3(0, 0, float.Parse(splitcommand[1])); - } + case "abextendarm": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveArm"; + action["position"] = new Vector3(0, 0, 0.5f); + action["speed"] = 5.0f; + action["disableRendering"] = false; + action["useLimits"] = true; - //action["fixedDeltaTime"] = 5.0f; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action["position"] = new Vector3(0, 0, float.Parse(splitcommand[1])); } - case "abretractarm": { - Dictionary action = new Dictionary(); - action["action"] = "MoveArm"; - action["position"] = new Vector3(0, 0, -0.5f); - action["speed"] = 5.0f; - action["disableRendering"] = false; - action["useLimits"] = true; + //action["fixedDeltaTime"] = 5.0f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - if (splitcommand.Length > 1) { - action["position"] = new Vector3(0, 0, float.Parse(splitcommand[1])); - } + case "abretractarm": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveArm"; + action["position"] = new Vector3(0, 0, -0.5f); + action["speed"] = 5.0f; + action["disableRendering"] = false; + action["useLimits"] = true; - //action["fixedDeltaTime"] = 5.0f; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action["position"] = new Vector3(0, 0, float.Parse(splitcommand[1])); } - case "abrotatewrist": { - Dictionary action = new Dictionary(); - action["action"] = "RotateWristRelative"; - action["yaw"] = 90f; - action["speed"] = 400f; - action["disableRendering"] = false; - //action["fixedDeltaTime"] = 5.0f; - CurrentActiveController().ProcessControlCommand(action); - break; - } + //action["fixedDeltaTime"] = 5.0f; + CurrentActiveController().ProcessControlCommand(action); + break; + } + + case "abrotatewrist": + { + Dictionary action = new Dictionary(); + action["action"] = "RotateWristRelative"; + action["yaw"] = 90f; + action["speed"] = 400f; + action["disableRendering"] = false; + //action["fixedDeltaTime"] = 5.0f; + CurrentActiveController().ProcessControlCommand(action); + break; + } // manual pickup object- test hand - case "abpickup": { - Dictionary action = new Dictionary(); - action["action"] = "PickupObject"; - if (splitcommand.Length > 1) { - List objectIds = new List(); - objectIds.Add(splitcommand[1]); - action["objectIdCandidates"] = objectIds; - } - CurrentActiveController().ProcessControlCommand(action); - break; + case "abpickup": + { + Dictionary action = new Dictionary(); + action["action"] = "PickupObject"; + if (splitcommand.Length > 1) + { + List objectIds = new List(); + objectIds.Add(splitcommand[1]); + action["objectIdCandidates"] = objectIds; } + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "abdrop": { - Dictionary action = new Dictionary(); - action["action"] = "ReleaseObject"; + case "abdrop": + { + Dictionary action = new Dictionary(); + action["action"] = "ReleaseObject"; - CurrentActiveController().ProcessControlCommand(action); - break; - } + CurrentActiveController().ProcessControlCommand(action); + break; + } + + case "gcfr": + { + Dictionary action = new Dictionary(); + action["action"] = "GetCoordinateFromRaycast"; + action["x"] = float.Parse(splitcommand[1]); + action["y"] = float.Parse(splitcommand[2]); + + CurrentActiveController().ProcessControlCommand(action); + break; + } + + case "abtelefull": + { + Dictionary action = new Dictionary(); + action["action"] = "TeleportFull"; + action["position"] = new Vector3(7f, 0.95f, 6.4f); + action["rotation"] = new Vector3(0f, 180f, 0f); + action["horizon"] = -20f; + CurrentActiveController().ProcessControlCommand(action); + break; + } - case "gcfr": { - Dictionary action = new Dictionary(); - action["action"] = "GetCoordinateFromRaycast"; + case "telefull": + { + Dictionary action = new Dictionary(); + action["action"] = "TeleportFull"; + action["x"] = -1f; + action["y"] = 0.9009995460510254f; + action["z"] = 1.5f; + Vector3 rotation = new Vector3(0, 135.0f, 0); + float horizon = Agent + .GetComponent() + .AgentCamera.transform.eulerAngles.x; + bool standing = true; + + if (splitcommand.Length > 1 && splitcommand.Length < 6) + { action["x"] = float.Parse(splitcommand[1]); action["y"] = float.Parse(splitcommand[2]); - - CurrentActiveController().ProcessControlCommand(action); - break; + action["z"] = float.Parse(splitcommand[3]); + rotation = new Vector3(0, float.Parse(splitcommand[4]), 0); } - - case "abtelefull": { - Dictionary action = new Dictionary(); - action["action"] = "TeleportFull"; - action["position"] = new Vector3(7f, 0.95f, 6.4f); - action["rotation"] = new Vector3(0f, 180f, 0f); - action["horizon"] = -20f; - CurrentActiveController().ProcessControlCommand(action); - break; + else if (splitcommand.Length >= 6) + { + action["x"] = float.Parse(splitcommand[1]); + action["y"] = float.Parse(splitcommand[2]); + action["z"] = float.Parse(splitcommand[3]); + rotation = new Vector3(0, float.Parse(splitcommand[4]), 0); + horizon = float.Parse(splitcommand[5]); } - case "telefull": { - Dictionary action = new Dictionary(); - action["action"] = "TeleportFull"; - action["x"] = -1f; - action["y"] = 0.9009995460510254f; - action["z"] = 1.5f; - Vector3 rotation = new Vector3(0, 135.0f, 0); - float horizon = Agent - .GetComponent() - .AgentCamera.transform.eulerAngles.x; - bool standing = true; + action["rotation"] = rotation; + action["horizon"] = horizon; + action["standing"] = standing; - if (splitcommand.Length > 1 && splitcommand.Length < 6) { - action["x"] = float.Parse(splitcommand[1]); - action["y"] = float.Parse(splitcommand[2]); - action["z"] = float.Parse(splitcommand[3]); - rotation = new Vector3(0, float.Parse(splitcommand[4]), 0); - } else if (splitcommand.Length >= 6) { - action["x"] = float.Parse(splitcommand[1]); - action["y"] = float.Parse(splitcommand[2]); - action["z"] = float.Parse(splitcommand[3]); - rotation = new Vector3(0, float.Parse(splitcommand[4]), 0); - horizon = float.Parse(splitcommand[5]); - } + CurrentActiveController().ProcessControlCommand(action); + break; + } - action["rotation"] = rotation; - action["horizon"] = horizon; - action["standing"] = standing; + 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"; + case "expfit": + { + Dictionary action = new Dictionary(); + action["action"] = "WhichContainersDoesAvailableObjectFitIn"; + action["objectName"] = "AlarmClock_dd21c3db"; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "scale": + { + Dictionary action = new Dictionary(); + action["action"] = "ScaleObject"; + action["objectId"] = "Box|+00.00|+01.33|-00.44"; + action["scale"] = 0.6746510624885559f; + action["scaleOverSeconds"] = 0f; + action["forceAction"] = true; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 1) + { + action["scale"] = float.Parse(splitcommand[1]); } - - case "expfit": { - Dictionary action = new Dictionary(); - action["action"] = "WhichContainersDoesAvailableObjectFitIn"; - action["objectName"] = "AlarmClock_dd21c3db"; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length > 2) + { + action["scaleOverSeconds"] = float.Parse(splitcommand[2]); } - case "scale": { - Dictionary action = new Dictionary(); - action["action"] = "ScaleObject"; - action["objectId"] = "Box|+00.00|+01.33|-00.44"; - action["scale"] = 0.6746510624885559f; - action["scaleOverSeconds"] = 0f; - action["forceAction"] = true; - if (splitcommand.Length > 1) { - action["scale"] = float.Parse(splitcommand[1]); - } - if (splitcommand.Length > 2) { - action["scaleOverSeconds"] = float.Parse(splitcommand[2]); + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "closepoints": + { + Dictionary action = new Dictionary(); + action["action"] = "PointOnObjectsCollidersClosestToPoint"; + action["objectId"] = "Dumbbell|+00.00|+00.90|+00.00"; + action["point"] = new Vector3(0f, 1000f, 0f); + //action["objectId"] = "2|1"; + //action["point"] = new Vector3(13.569999694824219f, 0.8979997634887695f, 2.1710000038146973f); + + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "mc": + { + Dictionary action = new Dictionary(); + action["action"] = "MoveAgent"; + action["speed"] = 1; + if (splitcommand.Length > 2) + { + action["ahead"] = float.Parse(splitcommand[1]); + action["right"] = float.Parse(splitcommand[2]); + + if (splitcommand.Length > 3) + { + action["speed"] = float.Parse(splitcommand[3]); } - - CurrentActiveController().ProcessControlCommand(action); - break; } - case "closepoints": { - Dictionary action = new Dictionary(); - action["action"] = "PointOnObjectsCollidersClosestToPoint"; - action["objectId"] = "Dumbbell|+00.00|+00.90|+00.00"; - action["point"] = new Vector3(0f, 1000f, 0f); - //action["objectId"] = "2|1"; - //action["point"] = new Vector3(13.569999694824219f, 0.8979997634887695f, 2.1710000038146973f); - CurrentActiveController().ProcessControlCommand(action); - break; - } - case "mc": { - Dictionary action = new Dictionary(); - action["action"] = "MoveAgent"; - action["speed"] = 1; - if (splitcommand.Length > 2) { - action["ahead"] = float.Parse(splitcommand[1]); - action["right"] = float.Parse(splitcommand[2]); + action["physicsSimulationParams"] = new PhysicsSimulationParams() + { + autoSimulation = false + }; + action["returnToStart"] = true; - if (splitcommand.Length > 3) { - action["speed"] = float.Parse(splitcommand[3]); - } - } + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "rc": + { + Dictionary action = new Dictionary(); + action["action"] = "RotateAgent"; + // if (splitcommand.Length > 2) { + action["degrees"] = float.Parse(splitcommand[1]); + + // if (splitcommand.Length >= 3) { + // action.speed = float.Parse(splitcommand[2]); + // } + + // if (splitcommand.Length >= 4) { + // action.disableRendering = bool.Parse(splitcommand[3]); + // } + + // if (splitcommand.Length >= 5) { + // action.returnToStart = bool.Parse(splitcommand[4]); + // } + // } + + CurrentActiveController().ProcessControlCommand(action); + break; + } - action["physicsSimulationParams"] = new PhysicsSimulationParams() { - autoSimulation = false - }; - action["returnToStart"] = true; + default: + { + Dictionary action = new Dictionary(); - CurrentActiveController().ProcessControlCommand(action); - break; + action["action"] = splitcommand[0]; + if (splitcommand.Length == 2) + { + action["objectId"] = splitcommand[1]; } - case "rc": { - Dictionary action = new Dictionary(); - action["action"] = "RotateAgent"; - // if (splitcommand.Length > 2) { - action["degrees"] = float.Parse(splitcommand[1]); - - // if (splitcommand.Length >= 3) { - // action.speed = float.Parse(splitcommand[2]); - // } - - // if (splitcommand.Length >= 4) { - // action.disableRendering = bool.Parse(splitcommand[3]); - // } - - // if (splitcommand.Length >= 5) { - // action.returnToStart = bool.Parse(splitcommand[4]); - // } - // } - - CurrentActiveController().ProcessControlCommand(action); - break; + else if (splitcommand.Length == 3) + { + action["x"] = float.Parse(splitcommand[1]); + action["z"] = float.Parse(splitcommand[2]); + } + else if (splitcommand.Length == 4) + { + action["x"] = float.Parse(splitcommand[1]); + action["y"] = float.Parse(splitcommand[2]); + action["z"] = float.Parse(splitcommand[3]); } + CurrentActiveController().ProcessControlCommand(action); + // Debug.Log("Invalid Command"); + break; + } - default: { - Dictionary action = new Dictionary(); + // rotate kinematic hand on arm + case "rmlh": + { + ServerAction action = new ServerAction(); + + action.action = "RotateMidLevelHand"; + + if (splitcommand.Length > 4) + { + action.rotation = new Vector3( + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]) + ); - action["action"] = splitcommand[0]; - if (splitcommand.Length == 2) { - action["objectId"] = splitcommand[1]; - } else if (splitcommand.Length == 3) { - action["x"] = float.Parse(splitcommand[1]); - action["z"] = float.Parse(splitcommand[2]); - } else if (splitcommand.Length == 4) { - action["x"] = float.Parse(splitcommand[1]); - action["y"] = float.Parse(splitcommand[2]); - action["z"] = float.Parse(splitcommand[3]); + if (splitcommand.Length >= 5) + { + action.speed = float.Parse(splitcommand[4]); } - CurrentActiveController().ProcessControlCommand(action); - // Debug.Log("Invalid Command"); - break; } - // rotate kinematic hand on arm - case "rmlh": { - ServerAction action = new ServerAction(); - - action.action = "RotateMidLevelHand"; + CurrentActiveController().ProcessControlCommand(action); - if (splitcommand.Length > 4) { - action.rotation = new Vector3( - float.Parse(splitcommand[1]), - float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]) - ); + break; + } - if (splitcommand.Length >= 5) { - action.speed = float.Parse(splitcommand[4]); - } - } + 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" + }; + CurrentActiveController().ProcessControlCommand(action); + break; + } - CurrentActiveController().ProcessControlCommand(action); + case "smooth": + { + Dictionary action = new Dictionary(); + action["action"] = "RandomizeSmoothness"; + action["objectIds"] = new string[] { "small|room|14", "Sofa1" }; + CurrentActiveController().ProcessControlCommand(action); + break; + } - break; - } + case "dmlh": + { + ServerAction action = new ServerAction(); + action.action = "DropMidLevelHand"; + CurrentActiveController().ProcessControlCommand(action); + break; + } + case "smlhr": + { + ServerAction action = new ServerAction(); + action.action = "SetHandSphereRadius"; - 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" - }; - CurrentActiveController().ProcessControlCommand(action); - break; + if (splitcommand.Length == 2) + { + action.radius = float.Parse(splitcommand[1]); } + CurrentActiveController().ProcessControlCommand(action); - case "smooth": { - Dictionary action = new Dictionary(); - action["action"] = "RandomizeSmoothness"; - action["objectIds"] = new string[] { "small|room|14", "Sofa1" }; - CurrentActiveController().ProcessControlCommand(action); - break; + break; + } + case "cr": + { + // dynamic action = new JObject(); + Dictionary action = new Dictionary(); + + // AssetDatabase.Refresh(); + action["action"] = "CreateRoom"; + TextAsset text = Resources.Load("rooms/" + "4.json"); + var ROOM_BASE_PATH = "/Resources/rooms/"; + 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" + ); } - - case "dmlh": { - ServerAction action = new ServerAction(); - action.action = "DropMidLevelHand"; - CurrentActiveController().ProcessControlCommand(action); - break; + else if (splitcommand.Length == 2) + { + // uses ./debug/{splitcommand[1]}[.json] + file = splitcommand[1].Trim(); + if (!file.EndsWith(".json")) + { + file += ".json"; + } + path = Application.dataPath + ROOM_BASE_PATH + file; } - case "smlhr": { - ServerAction action = new ServerAction(); - action.action = "SetHandSphereRadius"; + //var json = text.text; - if (splitcommand.Length == 2) { - action.radius = float.Parse(splitcommand[1]); - } - CurrentActiveController().ProcessControlCommand(action); + // var json = text.text; - break; - } - case "cr": { - // dynamic action = new JObject(); - Dictionary action = new Dictionary(); - - // AssetDatabase.Refresh(); - action["action"] = "CreateRoom"; - TextAsset text = Resources.Load("rooms/" + "4.json"); - var ROOM_BASE_PATH = "/Resources/rooms/"; - 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" - ); - } else if (splitcommand.Length == 2) { - // uses ./debug/{splitcommand[1]}[.json] - file = splitcommand[1].Trim(); - if (!file.EndsWith(".json")) { - file += ".json"; - } - path = Application.dataPath + ROOM_BASE_PATH + file; - } - //var json = text.text; + // var json = "{\r\n \"walls\": [\r\n {\r\n \"p0\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 9.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 8.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n },\r\n \"p1\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n },\r\n \"p1\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 8.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 8.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 9.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n },\r\n \"p1\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 9.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n },\r\n \"p1\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n },\r\n \"p1\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n },\r\n \"p1\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n },\r\n \"p1\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 9.5\r\n },\r\n \"p1\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n },\r\n \"p1\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n },\r\n \"p1\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 8.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 8.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 9.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n },\r\n \"p1\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n },\r\n \"p1\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n },\r\n \"p1\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 8.5\r\n },\r\n \"p1\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 9.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n }\r\n }\r\n ]\r\n}"; + // var walls = Newtonsoft.Json.JsonConvert.DeserializeObject(json); - // var json = text.text; + // Debug.Log($"App path {Application.dataPath}"); + var jsonStr = System.IO.File.ReadAllText(path); + Debug.Log($"jjson: {jsonStr}"); - // var json = "{\r\n \"walls\": [\r\n {\r\n \"p0\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 9.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 8.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n },\r\n \"p1\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n },\r\n \"p1\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 8.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 8.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 9.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n },\r\n \"p1\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 9.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n },\r\n \"p1\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n },\r\n \"p1\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n },\r\n \"p1\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n },\r\n \"p1\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 9.5\r\n },\r\n \"p1\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n },\r\n \"p1\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n },\r\n \"p1\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 8.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 2.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 3.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 10.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 8.5\r\n },\r\n \"p1\": {\r\n \"x\": 4.5,\r\n \"y\": 0,\r\n \"z\": 9.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 9.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n },\r\n \"p1\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 7.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n },\r\n \"p1\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n },\r\n \"p1\": {\r\n \"x\": 8.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 4.5\r\n },\r\n \"p1\": {\r\n \"x\": 0.5,\r\n \"y\": 0,\r\n \"z\": 5.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n },\r\n \"p1\": {\r\n \"x\": 7.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 8.5\r\n },\r\n \"p1\": {\r\n \"x\": 1.5,\r\n \"y\": 0,\r\n \"z\": 9.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n },\r\n \"p1\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 6.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 5.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n },\r\n \"p1\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 3.5\r\n }\r\n },\r\n {\r\n \"p0\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 1.5\r\n },\r\n \"p1\": {\r\n \"x\": 6.5,\r\n \"y\": 0,\r\n \"z\": 2.5\r\n }\r\n }\r\n ]\r\n}"; - // var walls = Newtonsoft.Json.JsonConvert.DeserializeObject(json); + JObject obj = JObject.Parse(jsonStr); - // Debug.Log($"App path {Application.dataPath}"); - var jsonStr = System.IO.File.ReadAllText(path); - Debug.Log($"jjson: {jsonStr}"); + // var k = JObject.Parse(jsonStr); + // JArray wallsJson = k["walls"]; - JObject obj = JObject.Parse(jsonStr); - // var k = JObject.Parse(jsonStr); - // JArray wallsJson = k["walls"]; + // foreach (JObject wall in wallsJson) { + // while (PhysicsController.IsProcessing) { + // yield return new WaitForEndOfFrame(); + // } + // CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + // } - // foreach (JObject wall in wallsJson) { - // while (PhysicsController.IsProcessing) { - // yield return new WaitForEndOfFrame(); - // } + // var r = k.ToObject(); - // CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - // } + // var l = new List(); + // foreach (var wall in wallsJson) { + // l.Add(wall.ToObject()); + // } + action["walls"] = obj["walls"]; + action["wallHeight"] = 2.0f; + action["wallMaterialId"] = "DrywallOrange"; + action["floorMaterialId"] = "DarkWoodFloors"; + action["ceilingMaterialId"] = ""; + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + + // CurrentActiveController().CreateRoom( + // new Wall[] { + // new Wall() { + // p0 = new Vector3(0, 0, 0), + // p1 = new Vector3(10, 0, 0), + // height = 2.0f, + // materialId = "DrywallOrange" + // }, + // new Wall() { + // p0 = new Vector3(0, 0, 10), + // p1 = new Vector3(10, 0, 10), + // height = 2.0f, + // materialId = "DrywallOrange" + // }, + // new Wall() { + // p0 = new Vector3(10, 0, 10), + // p1 = new Vector3(10, 0, 0), + // height = 2.0f, + // materialId = "DrywallOrange" + // }, + // new Wall() { + // p0 = new Vector3(0, 0, 10), + // p1 = new Vector3(0, 0, 0), + // height = 2.0f, + // materialId = "DrywallOrange" + // } + // }, + // 2.0f, + // "DrywallOrange", + // "DarkWoodFloors" + // ); + break; - // var r = k.ToObject(); + // 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; + } + case "newScene2": + { + UnityEngine.SceneManagement.SceneManager.LoadScene("Procedural"); + break; + } + case "ch": + { + Dictionary action = new Dictionary(); - // var l = new List(); - // foreach (var wall in wallsJson) { - // l.Add(wall.ToObject()); - // } - action["walls"] = obj["walls"]; - action["wallHeight"] = 2.0f; - action["wallMaterialId"] = "DrywallOrange"; - action["floorMaterialId"] = "DarkWoodFloors"; - action["ceilingMaterialId"] = ""; - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action)); - - // CurrentActiveController().CreateRoom( - // new Wall[] { - // new Wall() { - // p0 = new Vector3(0, 0, 0), - // p1 = new Vector3(10, 0, 0), - // height = 2.0f, - // materialId = "DrywallOrange" - // }, - // new Wall() { - // p0 = new Vector3(0, 0, 10), - // p1 = new Vector3(10, 0, 10), - // height = 2.0f, - // materialId = "DrywallOrange" - // }, - // new Wall() { - // p0 = new Vector3(10, 0, 10), - // p1 = new Vector3(10, 0, 0), - // height = 2.0f, - // materialId = "DrywallOrange" - // }, - // new Wall() { - // p0 = new Vector3(0, 0, 10), - // p1 = new Vector3(0, 0, 0), - // height = 2.0f, - // materialId = "DrywallOrange" - // } - // }, - // 2.0f, - // "DrywallOrange", - // "DarkWoodFloors" - // ); - break; + // AssetDatabase.Refresh(); + action["action"] = "CreateHouse"; - // 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; - } - case "newScene2": { - UnityEngine.SceneManagement.SceneManager.LoadScene("Procedural"); - break; - } - case "ch": { - Dictionary action = new Dictionary(); + var jsonStr = System.IO.File.ReadAllText( + Application.dataPath + "/Resources/rooms/house.json" + ); + Debug.Log($"jjson: {jsonStr}"); - // AssetDatabase.Refresh(); - action["action"] = "CreateHouse"; + JObject obj = JObject.Parse(jsonStr); - 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().CreateHouse( - // new House() { - // ceilingMaterialId = "DrywallOrange", - // rooms = new RectangleRoom[] { - // new RectangleRoom() { - // walls = - // new Wall[] { - // new Wall() { - // p0 = new Vector3(0, 0, 0), - // p1 = new Vector3(10, 0, 0), - // height = 2.0f, - // materialId = "DrywallOrange" - // }, - // new Wall() { - // p0 = new Vector3(0, 0, 10), - // p1 = new Vector3(10, 0, 10), - // height = 2.0f, - // materialId = "DrywallOrange" - // }, - // new Wall() { - // p0 = new Vector3(10, 0, 10), - // p1 = new Vector3(10, 0, 0), - // height = 2.0f, - // materialId = "DrywallOrange" - // }, - // new Wall() { - // p0 = new Vector3(0, 0, 10), - // p1 = new Vector3(0, 0, 0), - // height = 2.0f, - // materialId = "DrywallOrange" - // } - // }, - // rectangleFloor = new RectangleFloor() { - // materialId = "DarkWoodFloors" - // } - // }, - // new RectangleRoom() { - // walls = - // new Wall[] { - // new Wall() { - // p0 = new Vector3(2.5f, 0, 0), - // p1 = new Vector3(5, 0, 0), - // height = 2.0f, - // materialId = "DrywallOrange" - // }, - // new Wall() { - // p0 = new Vector3(2.5f, 0, 5), - // p1 = new Vector3(5, 0, 5), - // height = 2.0f, - // materialId = "DrywallOrange" - // }, - // new Wall() { - // p0 = new Vector3(5, 0, 5), - // p1 = new Vector3(5, 0, 0), - // height = 2.0f, - // materialId = "DrywallOrange" - // }, - // new Wall() { - // p0 = new Vector3(2.5f, 0, 5), - // p1 = new Vector3(2.5f, 0, 0), - // height = 2.0f, - // materialId = "DrywallOrange" - // } - // }, - // rectangleFloor = new RectangleFloor() { - // materialId = "DarkWoodFloors" - // } - // }, - // } - // } - // ); + action["house"] = obj; + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + + // CurrentActiveController().CreateHouse( + // new House() { + // ceilingMaterialId = "DrywallOrange", + // rooms = new RectangleRoom[] { + // new RectangleRoom() { + // walls = + // new Wall[] { + // new Wall() { + // p0 = new Vector3(0, 0, 0), + // p1 = new Vector3(10, 0, 0), + // height = 2.0f, + // materialId = "DrywallOrange" + // }, + // new Wall() { + // p0 = new Vector3(0, 0, 10), + // p1 = new Vector3(10, 0, 10), + // height = 2.0f, + // materialId = "DrywallOrange" + // }, + // new Wall() { + // p0 = new Vector3(10, 0, 10), + // p1 = new Vector3(10, 0, 0), + // height = 2.0f, + // materialId = "DrywallOrange" + // }, + // new Wall() { + // p0 = new Vector3(0, 0, 10), + // p1 = new Vector3(0, 0, 0), + // height = 2.0f, + // materialId = "DrywallOrange" + // } + // }, + // rectangleFloor = new RectangleFloor() { + // materialId = "DarkWoodFloors" + // } + // }, + // new RectangleRoom() { + // walls = + // new Wall[] { + // new Wall() { + // p0 = new Vector3(2.5f, 0, 0), + // p1 = new Vector3(5, 0, 0), + // height = 2.0f, + // materialId = "DrywallOrange" + // }, + // new Wall() { + // p0 = new Vector3(2.5f, 0, 5), + // p1 = new Vector3(5, 0, 5), + // height = 2.0f, + // materialId = "DrywallOrange" + // }, + // new Wall() { + // p0 = new Vector3(5, 0, 5), + // p1 = new Vector3(5, 0, 0), + // height = 2.0f, + // materialId = "DrywallOrange" + // }, + // new Wall() { + // p0 = new Vector3(2.5f, 0, 5), + // p1 = new Vector3(2.5f, 0, 0), + // height = 2.0f, + // materialId = "DrywallOrange" + // } + // }, + // rectangleFloor = new RectangleFloor() { + // materialId = "DarkWoodFloors" + // } + // }, + // } + // } + // ); - break; - } + break; + } - case "obj": { - // AssetDatabase.Refresh(); - var OBJECTS_BASE_PATH = "/Resources/objects/"; + case "obj": + { + // AssetDatabase.Refresh(); + var OBJECTS_BASE_PATH = "/Resources/objects/"; - path = Application.dataPath + OBJECTS_BASE_PATH + "main.json"; + path = Application.dataPath + OBJECTS_BASE_PATH + "main.json"; - if (splitcommand.Length == 2) { - // uses ./debug/{splitcommand[1]}[.json] - file = splitcommand[1].Trim(); - if (!file.EndsWith(".json")) { - file += ".json"; - } - path = Application.dataPath + OBJECTS_BASE_PATH + file; + if (splitcommand.Length == 2) + { + // uses ./debug/{splitcommand[1]}[.json] + file = splitcommand[1].Trim(); + if (!file.EndsWith(".json")) + { + file += ".json"; } + path = Application.dataPath + OBJECTS_BASE_PATH + file; + } - var jsonStr = System.IO.File.ReadAllText(path); - Debug.Log($"jjson: {jsonStr}"); + var jsonStr = System.IO.File.ReadAllText(path); + Debug.Log($"jjson: {jsonStr}"); - JObject obj = JObject.Parse(jsonStr); + JObject obj = JObject.Parse(jsonStr); - obj["action"] = "CreateRuntimeAsset"; - obj["serializable"] = true; - CurrentActiveController().ProcessControlCommand(new DynamicServerAction(obj)); + obj["action"] = "CreateRuntimeAsset"; + obj["serializable"] = true; + CurrentActiveController().ProcessControlCommand(new DynamicServerAction(obj)); - break; - } + break; + } - case "chp": { - Dictionary action = new Dictionary(); + case "chp": + { + Dictionary action = new Dictionary(); - // AssetDatabase.Refresh(); - action["action"] = "CreateHouse"; - var ROOM_BASE_PATH = "/Resources/rooms/"; + // AssetDatabase.Refresh(); + action["action"] = "CreateHouse"; + var ROOM_BASE_PATH = "/Resources/rooms/"; - path = Application.dataPath + "/Resources/rooms/house_full.json"; + path = Application.dataPath + "/Resources/rooms/house_full.json"; - if (splitcommand.Length == 2) { - // uses ./debug/{splitcommand[1]}[.json] - file = splitcommand[1].Trim(); - if (!file.EndsWith(".json")) { - file += ".json"; - } - path = Application.dataPath + ROOM_BASE_PATH + file; + if (splitcommand.Length == 2) + { + // uses ./debug/{splitcommand[1]}[.json] + file = splitcommand[1].Trim(); + if (!file.EndsWith(".json")) + { + file += ".json"; } + path = Application.dataPath + ROOM_BASE_PATH + file; + } - var jsonStr = System.IO.File.ReadAllText(path); - Debug.Log($"jjson: {jsonStr}"); + var jsonStr = System.IO.File.ReadAllText(path); + Debug.Log($"jjson: {jsonStr}"); - JObject obj = JObject.Parse(jsonStr); + JObject obj = JObject.Parse(jsonStr); - action["house"] = obj; - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action)); + action["house"] = obj; + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); - break; - } - case "chp_direct": { - Dictionary action = new Dictionary(); + break; + } + case "chp_direct": + { + Dictionary action = new Dictionary(); - // AssetDatabase.Refresh(); - action["action"] = "CreateHouse"; - var ROOM_BASE_PATH = "/Resources/rooms/"; + // AssetDatabase.Refresh(); + action["action"] = "CreateHouse"; + var ROOM_BASE_PATH = "/Resources/rooms/"; - path = Application.dataPath + "/Resources/rooms/house_full.json"; + path = Application.dataPath + "/Resources/rooms/house_full.json"; - if (splitcommand.Length == 2) { - // uses ./debug/{splitcommand[1]}[.json] - file = splitcommand[1].Trim(); - if (!file.EndsWith(".json")) { - file += ".json"; - } - path = Application.dataPath + ROOM_BASE_PATH + file; + if (splitcommand.Length == 2) + { + // uses ./debug/{splitcommand[1]}[.json] + file = splitcommand[1].Trim(); + if (!file.EndsWith(".json")) + { + file += ".json"; } + path = Application.dataPath + ROOM_BASE_PATH + file; + } - var jsonStr = System.IO.File.ReadAllText(path); - Debug.Log($"jjson: {jsonStr}"); + var jsonStr = System.IO.File.ReadAllText(path); + Debug.Log($"jjson: {jsonStr}"); - JObject obj = JObject.Parse(jsonStr); + JObject obj = JObject.Parse(jsonStr); - action["house"] = obj; - // CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); - ProceduralTools.CreateHouse( - obj.ToObject(), - ProceduralTools.GetMaterials() - ); - break; - } - case "chpt_direct": { - Dictionary action = new Dictionary(); + action["house"] = obj; + // CurrentActiveController().ProcessControlCommand(new DynamicServerAction(action)); + ProceduralTools.CreateHouse( + obj.ToObject(), + ProceduralTools.GetMaterials() + ); + break; + } + case "chpt_direct": + { + Dictionary action = new Dictionary(); - // AssetDatabase.Refresh(); - var ROOM_BASE_PATH = "/Resources/rooms/"; + // AssetDatabase.Refresh(); + var ROOM_BASE_PATH = "/Resources/rooms/"; - path = Application.dataPath + "/Resources/rooms/house-template.json"; + path = Application.dataPath + "/Resources/rooms/house-template.json"; - if (splitcommand.Length == 2) { - // uses ./debug/{splitcommand[1]}[.json] - file = splitcommand[1].Trim(); - if (!file.EndsWith(".json")) { - file += ".json"; - } - path = Application.dataPath + ROOM_BASE_PATH + file; + if (splitcommand.Length == 2) + { + // uses ./debug/{splitcommand[1]}[.json] + file = splitcommand[1].Trim(); + if (!file.EndsWith(".json")) + { + file += ".json"; } + path = Application.dataPath + ROOM_BASE_PATH + file; + } - var jsonStr = System.IO.File.ReadAllText(path); - Debug.Log($"jjson: {jsonStr}"); + var jsonStr = System.IO.File.ReadAllText(path); + Debug.Log($"jjson: {jsonStr}"); - JObject obj = JObject.Parse(jsonStr); + JObject obj = JObject.Parse(jsonStr); - var house = Thor.Procedural.Templates.createHouseFromTemplate( - obj.ToObject() - ); - // var house = CurrentActiveController().actionReturn; + var house = Thor.Procedural.Templates.createHouseFromTemplate( + obj.ToObject() + ); + // var house = CurrentActiveController().actionReturn; - action.Clear(); + action.Clear(); - action["action"] = "CreateHouse"; - action["house"] = house; + action["action"] = "CreateHouse"; + action["house"] = house; - 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 - } - ); + 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: " + 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); + 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(); + break; + } + case "chpt": + { + Dictionary action = new Dictionary(); - // AssetDatabase.Refresh(); - action["action"] = "GetHouseFromTemplate"; - var ROOM_BASE_PATH = "/Resources/rooms/"; + // AssetDatabase.Refresh(); + action["action"] = "GetHouseFromTemplate"; + var ROOM_BASE_PATH = "/Resources/rooms/"; - path = Application.dataPath + "/Resources/rooms/house-template.json"; + path = Application.dataPath + "/Resources/rooms/house-template.json"; - if (splitcommand.Length == 2) { - // uses ./debug/{splitcommand[1]}[.json] - file = splitcommand[1].Trim(); - if (!file.EndsWith(".json")) { - file += ".json"; - } - path = Application.dataPath + ROOM_BASE_PATH + file; + if (splitcommand.Length == 2) + { + // uses ./debug/{splitcommand[1]}[.json] + file = splitcommand[1].Trim(); + if (!file.EndsWith(".json")) + { + file += ".json"; } + path = Application.dataPath + ROOM_BASE_PATH + file; + } - var jsonStr = System.IO.File.ReadAllText(path); - Debug.Log($"jjson: {jsonStr}"); - - JObject obj = JObject.Parse(jsonStr); + var jsonStr = System.IO.File.ReadAllText(path); + Debug.Log($"jjson: {jsonStr}"); - action["template"] = obj; + JObject obj = JObject.Parse(jsonStr); - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action)); + action["template"] = obj; - var house = CurrentActiveController().actionReturn; + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); - Debug.Log(house); + var house = CurrentActiveController().actionReturn; - action.Clear(); + Debug.Log(house); - action["action"] = "CreateHouse"; - action["house"] = house; + action.Clear(); - 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"; + action["action"] = "CreateHouse"; + action["house"] = house; - System.IO.File.WriteAllText(destination, houseString); + 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"; - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action)); + System.IO.File.WriteAllText(destination, houseString); - break; - } - case "gad": { - Dictionary action = new Dictionary(); + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); - // AssetDatabase.Refresh(); - action["action"] = "GetAssetDatabase"; + break; + } + case "gad": + { + Dictionary action = new Dictionary(); - 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; - } + // AssetDatabase.Refresh(); + action["action"] = "GetAssetDatabase"; - case "gadt": { - CurrentActiveController().GetAssetDatabase(); - var assetMetadata = - (List)CurrentActiveController().actionReturn - as List; + 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; + } - 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)); - break; - } - case "soir": { - Dictionary action = new Dictionary(); - action["action"] = "SpawnObjectInReceptacle"; - action["prefabName"] = "Dining_Table_16_1"; - 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)); - break; - } - case "bnm": { - Dictionary action = new Dictionary(); - action["action"] = "BakeNavMesh"; - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action)); - break; - } - case "va": { - Dictionary action = new Dictionary(); - action["action"] = "SpawnAsset"; - action["assetId"] = "Dining_Table_16_1"; - action["generatedId"] = "asset_0"; - // action["skyboxColor"] = new Color(0, 0, 0, 1); + case "gadt": + { + CurrentActiveController().GetAssetDatabase(); + var assetMetadata = + (List)CurrentActiveController().actionReturn + as List; - if (splitcommand.Length == 2) { - action["assetId"] = splitcommand[1]; - } + 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)); + break; + } + case "soir": + { + Dictionary action = new Dictionary(); + action["action"] = "SpawnObjectInReceptacle"; + action["prefabName"] = "Dining_Table_16_1"; + 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)); + break; + } + case "bnm": + { + Dictionary action = new Dictionary(); + action["action"] = "BakeNavMesh"; + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + break; + } + case "va": + { + Dictionary action = new Dictionary(); + action["action"] = "SpawnAsset"; + action["assetId"] = "Dining_Table_16_1"; + action["generatedId"] = "asset_0"; + // action["skyboxColor"] = new Color(0, 0, 0, 1); - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action)); - break; + if (splitcommand.Length == 2) + { + action["assetId"] = splitcommand[1]; } - 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]) - ), - degrees = float.Parse(splitcommand[4]) - }; - } - if (splitcommand.Length == 6) { - action["absolute"] = bool.Parse(splitcommand[5]); - } - - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action)); - break; - } - case "laoc": { - Dictionary action = new Dictionary(); - action["action"] = "LookAtObjectCenter"; - action["objectId"] = "asset_0"; + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + break; + } - if (splitcommand.Length == 2) { - action["objectId"] = splitcommand[1]; - } + case "ra": + { + Dictionary action = new Dictionary(); + action["action"] = "RotateObject"; + action["objectId"] = "asset_0"; - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action)); - break; - } - case "sky": { - Dictionary action = new Dictionary(); - action["action"] = "SetSkybox"; - action["color"] = new Color(0, 0, 0, 1); - if (splitcommand.Length == 5) { - action["color"] = new Color( + if (splitcommand.Length > 4) + { + action["angleAxisRotation"] = new FlexibleRotation() + { + axis = new Vector3( float.Parse(splitcommand[1]), float.Parse(splitcommand[2]), - float.Parse(splitcommand[3]), - float.Parse(splitcommand[4]) - ); - } + float.Parse(splitcommand[3]) + ), + degrees = float.Parse(splitcommand[4]) + }; + } + if (splitcommand.Length == 6) + { + action["absolute"] = bool.Parse(splitcommand[5]); + } - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action)); - break; + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + break; + } + case "laoc": + { + Dictionary action = new Dictionary(); + action["action"] = "LookAtObjectCenter"; + action["objectId"] = "asset_0"; + + if (splitcommand.Length == 2) + { + action["objectId"] = splitcommand[1]; } - 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; - 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))}" + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + break; + } + case "sky": + { + Dictionary action = new Dictionary(); + action["action"] = "SetSkybox"; + action["color"] = new Color(0, 0, 0, 1); + if (splitcommand.Length == 5) + { + action["color"] = new Color( + float.Parse(splitcommand[1]), + float.Parse(splitcommand[2]), + float.Parse(splitcommand[3]), + float.Parse(splitcommand[4]) ); - break; } - case "ca_msg": { - if (splitcommand.Length == 2) { - var objectId = splitcommand[1]; + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); + break; + } + case "g3d": + { + Dictionary action = new Dictionary(); + action["action"] = "GetAsset3DGeometry"; + if (splitcommand.Length == 2) + { + action["assetId"] = splitcommand[1]; + } - var fname = objectId.Trim(); - // if (!fname.EndsWith(".json")) { - // fname += ".msgpack.gz"; - // } + 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))}" + ); + break; + } - var pathSplit = Application.dataPath.Split('/'); + case "ca_msg": + { + if (splitcommand.Length == 2) + { + var objectId = splitcommand[1]; - var repoRoot = pathSplit.Reverse().Skip(2).Reverse().ToList(); - Debug.Log(string.Join("/", repoRoot)); + var fname = objectId.Trim(); + // if (!fname.EndsWith(".json")) { + // fname += ".msgpack.gz"; + // } - var objaverseRoot = $"{string.Join("/", repoRoot)}/objaverse"; - var objectDir = $"{objaverseRoot}/{objectId}"; - var objectPath = $"{objectDir}/{fname}"; + var pathSplit = Application.dataPath.Split('/'); - // var filename = Path.GetFileName(objectPath); + var repoRoot = pathSplit.Reverse().Skip(2).Reverse().ToList(); + Debug.Log(string.Join("/", repoRoot)); - //var pathOut = Application.dataPath + $"/Resources/msgpack_test/{objectId}.json"; + var objaverseRoot = $"{string.Join("/", repoRoot)}/objaverse"; + var objectDir = $"{objaverseRoot}/{objectId}"; + var objectPath = $"{objectDir}/{fname}"; - var af = CurrentActiveController().CreateRuntimeAsset(fname, objaverseRoot); - Debug.Log($"ActionFinished {af.success} {af.errorMessage}"); - } + // var filename = Path.GetFileName(objectPath); - break; - } - case "caid_msg": { - if (splitcommand.Length == 2) { - var objectId = splitcommand[1]; + //var pathOut = Application.dataPath + $"/Resources/msgpack_test/{objectId}.json"; - var fname = objectId.Trim(); - if (!fname.EndsWith(".json")) { - fname += ".msgpack.gz"; - } + var af = CurrentActiveController().CreateRuntimeAsset(fname, objaverseRoot); + Debug.Log($"ActionFinished {af.success} {af.errorMessage}"); + } - var pathSplit = Application.dataPath.Split('/'); + break; + } + case "caid_msg": + { + if (splitcommand.Length == 2) + { + var objectId = splitcommand[1]; + + var fname = objectId.Trim(); + if (!fname.EndsWith(".json")) + { + fname += ".msgpack.gz"; + } - var repoRoot = pathSplit.Reverse().Skip(2).Reverse().ToList(); - Debug.Log(string.Join("/", repoRoot)); + var pathSplit = Application.dataPath.Split('/'); - var objaverseRoot = $"{string.Join("/", repoRoot)}/objaverse"; - var objectDir = $"{objaverseRoot}/{objectId}"; - var objectPath = $"{objectDir}/{fname}"; - var dir = Application.persistentDataPath; + var repoRoot = pathSplit.Reverse().Skip(2).Reverse().ToList(); + Debug.Log(string.Join("/", repoRoot)); - var filename = Path.GetFileName(objectPath); + var objaverseRoot = $"{string.Join("/", repoRoot)}/objaverse"; + var objectDir = $"{objaverseRoot}/{objectId}"; + var objectPath = $"{objectDir}/{fname}"; + var dir = Application.persistentDataPath; - var pathOut = - Application.dataPath + $"/Resources/msgpack_test/{objectId}.json"; + var filename = Path.GetFileName(objectPath); - CurrentActiveController().CreateRuntimeAsset(objectId, dir); - } + var pathOut = + Application.dataPath + $"/Resources/msgpack_test/{objectId}.json"; - break; + CurrentActiveController().CreateRuntimeAsset(objectId, dir); } - case "proc_mats": { - var mats = ProceduralTools.GetMaterials(); - var matString = string.Join("\n", mats.Keys()); - Debug.Log(matString); + break; + } - //string destination = Application.persistentDataPath + "/save.dat"; - // FileStream f; + case "proc_mats": + { + var mats = ProceduralTools.GetMaterials(); + var matString = string.Join("\n", mats.Keys()); + Debug.Log(matString); - StreamWriter f = new StreamWriter("mats.txt", append: false); + //string destination = Application.persistentDataPath + "/save.dat"; + // FileStream f; - f.WriteLine(matString); - break; - } - case "proc_prefabs": { - var prefabs = ProceduralTools.GetPrefabs(); - var prefabsStr = string.Join("\n", prefabs.Keys()); - Debug.Log(prefabsStr); + StreamWriter f = new StreamWriter("mats.txt", append: false); - //string destination = Application.persistentDataPath + "/save.dat"; - // FileStream f; + f.WriteLine(matString); + break; + } + case "proc_prefabs": + { + var prefabs = ProceduralTools.GetPrefabs(); + var prefabsStr = string.Join("\n", prefabs.Keys()); + Debug.Log(prefabsStr); - StreamWriter f = new StreamWriter("prefabs.txt", append: false); + //string destination = Application.persistentDataPath + "/save.dat"; + // FileStream f; - f.WriteLine(prefabsStr); - break; - } - case "nma": { - 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"; + StreamWriter f = new StreamWriter("prefabs.txt", append: false); - CurrentActiveController() - .ProcessControlCommand(new DynamicServerAction(action)); + f.WriteLine(prefabsStr); + break; + } + case "nma": + { + 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"; - var obj = (List)(CurrentActiveController().actionReturn); - Debug.Log($"{string.Join(",", obj)}"); - break; - } + CurrentActiveController() + .ProcessControlCommand(new DynamicServerAction(action)); - case "proc_arr": { - var arr = new int[][] - { + 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 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} - // }; + // 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) ] + // 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)) ] + // 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 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 @@ -5830,8 +6586,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 @@ -5848,33 +6604,33 @@ 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() - { + }, + // 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() @@ -5923,9 +6679,9 @@ 0 0 0 0 0 0 wallHeight = 3.0f } } - }, - doors = new Dictionary() - { + }, + doors = new Dictionary() + { { "=", new Thor.Procedural.Data.Door() @@ -5935,9 +6691,9 @@ 0 0 0 0 0 0 room0 = "1" } } - }, - objects = new Dictionary() - { + }, + objects = new Dictionary() + { { "*", new Thor.Procedural.Data.HouseObject() @@ -5965,18 +6721,19 @@ 0 0 0 0 0 0 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", - } + }, + proceduralParameters = new ProceduralParameters() + { + ceilingMaterial = new MaterialProperties() { name = "ps_mat" }, + floorColliderThickness = 1.0f, + receptacleHeight = 0.7f, + skyboxId = "Sky1", } - ); + } + ); - var temp = - @" + var temp = + @" { 'rooms': { '1': { @@ -5998,34 +6755,35 @@ 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); + 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()); + 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])); @@ -6035,7 +6793,8 @@ 0 0 0 0 0 0 #if UNITY_EDITOR // Taken from https://answers.unity.com/questions/1144378/copy-to-clipboard-with-a-button-unity-53-solution.html - public static void CopyToClipboard(string s) { + public static void CopyToClipboard(string s) + { TextEditor te = new TextEditor(); te.text = s; te.SelectAll(); @@ -6043,17 +6802,22 @@ public static void CopyToClipboard(string s) { } // used to show what's currently visible on the top left of the screen - void OnGUI() { + void OnGUI() + { if ( CurrentActiveController().VisibleSimObjPhysics != null && this.controlMode != ControlMode.MINIMAL_FPS - ) { - if (CurrentActiveController().VisibleSimObjPhysics.Length > 10) { + ) + { + if (CurrentActiveController().VisibleSimObjPhysics.Length > 10) + { int horzIndex = -1; GUILayout.BeginHorizontal(); - foreach (SimObjPhysics o in PhysicsController.VisibleSimObjPhysics) { + foreach (SimObjPhysics o in PhysicsController.VisibleSimObjPhysics) + { horzIndex++; - if (horzIndex >= 3) { + if (horzIndex >= 3) + { GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); horzIndex = 0; @@ -6066,11 +6830,14 @@ void OnGUI() { } GUILayout.EndHorizontal(); - } else { + } + else + { // Plane[] planes = GeometryUtility.CalculateFrustumPlanes(m_Camera); // int position_number = 0; - foreach (SimObjPhysics o in CurrentActiveController().VisibleSimObjPhysics) { + foreach (SimObjPhysics o in CurrentActiveController().VisibleSimObjPhysics) + { string suffix = ""; // Bounds bounds = new Bounds(o.gameObject.transform.position, new Vector3(0.05f, 0.05f, 0.05f)); // if (GeometryUtility.TestPlanesAABB(planes, bounds)) { @@ -6097,7 +6864,8 @@ void OnGUI() { UnityEditor.EditorStyles.miniButton, GUILayout.MinWidth(100f) ) - ) { + ) + { CopyToClipboard(o.ObjectID); } } diff --git a/unity/Assets/Scripts/DecalCollision.cs b/unity/Assets/Scripts/DecalCollision.cs index 07734ba8fe..e1e77dbdbf 100644 --- a/unity/Assets/Scripts/DecalCollision.cs +++ b/unity/Assets/Scripts/DecalCollision.cs @@ -2,13 +2,15 @@ using System.Collections.Generic; using UnityEngine; -public enum DecalRotationAxis { +public enum DecalRotationAxis +{ NONE, FORWARD, SIDE } -public class DecalCollision : Break { +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; @@ -37,26 +39,34 @@ public class DecalCollision : Break { private static int currentStencilId = 0; - void OnEnable() { + void OnEnable() + { breakType = BreakType.Decal; prevTime = Time.time; var mr = this.GetComponent(); - if (mr && mr.enabled) { - if (transparent) { - if (!sameStencilAsSiblings) { + if (mr && mr.enabled) + { + if (transparent) + { + if (!sameStencilAsSiblings) + { setStencilWriteValue(mr); - } else { + } + else + { 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) { + foreach (var spawnPlane in otherPlanes) + { if ( spawnPlane.isActiveAndEnabled && spawnPlane.stencilSet && spawnPlane.sameStencilAsSiblings - ) { + ) + { this.stencilWriteValue = spawnPlane.stencilWriteValue; this.stencilSet = true; mr.material.SetInt("_StencilRef", this.stencilWriteValue); @@ -64,21 +74,26 @@ void OnEnable() { break; } } - if (!stencilSet) { + if (!stencilSet) + { setStencilWriteValue(mr); } } - } else { + } + else + { this.stencilWriteValue = 1; mr.material.SetInt("_StencilRef", this.stencilWriteValue); } } } - private void setStencilWriteValue(MeshRenderer mr) { + private void setStencilWriteValue(MeshRenderer mr) + { DecalCollision.currentStencilId = DecalCollision.currentStencilId + 1; this.stencilWriteValue = DecalCollision.currentStencilId << 1; - if (this.stencilWriteValue > 0xFF) { + if (this.stencilWriteValue > 0xFF) + { this.stencilWriteValue = this.stencilWriteValue % 0xFF; // Debug.LogWarning("Stencil buffer write value overflow with: " + this.stencilWriteValue + " for " + this.gameObject.name + " wraping back to " + ", decal overlap with other spawn planes with same stencil value."); } @@ -87,15 +102,20 @@ private void setStencilWriteValue(MeshRenderer mr) { this.stencilSet = true; } - protected override void BreakForDecalType(Collision collision) { - if (!transparent) { - if (collision != null) { - foreach (ContactPoint contact in collision.contacts) { + protected override void BreakForDecalType(Collision collision) + { + if (!transparent) + { + if (collision != null) + { + foreach (ContactPoint contact in collision.contacts) + { float newTime = Time.time; float timeDiff = newTime - prevTime; var scale = contact.otherCollider.bounds.size; - if (timeDiff > nextDecalWaitTimeSeconds) { + if (timeDiff > nextDecalWaitTimeSeconds) + { this.prevTime = Time.time; // Taking into account the collider box of the object is breaking to resize the decal looks weirder than having the same decal size @@ -111,18 +131,25 @@ protected override void BreakForDecalType(Collision collision) { break; } } - } else { + } + else + { spawnDecal(transform.position, this.transform.rotation, decalScale * 2); } - } else { - if (collision != null) { - foreach (ContactPoint contact in collision.contacts) { + } + else + { + if (collision != null) + { + foreach (ContactPoint contact in collision.contacts) + { Debug.Log("Decal pre for " + this.stencilWriteValue); float newTime = Time.time; float timeDiff = newTime - prevTime; var scale = contact.otherCollider.bounds.size; - if (timeDiff > nextDecalWaitTimeSeconds) { + if (timeDiff > nextDecalWaitTimeSeconds) + { this.prevTime = Time.time; // Taking into account the collider box of the object is breaking to resize the decal looks weirder than having the same decal size @@ -143,7 +170,9 @@ protected override void BreakForDecalType(Collision collision) { break; } } - } else { + } + 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( @@ -160,10 +189,12 @@ public void SpawnDecal( bool worldSpace = false, Vector3? scale = null, DecalRotationAxis randomRotationAxis = DecalRotationAxis.NONE - ) { + ) + { // var pos = this.transform.InverseTransformPoint(worldPos); var pos = position; - if (worldSpace) { + if (worldSpace) + { pos = this.transform.InverseTransformPoint(position); } spawnDecal( @@ -180,23 +211,29 @@ private void spawnDecal( 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) { + if (minimumScale.x < scale.x || minimumScale.y < scale.y) + { var minimumDim = Mathf.Min(minimumScale.x, minimumScale.y); decalScale = new Vector3(minimumDim, minimumDim, scale.z); } var selectIndex = index; - if (index < 0) { + if (index < 0) + { selectIndex = Random.Range(0, decals.Length); } var randomRotation = Quaternion.identity; var randomAngle = Random.Range(-180.0f, 180.0f); - if (randomRotationAxis == DecalRotationAxis.FORWARD) { + if (randomRotationAxis == DecalRotationAxis.FORWARD) + { randomRotation = Quaternion.AngleAxis(randomAngle, Vector3.forward); - } else if (randomRotationAxis == DecalRotationAxis.SIDE) { + } + else if (randomRotationAxis == DecalRotationAxis.SIDE) + { randomRotation = Quaternion.AngleAxis(randomAngle, Vector3.right); } @@ -209,13 +246,16 @@ private void spawnDecal( decalCopy.transform.localScale = decalScale; var mr = decalCopy.GetComponent(); - if (transparent && mr && mr.enabled) { + if (transparent && mr && mr.enabled) + { mr.material.SetInt("_StencilRef", this.stencilWriteValue); } // Not needed if deffered decal prefab is correctly set with _StencilRef to 1 in material - else { + else + { var decal = decalCopy.GetComponent(); - if (decal) { + if (decal) + { decal.material.SetInt("_StencilRef", this.stencilWriteValue); } } diff --git a/unity/Assets/Scripts/DecalSpawner.cs b/unity/Assets/Scripts/DecalSpawner.cs index 4688455ea6..c096097442 100644 --- a/unity/Assets/Scripts/DecalSpawner.cs +++ b/unity/Assets/Scripts/DecalSpawner.cs @@ -2,19 +2,22 @@ using System.Collections.Generic; using UnityEngine; -public class DirtCoordinateBounds { +public class DirtCoordinateBounds +{ public float minX, maxX, minZ, maxZ; } -public class DirtSpawnPosition { +public class DirtSpawnPosition +{ public float x; public float z; } -public class DecalSpawner : MonoBehaviour { +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; @@ -43,26 +46,34 @@ public class DecalSpawner : MonoBehaviour { private static int currentStencilId = 0; - void OnEnable() { + void OnEnable() + { //breakType = BreakType.Decal; prevTime = Time.time; var mr = this.GetComponent(); - if (mr && mr.enabled) { - if (transparent) { - if (!sameStencilAsSiblings) { + if (mr && mr.enabled) + { + if (transparent) + { + if (!sameStencilAsSiblings) + { setStencilWriteValue(mr); - } else { + } + else + { 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) { + foreach (var spawnPlane in otherPlanes) + { if ( spawnPlane.isActiveAndEnabled && spawnPlane.stencilSet && spawnPlane.sameStencilAsSiblings - ) { + ) + { this.stencilWriteValue = spawnPlane.stencilWriteValue; this.stencilSet = true; mr.material.SetInt("_StencilRef", this.stencilWriteValue); @@ -70,11 +81,14 @@ void OnEnable() { break; } } - if (!stencilSet) { + if (!stencilSet) + { setStencilWriteValue(mr); } } - } else { + } + else + { this.stencilWriteValue = 1; mr.material.SetInt("_StencilRef", this.stencilWriteValue); } @@ -83,7 +97,8 @@ void OnEnable() { public void Update() { } - public DirtCoordinateBounds GetDirtCoordinateBounds() { + public DirtCoordinateBounds GetDirtCoordinateBounds() + { DirtCoordinateBounds coords = new DirtCoordinateBounds(); SimObjPhysics myParentSimObj = this.transform.GetComponentInParent(); @@ -96,20 +111,25 @@ public DirtCoordinateBounds GetDirtCoordinateBounds() { coords.minZ = spawnPointsArray[0].z; coords.maxZ = spawnPointsArray[0].z; - foreach (Vector3 v in spawnPointsArray) { - if (v.x < coords.minX) { + foreach (Vector3 v in spawnPointsArray) + { + if (v.x < coords.minX) + { coords.minX = v.x; } - if (v.x > coords.maxX) { + if (v.x > coords.maxX) + { coords.maxX = v.x; } - if (v.z < coords.minZ) { + if (v.z < coords.minZ) + { coords.minZ = v.z; } - if (v.z > coords.maxZ) { + if (v.z > coords.maxZ) + { coords.maxZ = v.z; } } @@ -128,13 +148,16 @@ public void SpawnDirt( int howMany = 1, int randomSeed = 0, DirtSpawnPosition[] spawnPointsArray = null - ) { - if (spawnPointsArray == null) { + ) + { + if (spawnPointsArray == null) + { DirtCoordinateBounds c = GetDirtCoordinateBounds(); Random.InitState(randomSeed); - for (int i = 0; i < howMany; i++) { + for (int i = 0; i < howMany; i++) + { //var randomPoint = Random.Range(0, spawnPointsArray.Length); var randomX = Random.Range(c.minX, c.maxX); var randomZ = Random.Range(c.minZ, c.maxZ); @@ -160,10 +183,12 @@ public void SpawnDirt( //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 - else { + else + { Random.InitState(randomSeed); - for (int i = 0; i < spawnPointsArray.Length; i++) { + for (int i = 0; i < spawnPointsArray.Length; i++) + { var randomScale = new Vector3( Random.Range(0.1f, 0.4f), Random.Range(0.1f, 0.4f), @@ -185,10 +210,12 @@ public void SpawnDirt( } } - private void setStencilWriteValue(MeshRenderer mr) { + private void setStencilWriteValue(MeshRenderer mr) + { DecalSpawner.currentStencilId = DecalSpawner.currentStencilId + 1; this.stencilWriteValue = DecalSpawner.currentStencilId << 1; - if (this.stencilWriteValue > 0xFF) { + if (this.stencilWriteValue > 0xFF) + { this.stencilWriteValue = this.stencilWriteValue % 0xFF; // Debug.LogWarning("Stencil buffer write value overflow with: " + this.stencilWriteValue + " for " + this.gameObject.name + " wraping back to " + ", decal overlap with other spawn planes with same stencil value."); } @@ -202,9 +229,11 @@ public void SpawnDecal( bool worldSpace = false, Vector3? scale = null, DecalRotationAxis randomRotationAxis = DecalRotationAxis.NONE - ) { + ) + { var pos = position; - if (worldSpace) { + if (worldSpace) + { pos = this.transform.InverseTransformPoint(position); } spawnDecal( @@ -221,23 +250,29 @@ private void spawnDecal( 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) { + if (minimumScale.x < scale.x || minimumScale.y < scale.y) + { var minimumDim = Mathf.Min(minimumScale.x, minimumScale.y); decalScale = new Vector3(minimumDim, minimumDim, scale.z); } var selectIndex = index; - if (index < 0) { + if (index < 0) + { selectIndex = Random.Range(0, decals.Length); } var randomRotation = Quaternion.identity; var randomAngle = Random.Range(-180.0f, 180.0f); - if (randomRotationAxis == DecalRotationAxis.FORWARD) { + if (randomRotationAxis == DecalRotationAxis.FORWARD) + { randomRotation = Quaternion.AngleAxis(randomAngle, Vector3.forward); - } else if (randomRotationAxis == DecalRotationAxis.SIDE) { + } + else if (randomRotationAxis == DecalRotationAxis.SIDE) + { randomRotation = Quaternion.AngleAxis(randomAngle, Vector3.right); } @@ -250,13 +285,16 @@ private void spawnDecal( decalCopy.transform.localScale = decalScale; var mr = decalCopy.GetComponent(); - if (transparent && mr && mr.enabled) { + if (transparent && mr && mr.enabled) + { mr.material.SetInt("_StencilRef", this.stencilWriteValue); } // Not needed if deffered decal prefab is correctly set with _StencilRef to 1 in material - else { + else + { var decal = decalCopy.GetComponent(); - if (decal) { + if (decal) + { decal.material.SetInt("_StencilRef", this.stencilWriteValue); } } diff --git a/unity/Assets/Scripts/DeferredDecal.cs b/unity/Assets/Scripts/DeferredDecal.cs index 901600a3b7..abfb447779 100644 --- a/unity/Assets/Scripts/DeferredDecal.cs +++ b/unity/Assets/Scripts/DeferredDecal.cs @@ -4,7 +4,8 @@ using UnityEngine; using UnityEngine.Rendering; -public enum DecalType { +public enum DecalType +{ DIFFUSE_ONLY, EMISSIVE_SPECULAR, NORMAL_DIFFUSE, @@ -12,7 +13,8 @@ public enum DecalType { FORWARD // TODO: not supported } -public class DeferredDecal : MonoBehaviour { +public class DeferredDecal : MonoBehaviour +{ [SerializeField] public Material material; @@ -28,7 +30,8 @@ public class DeferredDecal : MonoBehaviour { private List cameras; - void Start() { + void Start() + { this.buffer = new CommandBuffer(); buffer.name = "Deferred Decals"; var sceneM = GameObject.Find("PhysicsSceneManager"); @@ -41,20 +44,24 @@ void Start() { this.cameras = new List() { manager.primaryAgent.m_Camera } .Concat(manager.thirdPartyCameras) .ToList(); - foreach (var cam in cameras) { + foreach (var cam in cameras) + { cam.AddCommandBuffer(atRenderEvent, buffer); } } - public void OnWillRenderObject() { + public void OnWillRenderObject() + { // Happens when editor swap in code - if (buffer == null) { + if (buffer == null) + { buffer = new CommandBuffer(); buffer.name = "Deferred Decals"; } buffer.Clear(); - if (type == DecalType.EMISSIVE_SPECULAR) { + if (type == DecalType.EMISSIVE_SPECULAR) + { // Diffuse + specular decals RenderTargetIdentifier[] multipleRenderTargets = { @@ -63,7 +70,9 @@ public void OnWillRenderObject() { BuiltinRenderTextureType.GBuffer3 }; buffer.SetRenderTarget(multipleRenderTargets, BuiltinRenderTextureType.CameraTarget); - } else if (type == DecalType.NORMAL_DIFFUSE) { + } + else if (type == DecalType.NORMAL_DIFFUSE) + { // For decals that have normals RenderTargetIdentifier[] multipleRenderTargets = { @@ -71,7 +80,9 @@ public void OnWillRenderObject() { BuiltinRenderTextureType.GBuffer2 }; buffer.SetRenderTarget(multipleRenderTargets, BuiltinRenderTextureType.CameraTarget); - } else if (type == DecalType.EMISSIVE_SPECULAR) { + } + else if (type == DecalType.EMISSIVE_SPECULAR) + { // All render targets RenderTargetIdentifier[] multipleRenderTargets = { @@ -81,13 +92,17 @@ public void OnWillRenderObject() { BuiltinRenderTextureType.GBuffer3 }; buffer.SetRenderTarget(multipleRenderTargets, BuiltinRenderTextureType.CameraTarget); - } else if (type == DecalType.DIFFUSE_ONLY) { + } + else if (type == DecalType.DIFFUSE_ONLY) + { // Diffuse only, no MTR buffer.SetRenderTarget( BuiltinRenderTextureType.GBuffer0, BuiltinRenderTextureType.CameraTarget ); - } else if (type == DecalType.FORWARD) { + } + else if (type == DecalType.FORWARD) + { buffer.SetRenderTarget( BuiltinRenderTextureType.CurrentActive, BuiltinRenderTextureType.CameraTarget @@ -97,13 +112,16 @@ public void OnWillRenderObject() { buffer.DrawMesh(this.cubeMesh, this.transform.localToWorldMatrix, this.material); } - private void OnDisable() { - foreach (var cam in cameras) { + 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, @@ -122,8 +140,10 @@ void OnDrawGizmos() { new Vector3(+0.5f, -0.5f, +0.5f) }; - for (var i = 0; i < 4; i++) { - for (var j = 0; j < 3; j++) { + for (var i = 0; i < 4; i++) + { + for (var j = 0; j < 3; j++) + { var from = basePoints[i]; var to = from; to[j] += -Mathf.Sign(to[j]) * 1.0f; diff --git a/unity/Assets/Scripts/DirtAndWrite.cs b/unity/Assets/Scripts/DirtAndWrite.cs index dd9476eaaa..ef5f0c4035 100644 --- a/unity/Assets/Scripts/DirtAndWrite.cs +++ b/unity/Assets/Scripts/DirtAndWrite.cs @@ -10,7 +10,8 @@ using UnityEditor.SceneManagement; #endif -public class DirtAndWrite : MonoBehaviour { +public class DirtAndWrite : MonoBehaviour +{ // Start is called before the first frame update void Start() { } diff --git a/unity/Assets/Scripts/Dirty.cs b/unity/Assets/Scripts/Dirty.cs index 92db8bf9d8..de69b5eb14 100644 --- a/unity/Assets/Scripts/Dirty.cs +++ b/unity/Assets/Scripts/Dirty.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class Dirty : MonoBehaviour { +public class Dirty : MonoBehaviour +{ [SerializeField] public SwapObjList[] MaterialSwapObjects; // put objects that need amterial swaps here, use OnMaterials for Dirty, OffMaterials for Clean @@ -15,52 +16,64 @@ public class Dirty : MonoBehaviour { [SerializeField] protected bool isDirty = false; - public bool IsDirty() { + public bool IsDirty() + { return isDirty; } // Start is called before the first frame update - void Start() { + void Start() + { #if UNITY_EDITOR if ( !gameObject .GetComponent() .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeDirty) - ) { + ) + { Debug.LogError(gameObject.name + " is missing the CanBeDirty secondary property!"); } #endif } // Update is called once per frame - void Update() { + void Update() + { // if(Input.GetKeyDown(KeyCode.G)) // { // ToggleCleanOrDirty(); // } } - public void ToggleCleanOrDirty() { + public void ToggleCleanOrDirty() + { // if clean make dirty - if (!isDirty) { + if (!isDirty) + { // swap all material swap objects to OnMaterials - if (MaterialSwapObjects.Length > 0) { - for (int i = 0; i < MaterialSwapObjects.Length; i++) { + if (MaterialSwapObjects.Length > 0) + { + for (int i = 0; i < MaterialSwapObjects.Length; i++) + { MaterialSwapObjects[i].MyObject.GetComponent().materials = MaterialSwapObjects[i].OnMaterials; } } // disable disable all clean objects - if (ObjectsToEnableIfClean.Length > 0) { - for (int i = 0; i < ObjectsToEnableIfClean.Length; i++) { + if (ObjectsToEnableIfClean.Length > 0) + { + for (int i = 0; i < ObjectsToEnableIfClean.Length; i++) + { ObjectsToEnableIfClean[i].SetActive(false); } } // enable all dirty objects - if (ObjectsToEnableIfDirty.Length > 0) { - for (int i = 0; i < ObjectsToEnableIfDirty.Length; i++) { + if (ObjectsToEnableIfDirty.Length > 0) + { + for (int i = 0; i < ObjectsToEnableIfDirty.Length; i++) + { ObjectsToEnableIfDirty[i].SetActive(true); } } @@ -68,25 +81,32 @@ public void ToggleCleanOrDirty() { isDirty = true; } // if dirt, make clean - else { + else + { // swap all material swap object to OffMaterials - if (MaterialSwapObjects.Length > 0) { - for (int i = 0; i < MaterialSwapObjects.Length; i++) { + if (MaterialSwapObjects.Length > 0) + { + for (int i = 0; i < MaterialSwapObjects.Length; i++) + { MaterialSwapObjects[i].MyObject.GetComponent().materials = MaterialSwapObjects[i].OffMaterials; } } // enable all clean objects - if (ObjectsToEnableIfClean.Length > 0) { - for (int i = 0; i < ObjectsToEnableIfClean.Length; i++) { + if (ObjectsToEnableIfClean.Length > 0) + { + for (int i = 0; i < ObjectsToEnableIfClean.Length; i++) + { ObjectsToEnableIfClean[i].SetActive(true); } } // disable all dirty objects - if (ObjectsToEnableIfDirty.Length > 0) { - for (int i = 0; i < ObjectsToEnableIfDirty.Length; i++) { + if (ObjectsToEnableIfDirty.Length > 0) + { + for (int i = 0; i < ObjectsToEnableIfDirty.Length; i++) + { ObjectsToEnableIfDirty[i].SetActive(false); } } @@ -96,9 +116,11 @@ public void ToggleCleanOrDirty() { } // similar to Fire and Candles, if touching water and this object is dirty, auto toggle to clean - public void OnTriggerStay(Collider other) { + public void OnTriggerStay(Collider other) + { // only clean the object if touching a running water zone (tagged Liquid). Object will not be cleaned if touching standing, still water. - if (isDirty && other.CompareTag("Liquid")) { + if (isDirty && other.CompareTag("Liquid")) + { ToggleCleanOrDirty(); } } diff --git a/unity/Assets/Scripts/DiscreteHidenSeekAgentController.cs b/unity/Assets/Scripts/DiscreteHidenSeekAgentController.cs index 354b1045a5..2d678d3a64 100644 --- a/unity/Assets/Scripts/DiscreteHidenSeekAgentController.cs +++ b/unity/Assets/Scripts/DiscreteHidenSeekAgentController.cs @@ -4,14 +4,17 @@ using UnityEngine; using UnityEngine.UI; -namespace UnityStandardAssets.Characters.FirstPerson { +namespace UnityStandardAssets.Characters.FirstPerson +{ [Serializable] - public class ObjectSpanwMetadata { + public class ObjectSpanwMetadata + { public string objectType; public int objectVariation; } - public class DiscreteHidenSeekgentController : MonoBehaviour { + public class DiscreteHidenSeekgentController : MonoBehaviour + { [SerializeField] private float HandMoveMagnitude = 0.1f; public PhysicsRemoteFPSAgentController PhysicsController = null; @@ -24,7 +27,8 @@ public class DiscreteHidenSeekgentController : MonoBehaviour { public string onlyPickableObjectId = null; public bool disableCollistionWithPickupObject = false; - void Start() { + void Start() + { var Debug_Canvas = GameObject.Find("DebugCanvasPhysics"); AgentManager agentManager = GameObject .Find("PhysicsSceneManager") @@ -50,35 +54,42 @@ void Start() { // SpawnObjectToHide("{\"objectType\": \"Plunger\", \"objectVariation\": 1}"); } - public void OnEnable() { + public void OnEnable() + { InputMode_Text = GameObject.Find("DebugCanvasPhysics/InputModeText"); throwForceBar = GameObject.Find("DebugCanvasPhysics/ThrowForceBar"); var camera = GetComponentInChildren(); camera.fieldOfView = 90.0f; // camera.transform.rotation = Quaternion.Euler(30, 0, 0); camera.transform.Rotate(30, 0, 0); - if (InputMode_Text) { + if (InputMode_Text) + { InputMode_Text.GetComponent().text = "Point and Click Mode"; } - if (throwForceBar) { + if (throwForceBar) + { throwForceBar.SetActive(false); } // InputFieldObj = GameObject.Find("DebugCanvasPhysics/InputField"); // TODO: move debug input field script from, Input Field and disable here } - public void OnDisable() { - if (throwForceBar) { + public void OnDisable() + { + if (throwForceBar) + { throwForceBar.SetActive(true); } // TODO: move debug input field script from, Input Field and enable here } - public void SpawnObjectToHide(string objectMeta) { + public void SpawnObjectToHide(string objectMeta) + { var objectData = new ObjectSpanwMetadata(); Debug.Log(objectMeta); JsonUtility.FromJsonOverwrite(objectMeta, objectData); - ServerAction action = new ServerAction() { + ServerAction action = new ServerAction() + { action = "CreateObject", objectType = objectData.objectType, objectVariation = objectData.objectVariation @@ -89,59 +100,73 @@ public void SpawnObjectToHide(string objectMeta) { // DisableObjectCollisionWithAgent(onlyPickableObjectId); } - public void SetOnlyPickableObject(string objectId) { + public void SetOnlyPickableObject(string objectId) + { onlyPickableObjectId = objectId; this.highlightController.SetOnlyPickableId(objectId); } - public void SetOnlyObjectId(string objectId) { + public void SetOnlyObjectId(string objectId) + { onlyPickableObjectId = objectId; this.highlightController.SetOnlyPickableId(objectId); } - public void SetOnlyObjectIdSeeker(string objectId) { + public void SetOnlyObjectIdSeeker(string objectId) + { onlyPickableObjectId = objectId; this.highlightController.SetOnlyPickableId(objectId, true); } - public void SpawnAgent(int randomSeed) { - ServerAction action = new ServerAction() { + public void SpawnAgent(int randomSeed) + { + ServerAction action = new ServerAction() + { action = "RandomlyMoveAgent", randomSeed = randomSeed }; PhysicsController.ProcessControlCommand(action); } - public void DisableObjectCollisionWithAgent(string objectId) { + public void DisableObjectCollisionWithAgent(string objectId) + { var physicsSceneManager = FindObjectOfType(); - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { return; } SimObjPhysics target = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; disableCollistionWithPickupObject = true; - foreach (Collider c0 in this.GetComponentsInChildren()) { - foreach (Collider c1 in target.GetComponentsInChildren()) { + foreach (Collider c0 in this.GetComponentsInChildren()) + { + foreach (Collider c1 in target.GetComponentsInChildren()) + { Physics.IgnoreCollision(c0, c1); } } } - public void SetObjectVisible(bool visible) { + public void SetObjectVisible(bool visible) + { visibleObject = visible; // Debug.Log("Calling disply with "+ visibleObject); var go = PhysicsController.WhatAmIHolding(); PhysicsController.UpdateDisplayGameObject(go, visibleObject); var layer = go.layer; - if (!visibleObject) { + if (!visibleObject) + { // go.layer = LayerMask.NameToLayer("SimObjInvisible"); SetLayerRecursively(go, LayerMask.NameToLayer("SimObjInvisible")); - } else { + } + else + { SetLayerRecursively(go, LayerMask.NameToLayer("SimObjVisible")); } } - public void Step(string serverAction) { + public void Step(string serverAction) + { ServerAction controlCommand = new ServerAction(); JsonUtility.FromJsonOverwrite(serverAction, controlCommand); PhysicsController.ProcessControlCommand(controlCommand); @@ -153,36 +178,43 @@ public void Step(string serverAction) { // PhysicsController.ProcessControlCommand(command); // } - void Update() { + void Update() + { highlightController.UpdateHighlightedObject(Input.mousePosition); highlightController.MouseControls(); - if (PhysicsController.ReadyForCommand) { + if (PhysicsController.ReadyForCommand) + { handMode = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); float WalkMagnitude = 0.25f; - if (!handMode && !hidingPhase) { - if (Input.GetKeyDown(KeyCode.W)) { + if (!handMode && !hidingPhase) + { + if (Input.GetKeyDown(KeyCode.W)) + { ServerAction action = new ServerAction(); action.action = "MoveAhead"; action.moveMagnitude = WalkMagnitude; PhysicsController.ProcessControlCommand(action); } - if (Input.GetKeyDown(KeyCode.S)) { + if (Input.GetKeyDown(KeyCode.S)) + { ServerAction action = new ServerAction(); action.action = "MoveBack"; action.moveMagnitude = WalkMagnitude; PhysicsController.ProcessControlCommand(action); } - if (Input.GetKeyDown(KeyCode.A)) { + if (Input.GetKeyDown(KeyCode.A)) + { ServerAction action = new ServerAction(); action.action = "MoveLeft"; action.moveMagnitude = WalkMagnitude; PhysicsController.ProcessControlCommand(action); } - if (Input.GetKeyDown(KeyCode.D)) { + if (Input.GetKeyDown(KeyCode.D)) + { ServerAction action = new ServerAction(); action.action = "MoveRight"; action.moveMagnitude = WalkMagnitude; @@ -208,25 +240,39 @@ void Update() { } } - if (this.PhysicsController.WhatAmIHolding() != null && handMode) { + if (this.PhysicsController.WhatAmIHolding() != null && handMode) + { var actionName = "MoveHandForce"; var localPos = new Vector3(0, 0, 0); // Debug.Log(" Key down shift ? " + Input.GetKey(KeyCode.LeftAlt) + " up " + Input.GetKeyDown(KeyCode.UpArrow)); - if (Input.GetKeyDown(KeyCode.W)) { + if (Input.GetKeyDown(KeyCode.W)) + { localPos.y += HandMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.S)) { + } + else if (Input.GetKeyDown(KeyCode.S)) + { localPos.y -= HandMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.UpArrow)) { + } + else if (Input.GetKeyDown(KeyCode.UpArrow)) + { localPos.z += HandMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.DownArrow)) { + } + else if (Input.GetKeyDown(KeyCode.DownArrow)) + { localPos.z -= HandMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A)) { + } + else if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A)) + { localPos.x -= HandMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D)) { + } + else if (Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D)) + { localPos.x += HandMoveMagnitude; } - if (actionName != "" && localPos.sqrMagnitude > 0) { - ServerAction action = new ServerAction { + if (actionName != "" && localPos.sqrMagnitude > 0) + { + ServerAction action = new ServerAction + { action = "MoveHandForce", x = localPos.x, y = localPos.y, @@ -235,20 +281,26 @@ void Update() { this.PhysicsController.ProcessControlCommand(action); } - if (Input.GetKeyDown(KeyCode.Space)) { + if (Input.GetKeyDown(KeyCode.Space)) + { SetObjectVisible(true); - var action = new ServerAction { + var action = new ServerAction + { action = "DropHandObject", forceAction = true }; this.PhysicsController.ProcessControlCommand(action); } - } else if (handMode) { - if (Input.GetKeyDown(KeyCode.Space)) { + } + else if (handMode) + { + if (Input.GetKeyDown(KeyCode.Space)) + { var withinReach = PhysicsController.FindObjectInVisibleSimObjPhysics(onlyPickableObjectId) != null; - if (withinReach) { + if (withinReach) + { ServerAction action = new ServerAction(); action.objectId = onlyPickableObjectId; action.action = "PickupObject"; @@ -262,34 +314,44 @@ void Update() { || Input.GetKeyDown(KeyCode.C) || Input.GetKeyDown(KeyCode.RightControl) ) && PhysicsController.ReadyForCommand - ) { + ) + { ServerAction action = new ServerAction(); - if (this.PhysicsController.isStanding()) { + if (this.PhysicsController.isStanding()) + { action.action = "Crouch"; PhysicsController.ProcessControlCommand(action); - } else { + } + else + { action.action = "Stand"; PhysicsController.ProcessControlCommand(action); } } - if (PhysicsController.WhatAmIHolding() != null) { - if (Input.GetKeyDown(KeyCode.Space) && !hidingPhase && !handMode) { + if (PhysicsController.WhatAmIHolding() != null) + { + if (Input.GetKeyDown(KeyCode.Space) && !hidingPhase && !handMode) + { SetObjectVisible(!visibleObject); } } } } - private static void SetLayerRecursively(GameObject obj, int newLayer) { - if (null == obj) { + private static void SetLayerRecursively(GameObject obj, int newLayer) + { + if (null == obj) + { return; } obj.layer = newLayer; - foreach (Transform child in obj.transform) { - if (null == child) { + foreach (Transform child in obj.transform) + { + if (null == child) + { continue; } SetLayerRecursively(child.gameObject, newLayer); diff --git a/unity/Assets/Scripts/DiscretePointClickAgentController.cs b/unity/Assets/Scripts/DiscretePointClickAgentController.cs index f6f0dfb8d9..9638e15db2 100644 --- a/unity/Assets/Scripts/DiscretePointClickAgentController.cs +++ b/unity/Assets/Scripts/DiscretePointClickAgentController.cs @@ -3,8 +3,10 @@ using UnityEngine; using UnityEngine.UI; -namespace UnityStandardAssets.Characters.FirstPerson { - public class DiscretePointClickAgentController : MonoBehaviour { +namespace UnityStandardAssets.Characters.FirstPerson +{ + public class DiscretePointClickAgentController : MonoBehaviour + { [SerializeField] private float HandMoveMagnitude = 0.1f; public PhysicsRemoteFPSAgentController PhysicsController = null; @@ -13,7 +15,8 @@ public class DiscretePointClickAgentController : MonoBehaviour { private GameObject throwForceBar = null; private bool handMode = false; - void Start() { + void Start() + { var Debug_Canvas = GameObject.Find("DebugCanvasPhysics"); AgentManager agentManager = GameObject .Find("PhysicsSceneManager") @@ -33,13 +36,16 @@ void Start() { ); } - public void OnEnable() { + public void OnEnable() + { InputMode_Text = GameObject.Find("DebugCanvasPhysics/InputModeText"); throwForceBar = GameObject.Find("DebugCanvasPhysics/ThrowForceBar"); - if (InputMode_Text) { + if (InputMode_Text) + { InputMode_Text.GetComponent().text = "Point and Click Mode"; } - if (throwForceBar) { + if (throwForceBar) + { throwForceBar.SetActive(false); } @@ -47,54 +53,67 @@ public void OnEnable() { // TODO: move debug input field script from, Input Field and disable here } - public void OnDisable() { - if (throwForceBar) { + public void OnDisable() + { + if (throwForceBar) + { throwForceBar.SetActive(true); } // TODO: move debug input field script from, Input Field and enable here } - private void executeAction(string actionName, float moveMagnitude) { + private void executeAction(string actionName, float moveMagnitude) + { Dictionary action = new Dictionary(); action["action"] = actionName; action["moveMagnitude"] = moveMagnitude; PhysicsController.ProcessControlCommand(action); } - private void executeAction(string actionName) { + private void executeAction(string actionName) + { Dictionary action = new Dictionary(); action["action"] = actionName; PhysicsController.ProcessControlCommand(action); } - void Update() { + void Update() + { highlightController.UpdateHighlightedObject(Input.mousePosition); highlightController.MouseControls(); - if (PhysicsController.ReadyForCommand) { + if (PhysicsController.ReadyForCommand) + { float WalkMagnitude = 0.25f; - if (!handMode) { - if (Input.GetKeyDown(KeyCode.W)) { + if (!handMode) + { + if (Input.GetKeyDown(KeyCode.W)) + { executeAction("MoveAhead", WalkMagnitude); } - if (Input.GetKeyDown(KeyCode.S)) { + if (Input.GetKeyDown(KeyCode.S)) + { executeAction("MoveBack", WalkMagnitude); } - if (Input.GetKeyDown(KeyCode.A)) { + if (Input.GetKeyDown(KeyCode.A)) + { executeAction("MoveLeft", WalkMagnitude); } - if (Input.GetKeyDown(KeyCode.D)) { + if (Input.GetKeyDown(KeyCode.D)) + { executeAction("MoveRight", WalkMagnitude); } - if (Input.GetKeyDown(KeyCode.UpArrow)) { + if (Input.GetKeyDown(KeyCode.UpArrow)) + { executeAction("LookUp"); } - if (Input.GetKeyDown(KeyCode.DownArrow)) { + if (Input.GetKeyDown(KeyCode.DownArrow)) + { executeAction("LookDown"); } @@ -109,30 +128,46 @@ void Update() { } } - if (Input.GetKeyDown(KeyCode.LeftShift)) { + if (Input.GetKeyDown(KeyCode.LeftShift)) + { handMode = true; - } else if (Input.GetKeyUp(KeyCode.LeftShift)) { + } + else if (Input.GetKeyUp(KeyCode.LeftShift)) + { handMode = false; } - if (this.PhysicsController.WhatAmIHolding() != null && handMode) { + if (this.PhysicsController.WhatAmIHolding() != null && handMode) + { var actionName = "MoveHandForce"; var localPos = new Vector3(0, 0, 0); // Debug.Log(" Key down shift ? " + Input.GetKey(KeyCode.LeftAlt) + " up " + Input.GetKeyDown(KeyCode.UpArrow)); - if (Input.GetKeyDown(KeyCode.W)) { + if (Input.GetKeyDown(KeyCode.W)) + { localPos.z += HandMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.S)) { + } + else if (Input.GetKeyDown(KeyCode.S)) + { localPos.z -= HandMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.UpArrow)) { + } + else if (Input.GetKeyDown(KeyCode.UpArrow)) + { localPos.y += HandMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.DownArrow)) { + } + else if (Input.GetKeyDown(KeyCode.DownArrow)) + { localPos.y -= HandMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.LeftArrow)) { + } + else if (Input.GetKeyDown(KeyCode.LeftArrow)) + { localPos.x -= HandMoveMagnitude; - } else if (Input.GetKeyDown(KeyCode.RightArrow)) { + } + else if (Input.GetKeyDown(KeyCode.RightArrow)) + { localPos.x += HandMoveMagnitude; } - if (actionName != "") { + if (actionName != "") + { Dictionary action = new Dictionary(); action["action"] = actionName; action["x"] = localPos.x; diff --git a/unity/Assets/Scripts/Door.cs b/unity/Assets/Scripts/Door.cs index e7a7cdae46..9fb1c5c3bb 100644 --- a/unity/Assets/Scripts/Door.cs +++ b/unity/Assets/Scripts/Door.cs @@ -3,22 +3,27 @@ using UnityEngine; [ExecuteInEditMode] -public class Door : MonoBehaviour { +public class Door : MonoBehaviour +{ public SimObj ParentObj; public Vector3 OpenRotation; public Vector3 ClosedRotation; public Transform Pivot; public bool EditorOpen; - void OnEnable() { + void OnEnable() + { ParentObj = gameObject.GetComponent(); - if (ParentObj == null) { + if (ParentObj == null) + { ParentObj = gameObject.AddComponent(); } - if (!Application.isPlaying) { + if (!Application.isPlaying) + { Animator a = ParentObj.gameObject.GetComponent(); - if (a == null) { + if (a == null) + { a = ParentObj.gameObject.AddComponent(); a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; @@ -26,9 +31,11 @@ void OnEnable() { } } - void Update() { + void Update() + { bool open = EditorOpen; - if (Application.isPlaying) { + if (Application.isPlaying) + { open = ParentObj.Animator.GetBool("AnimState1"); } Pivot.localEulerAngles = open ? OpenRotation : ClosedRotation; diff --git a/unity/Assets/Scripts/DraggablePoint.cs b/unity/Assets/Scripts/DraggablePoint.cs index 43861b29ec..3fcba5f5e3 100644 --- a/unity/Assets/Scripts/DraggablePoint.cs +++ b/unity/Assets/Scripts/DraggablePoint.cs @@ -8,24 +8,31 @@ public class DraggablePoint : PropertyAttribute { } #if UNITY_EDITOR // [CustomEditor(typeof(MonoBehaviour), true)] -public class DraggablePointDrawer : Editor { +public class DraggablePointDrawer : Editor +{ readonly GUIStyle style = new GUIStyle(); - void OnEnable() { + void OnEnable() + { style.fontStyle = FontStyle.Bold; style.normal.textColor = Color.white; } - public void OnSceneGUI() { + public void OnSceneGUI() + { var property = serializedObject.GetIterator(); - while (property.Next(true)) { - if (property.propertyType == SerializedPropertyType.Vector3) { + while (property.Next(true)) + { + if (property.propertyType == SerializedPropertyType.Vector3) + { var field = serializedObject.targetObject.GetType().GetField(property.name); - if (field == null) { + if (field == null) + { continue; } var draggablePoints = field.GetCustomAttributes(typeof(DraggablePoint), false); - if (draggablePoints.Length > 0) { + if (draggablePoints.Length > 0) + { Handles.Label(property.vector3Value, property.name); property.vector3Value = Handles.PositionHandle( property.vector3Value, diff --git a/unity/Assets/Scripts/DroneBasket.cs b/unity/Assets/Scripts/DroneBasket.cs index 1353c6fdf3..37fa5c2b0b 100644 --- a/unity/Assets/Scripts/DroneBasket.cs +++ b/unity/Assets/Scripts/DroneBasket.cs @@ -6,7 +6,8 @@ #if UNITY_EDITOR using UnityEditor; #endif -public class DroneBasket : MonoBehaviour { +public class DroneBasket : MonoBehaviour +{ public GameObject myParent = null; private PhysicsSceneManager psManager; @@ -14,21 +15,25 @@ public class DroneBasket : MonoBehaviour { protected List CurrentlyContains = new List(); // Use this for initialization - void Start() { + void Start() + { psManager = GameObject.Find("PhysicsSceneManager").GetComponent(); } // Update is called once per frame void Update() { } - public void OnTriggerStay(Collider other) { + 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) { + if (other.GetComponentInParent() && !other.isTrigger) + { SimObjPhysics sop = other.GetComponentInParent(); // don't add any parent objects in case this is a child sim object - if (sop.transform == myParent.transform) { + if (sop.transform == myParent.transform) + { return; } @@ -42,7 +47,8 @@ public void OnTriggerStay(Collider other) { sop.transform.Find("TriggerColliders").gameObject.SetActive(false); sop.transform.Find("BoundingBox").gameObject.SetActive(false); - if (sop.GetComponent()) { + if (sop.GetComponent()) + { Rigidbody rb = sop.GetComponent(); psManager.RemoveFromRBSInScene(rb); diff --git a/unity/Assets/Scripts/DroneFPSAgentController.cs b/unity/Assets/Scripts/DroneFPSAgentController.cs index 6a916cce30..e40570959b 100644 --- a/unity/Assets/Scripts/DroneFPSAgentController.cs +++ b/unity/Assets/Scripts/DroneFPSAgentController.cs @@ -7,9 +7,11 @@ using UnityEngine.AI; using UnityEngine.Rendering.PostProcessing; -namespace UnityStandardAssets.Characters.FirstPerson { +namespace UnityStandardAssets.Characters.FirstPerson +{ [RequireComponent(typeof(CharacterController))] - public class DroneFPSAgentController : BaseFPSAgentController { + public class DroneFPSAgentController : BaseFPSAgentController + { public GameObject basket; public GameObject basketTrigger; public List caught_object = new List(); @@ -28,12 +30,14 @@ AgentManager agentManager ) : base(baseAgentComponent, agentManager) { } - protected override void resumePhysics() { + protected override void resumePhysics() + { if ( Time.timeScale == 0 && !Physics.autoSimulation && physicsSceneManager.physicsSimulationPaused - ) { + ) + { Time.timeScale = this.autoResetTimeScale; Physics.autoSimulation = true; physicsSceneManager.physicsSimulationPaused = false; @@ -41,7 +45,8 @@ protected override void resumePhysics() { } } - public override ActionFinished InitializeBody(ServerAction initializeAction) { + public override ActionFinished InitializeBody(ServerAction initializeAction) + { VisibilityCapsule = DroneVisCap; m_CharacterController.center = new Vector3(0, 0, 0); m_CharacterController.radius = 0.2f; @@ -71,23 +76,28 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { return ActionFinished.Success; } - public void MoveLeft(ServerAction action) { + public void MoveLeft(ServerAction action) + { moveCharacter(action, 270); } - public void MoveRight(ServerAction action) { + public void MoveRight(ServerAction action) + { moveCharacter(action, 90); } - public void MoveAhead(ServerAction action) { + public void MoveAhead(ServerAction action) + { moveCharacter(action, 0); } - public void MoveBack(ServerAction action) { + public void MoveBack(ServerAction action) + { moveCharacter(action, 180); } - public void MoveRelative(ServerAction action) { + public void MoveRelative(ServerAction action) + { var moveLocal = new Vector3(action.x, 0, action.z); Vector3 moveWorldSpace = transform.rotation * moveLocal; moveWorldSpace.y = Physics.gravity.y * this.m_GravityMultiplier; @@ -95,9 +105,11 @@ public void MoveRelative(ServerAction action) { actionFinished(true); } - public void RotateRight(ServerAction action) { + public void RotateRight(ServerAction action) + { // if controlCommand.degrees is default (0), rotate by the default rotation amount set on initialize - if (action.degrees == 0f) { + if (action.degrees == 0f) + { action.degrees = rotateStepDegrees; } @@ -105,9 +117,11 @@ public void RotateRight(ServerAction action) { actionFinished(true); } - public void RotateLeft(ServerAction action) { + public void RotateLeft(ServerAction action) + { // if controlCommand.degrees is default (0), rotate by the default rotation amount set on initialize - if (action.degrees == 0f) { + if (action.degrees == 0f) + { action.degrees = rotateStepDegrees; } @@ -115,7 +129,8 @@ public void RotateLeft(ServerAction action) { actionFinished(true); } - public override void FixedUpdate() { + public override void FixedUpdate() + { // when in drone mode, automatically pause time and physics simulation here // time and physics will continue once emitFrame is called // Note: this is to keep drone and object movement in sync, as pausing just object physics would @@ -127,17 +142,22 @@ public override void FixedUpdate() { // it's unclear whether this is only an in-editor debug draw issue, or the actual metadata for the axis // aligned box is messed up, but yeah. - if (hasFixedUpdateHappened) { + if (hasFixedUpdateHappened) + { Time.timeScale = 0; Physics.autoSimulation = false; physicsSceneManager.physicsSimulationPaused = true; - } else { + } + else + { fixupdateCnt++; hasFixedUpdateHappened = true; } - if (thrust.magnitude > 0.0001 && Time.timeScale != 0) { - if (dronePositionRandomNoiseSigma > 0) { + if (thrust.magnitude > 0.0001 && Time.timeScale != 0) + { + if (dronePositionRandomNoiseSigma > 0) + { var noiseX = (float) systemRandom.NextGaussian(0.0f, dronePositionRandomNoiseSigma / 3.0f); var noiseY = (float) @@ -146,12 +166,15 @@ public override void FixedUpdate() { systemRandom.NextGaussian(0.0f, dronePositionRandomNoiseSigma / 3.0f); Vector3 noise = new Vector3(noiseX, noiseY, noiseZ); m_CharacterController.Move((thrust * Time.fixedDeltaTime) + noise); - } else { + } + else + { m_CharacterController.Move(thrust * Time.fixedDeltaTime); } } - if (this.agentState == AgentState.PendingFixedUpdate) { + if (this.agentState == AgentState.PendingFixedUpdate) + { this.agentState = AgentState.ActionComplete; } } @@ -161,7 +184,8 @@ public override ObjectMetadata ObjectMetadataFromSimObjPhysics( SimObjPhysics simObj, bool isVisible, bool isInteractable - ) { + ) + { DroneObjectMetadata objMeta = new DroneObjectMetadata(); objMeta.isCaught = this.isObjectCaught(simObj); objMeta.numSimObjHits = simObj.numSimObjHit; @@ -177,43 +201,51 @@ bool isInteractable objMeta.receptacle = simObj.IsReceptacle; objMeta.openable = simObj.IsOpenable; - if (objMeta.openable) { + if (objMeta.openable) + { objMeta.isOpen = simObj.IsOpen; } objMeta.toggleable = simObj.IsToggleable; - if (objMeta.toggleable) { + if (objMeta.toggleable) + { objMeta.isToggled = simObj.IsToggled; } objMeta.breakable = simObj.IsBreakable; - if (objMeta.breakable) { + if (objMeta.breakable) + { objMeta.isBroken = simObj.IsBroken; } objMeta.canFillWithLiquid = simObj.IsFillable; - if (objMeta.canFillWithLiquid) { + if (objMeta.canFillWithLiquid) + { objMeta.isFilledWithLiquid = simObj.IsFilled; objMeta.fillLiquid = simObj.FillLiquid; } objMeta.dirtyable = simObj.IsDirtyable; - if (objMeta.dirtyable) { + if (objMeta.dirtyable) + { objMeta.isDirty = simObj.IsDirty; } objMeta.cookable = simObj.IsCookable; - if (objMeta.cookable) { + if (objMeta.cookable) + { objMeta.isCooked = simObj.IsCooked; } // if the sim object is moveable or pickupable - if (simObj.IsPickupable || simObj.IsMoveable) { + if (simObj.IsPickupable || simObj.IsMoveable) + { // this object should report back mass and salient materials string[] salientMaterialsToString = new string[simObj.salientMaterials.Length]; - for (int i = 0; i < simObj.salientMaterials.Length; i++) { + for (int i = 0; i < simObj.salientMaterials.Length; i++) + { salientMaterialsToString[i] = simObj.salientMaterials[i].ToString(); } @@ -221,7 +253,8 @@ bool isInteractable // record the mass unless the object was caught by the drone, which means the // rigidbody was disabled - if (!objMeta.isCaught) { + if (!objMeta.isCaught) + { objMeta.mass = simObj.Mass; } } @@ -233,12 +266,14 @@ bool isInteractable objMeta.isColdSource = simObj.isColdSource; objMeta.sliceable = simObj.IsSliceable; - if (objMeta.sliceable) { + if (objMeta.sliceable) + { objMeta.isSliced = simObj.IsSliced; } objMeta.canBeUsedUp = simObj.CanBeUsedUp; - if (objMeta.canBeUsedUp) { + if (objMeta.canBeUsedUp) + { objMeta.isUsedUp = simObj.IsUsedUp; } @@ -270,7 +305,8 @@ bool isInteractable return objMeta; } - public override MetadataWrapper generateMetadataWrapper() { + public override MetadataWrapper generateMetadataWrapper() + { MetadataWrapper metadata = base.generateMetadataWrapper(); // For Drone controller, currentTime should be based on @@ -296,12 +332,14 @@ public override MetadataWrapper generateMetadataWrapper() { return metadata; } - public float DroneTimeSinceStart() { + public float DroneTimeSinceStart() + { return fixupdateCnt * Time.fixedDeltaTime; } // Flying drone agent controls - public Vector3 GetFlyingOrientation(float moveMagnitude, int targetOrientation) { + public Vector3 GetFlyingOrientation(float moveMagnitude, int targetOrientation) + { Vector3 m; int currentRotation = (int)Math.Round(transform.rotation.eulerAngles.y, 0); Dictionary actionOrientation = new Dictionary(); @@ -311,9 +349,12 @@ public Vector3 GetFlyingOrientation(float moveMagnitude, int targetOrientation) actionOrientation.Add(270, new Vector3(-1.0f, 0.0f, 0.0f)); int delta = (currentRotation + targetOrientation) % 360; - if (actionOrientation.ContainsKey(delta)) { + if (actionOrientation.ContainsKey(delta)) + { m = actionOrientation[delta]; - } else { + } + else + { actionOrientation = new Dictionary(); actionOrientation.Add(0, transform.forward); actionOrientation.Add(90, transform.right); @@ -329,16 +370,22 @@ public Vector3 GetFlyingOrientation(float moveMagnitude, int targetOrientation) // Flying drone agent controls // use get reachable positions, get two positions, one in front of the other - public Vector3[] SeekTwoPos(Vector3[] shuffledCurrentlyReachable) { + public Vector3[] SeekTwoPos(Vector3[] shuffledCurrentlyReachable) + { Vector3[] output = new Vector3[2]; List y_candidates = new List(new float[] { 1.0f, 1.25f, 1.5f }); - foreach (Vector3 p in shuffledCurrentlyReachable) { - foreach (Vector3 p2 in shuffledCurrentlyReachable) { - if (!p.Equals(p2)) { - if (p2.z >= (p.z + 1.5f) && Mathf.Abs(p.z - p2.z) <= 2.5f) { + foreach (Vector3 p in shuffledCurrentlyReachable) + { + foreach (Vector3 p2 in shuffledCurrentlyReachable) + { + if (!p.Equals(p2)) + { + if (p2.z >= (p.z + 1.5f) && Mathf.Abs(p.z - p2.z) <= 2.5f) + { // 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) { + if (Mathf.Abs(p.x - p2.x) <= 0.5) + { float y = y_candidates.OrderBy(x => systemRandom.Next()).ToArray()[ 0 ]; @@ -354,7 +401,8 @@ public Vector3[] SeekTwoPos(Vector3[] shuffledCurrentlyReachable) { } // change what timeScale is automatically reset to on emitFrame when in FlightMode - public void ChangeAutoResetTimeScale(float timeScale) { + public void ChangeAutoResetTimeScale(float timeScale) + { autoResetTimeScale = timeScale; actionFinished(true); } @@ -364,7 +412,8 @@ public void Teleport( Vector3? rotation = null, float? horizon = null, bool forceAction = false - ) { + ) + { base.teleport( position: position, rotation: rotation, @@ -379,7 +428,8 @@ public void TeleportFull( Vector3? rotation, float? horizon, bool forceAction = false - ) { + ) + { base.teleportFull( position: position, rotation: rotation, @@ -389,7 +439,8 @@ public void TeleportFull( actionFinished(success: true); } - public void FlyRandomStart(float y) { + public void FlyRandomStart(float y) + { Vector3[] shuffledCurrentlyReachable = getReachablePositions() .OrderBy(x => systemRandom.Next()) .ToArray(); @@ -406,7 +457,8 @@ public void FlyRandomStart(float y) { // move drone and launcher to some start position // using the 'position' variable name is an artifact from using ServerAction.position for the thrust_dt - public void FlyAssignStart(Vector3 position, float x, float y, float z) { + public void FlyAssignStart(Vector3 position, float x, float y, float z) + { // drone uses action.position Vector3 thrust_dt = position; transform.position = thrust_dt; @@ -420,7 +472,8 @@ public void FlyAssignStart(Vector3 position, float x, float y, float z) { } // Flying Drone Agent Controls - public void FlyTo(float x, float y, float z, Vector3 rotation, float horizon) { + public void FlyTo(float x, float y, float z, Vector3 rotation, float horizon) + { transform.rotation = Quaternion.Euler(new Vector3(0.0f, rotation.y, 0.0f)); m_Camera.transform.localEulerAngles = new Vector3(horizon, 0.0f, 0.0f); thrust += new Vector3(x, y, z); @@ -428,31 +481,36 @@ public void FlyTo(float x, float y, float z, Vector3 rotation, float horizon) { } // Flying Drone Agent Controls - public void FlyAhead(float moveMagnitude) { + public void FlyAhead(float moveMagnitude) + { thrust += GetFlyingOrientation(moveMagnitude, 0); actionFinished(true); } // Flying Drone Agent Controls - public void FlyBack(float moveMagnitude) { + public void FlyBack(float moveMagnitude) + { thrust += GetFlyingOrientation(moveMagnitude, 180); actionFinished(true); } // Flying Drone Agent Controls - public void FlyLeft(float moveMagnitude) { + public void FlyLeft(float moveMagnitude) + { thrust += GetFlyingOrientation(moveMagnitude, 270); actionFinished(true); } // Flying Drone Agent Controls - public void FlyRight(float moveMagnitude) { + public void FlyRight(float moveMagnitude) + { thrust += GetFlyingOrientation(moveMagnitude, 90); actionFinished(true); } // Flying Drone Agent Controls - public void FlyUp(float moveMagnitude) { + public void FlyUp(float moveMagnitude) + { // Vector3 targetPosition = transform.position + transform.up * action.moveMagnitude; // transform.position = targetPosition; thrust += new Vector3(0, moveMagnitude, 0); @@ -460,7 +518,8 @@ public void FlyUp(float moveMagnitude) { } // Flying Drone Agent Controls - public void FlyDown(float moveMagnitude) { + public void FlyDown(float moveMagnitude) + { // Vector3 targetPosition = transform.position + -transform.up * action.moveMagnitude; // transform.position = targetPosition; thrust += new Vector3(0, -moveMagnitude, 0); @@ -476,45 +535,57 @@ public void LaunchDroneObject( float x, float y, float z - ) { + ) + { Launch(moveMagnitude, objectName, objectRandom, x, y, z); actionFinished(true); fixupdateCnt = 0f; } // spawn a launcher object at action.position coordinates - public void SpawnDroneLauncher(Vector3 position) { + public void SpawnDroneLauncher(Vector3 position) + { SpawnLauncher(position); actionFinished(true); } // in case you want to change the fixed delta time - public void ChangeFixedDeltaTime(float? fixedDeltaTime = null) { + public void ChangeFixedDeltaTime(float? fixedDeltaTime = null) + { var fdtime = fixedDeltaTime.GetValueOrDefault(Time.fixedDeltaTime); - if (fdtime > 0) { + if (fdtime > 0) + { Time.fixedDeltaTime = fdtime; actionFinished(true); - } else { + } + else + { errorMessage = "FixedDeltaTime must be >0"; actionFinished(false); } } - public void ChangeDronePositionRandomNoiseSigma(float dronePositionRandomNoiseSigma = 0.0f) { + public void ChangeDronePositionRandomNoiseSigma(float dronePositionRandomNoiseSigma = 0.0f) + { this.dronePositionRandomNoiseSigma = dronePositionRandomNoiseSigma; actionFinished(true); } - public bool HasLaunch(SimObjPhysics obj) { + public bool HasLaunch(SimObjPhysics obj) + { return DroneObjectLauncher.HasLaunch(obj); } - public bool isObjectCaught(SimObjPhysics check_obj) { + public bool isObjectCaught(SimObjPhysics check_obj) + { bool caught_object_bool = false; - foreach (SimObjPhysics obj in caught_object) { - if (obj.Type == check_obj.Type) { - if (obj.name == check_obj.name) { + foreach (SimObjPhysics obj in caught_object) + { + if (obj.Type == check_obj.Type) + { + if (obj.name == check_obj.name) + { caught_object_bool = true; // Debug.Log("catch!!!"); break; @@ -531,20 +602,24 @@ public void Launch( float x, float y, float z - ) { + ) + { Vector3 LaunchAngle = new Vector3(x, y, z); DroneObjectLauncher.Launch(this, moveMagnitude, LaunchAngle, objectName, objectRandom); } - public void MoveLauncher(Vector3 position) { + public void MoveLauncher(Vector3 position) + { DroneObjectLauncher.transform.position = position; } - public Vector3 GetLauncherPosition() { + public Vector3 GetLauncherPosition() + { return DroneObjectLauncher.transform.position; } - public void SpawnLauncher(Vector3 position) { + 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 9bfd4ac392..24e2883ec3 100644 --- a/unity/Assets/Scripts/DroneObjectLauncher.cs +++ b/unity/Assets/Scripts/DroneObjectLauncher.cs @@ -4,7 +4,8 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public class DroneObjectLauncher : MonoBehaviour { +public class DroneObjectLauncher : MonoBehaviour +{ [SerializeField] public GameObject[] prefabsToLaunch; @@ -17,28 +18,34 @@ void Start() { } // Update is called once per frame void Update() { } - public bool HasLaunch(SimObjPhysics obj) { + public bool HasLaunch(SimObjPhysics obj) + { return launch_object.Contains(obj); } - public GameObject GetGameObject(string objectType, bool randomize, int variation) { + public GameObject GetGameObject(string objectType, bool randomize, int variation) + { List candidates = new List(); SimObjType target = (SimObjType)Enum.Parse(typeof(SimObjType), objectType); // Debug.Log(target); - foreach (GameObject go in prefabsToLaunch) { + foreach (GameObject go in prefabsToLaunch) + { // Debug.Log(go.GetComponent().Type); // does a prefab of objectType exist in the current array of prefabs to spawn? - if (go.GetComponent().Type == target) { + if (go.GetComponent().Type == target) + { candidates.Add(go); } } // Figure out which variation to use, if no variation use first candidate found - if (randomize) { + if (randomize) + { variation = UnityEngine.Random.Range(1, candidates.Count); } - if (variation != 0) { + if (variation != 0) + { variation -= 1; } @@ -51,7 +58,8 @@ public void Launch( Vector3 direction, string objectName, bool randomize - ) { + ) + { GameObject toLaunch = GetGameObject(objectName, randomize, 0); GameObject fireaway = Instantiate( toLaunch, diff --git a/unity/Assets/Scripts/EditorSetupSimObjPhysics.cs b/unity/Assets/Scripts/EditorSetupSimObjPhysics.cs index 41124c7702..2590888cb2 100644 --- a/unity/Assets/Scripts/EditorSetupSimObjPhysics.cs +++ b/unity/Assets/Scripts/EditorSetupSimObjPhysics.cs @@ -3,7 +3,8 @@ using UnityEngine; // THIS IS WINSON EXPERIMENTING WITH SETUP FUNCTIONS< DO NOT USE RIGHT NOW -public class EditorSetupSimObjPhysics : MonoBehaviour { +public class EditorSetupSimObjPhysics : MonoBehaviour +{ public SimObjType Type; public SimObjPrimaryProperty Primary; public SimObjSecondaryProperty[] Secondary; @@ -14,7 +15,8 @@ void Start() { } // Update is called once per frame void Update() { } - public void Mirror() { + public void Mirror() + { // SimObjSecondaryProperty[] MirrorSecondary = new SimObjSecondaryProperty[]{SimObjSecondaryProperty.CanBeCleanedGlass}; // Setup(SimObjType.Mirror, SimObjPrimaryProperty.Static, MirrorSecondary); } @@ -25,7 +27,8 @@ public void Setup( 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 411498983b..011cbb37bc 100644 --- a/unity/Assets/Scripts/ExpRoom/ArmAgentController_partial_ExpRoom.cs +++ b/unity/Assets/Scripts/ExpRoom/ArmAgentController_partial_ExpRoom.cs @@ -13,10 +13,14 @@ using UnityStandardAssets.ImageEffects; using UnityStandardAssets.Utility; -namespace UnityStandardAssets.Characters.FirstPerson { - public partial class KinovaArmAgentController : ArmAgentController { - public void AttachObjectToArmWithFixedJoint(string objectId) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { +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}."; actionFinishedEmit(false); return; @@ -26,7 +30,8 @@ public void AttachObjectToArmWithFixedJoint(string objectId) { actionFinished(getArmImplementation().AttachObjectToArmWithFixedJoint(target)); } - public void BreakFixedJoints() { + public void BreakFixedJoints() + { actionFinished(getArmImplementation().BreakFixedJoints()); } } 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 8616af0013..2e83288286 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 @@ -13,10 +13,14 @@ using UnityStandardAssets.ImageEffects; using UnityStandardAssets.Utility; -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) { +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) + { return true; } } @@ -30,8 +34,10 @@ public bool AttachObjectToArmWithFixedJoint(SimObjPhysics target) { return true; } - public bool BreakFixedJoints() { - foreach (FixedJoint fj in magnetSphere.gameObject.GetComponents()) { + public bool BreakFixedJoints() + { + foreach (FixedJoint fj in magnetSphere.gameObject.GetComponents()) + { Destroy(fj); } return true; diff --git a/unity/Assets/Scripts/ExpRoom/PhysicsRemoteFPSAgentController_partial_ExpRoom.cs b/unity/Assets/Scripts/ExpRoom/PhysicsRemoteFPSAgentController_partial_ExpRoom.cs index ef6f0130a5..0cb8c1dda1 100644 --- a/unity/Assets/Scripts/ExpRoom/PhysicsRemoteFPSAgentController_partial_ExpRoom.cs +++ b/unity/Assets/Scripts/ExpRoom/PhysicsRemoteFPSAgentController_partial_ExpRoom.cs @@ -13,16 +13,22 @@ using UnityStandardAssets.ImageEffects; using UnityStandardAssets.Utility; -namespace UnityStandardAssets.Characters.FirstPerson { - public partial class PhysicsRemoteFPSAgentController : BaseFPSAgentController { +namespace UnityStandardAssets.Characters.FirstPerson +{ + public partial class PhysicsRemoteFPSAgentController : BaseFPSAgentController + { protected Dictionary cachedAvailableExpRoomObjectsDict = null; protected Dictionary cachedAvailableExpRoomContainersDict = null; - public Dictionary availableExpRoomObjectsDict { - get { - if (cachedAvailableExpRoomObjectsDict == null) { + public Dictionary availableExpRoomObjectsDict + { + get + { + if (cachedAvailableExpRoomObjectsDict == null) + { cachedAvailableExpRoomObjectsDict = new Dictionary(); - foreach (Transform t in GameObject.Find("AvailableObjects").transform) { + foreach (Transform t in GameObject.Find("AvailableObjects").transform) + { SimObjPhysics sop = t.gameObject.GetComponent(); cachedAvailableExpRoomObjectsDict.Add(sop.name, sop); } @@ -31,11 +37,15 @@ public Dictionary availableExpRoomObjectsDict { } } - public Dictionary availableExpRoomContainersDict { - get { - if (cachedAvailableExpRoomContainersDict == null) { + public Dictionary availableExpRoomContainersDict + { + get + { + if (cachedAvailableExpRoomContainersDict == null) + { cachedAvailableExpRoomContainersDict = new Dictionary(); - foreach (Transform t in GameObject.Find("AvailableContainers").transform) { + foreach (Transform t in GameObject.Find("AvailableContainers").transform) + { SimObjPhysics sop = t.gameObject.GetComponent(); cachedAvailableExpRoomContainersDict.Add(sop.name, sop); } @@ -44,16 +54,19 @@ public Dictionary availableExpRoomContainersDict { } } - public static void emptyEnumerator(IEnumerator enumerator) { + public static void emptyEnumerator(IEnumerator enumerator) + { while (enumerator.MoveNext()) { } } public void WhichContainersDoesAvailableObjectFitIn( string objectName, int? thirdPartyCameraIndex = null - ) { + ) + { Camera camera = m_Camera; - if (thirdPartyCameraIndex.HasValue) { + if (thirdPartyCameraIndex.HasValue) + { camera = agentManager.thirdPartyCameras[thirdPartyCameraIndex.Value]; } PhysicsSceneManager.StartPhysicsCoroutine( @@ -68,14 +81,17 @@ public void WhichContainersDoesAvailableObjectFitIn( public IEnumerator whichContainersDoesAvailableObjectFitIn( string objectName, Camera visibilityCheckCamera - ) { - Action activateSop = (sop) => { + ) + { + Action activateSop = (sop) => + { sop.gameObject.SetActive(true); sop.ObjectID = sop.name; physicsSceneManager.AddToObjectsInScene(sop); }; - Action deactivateSop = (sop) => { + Action deactivateSop = (sop) => + { sop.gameObject.SetActive(false); physicsSceneManager.RemoveFromObjectsInScene(sop); }; @@ -85,7 +101,8 @@ Camera visibilityCheckCamera Dictionary coverNameToScale = new Dictionary(); - if (!availableExpRoomObjectsDict.ContainsKey(objectName)) { + if (!availableExpRoomObjectsDict.ContainsKey(objectName)) + { errorMessage = $"Could not find object with name {objectName}"; actionFinished(false); yield break; @@ -93,7 +110,8 @@ Camera visibilityCheckCamera SimObjPhysics toCover = availableExpRoomObjectsDict[objectName]; - if (toCover.GetComponent()) { + if (toCover.GetComponent()) + { toCover.GetComponent().Unbreakable = true; } @@ -106,7 +124,8 @@ Camera visibilityCheckCamera rotation: null, forceKinematic: true ) - ) { + ) + { deactivateSop(toCover); errorMessage = $"{toCover.name} failed to place"; actionFinished(false); @@ -122,8 +141,10 @@ Camera visibilityCheckCamera SimObjPhysics cover in availableExpRoomContainersDict .OrderBy(kvp => kvp.Key) .Select(kvp => kvp.Value) - ) { - if (cover.GetComponent()) { + ) + { + if (cover.GetComponent()) + { cover.GetComponent().Unbreakable = true; } @@ -140,7 +161,8 @@ SimObjPhysics cover in availableExpRoomContainersDict float minScale = Mathf.Min(0.5f, maxScale / 2.0f); float lastScale = 1.0f; - Func tryScale = (scale) => { + Func tryScale = (scale) => + { emptyEnumerator( scaleObject( scale: scale / lastScale, @@ -161,7 +183,8 @@ SimObjPhysics cover in availableExpRoomContainersDict forceKinematic: true, includeErrorMessage: true ) - ) { + ) + { #if UNITY_EDITOR Debug.Log($"{cover.name} failed to place: {errorMessage}"); #endif @@ -171,7 +194,8 @@ SimObjPhysics cover in availableExpRoomContainersDict float coverY = cover.transform.position.y; float toCoverHeight = toCover.BoundingBox.GetComponent().size.y; - for (int i = 0; i < 4; i++) { + for (int i = 0; i < 4; i++) + { cover.transform.position = new Vector3( toCoverPos.x, coverY + toCoverHeight * (i / 4f), @@ -182,12 +206,15 @@ SimObjPhysics cover in availableExpRoomContainersDict Collider coverCollidingWith = UtilityFunctions.firstColliderObjectCollidingWith(go: cover.gameObject); - if (coverCollidingWith != null) { + if (coverCollidingWith != null) + { //Debug.Log($"{cover.name} colliding with {coverCollidingWith.transform.parent.name}"); return false; } - if (i == 0) { - if (isSimObjVisible(visibilityCheckCamera, toCover, 10f).visible) { + if (i == 0) + { + if (isSimObjVisible(visibilityCheckCamera, toCover, 10f).visible) + { return false; } } @@ -195,12 +222,17 @@ SimObjPhysics cover in availableExpRoomContainersDict return true; }; - if (tryScale(maxScale)) { - for (int i = 0; i <= 5; i++) { + if (tryScale(maxScale)) + { + for (int i = 0; i <= 5; i++) + { float newScale = (minScale + maxScale) / 2.0f; - if (tryScale(newScale)) { + if (tryScale(newScale)) + { maxScale = newScale; - } else { + } + else + { minScale = newScale; } yield return null; @@ -229,7 +261,8 @@ SimObjPhysics cover in availableExpRoomContainersDict Newtonsoft.Json.JsonConvert.SerializeObject( coverNameToScale, Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { + new Newtonsoft.Json.JsonSerializerSettings() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = new ShouldSerializeContractResolver() } @@ -244,8 +277,10 @@ SimObjPhysics cover in availableExpRoomContainersDict actionFinished(true, coverNameToScale); } - public void SetCollisionDetectionModeToContinuousSpeculative(string objectId) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void SetCollisionDetectionModeToContinuousSpeculative(string objectId) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; @@ -253,56 +288,77 @@ public void SetCollisionDetectionModeToContinuousSpeculative(string objectId) { SimObjPhysics target = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; Rigidbody rb = target.GetComponent(); - if (!rb) { + if (!rb) + { errorMessage = $"Could not find rigid body for {objectId}"; actionFinished(false); return; - } else { + } + else + { rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; actionFinished(true, availableExpRoomContainersDict.Keys.ToList()); } } - public void AvailableExpRoomObjects() { + public void AvailableExpRoomObjects() + { actionFinished(true, availableExpRoomObjectsDict.Keys.ToList()); } - public void AvailableExpRoomContainers() { + public void AvailableExpRoomContainers() + { actionFinished(true, availableExpRoomContainersDict.Keys.ToList()); } - public void ToggleExpRoomObject(string objectName, bool? enable = null) { + public void ToggleExpRoomObject(string objectName, bool? enable = null) + { SimObjPhysics target = null; - if (availableExpRoomObjectsDict.ContainsKey(objectName)) { + if (availableExpRoomObjectsDict.ContainsKey(objectName)) + { target = availableExpRoomObjectsDict[objectName]; - } else if (availableExpRoomContainersDict.ContainsKey(objectName)) { + } + else if (availableExpRoomContainersDict.ContainsKey(objectName)) + { target = availableExpRoomContainersDict[objectName]; - } else { + } + else + { errorMessage = $"Could not find object with name {objectName}"; actionFinishedEmit(false); return; } - if (!enable.HasValue) { + if (!enable.HasValue) + { enable = !target.gameObject.activeSelf; } target.gameObject.SetActive(enable.Value); - if (enable.Value) { - foreach (Renderer r in target.GetComponentsInChildren()) { - if (!r.enabled) { + if (enable.Value) + { + foreach (Renderer r in target.GetComponentsInChildren()) + { + if (!r.enabled) + { initiallyDisabledRenderers.Add(r.GetInstanceID()); } } target.ObjectID = target.name; physicsSceneManager.AddToObjectsInScene(target); actionFinished(true, target.ObjectID); - } else { - foreach (Renderer r in target.GetComponentsInChildren()) { - if (initiallyDisabledRenderers.Contains(r.GetInstanceID())) { + } + else + { + foreach (Renderer r in target.GetComponentsInChildren()) + { + if (initiallyDisabledRenderers.Contains(r.GetInstanceID())) + { initiallyDisabledRenderers.Remove(r.GetInstanceID()); r.enabled = false; - } else { + } + else + { r.enabled = true; } } @@ -311,8 +367,10 @@ public void ToggleExpRoomObject(string objectName, bool? enable = null) { } } - public void ToggleObjectIsKinematic(string objectId, bool? isKinematic = null) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void ToggleObjectIsKinematic(string objectId, bool? isKinematic = null) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; @@ -321,9 +379,12 @@ public void ToggleObjectIsKinematic(string objectId, bool? isKinematic = null) { Rigidbody rb = physicsSceneManager .ObjectIdToSimObjPhysics[objectId] .GetComponent(); - if (isKinematic.HasValue) { + if (isKinematic.HasValue) + { rb.isKinematic = isKinematic.Value; - } else { + } + else + { rb.isKinematic = !rb.isKinematic; } actionFinishedEmit(true); @@ -337,8 +398,10 @@ public void SetRigidbodyConstraints( bool freezeXRotation = false, bool freezeYRotation = false, bool freezeZRotation = false - ) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + ) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; @@ -348,38 +411,47 @@ public void SetRigidbodyConstraints( Rigidbody rb = target.GetComponent(); rb.constraints = RigidbodyConstraints.None; - if (freezeX) { + if (freezeX) + { rb.constraints = rb.constraints | RigidbodyConstraints.FreezePositionX; } - if (freezeY) { + if (freezeY) + { rb.constraints = rb.constraints | RigidbodyConstraints.FreezePositionY; } - if (freezeZ) { + if (freezeZ) + { rb.constraints = rb.constraints | RigidbodyConstraints.FreezePositionZ; } - if (freezeXRotation) { + if (freezeXRotation) + { rb.constraints = rb.constraints | RigidbodyConstraints.FreezeRotationX; } - if (freezeYRotation) { + if (freezeYRotation) + { rb.constraints = rb.constraints | RigidbodyConstraints.FreezeRotationY; } - if (freezeZRotation) { + if (freezeZRotation) + { rb.constraints = rb.constraints | RigidbodyConstraints.FreezeRotationZ; } actionFinished(true); } - public List pointOnObjectsCollidersClosestToPoint(string objectId, Vector3 point) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public List pointOnObjectsCollidersClosestToPoint(string objectId, Vector3 point) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; return null; } SimObjPhysics target = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; List closePoints = new List(); - foreach (Collider c in target.GetComponentsInChildren()) { + foreach (Collider c in target.GetComponentsInChildren()) + { // The below subtype checks are required as `ClosestPoint` only works // 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. @@ -392,7 +464,8 @@ c is BoxCollider || c is CapsuleCollider || (c is MeshCollider && ((MeshCollider)c).convex) ) - ) { + ) + { closePoints.Add(c.ClosestPoint(point)); #if UNITY_EDITOR Vector3 closePoint = closePoints[closePoints.Count - 1]; @@ -402,7 +475,8 @@ c is BoxCollider #endif } } - if (closePoints.Count == 0) { + if (closePoints.Count == 0) + { target.syncBoundingBoxes(forceCreateObjectOrientedBoundingBox: true); BoxCollider bbox = target.BoundingBox.GetComponent(); bbox.enabled = true; @@ -442,7 +516,8 @@ c is BoxCollider /// /// 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) { + public void PointOnObjectsCollidersClosestToPoint(string objectId, Vector3 point) + { List closePoints = pointOnObjectsCollidersClosestToPoint( objectId: objectId, point: point @@ -450,8 +525,10 @@ public void PointOnObjectsCollidersClosestToPoint(string objectId, Vector3 point actionFinishedEmit(closePoints != null, closePoints); } - public void PointOnObjectsMeshClosestToPoint(string objectId, Vector3 point) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void PointOnObjectsMeshClosestToPoint(string objectId, Vector3 point) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; @@ -459,23 +536,28 @@ public void PointOnObjectsMeshClosestToPoint(string objectId, Vector3 point) { SimObjPhysics target = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; List points = new List(); - foreach (MeshFilter mf in target.GetComponentsInChildren()) { - foreach (Vector3 v in mf.mesh.vertices) { + foreach (MeshFilter mf in target.GetComponentsInChildren()) + { + foreach (Vector3 v in mf.mesh.vertices) + { points.Add(mf.transform.TransformPoint(v)); } } points = points.OrderBy(x => Vector3.Distance(point, x)).ToList(); #if UNITY_EDITOR - foreach (Vector3 p in points) { + foreach (Vector3 p in points) + { Debug.Log($"{p} has dist {Vector3.Distance(p, point)}"); } #endif actionFinishedEmit(true, points); } - public void ProportionOfObjectVisible(string objectId, int? thirdPartyCameraIndex = null) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void ProportionOfObjectVisible(string objectId, int? thirdPartyCameraIndex = null) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; @@ -484,17 +566,20 @@ public void ProportionOfObjectVisible(string objectId, int? thirdPartyCameraInde SimObjPhysics target = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; float propVisible = 0f; - if (target.VisibilityPoints != null && target.VisibilityPoints.Length > 0) { + if (target.VisibilityPoints != null && target.VisibilityPoints.Length > 0) + { Transform[] visPoints = target.VisibilityPoints; int visPointCount = 0; Camera camera = thirdPartyCameraIndex.HasValue ? agentManager.thirdPartyCameras[thirdPartyCameraIndex.Value] : m_Camera; - foreach (Transform point in visPoints) { + foreach (Transform point in visPoints) + { // if this particular point is in view... - if (CheckIfVisibilityPointInViewport(target, point, camera, false).visible) { + if (CheckIfVisibilityPointInViewport(target, point, camera, false).visible) + { visPointCount++; } } @@ -505,9 +590,11 @@ public void ProportionOfObjectVisible(string objectId, int? thirdPartyCameraInde actionFinishedEmit(true, propVisible); } - protected GameObject addClippingPlaneToObject(SimObjPhysics target) { + protected GameObject addClippingPlaneToObject(SimObjPhysics target) + { Ronja.ClippingPlane clipPlane = target.GetComponentInChildren(); - if (clipPlane != null) { + if (clipPlane != null) + { return clipPlane.gameObject; } @@ -519,17 +606,22 @@ protected GameObject addClippingPlaneToObject(SimObjPhysics target) { clipPlane = clipPlaneGo.AddComponent(); List materials = new List(); - foreach (MeshRenderer mr in target.GetComponentsInChildren()) { + foreach (MeshRenderer mr in target.GetComponentsInChildren()) + { List newMRMaterials = new List(); bool anyOpaque = false; - foreach (Material mat in mr.materials) { - if (mat.GetTag("RenderType", false) == "Opaque") { + foreach (Material mat in mr.materials) + { + if (mat.GetTag("RenderType", false) == "Opaque") + { anyOpaque = true; break; } } - foreach (Material mat in mr.materials) { - if (!anyOpaque || mat.GetTag("RenderType", false) == "Opaque") { + foreach (Material mat in mr.materials) + { + if (!anyOpaque || mat.GetTag("RenderType", false) == "Opaque") + { newMRMaterials.Add(mat); Vector4 col = mat.GetVector("_Color"); Vector4 emission = mat.GetVector("_EmissionColor"); @@ -553,8 +645,10 @@ public void AddClippingPlaneToObject( Vector3? position = null, Vector3? normal = null, bool? enabled = null - ) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + ) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; @@ -564,16 +658,19 @@ public void AddClippingPlaneToObject( GameObject planeGo = addClippingPlaneToObject(target); - if (position.HasValue) { + if (position.HasValue) + { planeGo.transform.position = position.Value; } - if (normal.HasValue) { + if (normal.HasValue) + { planeGo.transform.up = Vector3.Normalize(normal.Value); } Ronja.ClippingPlane clipPlane = planeGo.GetComponent(); - if (enabled.HasValue) { + if (enabled.HasValue) + { clipPlane.shouldClip = enabled.Value; } @@ -584,8 +681,10 @@ public void AddClippingPlaneToObject( actionFinished(true, toReturn); } - public void AddClippingPlaneToObjectToExcludeBox(string objectId, List boxCorners) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void AddClippingPlaneToObjectToExcludeBox(string objectId, List boxCorners) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; @@ -606,19 +705,24 @@ public void AddClippingPlaneToObjectToExcludeBox(string objectId, List toReturn["enabled"] = planeGo.GetComponentInChildren().shouldClip; toReturn["position"] = planeGo.transform.position; toReturn["normal"] = planeGo.transform.up; - if (!(bool)toReturn["enabled"]) { + 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." ); actionFinished(false, toReturn); - } else { + } + else + { actionFinished(true, toReturn); } } - public void GetClippingPlane(string objectId) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void GetClippingPlane(string objectId) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; @@ -626,7 +730,8 @@ public void GetClippingPlane(string objectId) { SimObjPhysics target = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; Ronja.ClippingPlane clipPlane = target.GetComponentInChildren(); - if (clipPlane == null) { + if (clipPlane == null) + { errorMessage = $"Object with id {objectId} does not have a clipping plane associated with it."; actionFinishedEmit(false); @@ -641,8 +746,10 @@ public void GetClippingPlane(string objectId) { actionFinishedEmit(true, toReturn); } - public void ToggleClippingPlane(string objectId, bool? enabled = null) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void ToggleClippingPlane(string objectId, bool? enabled = null) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; @@ -650,19 +757,22 @@ public void ToggleClippingPlane(string objectId, bool? enabled = null) { SimObjPhysics target = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; Ronja.ClippingPlane clipPlane = target.GetComponentInChildren(); - if (clipPlane == null) { + if (clipPlane == null) + { errorMessage = $"Object with id {objectId} does not have a clipping plane associated with it."; actionFinished(false); return; } - if (!enabled.HasValue) { + if (!enabled.HasValue) + { enabled = !clipPlane.shouldClip; } bool changed = false; - if (enabled.Value != clipPlane.shouldClip) { + if (enabled.Value != clipPlane.shouldClip) + { changed = true; clipPlane.shouldClip = enabled.Value; } @@ -672,22 +782,29 @@ public void ToggleClippingPlane(string objectId, bool? enabled = null) { toReturn["enabled"] = enabled.Value; toReturn["position"] = planeGo.transform.position; toReturn["normal"] = planeGo.transform.up; - if (changed) { + if (changed) + { actionFinished(true, toReturn); - } else { + } + else + { actionFinishedEmit(true, toReturn); } } - protected List cornersOfBounds(Bounds b) { + protected List cornersOfBounds(Bounds b) + { List corners = new List(); - for (int i = 0; i < 2; i++) { + for (int i = 0; i < 2; i++) + { float x = i == 0 ? b.min.x : b.max.x; - for (int j = 0; j < 2; j++) { + for (int j = 0; j < 2; j++) + { float y = j == 0 ? b.min.y : b.max.y; - for (int k = 0; k < 2; k++) { + for (int k = 0; k < 2; k++) + { float z = k == 0 ? b.min.z : b.max.z; corners.Add(new Vector3(x, y, z)); @@ -700,9 +817,11 @@ protected List cornersOfBounds(Bounds b) { public GameObject addClippingPlaneToObjectToExcludeBox( SimObjPhysics target, float[][] boxCorners - ) { + ) + { List boxCornersV3 = new List(); - for (int i = 0; i < boxCorners.Length; i++) { + for (int i = 0; i < boxCorners.Length; i++) + { boxCornersV3.Add(new Vector3(boxCorners[i][0], boxCorners[i][1], boxCorners[i][2])); } return addClippingPlaneToObjectToExcludeBox(target, boxCornersV3); @@ -711,32 +830,40 @@ float[][] boxCorners public GameObject addClippingPlaneToObjectToExcludeBox( SimObjPhysics target, List boxCorners - ) { + ) + { GameObject clipPlaneGo = addClippingPlaneToObject(target); Bounds boundsOfInputBox = UtilityFunctions.CreateEmptyBounds(); - foreach (Vector3 bc in boxCorners) { + foreach (Vector3 bc in boxCorners) + { boundsOfInputBox.Encapsulate(bc); } Bounds boundsOfVerticesToExclude = UtilityFunctions.CreateEmptyBounds(); bool anythingEncapsulated = false; - foreach (MeshFilter mf in target.GetComponentsInChildren()) { + foreach (MeshFilter mf in target.GetComponentsInChildren()) + { Mesh m = mf.mesh; - for (int i = 0; i < m.vertices.Length; i++) { + for (int i = 0; i < m.vertices.Length; i++) + { Vector3 v = mf.transform.TransformPoint(m.vertices[i]); - if (boundsOfInputBox.Contains(v)) { + if (boundsOfInputBox.Contains(v)) + { anythingEncapsulated = true; boundsOfVerticesToExclude.Encapsulate(v); } } } - if (!anythingEncapsulated) { + if (!anythingEncapsulated) + { clipPlaneGo.GetComponent().shouldClip = false; return clipPlaneGo; - } else { + } + else + { clipPlaneGo.GetComponent().shouldClip = true; } @@ -745,28 +872,37 @@ List boxCorners Vector3 direction = boundsOfVerticesToExclude.center - target.transform.position; this.autoSyncTransforms(); - if (Math.Abs(direction.x) > Math.Abs(direction.z)) { + if (Math.Abs(direction.x) > Math.Abs(direction.z)) + { Vector3 lookOffset = new Vector3(Mathf.Sign(direction.x), 0f, 0f); clipPlaneGo.transform.LookAt(lookOffset + startPos); clipPlaneGo.transform.Rotate(new Vector3(90f, 0f, 0f)); - if (lookOffset.x > 0f) { + if (lookOffset.x > 0f) + { clipPlaneGo.transform.position = new Vector3(boundsOfVerticesToExclude.min.x - startPos.x, 0f, 0f) + startPos; - } else { + } + else + { clipPlaneGo.transform.position = new Vector3(boundsOfVerticesToExclude.max.x - startPos.x, 0f, 0f) + startPos; } - } else { + } + 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) { + if (lookOffset.z > 0f) + { clipPlaneGo.transform.position = new Vector3(0f, 0f, boundsOfVerticesToExclude.min.z - startPos.z) + startPos; - } else { + } + else + { clipPlaneGo.transform.position = new Vector3(0f, 0f, boundsOfVerticesToExclude.max.z - startPos.z) + startPos; @@ -780,7 +916,8 @@ List boxCorners // creates a grid starting from the agent's current hand position and projects that grid // forward relative to the agent // 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) { + public void GetReceptacleCoordinatesExpRoom(float gridSize, int maxStepCount) + { var agent = this.agentManager.agents[0]; ExperimentRoomSceneManager ersm = physicsSceneManager.GetComponent(); @@ -803,15 +940,18 @@ public void SpawnExperimentObjAtPoint( Vector3 position, float rotation, int objectVariation = 0 - ) { - if (receptacleObjectId == null) { + ) + { + if (receptacleObjectId == null) + { errorMessage = "please give valid receptacleObjectId for SpawnExperimentReceptacleAtPoint action"; actionFinished(false); return; } - if (objectType == null) { + if (objectType == null) + { errorMessage = "please use either 'receptacle' or 'screen' to specify which experiment object to spawn"; actionFinished(false); @@ -820,13 +960,16 @@ public void SpawnExperimentObjAtPoint( SimObjPhysics target = null; // find the object in the scene, disregard visibility - foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - if (sop.objectID == receptacleObjectId) { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { + if (sop.objectID == receptacleObjectId) + { target = sop; } } - if (target == null) { + if (target == null) + { errorMessage = "no receptacle object with id: " + receptacleObjectId @@ -846,9 +989,12 @@ public void SpawnExperimentObjAtPoint( position, rotation ) - ) { + ) + { actionFinished(true); - } else { + } + else + { errorMessage = $"Experiment object could not be placed on {receptacleObjectId}"; actionFinished(false); } @@ -862,15 +1008,18 @@ public void SpawnExperimentObjAtRandom( float rotation, int randomSeed, int objectVariation = 0 - ) { - if (receptacleObjectId == null) { + ) + { + if (receptacleObjectId == null) + { errorMessage = "please give valid receptacleObjectId for SpawnExperimentReceptacleAtRandom action"; actionFinished(false); return; } - if (objectType == null) { + if (objectType == null) + { errorMessage = "please use either 'receptacle' or 'screen' to specify which experiment object to spawn"; actionFinished(false); @@ -879,13 +1028,16 @@ public void SpawnExperimentObjAtRandom( SimObjPhysics target = null; // find the object in the scene, disregard visibility - foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - if (sop.objectID == receptacleObjectId) { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { + if (sop.objectID == receptacleObjectId) + { target = sop; } } - if (target == null) { + if (target == null) + { errorMessage = "no receptacle object with id: " + receptacleObjectId @@ -905,24 +1057,30 @@ public void SpawnExperimentObjAtRandom( target, rotation ) - ) { + ) + { actionFinished(true); - } else { + } + else + { errorMessage = "Experiment object could not be placed on " + receptacleObjectId; actionFinished(false); } } // specify a screen by objectId in exp room and change material to objectVariation - public void ChangeScreenMaterialExpRoom(string objectId, int objectVariation) { + public void ChangeScreenMaterialExpRoom(string objectId, int objectVariation) + { // only 5 material options at the moment - if (objectVariation < 0 || objectVariation > 4) { + if (objectVariation < 0 || objectVariation > 4) + { errorMessage = "please use objectVariation [0, 4] inclusive"; actionFinished(false); return; } - if (objectId == null) { + if (objectId == null) + { errorMessage = "please give valid objectId for ChangeScreenMaterialExpRoom action"; actionFinished(false); return; @@ -930,13 +1088,16 @@ public void ChangeScreenMaterialExpRoom(string objectId, int objectVariation) { SimObjPhysics target = null; // find the object in the scene, disregard visibility - foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - if (sop.objectID == objectId) { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { + if (sop.objectID == objectId) + { target = sop; } } - if (target == null) { + if (target == null) + { errorMessage = "no object with id: " + objectId @@ -952,8 +1113,10 @@ public void ChangeScreenMaterialExpRoom(string objectId, int objectVariation) { } // 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) { + public void ChangeScreenColorExpRoom(string objectId, float r, float g, float b) + { + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) + { errorMessage = "rgb values must be [0-255]"; actionFinished(false); return; @@ -961,13 +1124,16 @@ public void ChangeScreenColorExpRoom(string objectId, float r, float g, float b) SimObjPhysics target = null; // find the object in the scene, disregard visibility - foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - if (sop.objectID == objectId) { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { + if (sop.objectID == objectId) + { target = sop; } } - if (target == null) { + if (target == null) + { errorMessage = "no object with id: " + objectId @@ -983,9 +1149,11 @@ public void ChangeScreenColorExpRoom(string objectId, float r, float g, float b) } // change wall to material [variation] - public void ChangeWallMaterialExpRoom(int objectVariation) { + public void ChangeWallMaterialExpRoom(int objectVariation) + { // only 5 material options at the moment - if (objectVariation < 0 || objectVariation > 4) { + if (objectVariation < 0 || objectVariation > 4) + { errorMessage = "please use objectVariation [0, 4] inclusive"; actionFinished(false); return; @@ -998,8 +1166,10 @@ public void ChangeWallMaterialExpRoom(int objectVariation) { } // 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) { + public void ChangeWallColorExpRoom(float r, float g, float b) + { + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) + { errorMessage = "rgb values must be [0-255]"; actionFinished(false); return; @@ -1012,9 +1182,11 @@ public void ChangeWallColorExpRoom(float r, float g, float b) { } // change floor to material [variation] - public void ChangeFloorMaterialExpRoom(int objectVariation) { + public void ChangeFloorMaterialExpRoom(int objectVariation) + { // only 5 material options at the moment - if (objectVariation < 0 || objectVariation > 4) { + if (objectVariation < 0 || objectVariation > 4) + { errorMessage = "please use objectVariation [0, 4] inclusive"; actionFinished(false); return; @@ -1027,8 +1199,10 @@ public void ChangeFloorMaterialExpRoom(int objectVariation) { } // 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) { + public void ChangeFloorColorExpRoom(float r, float g, float b) + { + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) + { errorMessage = "rgb values must be [0-255]"; actionFinished(false); return; @@ -1041,8 +1215,10 @@ public void ChangeFloorColorExpRoom(float r, float g, float b) { } // 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) { + public void ChangeLightColorExpRoom(float r, float g, float b) + { + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) + { errorMessage = "rgb values must be [0-255]"; actionFinished(false); return; @@ -1056,9 +1232,11 @@ public void ChangeLightColorExpRoom(float r, float g, float b) { // change intensity of lights in exp room [0-5] these arent in like... lumens or anything // just a relative intensity value - public void ChangeLightIntensityExpRoom(float intensity) { + public void ChangeLightIntensityExpRoom(float intensity) + { // restrict this to [0-5] - if (intensity < 0 || intensity > 5) { + if (intensity < 0 || intensity > 5) + { errorMessage = "light intensity must be [0.0 , 5.0] inclusive"; actionFinished(false); return; @@ -1070,9 +1248,11 @@ public void ChangeLightIntensityExpRoom(float intensity) { actionFinished(true); } - public void ChangeTableTopMaterialExpRoom(int objectVariation) { + public void ChangeTableTopMaterialExpRoom(int objectVariation) + { // only 5 material options at the moment - if (objectVariation < 0 || objectVariation > 4) { + if (objectVariation < 0 || objectVariation > 4) + { errorMessage = "please use objectVariation [0, 4] inclusive"; actionFinished(false); return; @@ -1084,8 +1264,10 @@ public void ChangeTableTopMaterialExpRoom(int 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) { + public void ChangeTableTopColorExpRoom(float r, float g, float b) + { + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) + { errorMessage = "rgb values must be [0-255]"; actionFinished(false); return; @@ -1097,9 +1279,11 @@ public void ChangeTableTopColorExpRoom(float r, float g, float b) { actionFinished(true); } - public void ChangeTableLegMaterialExpRoom(int objectVariation) { + public void ChangeTableLegMaterialExpRoom(int objectVariation) + { // only 5 material options at the moment - if (objectVariation < 0 || objectVariation > 4) { + if (objectVariation < 0 || objectVariation > 4) + { errorMessage = "please use objectVariation [0, 4] inclusive"; actionFinished(false); return; @@ -1111,8 +1295,10 @@ public void ChangeTableLegMaterialExpRoom(int 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) { + public void ChangeTableLegColorExpRoom(float r, float g, float b) + { + if (r < 0 || r > 255 || g < 0 || g > 255 || b < 0 || b > 255) + { errorMessage = "rgb values must be [0-255]"; actionFinished(false); return; @@ -1132,22 +1318,26 @@ public void ReturnValidSpawnsExpRoom( string receptacleObjectId, float rotation, int objectVariation = 0 - ) { - if (receptacleObjectId == null) { + ) + { + if (receptacleObjectId == null) + { errorMessage = "please give valid receptacleObjectId for ReturnValidSpawnsExpRoom action"; actionFinished(false); return; } - if (objectType == null) { + if (objectType == null) + { errorMessage = "please use either 'receptacle' or 'screen' to specify which experiment object to spawn"; actionFinished(false); return; } - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(receptacleObjectId)) { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(receptacleObjectId)) + { errorMessage = $"Cannot find object with id {receptacleObjectId}."; actionFinished(false); return; diff --git a/unity/Assets/Scripts/ExperimentRoomSceneManager.cs b/unity/Assets/Scripts/ExperimentRoomSceneManager.cs index 677c4aa389..0fcbc268b8 100644 --- a/unity/Assets/Scripts/ExperimentRoomSceneManager.cs +++ b/unity/Assets/Scripts/ExperimentRoomSceneManager.cs @@ -4,7 +4,8 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public class ExperimentRoomSceneManager : MonoBehaviour { +public class ExperimentRoomSceneManager : MonoBehaviour +{ public GameObject[] replacementObjectsToSpawn = null; // set of experiment receptacle objects @@ -49,7 +50,8 @@ public class ExperimentRoomSceneManager : MonoBehaviour { Vector3 initialSpawnPosition = new Vector3(0, 100, 0); // Start is called before the first frame update - void Start() { + void Start() + { agentManager = gameObject.GetComponent(); sceneManager = gameObject.GetComponent(); } @@ -72,18 +74,21 @@ public List ValidGrid( float gridIncrement, int count, BaseFPSAgentController agent - ) { + ) + { // start from origin which will be agent's hand List pointsOnGrid = new List(); - for (int i = 0; i < count; i++) { + for (int i = 0; i < count; i++) + { // from origin, go gridIncrement a number of times equal to gridDimension // in the agent's forward direction Vector3 thisPoint = origin + agent.transform.forward * gridIncrement * i; pointsOnGrid.Add(thisPoint); // then, from this point, go gridDimension times in both left and right direction - for (int j = 1; j < count + 1; j++) { + for (int j = 1; j < count + 1; j++) + { pointsOnGrid.Add(thisPoint + agent.transform.right * gridIncrement * j); pointsOnGrid.Add(thisPoint + -agent.transform.right * gridIncrement * j); } @@ -96,7 +101,8 @@ BaseFPSAgentController agent List actualPoints = new List(); RaycastHit[] hits; - foreach (Vector3 point in pointsOnGrid) { + foreach (Vector3 point in pointsOnGrid) + { hits = Physics.RaycastAll( point + new Vector3(0, 5, 0), Vector3.down, @@ -106,16 +112,20 @@ BaseFPSAgentController agent ); float[] hitDistances = new float[hits.Length]; - for (int i = 0; i < hitDistances.Length; i++) { + for (int i = 0; i < hitDistances.Length; i++) + { hitDistances[i] = hits[i].distance; } Array.Sort(hitDistances, hits); - foreach (RaycastHit h in hits) { - if (h.transform.GetComponent()) { + foreach (RaycastHit h in hits) + { + if (h.transform.GetComponent()) + { var o = h.transform.GetComponent(); - if (o.Type != SimObjType.DiningTable && o.Type != SimObjType.Floor) { + if (o.Type != SimObjType.DiningTable && o.Type != SimObjType.Floor) + { actualPoints.Add(point); } } @@ -131,89 +141,107 @@ BaseFPSAgentController agent } // change specified screen object's material to color rgb - public void ChangeScreenColor(SimObjPhysics screen, float r, float g, float b) { + public void ChangeScreenColor(SimObjPhysics screen, float r, float g, float b) + { List renderers = GetAllRenderersOfObject(screen); - foreach (MeshRenderer sr in renderers) { + foreach (MeshRenderer sr in renderers) + { // set first element, the primary mat, of the mat array's color sr.material.color = new Color(r / 255f, g / 255f, b / 255f); } } // change specified screen object's material to variation - public void ChangeScreenMaterial(SimObjPhysics screen, int variation) { + public void ChangeScreenMaterial(SimObjPhysics screen, int variation) + { List renderers = GetAllRenderersOfObject(screen); - foreach (MeshRenderer sr in renderers) { + foreach (MeshRenderer sr in renderers) + { sr.material = screenMaterials[variation]; } } - public List GetAllRenderersOfObject(SimObjPhysics obj) { + public List GetAllRenderersOfObject(SimObjPhysics obj) + { List renderers = new List(); renderers.AddRange(obj.transform.gameObject.GetComponentsInChildren()); return renderers; } - public void ChangeLightColor(float r, float g, float b) { - foreach (GameObject light in allOfTheLights) { + public void ChangeLightColor(float r, float g, float b) + { + foreach (GameObject light in allOfTheLights) + { light.GetComponent().color = new Color(r / 255f, g / 255f, b / 255f); } } // 0 to like 5 is reasonable - public void ChangeLightIntensity(float intensity) { - foreach (GameObject light in allOfTheLights) { + public void ChangeLightIntensity(float intensity) + { + foreach (GameObject light in allOfTheLights) + { light.GetComponent().intensity = intensity; } } - public void ChangeTableTopMaterial(int variation = 0) { + public void ChangeTableTopMaterial(int variation = 0) + { Material[] mats = table.materials; mats[0] = tableTopMaterials[variation]; table.materials = mats; } - public void ChangeTableTopColor(float r, float g, float b) { + public void ChangeTableTopColor(float r, float g, float b) + { Material[] mats = table.materials; mats[0].color = new Color(r / 255f, g / 255f, b / 255f); table.materials = mats; } - public void ChangeTableLegMaterial(int variation = 0) { + public void ChangeTableLegMaterial(int variation = 0) + { Material[] mats = table.materials; mats[1] = tableTopMaterials[variation]; table.materials = mats; } - public void ChangeTableLegColor(float r, float g, float b) { + public void ChangeTableLegColor(float r, float g, float b) + { Material[] mats = table.materials; mats[1].color = new Color(r / 255f, g / 255f, b / 255f); table.materials = mats; } - public void ChangeLightConfig(int variation = 0) { + public void ChangeLightConfig(int variation = 0) + { // disable all lights // enable the specific variation } // change wall material variation - public void ChangeWallMaterial(int variation = 0) { + public void ChangeWallMaterial(int variation = 0) + { wall.material = wallMaterials[variation]; } // change wall color r g b - public void ChangeWallColor(float r, float g, float b) { + public void ChangeWallColor(float r, float g, float b) + { // Color() takes 0-1.0, so yeah convert var color = new Color(r / 255f, g / 255f, b / 255f); wall.material.color = color; } // change floor material variation - public void ChangeFloorMaterial(int variation = 0) { + public void ChangeFloorMaterial(int variation = 0) + { floor.material = floorMaterials[variation]; } // change floor color - public void ChangeFloorColor(float r, float g, float b) { + public void ChangeFloorColor(float r, float g, float b) + { // Color() takes 0-1.0, so yeah convert var color = new Color(r / 255f, g / 255f, b / 255f); floor.material.color = color; @@ -227,14 +255,17 @@ public List ReturnValidSpawns( int variation, SimObjPhysics targetReceptacle, float yRot = 0 - ) { + ) + { toSpawn = null; - if (objType == "screen") { + if (objType == "screen") + { toSpawn = screensToSpawn[variation].GetComponent(); } - if (objType == "receptacle") { + if (objType == "receptacle") + { toSpawn = receptaclesToSpawn[variation].GetComponent(); } @@ -256,7 +287,8 @@ public List ReturnValidSpawns( List returnCoordinates = new List(); // try and place object at every spawn coordinate and if it works, add it to the valid coords to return - for (int i = 0; i < spawnCoordinates.Count; i++) { + for (int i = 0; i < spawnCoordinates.Count; i++) + { // place object at the given point, then check if the corners are ok agent.placeObjectAtPoint(toSpawn, spawnCoordinates[i]); @@ -264,8 +296,10 @@ public List ReturnValidSpawns( Contains con = targetReceptacle.ReceptacleTriggerBoxes[0].GetComponent(); bool cornerCheck = true; - foreach (Vector3 p in corners) { - if (!con.CheckIfPointIsAboveReceptacleTriggerBox(p)) { + foreach (Vector3 p in corners) + { + if (!con.CheckIfPointIsAboveReceptacleTriggerBox(p)) + { cornerCheck = false; // this position would cause object to fall off table // double back and reset object to try again with another point @@ -274,7 +308,8 @@ public List ReturnValidSpawns( } } - if (cornerCheck) { + if (cornerCheck) + { returnCoordinates.Add(spawnCoordinates[i]); // all corners were ok, so add it to the points that are valid } @@ -301,20 +336,24 @@ public bool SpawnExperimentObjAtPoint( SimObjPhysics targetReceptacle, Vector3 point, float yRot = 0 - ) { + ) + { toSpawn = null; bool success = false; - if (objType == "screen") { + if (objType == "screen") + { toSpawn = screensToSpawn[variation].GetComponent(); } - if (objType == "receptacle") { + if (objType == "receptacle") + { toSpawn = receptaclesToSpawn[variation].GetComponent(); } - if (objType == "replacement") { + if (objType == "replacement") + { toSpawn = replacementObjectsToSpawn[variation].GetComponent(); } @@ -331,7 +370,8 @@ public bool SpawnExperimentObjAtPoint( // apply rotation to object, default quaternion.identity spawned.transform.Rotate(new Vector3(0, yRot, 0), Space.Self); - if (agent.placeObjectAtPoint(toSpawn, point)) { + if (agent.placeObjectAtPoint(toSpawn, point)) + { // we set success to true, if one of the corners doesn't fit on the table // this will be switched to false and will be returned at the end success = true; @@ -344,8 +384,10 @@ public bool SpawnExperimentObjAtPoint( List corners = GetCorners(spawned); Contains con = targetReceptacle.ReceptacleTriggerBoxes[0].GetComponent(); - foreach (Vector3 p in corners) { - if (!con.CheckIfPointIsAboveReceptacleTriggerBox(p)) { + foreach (Vector3 p in corners) + { + if (!con.CheckIfPointIsAboveReceptacleTriggerBox(p)) + { success = false; // this position would cause object to fall off table // double back and reset object to try again with another point @@ -355,7 +397,8 @@ public bool SpawnExperimentObjAtPoint( } } - if (success) { + if (success) + { rb.isKinematic = false; // run scene setup to grab reference to object and give it objectId sceneManager.SetupScene(); @@ -364,7 +407,8 @@ public bool SpawnExperimentObjAtPoint( // no objects could be spawned at any of the spawn points // destroy the thing we tried to place on target receptacle - if (!success) { + if (!success) + { Destroy(spawned.transform.gameObject); } @@ -379,18 +423,21 @@ public bool SpawnExperimentObjAtRandom( int seed, SimObjPhysics targetReceptacle, float yRot = 0 - ) { + ) + { toSpawn = null; bool success = false; // init random state UnityEngine.Random.InitState(seed); - if (objType == "screen") { + if (objType == "screen") + { toSpawn = screensToSpawn[variation].GetComponent(); } - if (objType == "receptacle") { + if (objType == "receptacle") + { toSpawn = receptaclesToSpawn[variation].GetComponent(); } @@ -411,10 +458,12 @@ public bool SpawnExperimentObjAtRandom( // apply rotation to object, default quaternion.identity spawned.transform.Rotate(new Vector3(0, yRot, 0), Space.Self); - for (int i = 0; i < spawnCoordinates.Count; i++) { + for (int i = 0; i < spawnCoordinates.Count; i++) + { // place object at the given point, this also checks the spawn area to see if its clear // if not clear, it will return false - if (agent.placeObjectAtPoint(toSpawn, spawnCoordinates[i])) { + if (agent.placeObjectAtPoint(toSpawn, spawnCoordinates[i])) + { // we set success to true, if one of the corners doesn't fit on the table // this will be switched to false and will be returned at the end success = true; @@ -428,8 +477,10 @@ public bool SpawnExperimentObjAtRandom( Contains con = targetReceptacle.ReceptacleTriggerBoxes[0].GetComponent(); bool cornerCheck = true; - foreach (Vector3 p in corners) { - if (!con.CheckIfPointIsAboveReceptacleTriggerBox(p)) { + foreach (Vector3 p in corners) + { + if (!con.CheckIfPointIsAboveReceptacleTriggerBox(p)) + { cornerCheck = false; // this position would cause object to fall off table // double back and reset object to try again with another point @@ -438,14 +489,16 @@ public bool SpawnExperimentObjAtRandom( } } - if (!cornerCheck) { + if (!cornerCheck) + { success = false; continue; } } // if all corners were succesful, break out of this loop, don't keep trying - if (success) { + if (success) + { rb.isKinematic = false; // run scene setup to grab reference to object and give it objectId sceneManager.SetupScene(); @@ -456,7 +509,8 @@ public bool SpawnExperimentObjAtRandom( // no objects could be spawned at any of the spawn points // destroy the thing we tried to place on target receptacle - if (!success) { + if (!success) + { Destroy(spawned.transform.gameObject); } @@ -465,7 +519,8 @@ public bool SpawnExperimentObjAtRandom( // helper function to return world coordinates of all 8 corners of a // sim object's bounding box - private List GetCorners(SimObjPhysics sop) { + private List GetCorners(SimObjPhysics sop) + { // get corners of the bounding box of the object spawned in GameObject bb = sop.BoundingBox.transform.gameObject; BoxCollider bbcol = bb.GetComponent(); @@ -526,8 +581,10 @@ private List GetCorners(SimObjPhysics sop) { } #if UNITY_EDITOR - void OnDrawGizmos() { - foreach (Vector3 v in debugCoords) { + void OnDrawGizmos() + { + foreach (Vector3 v in debugCoords) + { Gizmos.color = Color.red; Gizmos.DrawSphere(v, 0.05f); } diff --git a/unity/Assets/Scripts/Extensions.cs b/unity/Assets/Scripts/Extensions.cs index 5049372db3..a2a57b014a 100644 --- a/unity/Assets/Scripts/Extensions.cs +++ b/unity/Assets/Scripts/Extensions.cs @@ -10,10 +10,13 @@ using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; -public static class ExtensionMethods { - public static T DeepClone(this T obj) { +public static class ExtensionMethods +{ + public static T DeepClone(this T obj) + { // Don't serialize a null object, simply return the default for that object - if (ReferenceEquals(obj, null)) { + if (ReferenceEquals(obj, null)) + { return default; } @@ -21,7 +24,8 @@ public static T DeepClone(this T obj) { // 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 { + var deserializeSettings = new JsonSerializerSettings + { ObjectCreationHandling = ObjectCreationHandling.Replace }; @@ -29,7 +33,8 @@ public static T DeepClone(this T obj) { var str = Newtonsoft.Json.JsonConvert.SerializeObject( obj, Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { + new Newtonsoft.Json.JsonSerializerSettings() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver } @@ -44,17 +49,22 @@ 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)) { + if (dictionary.ContainsKey(key)) + { dictionary[key] = dictionary[key] + count; - } else { + } + else + { dictionary[key] = count; } return dictionary[key]; @@ -62,7 +72,8 @@ public static int AddCount(this Dictionary dictionary, TKey key public static IEnumerable> CartesianProduct( this IEnumerable> sequences - ) { + ) + { IEnumerable> emptyProduct = new[] { Enumerable.Empty() }; return sequences.Aggregate( emptyProduct, diff --git a/unity/Assets/Scripts/FifoServer.cs b/unity/Assets/Scripts/FifoServer.cs index 86dd645258..fdeb044f74 100644 --- a/unity/Assets/Scripts/FifoServer.cs +++ b/unity/Assets/Scripts/FifoServer.cs @@ -5,8 +5,10 @@ using System.Net; using System.Text; -namespace FifoServer { - public class Client { +namespace FifoServer +{ + public class Client + { private static Client singletonClient; private int headerLength = 5; private FileStream serverPipe; @@ -31,18 +33,22 @@ public class Client { { "image_thirdParty_flow", FieldType.ThirdPartyFlow } }; - public static 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); } - public static 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) { + public string ReceiveMessage() + { + if (clientPipe == null) + { this.clientPipe = new FileStream( this.clientPipePath, FileMode.Open, @@ -50,26 +56,31 @@ public string ReceiveMessage() { ); } string action = null; - while (true) { + while (true) + { byte[] header = new byte[headerLength]; int bytesRead = clientPipe.Read(header, 0, header.Length); - if (bytesRead == 0) { + if (bytesRead == 0) + { throw new EndOfStreamException( "zero bytes read trying to read header; assuming disconnect" ); } FieldType fieldType = (FieldType)header[0]; - if (fieldType == FieldType.EndOfMessage) { + if (fieldType == FieldType.EndOfMessage) + { // Console.WriteLine("Got eom"); break; } int fieldLength = UnpackNetworkBytes(header, 1); byte[] body = new byte[fieldLength]; int totalBytesRead = 0; - while (totalBytesRead < body.Length) { + while (totalBytesRead < body.Length) + { bytesRead = clientPipe.Read(body, totalBytesRead, body.Length - totalBytesRead); // didn't read anything new, assume that we have a disconnect - if (bytesRead == 0) { + if (bytesRead == 0) + { throw new EndOfStreamException( "number of bytes read did not change during body read; assuming disconnect" ); @@ -77,7 +88,8 @@ public string ReceiveMessage() { totalBytesRead += bytesRead; } - switch (fieldType) { + switch (fieldType) + { case FieldType.Action: // Console.WriteLine("Got action"); action = Encoding.Default.GetString(body); @@ -89,13 +101,16 @@ public string ReceiveMessage() { return action; } - public void SendEOM() { + public void SendEOM() + { serverPipe.Write(this.eomHeader, 0, this.headerLength); serverPipe.Flush(); } - public void SendMessage(FieldType t, byte[] body) { - if (this.serverPipe == null) { + public void SendMessage(FieldType t, byte[] body) + { + if (this.serverPipe == null) + { this.serverPipe = new FileStream( this.serverPipePath, FileMode.Open, @@ -110,22 +125,26 @@ public void SendMessage(FieldType t, byte[] body) { serverPipe.Write(body, 0, body.Length); } - private Client(string serverPipePath, string clientPipePath) { + private Client(string serverPipePath, string clientPipePath) + { this.serverPipePath = serverPipePath; this.clientPipePath = clientPipePath; this.eomHeader = new byte[headerLength]; this.eomHeader[0] = (byte)FieldType.EndOfMessage; } - public static Client GetInstance(string serverPipePath, string clientPipePath) { - if (singletonClient == null) { + public static Client GetInstance(string serverPipePath, string clientPipePath) + { + if (singletonClient == null) + { singletonClient = new Client(serverPipePath, clientPipePath); } return singletonClient; } } - public enum FieldType : byte { + public enum FieldType : byte + { Metadata = 0x01, Action = 0x02, ActionResult = 0x03, diff --git a/unity/Assets/Scripts/Fill.cs b/unity/Assets/Scripts/Fill.cs index 4121486184..c979d1e277 100644 --- a/unity/Assets/Scripts/Fill.cs +++ b/unity/Assets/Scripts/Fill.cs @@ -4,7 +4,8 @@ using UnityEngine; using Random = UnityEngine.Random; -public class Fill : MonoBehaviour { +public class Fill : MonoBehaviour +{ [SerializeField] protected GameObject WaterObject = null; @@ -21,21 +22,25 @@ public class Fill : MonoBehaviour { public Dictionary Liquids = new Dictionary(); - public bool IsFilled() { + public bool IsFilled() + { return isFilled; } - public string FilledLiquid() { + public string FilledLiquid() + { return currentlyFilledWith; } - void Awake() { + void Awake() + { #if UNITY_EDITOR if ( !gameObject .GetComponent() .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeFilled) - ) { + ) + { Debug.LogError(gameObject.name + " is missing the CanBeFilled secondary property!"); } #endif @@ -46,20 +51,25 @@ void Awake() { } // Update is called once per frame - void Update() { + void Update() + { // check if the object is rotated too much, if so it should spill out - if (Vector3.Angle(gameObject.transform.up, Vector3.up) > 90) { + if (Vector3.Angle(gameObject.transform.up, Vector3.up) > 90) + { // print("spilling!"); - if (isFilled) { + if (isFilled) + { EmptyObject(); } } } // fill the object with a random liquid - public void FillObjectRandomLiquid() { + public void FillObjectRandomLiquid() + { int whichone = Random.Range(1, 3); - switch (whichone) { + switch (whichone) + { case 1: FillObject("water"); break; @@ -72,25 +82,30 @@ public void FillObjectRandomLiquid() { } } - public void FillObject(string whichLiquid) { - if (!Liquids.ContainsKey(whichLiquid)) { + public void FillObject(string whichLiquid) + { + if (!Liquids.ContainsKey(whichLiquid)) + { throw new ArgumentException("Unknown liquid: " + 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) { + if (Liquids[whichLiquid] == null) + { throw new ArgumentException($"The liquid {whichLiquid} is not setup for this object."); } Liquids[whichLiquid].transform.gameObject.SetActive(true); // coffee is hot so change the object's temperature if whichLiquid was coffee - if (whichLiquid == "coffee") { + if (whichLiquid == "coffee") + { // coffee is hot! SimObjPhysics sop = gameObject.GetComponent(); sop.CurrentTemperature = Temperature.Hot; - if (sop.HowManySecondsUntilRoomTemp != sop.GetTimerResetValue()) { + if (sop.HowManySecondsUntilRoomTemp != sop.GetTimerResetValue()) + { sop.HowManySecondsUntilRoomTemp = sop.GetTimerResetValue(); } sop.SetStartRoomTempTimer(false); @@ -100,11 +115,14 @@ public void FillObject(string whichLiquid) { currentlyFilledWith = whichLiquid; } - public void EmptyObject() { + 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) { + foreach (KeyValuePair gogogo in Liquids) + { // if the value field is not null and has a reference to a liquid object - if (gogogo.Value != null) { + if (gogogo.Value != null) + { gogogo.Value.SetActive(false); } } @@ -112,9 +130,11 @@ public void EmptyObject() { isFilled = false; } - public void OnTriggerStay(Collider other) { + public void OnTriggerStay(Collider other) + { // if touching running water, automatically fill with water. - if (!isFilled && other.CompareTag("Liquid")) { + if (!isFilled && other.CompareTag("Liquid")) + { FillObject("water"); } } diff --git a/unity/Assets/Scripts/FirstPersonCharacterCull.cs b/unity/Assets/Scripts/FirstPersonCharacterCull.cs index ce83224dd9..1d52df674e 100644 --- a/unity/Assets/Scripts/FirstPersonCharacterCull.cs +++ b/unity/Assets/Scripts/FirstPersonCharacterCull.cs @@ -4,10 +4,12 @@ using UnityStandardAssets.Characters.FirstPerson; [ExecuteInEditMode] -public class FirstPersonCharacterCull : MonoBehaviour { +public class FirstPersonCharacterCull : MonoBehaviour +{ private bool _stopCullingThingsForASecond = false; - public bool StopCullingThingsForASecond { + public bool StopCullingThingsForASecond + { get { return this._stopCullingThingsForASecond; } set { this._stopCullingThingsForASecond = value; } } @@ -15,10 +17,13 @@ public bool StopCullingThingsForASecond { public MeshRenderer[] RenderersToHide; // Mesh renderer that you want this script's camera to cull public BaseAgentComponent FPSController; - public void SwitchRenderersToHide(GameObject visibilityCapsule) { + public void SwitchRenderersToHide(GameObject visibilityCapsule) + { List renderers = new List(); - foreach (var r in visibilityCapsule.GetComponentsInChildren()) { - if (r.shadowCastingMode == ShadowCastingMode.Off) { + foreach (var r in visibilityCapsule.GetComponentsInChildren()) + { + if (r.shadowCastingMode == ShadowCastingMode.Off) + { renderers.Add(r); } } @@ -28,14 +33,17 @@ public void SwitchRenderersToHide(GameObject visibilityCapsule) { void OnPreRender() // Just before this camera starts to render... { - if (!StopCullingThingsForASecond) { + if (!StopCullingThingsForASecond) + { if ( FPSController != null && FPSController.agent != null && (RenderersToHide != null || RenderersToHide.Length != 0) && FPSController.agent.IsVisible - ) { // only do this if visibility capsule has been toggled on - foreach (MeshRenderer mr in RenderersToHide) { + ) + { // only do this if visibility capsule has been toggled on + foreach (MeshRenderer mr in RenderersToHide) + { mr.enabled = false; // Turn off renderer } } @@ -44,14 +52,17 @@ void OnPreRender() // Just before this camera starts to render... void OnPostRender() // Immediately after this camera renders... { - if (!StopCullingThingsForASecond) { + if (!StopCullingThingsForASecond) + { if ( FPSController != null && FPSController.agent != null && (RenderersToHide != null || RenderersToHide.Length != 0) && FPSController.agent.IsVisible - ) { // only do this if visibility capsule is toggled on - foreach (MeshRenderer mr in RenderersToHide) { + ) + { // only do this if visibility capsule is toggled on + foreach (MeshRenderer mr in RenderersToHide) + { mr.enabled = true; // Turn it back on } } diff --git a/unity/Assets/Scripts/Flame.cs b/unity/Assets/Scripts/Flame.cs index 28abb12afd..7f41037216 100644 --- a/unity/Assets/Scripts/Flame.cs +++ b/unity/Assets/Scripts/Flame.cs @@ -8,7 +8,8 @@ // this means fire sources (the candle flame particle itself, stove top fire etc) must have a trigger box on it tagged fire so that this component can take care of itself. // for the cancle specifically, this box will control whether or not to turn the flame particle on or off, the flame particle itself has a triggerbox called tagged "flame" on it, so it can independantly be used to light another candle on fire -public class Flame : MonoBehaviour { +public class Flame : MonoBehaviour +{ // my parent object to find the CanToggleOnOff component public GameObject MyObject; @@ -19,16 +20,21 @@ void Start() { } void Update() { } // if this touches water and it's on, it is put out. Fire safety is important! - public void OnTriggerStay(Collider MagiciansRed) { + public void OnTriggerStay(Collider MagiciansRed) + { // check if the fire zone is touching Liquid(running water effects) or StandingLiquid(filled water effects) - if (MagiciansRed.CompareTag("Liquid") || MagiciansRed.CompareTag("StandingLiquid")) { - if (MyObject.GetComponent().isOn) { + if (MagiciansRed.CompareTag("Liquid") || MagiciansRed.CompareTag("StandingLiquid")) + { + if (MyObject.GetComponent().isOn) + { MyObject.GetComponent().Toggle(); } } - if (MagiciansRed.CompareTag("Fire")) { - if (!MyObject.GetComponent().isOn) { + if (MagiciansRed.CompareTag("Fire")) + { + if (!MyObject.GetComponent().isOn) + { MyObject.GetComponent().Toggle(); } } diff --git a/unity/Assets/Scripts/FpinAgentController.cs b/unity/Assets/Scripts/FpinAgentController.cs index 9571325c7e..f35e3696f7 100644 --- a/unity/Assets/Scripts/FpinAgentController.cs +++ b/unity/Assets/Scripts/FpinAgentController.cs @@ -11,8 +11,10 @@ using UnityEngine.Rendering.PostProcessing; using UnityEngine.UIElements; -namespace UnityStandardAssets.Characters.FirstPerson { - public class BoxBounds { +namespace UnityStandardAssets.Characters.FirstPerson +{ + public class BoxBounds + { public Vector3 worldCenter; public Vector3 agentRelativeCenter; public Vector3 size; @@ -20,7 +22,8 @@ public class BoxBounds { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class LoadInUnityProceduralAsset { + public class LoadInUnityProceduralAsset + { public string id; public string dir; public string extension = ".msgpack.gz"; @@ -30,7 +33,8 @@ public class LoadInUnityProceduralAsset { #nullable enable [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class BodyAsset { + public class BodyAsset + { public string? assetId = null; public LoadInUnityProceduralAsset? dynamicAsset = null; public ProceduralAsset? asset = null; @@ -40,7 +44,8 @@ public class BodyAsset { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class BackwardsCompatibleInitializeParams { + public class BackwardsCompatibleInitializeParams + { // Make what parameters it uses explicit public float maxUpwardLookAngle = 0.0f; public float maxDownwardLookAngle = 0.0f; @@ -64,7 +69,8 @@ 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; @@ -73,9 +79,12 @@ public class FpinAgentController : PhysicsRemoteFPSAgentController { private Transform topMeshTransform = null; private Bounds? agentBounds = null; public BoxBounds boxBounds = null; - public BoxBounds BoxBounds { - get { - if (spawnedBoxCollider != null) { + public BoxBounds BoxBounds + { + get + { + if (spawnedBoxCollider != null) + { BoxBounds currentBounds = new BoxBounds(); currentBounds.worldCenter = spawnedBoxCollider.transform.TransformPoint( @@ -91,7 +100,9 @@ public BoxBounds BoxBounds { // 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; } @@ -106,7 +117,8 @@ public BoxBounds BoxBounds { public FpinAgentController(BaseAgentComponent baseAgentComponent, AgentManager agentManager) : base(baseAgentComponent, agentManager) { } - public void Start() { + public void Start() + { //put stuff we need here when we need it maybe } @@ -117,7 +129,8 @@ public override RaycastHit[] CastBodyTrayectory( float moveMagnitude, int layerMask, CapsuleData cachedCapsule - ) { + ) + { Vector3 startPositionBoxCenter = startPosition + this.transform.TransformDirection(this.boxBounds.agentRelativeCenter); @@ -135,14 +148,16 @@ CapsuleData cachedCapsule //since the size returned by the box collider only reflects its size in local space DISREGARDING ANY TRANSFORM SCALES //IN ITS PARENTS OR ITSELF here we go - public Vector3 GetTrueSizeOfBoxCollider(BoxCollider collider) { + public Vector3 GetTrueSizeOfBoxCollider(BoxCollider collider) + { Vector3 trueSize = collider.size; // get the transform of the collider itself 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; @@ -155,24 +170,29 @@ public Vector3 GetTrueSizeOfBoxCollider(BoxCollider collider) { } //override so we can access to fpin specific stuff - public override MetadataWrapper generateMetadataWrapper() { + 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) { + if (boxBounds != null) + { //get from BoxBounds as box world center will update as agent moves so we can't cache it metaWrap.agent.fpinColliderSize = BoxBounds.size; metaWrap.agent.fpinColliderWorldCenter = BoxBounds.worldCenter; metaWrap.agent.fpinColliderAgentRelativeCenter = BoxBounds.agentRelativeCenter; - } else { + } + else + { metaWrap.agent.fpinColliderSize = new Vector3(0, 0, 0); } 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; @@ -183,8 +203,10 @@ public List SamplePointsOnNavMesh(int sampleCount, float maxDistance) { 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++) { + 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), @@ -197,14 +219,17 @@ public List SamplePointsOnNavMesh(int sampleCount, float maxDistance) { initPoints.Shuffle_(); List pointsOnMesh = new List(); - for (int i = 0; i < initPoints.Count; i++) { - if (pointsOnMesh.Count >= sampleCount) { + for (int i = 0; i < initPoints.Count; i++) + { + if (pointsOnMesh.Count >= sampleCount) + { break; } NavMeshHit hit; Vector3 randomPoint = initPoints[i]; - if (NavMesh.SamplePosition(randomPoint, out hit, maxDistance, NavMesh.AllAreas)) { + if (NavMesh.SamplePosition(randomPoint, out hit, maxDistance, NavMesh.AllAreas)) + { # if UNITY_EDITOR Debug.DrawLine( hit.position, @@ -222,14 +247,17 @@ public List SamplePointsOnNavMesh(int sampleCount, float maxDistance) { return pointsOnMesh; } - public void RandomlyPlaceAgentOnNavMesh(int n = 200, float maxDistance = 0.1f) { + public void RandomlyPlaceAgentOnNavMesh(int n = 200, float maxDistance = 0.1f) + { List pointsOnMesh = SamplePointsOnNavMesh(n, maxDistance: maxDistance); - if (pointsOnMesh.Count == 0) { + if (pointsOnMesh.Count == 0) + { throw new InvalidOperationException("No points on the navmesh"); } Bounds b = UtilityFunctions.CreateEmptyBounds(); - foreach (Collider c in GetComponentsInChildren()) { + foreach (Collider c in GetComponentsInChildren()) + { b.Encapsulate(c.bounds); } @@ -238,8 +266,10 @@ public void RandomlyPlaceAgentOnNavMesh(int n = 200, float maxDistance = 0.1f) { //Debug.Log($"yOffset is: {yOffset}"); bool success = false; - foreach (Vector3 point in pointsOnMesh) { - try { + foreach (Vector3 point in pointsOnMesh) + { + try + { //Debug.Log($"what is the point we are trying from the pointsOnMesh? {point:F8}"); teleportFull( position: point + new Vector3(0, yOffset, 0), @@ -249,7 +279,9 @@ public void RandomlyPlaceAgentOnNavMesh(int n = 200, float maxDistance = 0.1f) { ); success = true; break; - } catch (InvalidOperationException) { + } + catch (InvalidOperationException) + { continue; } } @@ -264,7 +296,8 @@ public void spawnAgentBoxCollider( 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"); @@ -299,22 +332,27 @@ public void spawnAgentBoxCollider( //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) { + if (spawnedBoxCollider != null) + { UnityEngine.Object.DestroyImmediate(spawnedBoxCollider.transform.gameObject); spawnedBoxCollider = null; } - if (spawnedTriggerBoxCollider != null) { + if (spawnedTriggerBoxCollider != null) + { UnityEngine.Object.DestroyImmediate(spawnedTriggerBoxCollider.transform.gameObject); spawnedTriggerBoxCollider = null; } - if (visibleBox != null) { + if (visibleBox != null) + { UnityEngine.Object.DestroyImmediate(visibleBox); } #if UNITY_EDITOR GameObject visualizedBoxCollider = GameObject.Find("VisualizedBoxCollider"); - if (visualizedBoxCollider != null) { + if (visualizedBoxCollider != null) + { UnityEngine.Object.DestroyImmediate(visualizedBoxCollider); } #endif @@ -330,30 +368,36 @@ private Transform CopyMeshChildrenRecursive( Transform sourceTransform, Transform targetTransform, bool isTopMost = true - ) { + ) + { Transform thisTransform = null; - foreach (Transform child in sourceTransform) { + foreach (Transform child in sourceTransform) + { GameObject copiedChild = null; // Check if the child has a MeshFilter component MeshFilter meshFilter = child.GetComponent(); - if (meshFilter != null) { + if (meshFilter != null) + { copiedChild = CopyMeshToTarget(child, targetTransform); } // Process children only if necessary (i.e., they contain MeshFilters) - if (HasMeshInChildrenOrSelf(child)) { + if (HasMeshInChildrenOrSelf(child)) + { Transform parentForChildren = (copiedChild != null) ? copiedChild.transform : CreateContainerForHierarchy(child, targetTransform).transform; CopyMeshChildrenRecursive(child, parentForChildren, false); - if (isTopMost) { + if (isTopMost) + { thisTransform = parentForChildren; } } } - if (isTopMost) { + if (isTopMost) + { // Set up intermediate object for scaling the mesh in agent-space (since the top-level mesh could be rotated, potentially introducing a complex matrix of scales) GameObject agentScaleObject = new GameObject("AgentScaleObject"); agentScaleObject.transform.position = thisTransform.position; @@ -365,7 +409,8 @@ private Transform CopyMeshChildrenRecursive( return null; } - private GameObject CopyMeshToTarget(Transform child, Transform targetParent) { + private GameObject CopyMeshToTarget(Transform child, Transform targetParent) + { // Create a new GameObject and copy components GameObject copiedChild = new GameObject(child.name); copiedChild.transform.SetParent(targetParent); @@ -375,7 +420,8 @@ private GameObject CopyMeshToTarget(Transform child, Transform targetParent) { copiedMeshFilter.mesh = meshFilter.mesh; MeshRenderer sourceMeshRenderer = child.GetComponent(); - if (sourceMeshRenderer != null) { + if (sourceMeshRenderer != null) + { MeshRenderer copiedMeshRenderer = copiedChild.AddComponent(); copiedMeshRenderer.sharedMaterials = sourceMeshRenderer.sharedMaterials; } @@ -387,21 +433,26 @@ private GameObject CopyMeshToTarget(Transform child, Transform targetParent) { return copiedChild; } - private bool HasMeshInChildrenOrSelf(Transform transform) { - foreach (Transform child in transform) { - if (child.GetComponent() != null || HasMeshInChildrenOrSelf(child)) { + private bool HasMeshInChildrenOrSelf(Transform transform) + { + foreach (Transform child in transform) + { + if (child.GetComponent() != null || HasMeshInChildrenOrSelf(child)) + { return true; } } - if (transform.GetComponent() != null) { + if (transform.GetComponent() != null) + { return true; } return false; } - private GameObject CreateContainerForHierarchy(Transform child, Transform targetParent) { + private GameObject CreateContainerForHierarchy(Transform child, Transform targetParent) + { GameObject container = new GameObject(child.name + "_Container"); container.transform.SetParent(targetParent); container.transform.localPosition = child.localPosition; @@ -413,22 +464,26 @@ private GameObject CreateContainerForHierarchy(Transform child, Transform target 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); HashSet transformedVertices = new HashSet(); - foreach (Vector3 vertex in vertices) { + foreach (Vector3 vertex in vertices) + { transformedVertices.Add(localToWorld.MultiplyPoint3x4(vertex)); } return transformedVertices; } - public ActionFinished GetBoxBounds() { + public ActionFinished GetBoxBounds() + { 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; // Rotate it @@ -440,23 +495,31 @@ public Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Vector3 angl 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 - if (Mathf.Approximately(args.maxUpwardLookAngle, 0.0f)) { + if (Mathf.Approximately(args.maxUpwardLookAngle, 0.0f)) + { this.maxUpwardLookAngle = 30f; - } else { + } + else + { this.maxUpwardLookAngle = args.maxUpwardLookAngle; } - if (Mathf.Approximately(args.maxDownwardLookAngle, 0.0f)) { + if (Mathf.Approximately(args.maxDownwardLookAngle, 0.0f)) + { this.maxDownwardLookAngle = 60f; - } else { + } + else + { this.maxDownwardLookAngle = args.maxDownwardLookAngle; } - if (args.antiAliasing != null) { + if (args.antiAliasing != null) + { agentManager.updateAntiAliasing( postProcessLayer: m_Camera.gameObject.GetComponentInChildren(), antiAliasing: args.antiAliasing @@ -464,62 +527,77 @@ BackwardsCompatibleInitializeParams args } // m_Camera.GetComponent().SwitchRenderersToHide(this.VisibilityCapsule); - if (args.gridSize == 0) { + if (args.gridSize == 0) + { args.gridSize = 0.25f; } // note: this overrides the default FOV values set in InitializeBody() - if (args.fieldOfView > 0 && args.fieldOfView < 180) { + if (args.fieldOfView > 0 && args.fieldOfView < 180) + { m_Camera.fieldOfView = args.fieldOfView; - } else if (args.fieldOfView < 0 || args.fieldOfView >= 180) { + } + else if (args.fieldOfView < 0 || args.fieldOfView >= 180) + { errorMessage = "fov must be set to (0, 180) noninclusive."; Debug.Log(errorMessage); return new ActionFinished(success: false, errorMessage: errorMessage); } - if (args.cameraNearPlane > 0) { + if (args.cameraNearPlane > 0) + { m_Camera.nearClipPlane = args.cameraNearPlane; } - if (args.cameraFarPlane > 0) { + if (args.cameraFarPlane > 0) + { m_Camera.farClipPlane = args.cameraFarPlane; } - if (args.timeScale > 0) { - if (Time.timeScale != args.timeScale) { + if (args.timeScale > 0) + { + if (Time.timeScale != args.timeScale) + { Time.timeScale = args.timeScale; } - } else { + } + else + { errorMessage = "Time scale must be > 0"; Debug.Log(errorMessage); return new ActionFinished(success: false, errorMessage: errorMessage); } - if (args.rotateStepDegrees <= 0.0) { + if (args.rotateStepDegrees <= 0.0) + { errorMessage = "rotateStepDegrees must be a non-zero, non-negative float"; Debug.Log(errorMessage); return new ActionFinished(success: false, errorMessage: errorMessage); } // default is 90 defined in the ServerAction class, specify whatever you want the default to be - if (args.rotateStepDegrees > 0.0) { + if (args.rotateStepDegrees > 0.0) + { this.rotateStepDegrees = args.rotateStepDegrees; } - if (args.snapToGrid && !ValidRotateStepDegreesWithSnapToGrid(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."; 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); @@ -532,18 +610,21 @@ BackwardsCompatibleInitializeParams args || args.renderSemanticSegmentation || args.renderInstanceSegmentation || args.renderNormalsImage - ) { + ) + { this.updateImageSynthesis(true); } - if (args.visibilityDistance > 0.0f) { + if (args.visibilityDistance > 0.0f) + { this.maxVisibleDistance = args.visibilityDistance; } var navmeshAgent = this.GetComponentInChildren(); var collider = this.GetComponent(); - if (collider != null && navmeshAgent != null) { + if (collider != null && navmeshAgent != null) + { navmeshAgent.radius = collider.radius; navmeshAgent.height = collider.height; navmeshAgent.transform.localPosition = new Vector3( @@ -555,11 +636,14 @@ BackwardsCompatibleInitializeParams args // navmeshAgent.radius = - if (args.gridSize <= 0 || args.gridSize > 5) { + if (args.gridSize <= 0 || args.gridSize > 5) + { errorMessage = "grid size must be in the range (0,5]"; Debug.Log(errorMessage); return new ActionFinished(success: false, errorMessage: errorMessage); - } else { + } + else + { gridSize = args.gridSize; // Don't know what this was for @@ -582,7 +666,8 @@ BackwardsCompatibleInitializeParams args return new ActionFinished( success: true, - actionReturn: new InitializeReturn { + actionReturn: new InitializeReturn + { cameraNearPlane = m_Camera.nearClipPlane, cameraFarPlane = m_Camera.farClipPlane } @@ -597,7 +682,8 @@ public ActionFinished Initialize( Vector3? colliderScaleRatio = null, bool useAbsoluteSize = false, bool useVisibleColliderBase = false - ) { + ) + { this.visibilityScheme = VisibilityScheme.Distance; var actionFinished = this.InitializeBody( bodyAsset: bodyAsset, @@ -619,14 +705,16 @@ public ActionFinished InitializeBody( Vector3? colliderScaleRatio = null, bool useAbsoluteSize = false, 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 // ratio on Vector3 meshScaleRatio = colliderScaleRatio.GetValueOrDefault(Vector3.one); bool noMesh = false; - if (bodyAsset == null) { + if (bodyAsset == null) + { useAbsoluteSize = true; noMesh = true; } @@ -641,18 +729,21 @@ public ActionFinished InitializeBody( //remove any old copied meshes or generated colliders from previous fpin agent now destroyAgentBoxCollider(); - if (fpinVisibilityCapsule != null) { + if (fpinVisibilityCapsule != null) + { UnityEngine.Object.DestroyImmediate(fpinVisibilityCapsule); } 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 - if (!spawnAssetActionFinished.success) { + if (!spawnAssetActionFinished.success) + { return spawnAssetActionFinished; } @@ -668,13 +759,18 @@ public ActionFinished InitializeBody( // so we'll take the bounds-center of the first meshRenderer MeshRenderer[] meshRenderers = topMeshTransform.gameObject.GetComponentsInChildren(); - foreach (MeshRenderer mr in meshRenderers) { + 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) { + if (mr.transform.eulerAngles.magnitude < 1e-4f) + { meshBoundsWorld.Encapsulate(mr.bounds); - } else { + } + else + { HashSet vertices = TransformedMeshRendererVertices(mr); - foreach (Vector3 vertex in vertices) { + foreach (Vector3 vertex in vertices) + { meshBoundsWorld.Encapsulate(vertex); } } @@ -685,14 +781,17 @@ public ActionFinished InitializeBody( topMeshTransform.position = meshBoundsWorld.center; topMeshTransform.GetChild(0).position = currentTopMeshTransformChildPos; - if (useAbsoluteSize) { + if (useAbsoluteSize) + { topMeshTransform.localScale = new Vector3( meshScaleRatio.x / meshBoundsWorld.size.x, meshScaleRatio.y / meshBoundsWorld.size.y, meshScaleRatio.z / meshBoundsWorld.size.z ); meshBoundsWorld.size = meshScaleRatio; - } else { + } + else + { topMeshTransform.localScale = meshScaleRatio; meshBoundsWorld.size = new Vector3( meshScaleRatio.x * meshBoundsWorld.size.x, @@ -711,14 +810,18 @@ public ActionFinished InitializeBody( this.transform.position + Vector3.up * meshBoundsWorld.extents.y; // remove the spawned mesh cause we are done with it - foreach (var sop in spawnedMesh.GetComponentsInChildren()) { + foreach (var sop in spawnedMesh.GetComponentsInChildren()) + { agentManager.physicsSceneManager.RemoveFromObjectsInScene(sop); } - if (spawnedMesh.activeInHierarchy) { + if (spawnedMesh.activeInHierarchy) + { UnityEngine.Object.DestroyImmediate(spawnedMesh); } - } else { + } + else + { meshBoundsWorld = new Bounds( this.transform.position + (Vector3.up * meshScaleRatio.y / 2), meshScaleRatio @@ -733,7 +836,8 @@ public ActionFinished InitializeBody( // set reference to the meshes so the base agent and fpin agent are happy VisibilityCapsule = fpinVisibilityCapsule = viscap; - if (topMeshTransform != null) { + if (topMeshTransform != null) + { topMeshTransform.SetParent(viscap.transform); } @@ -749,7 +853,8 @@ public ActionFinished InitializeBody( ); // spawn the visible collider base if we need to - if (useVisibleColliderBase) { + if (useVisibleColliderBase) + { GameObject visibleBase = GameObject.CreatePrimitive(PrimitiveType.Cube); visibleBase.name = "visibleBase"; visibleBase.GetComponent().enabled = false; @@ -861,7 +966,8 @@ public ActionFinished InitializeBody( originalRotation, checkBoxLayerMask ) - ) { + ) + { this.transform.position = originalPosition; this.transform.rotation = originalRotation; string error = @@ -883,8 +989,10 @@ public ActionFinished InitializeBody( fpinMovable = new FpinMovableContinuous(this.GetComponentInParent()); // we had a body asset used, so actionFinished returns info related to that - if (bodyAsset != null) { - return new ActionFinished(spawnAssetActionFinished) { + if (bodyAsset != null) + { + return new ActionFinished(spawnAssetActionFinished) + { // TODO: change to a proper class once metadata return is defined actionReturn = new Dictionary() { @@ -898,8 +1006,11 @@ spawnAssetActionFinished.actionReturn as ObjectSphereBounds { "cameraFarPlane", m_Camera.farClipPlane } } }; - } else { - return new ActionFinished() { + } + else + { + return new ActionFinished() + { // TODO: change to a proper class once metadata return is defined actionReturn = new Dictionary() { @@ -911,14 +1022,18 @@ spawnAssetActionFinished.actionReturn as ObjectSphereBounds } } - private ActionFinished spawnBodyAsset(BodyAsset bodyAsset, out GameObject spawnedMesh) { - if (bodyAsset == null) { + 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 - ) { + } + 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." ); @@ -932,7 +1047,8 @@ private ActionFinished spawnBodyAsset(BodyAsset bodyAsset, out GameObject spawne if ( (bodyAsset.dynamicAsset != null || bodyAsset.asset != null) && bodyAsset.assetId == null - ) { + ) + { var id = bodyAsset.dynamicAsset != null ? bodyAsset.dynamicAsset.id @@ -940,20 +1056,24 @@ private ActionFinished spawnBodyAsset(BodyAsset bodyAsset, out GameObject spawne var assetMap = ProceduralTools.getAssetMap(); // Check if asset is in AssetDatabase already - if (assetMap.ContainsKey(id)) { + if (assetMap.ContainsKey(id)) + { Debug.Log("------- Already contains key"); bodyAsset.assetId = id; } } - if (bodyAsset.assetId != null) { + if (bodyAsset.assetId != null) + { 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, @@ -962,7 +1082,9 @@ 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); } @@ -970,7 +1092,8 @@ private ActionFinished spawnBodyAsset(BodyAsset bodyAsset, out GameObject spawne if ( bodyAsset.assetId == null && (bodyAsset.dynamicAsset != null || bodyAsset.asset != null) - ) { + ) + { var id = bodyAsset.dynamicAsset != null ? bodyAsset.dynamicAsset.id @@ -978,7 +1101,8 @@ private ActionFinished spawnBodyAsset(BodyAsset bodyAsset, out GameObject spawne Debug.Log( $"-- checks {bodyAsset.assetId == null} {bodyAsset.dynamicAsset != null} {bodyAsset.asset != null} " ); - if (!actionFinished.success || actionFinished.actionReturn == null) { + if (!actionFinished.success || actionFinished.actionReturn == null) + { return new ActionFinished( success: false, errorMessage: $"Could not create asset `{bodyAsset.dynamicAsset}` error: {actionFinished.errorMessage}" @@ -991,7 +1115,8 @@ private ActionFinished spawnBodyAsset(BodyAsset bodyAsset, out GameObject spawne return actionFinished; } - protected override LayerMask GetVisibilityRaycastLayerMask(bool withSimObjInvisible = false) { + protected override LayerMask GetVisibilityRaycastLayerMask(bool withSimObjInvisible = false) + { // No agent because camera can be in the path of colliders string[] layers = new string[] { @@ -1001,7 +1126,8 @@ protected override LayerMask GetVisibilityRaycastLayerMask(bool withSimObjInvisi "Procedural3", "Procedural0" //, "Agent" }; - if (withSimObjInvisible) { + if (withSimObjInvisible) + { layers = layers.Append("SimObjInvisible").ToArray(); } return LayerMask.GetMask(layers); @@ -1014,7 +1140,8 @@ public override void TeleportFull( float? horizon = null, bool? standing = null, bool forceAction = false - ) { + ) + { teleportFull( position: position, rotation: rotation, @@ -1028,7 +1155,8 @@ protected override void teleportFull( Vector3? rotation, float? horizon, bool forceAction - ) { + ) + { //Debug.Log($"what even is the position passed in at the start? {position:F8}"); if ( rotation.HasValue @@ -1036,7 +1164,8 @@ bool forceAction !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")}." @@ -1048,7 +1177,8 @@ bool forceAction !forceAction && horizon.HasValue && (horizon.Value > maxDownwardLookAngle || horizon.Value < -maxUpwardLookAngle) - ) { + ) + { throw new ArgumentOutOfRangeException( $"Each horizon must be in [{-maxUpwardLookAngle}:{maxDownwardLookAngle}]. You gave {horizon}." ); @@ -1058,13 +1188,15 @@ bool forceAction !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." ); } - if (!forceAction && position.HasValue && !isPositionOnGrid(position.Value)) { + if (!forceAction && position.HasValue && !isPositionOnGrid(position.Value)) + { throw new ArgumentOutOfRangeException( $"Teleport position {position.Value.ToString("F6")} is not on the grid of size {gridSize}." ); @@ -1093,13 +1225,15 @@ bool forceAction targetPosition: position.GetValueOrDefault(transform.position) ); - if (!forceAction) { + if (!forceAction) + { if ( isAgentCapsuleColliding( collidersToIgnore: collidersToIgnoreDuringMovement, includeErrorMessage: true ) - ) { + ) + { transform.position = oldPosition; transform.rotation = oldRotation; autoSyncTransforms(); @@ -1113,7 +1247,8 @@ bool forceAction collidersToIgnore: collidersToIgnoreDuringMovement, includeErrorMessage: true ) - ) { + ) + { transform.position = oldPosition; transform.rotation = oldRotation; autoSyncTransforms(); @@ -1125,9 +1260,11 @@ bool forceAction actionFinished(success: true); } - protected override void assertTeleportedNearGround(Vector3? targetPosition) { + protected override void assertTeleportedNearGround(Vector3? targetPosition) + { // position should not change if it's null. - if (targetPosition == null) { + if (targetPosition == null) + { return; } @@ -1142,7 +1279,8 @@ protected override void assertTeleportedNearGround(Vector3? targetPosition) { 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) { + 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." @@ -1156,8 +1294,10 @@ public IEnumerator MoveAgent( float ahead = 0, float right = 0, float speed = 1 - ) { - if (ahead == 0 && right == 0) { + ) + { + if (ahead == 0 && right == 0) + { throw new ArgumentException("Must specify ahead or right!"); } Vector3 direction = new Vector3(x: right, y: 0, z: ahead); @@ -1185,7 +1325,8 @@ public IEnumerator MoveAhead( float? moveMagnitude = null, float speed = 1, bool returnToStart = true - ) { + ) + { return MoveAgent( ahead: moveMagnitude.GetValueOrDefault(gridSize), speed: speed, @@ -1197,7 +1338,8 @@ public IEnumerator MoveBack( float? moveMagnitude = null, float speed = 1, bool returnToStart = true - ) { + ) + { return MoveAgent( ahead: -moveMagnitude.GetValueOrDefault(gridSize), speed: speed, @@ -1209,7 +1351,8 @@ public IEnumerator MoveRight( float? moveMagnitude = null, float speed = 1, bool returnToStart = true - ) { + ) + { return MoveAgent( right: moveMagnitude.GetValueOrDefault(gridSize), speed: speed, @@ -1221,7 +1364,8 @@ public IEnumerator MoveLeft( float? moveMagnitude = null, float speed = 1, bool returnToStart = true - ) { + ) + { return MoveAgent( right: -moveMagnitude.GetValueOrDefault(gridSize), speed: speed, @@ -1233,7 +1377,8 @@ public IEnumerator RotateRight( float? degrees = null, float speed = 1.0f, bool returnToStart = true - ) { + ) + { return RotateAgent( degrees: degrees.GetValueOrDefault(rotateStepDegrees), speed: speed, @@ -1245,7 +1390,8 @@ public IEnumerator RotateLeft( float? degrees = null, float speed = 1.0f, bool returnToStart = true - ) { + ) + { return RotateAgent( degrees: -degrees.GetValueOrDefault(rotateStepDegrees), speed: speed, @@ -1257,7 +1403,8 @@ public virtual IEnumerator RotateAgent( float degrees, float speed = 1.0f, bool returnToStart = true - ) { + ) + { CollisionListener collisionListener = fpinMovable.collisionListener; collisionListener.Reset(); diff --git a/unity/Assets/Scripts/FpinMovableContinuous.cs b/unity/Assets/Scripts/FpinMovableContinuous.cs index fabefa08fb..b1d5277f2a 100644 --- a/unity/Assets/Scripts/FpinMovableContinuous.cs +++ b/unity/Assets/Scripts/FpinMovableContinuous.cs @@ -3,28 +3,34 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public class FpinMovableContinuous : MovableContinuous { +public class FpinMovableContinuous : MovableContinuous +{ public CollisionListener collisionListener { get; private set; } - public FpinMovableContinuous(CollisionListener collisionListener) { + public FpinMovableContinuous(CollisionListener collisionListener) + { this.collisionListener = collisionListener; } - public string GetHaltMessage() { + public string GetHaltMessage() + { var staticCollisions = collisionListener?.StaticCollisions().ToList(); - if (staticCollisions.Count > 0) { + if (staticCollisions.Count > 0) + { var sc = staticCollisions[0]; // if we hit a sim object - if (sc.isSimObj) { + if (sc.isSimObj) + { return "Collided with static/kinematic sim object: '" + sc.simObjPhysics.name + "', could not reach target."; } // if we hit a structural object that isn't a sim object but still has static collision - if (!sc.isSimObj) { + if (!sc.isSimObj) + { return "Collided with static structure in scene: '" + sc.gameObject.name + "', could not reach target."; @@ -33,15 +39,18 @@ public string GetHaltMessage() { return ""; } - public virtual bool ShouldHalt() { + public virtual bool ShouldHalt() + { return collisionListener.ShouldHalt(); } - public virtual void ContinuousUpdate(float fixedDeltaTime) { + public virtual void ContinuousUpdate(float fixedDeltaTime) + { // Here would go the arm manipulation } - public virtual ActionFinished FinishContinuousMove(BaseFPSAgentController controller) { + public virtual ActionFinished FinishContinuousMove(BaseFPSAgentController controller) + { bool actionSuccess = !this.ShouldHalt(); string errorMessage = this.GetHaltMessage(); diff --git a/unity/Assets/Scripts/FrameCollider.cs b/unity/Assets/Scripts/FrameCollider.cs index b8287ff850..510f19e00f 100644 --- a/unity/Assets/Scripts/FrameCollider.cs +++ b/unity/Assets/Scripts/FrameCollider.cs @@ -11,16 +11,19 @@ // 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 // frame the interior of the cabinet and since they are indivdual and isolated can be moved around to suite any shape or form interior space -public class FrameCollider : MonoBehaviour { +public class FrameCollider : MonoBehaviour +{ public Transform myObject; // Use this for initialization - void Start() { + void Start() + { myObject = gameObject.GetComponentInParent().transform; } // Update is called once per frame - void Update() { + 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 // compound box collider would not propogate up to the rigidbody for visibility detection, so here we are this seems to work! diff --git a/unity/Assets/Scripts/FreezeObject.cs b/unity/Assets/Scripts/FreezeObject.cs index 7cfe23f2d5..79e51c078d 100644 --- a/unity/Assets/Scripts/FreezeObject.cs +++ b/unity/Assets/Scripts/FreezeObject.cs @@ -2,7 +2,8 @@ using UnityEngine; [ExecuteInEditMode] -public class FreezeObject : MonoBehaviour { +public class FreezeObject : MonoBehaviour +{ public Space space = Space.World; public bool FreezePosition = false; public bool FreezeRotation = false; @@ -13,40 +14,54 @@ public class FreezeObject : MonoBehaviour { private Vector3 m_Position = Vector3.zero; private Quaternion m_Rotation = Quaternion.identity; - void Awake() { - if (Application.isPlaying) { + void Awake() + { + if (Application.isPlaying) + { Destroy(this); } } - void Update() { - if (!Application.isEditor) { + void Update() + { + if (!Application.isEditor) + { Destroy(this); return; } - if (FreezePosition) { + if (FreezePosition) + { // Save current position if enabled - if ((FreezePosition != m_OldFreezePosition) || (space != m_OldSpace)) { + if ((FreezePosition != m_OldFreezePosition) || (space != m_OldSpace)) + { m_Position = (space == Space.World) ? transform.position : transform.localPosition; } // Freeze the position - if (space == Space.World) { + if (space == Space.World) + { transform.position = m_Position; - } else { + } + else + { transform.localPosition = m_Position; } } - if (FreezeRotation) { + if (FreezeRotation) + { // Save current rotation if enabled - if ((FreezeRotation != m_OldFreezeRotation) || (space != m_OldSpace)) { + if ((FreezeRotation != m_OldFreezeRotation) || (space != m_OldSpace)) + { m_Rotation = (space == Space.World) ? transform.rotation : transform.localRotation; } // Freeze the rotation - if (space == Space.World) { + if (space == Space.World) + { transform.rotation = m_Rotation; - } else { + } + else + { transform.localRotation = m_Rotation; } } diff --git a/unity/Assets/Scripts/Fridge.cs b/unity/Assets/Scripts/Fridge.cs index 36893251aa..5fb5412c23 100644 --- a/unity/Assets/Scripts/Fridge.cs +++ b/unity/Assets/Scripts/Fridge.cs @@ -2,7 +2,8 @@ using System.Collections; using UnityEngine; -public class Fridge : MonoBehaviour { +public class Fridge : MonoBehaviour +{ public SimObj ParentObj; public Transform[] Doors; @@ -16,32 +17,39 @@ public class Fridge : MonoBehaviour { Vector3 drawerTargetPosition; float distanceToTarget; - void Awake() { + void Awake() + { ParentObj = gameObject.GetComponent(); } - void Update() { + void Update() + { bool open = false; - if (!ParentObj.IsAnimated) { + if (!ParentObj.IsAnimated) + { return; } open = ParentObj.Animator.GetBool("AnimState1"); - switch (SceneManager.Current.AnimationMode) { + switch (SceneManager.Current.AnimationMode) + { case SceneAnimationMode.Instant: default: - for (int i = 0; i < Doors.Length; i++) { + for (int i = 0; i < Doors.Length; i++) + { Doors[i].localEulerAngles = open ? OpenRotations[i] : ClosedRotations[i]; } - for (int i = 0; i < Drawers.Length; i++) { + for (int i = 0; i < Drawers.Length; i++) + { Drawers[i].localPosition = open ? OpenPositions[i] : ClosedPositions[i]; } break; case SceneAnimationMode.Smooth: distanceToTarget = 0f; - for (int i = 0; i < Doors.Length; i++) { + for (int i = 0; i < Doors.Length; i++) + { doorTargetRotation = open ? OpenRotations[i] : ClosedRotations[i]; Quaternion doorStartRotation = Doors[i].rotation; Doors[i].localEulerAngles = doorTargetRotation; @@ -56,7 +64,8 @@ void Update() { Vector3.Distance(Doors[i].localEulerAngles, doorTargetRotation) ); } - for (int i = 0; i < Drawers.Length; i++) { + for (int i = 0; i < Drawers.Length; i++) + { drawerTargetPosition = open ? OpenPositions[i] : ClosedPositions[i]; Drawers[i].localPosition = Vector3.Lerp( Drawers[i].localPosition, @@ -69,7 +78,8 @@ void Update() { ); } - if (distanceToTarget >= 360f) { + if (distanceToTarget >= 360f) + { distanceToTarget -= 360f; } diff --git a/unity/Assets/Scripts/GenerateRoboTHOR.cs b/unity/Assets/Scripts/GenerateRoboTHOR.cs index 9d925df97f..ef70c61d3d 100644 --- a/unity/Assets/Scripts/GenerateRoboTHOR.cs +++ b/unity/Assets/Scripts/GenerateRoboTHOR.cs @@ -6,7 +6,8 @@ using UnityEngine; using Random = UnityEngine.Random; -public class GenerateRoboTHOR : MonoBehaviour { +public class GenerateRoboTHOR : MonoBehaviour +{ [SerializeField] protected GameObject wallPrefab; @@ -48,7 +49,8 @@ public class GenerateRoboTHOR : MonoBehaviour { protected float[] validStartingAgentRotations = new float[] { 0, 90, 180, 270 }; protected string[] validOrientations = new string[] { "left", "right", "top", "bottom" }; - protected class WallCell { + protected class WallCell + { public bool visited; public Dictionary walls; @@ -56,9 +58,11 @@ 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 { + this.walls = new Dictionary + { ["left"] = left, ["right"] = right, ["top"] = top, @@ -69,24 +73,30 @@ public WallCell(bool visited, bool? left, bool? right, bool? top, bool? bottom) // Returns the neighbor cell if a wall boundary is removed, and returns // null if all neighbors have been visited. - protected (int, int)? VisitCell(int xGridCell, int zGridCell) { - if (xGridCell < 0 || xGridCell >= xWalls) { + protected (int, int)? VisitCell(int xGridCell, int zGridCell) + { + if (xGridCell < 0 || xGridCell >= xWalls) + { throw new ArgumentOutOfRangeException( $"xGridCell must be in [0:xWalls), not {xGridCell}" ); - } else if (zGridCell < 0 || zGridCell >= zWalls) { + } + else if (zGridCell < 0 || zGridCell >= zWalls) + { throw new ArgumentOutOfRangeException( $"zGridCell must be in [0:zWalls), not {zGridCell}" ); } - if (!wallCells[xGridCell, zGridCell].visited) { + if (!wallCells[xGridCell, zGridCell].visited) + { cellsVisited += 1; wallCells[xGridCell, zGridCell].visited = true; } List choicesToRemove = new List(); - foreach (string orientation in validOrientations) { + foreach (string orientation in validOrientations) + { (int, int)? neighborCell = GetNeighbor( xGridCell: xGridCell, zGridCell: zGridCell, @@ -96,13 +106,15 @@ public WallCell(bool visited, bool? left, bool? right, bool? top, bool? bottom) if ( neighborCell.HasValue && !wallCells[neighborCell.Value.Item1, neighborCell.Value.Item2].visited - ) { + ) + { choicesToRemove.Add(orientation); } } // all neighbors are visited - if (choicesToRemove.Count == 0) { + if (choicesToRemove.Count == 0) + { return null; } @@ -123,40 +135,50 @@ public WallCell(bool visited, bool? left, bool? right, bool? top, bool? bottom) /** * Returns the position of the neighbor. If the neighbor is out of bounds, null is returned. */ - protected (int, int)? GetNeighbor(int xGridCell, int zGridCell, string orientation) { - if (xGridCell < 0 || xGridCell >= xWalls) { + 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}" ); - } else if (zGridCell < 0 || zGridCell >= zWalls) { + } + else if (zGridCell < 0 || zGridCell >= zWalls) + { throw new ArgumentOutOfRangeException( $"zGridCell must be in [0:zWalls), not {zGridCell}" ); } - if (!wallCells[xGridCell, zGridCell].walls[orientation].HasValue) { + if (!wallCells[xGridCell, zGridCell].walls[orientation].HasValue) + { return null; } // remove neighboring instance - switch (orientation) { + switch (orientation) + { case "left": - if (xGridCell > 0) { + if (xGridCell > 0) + { return (xGridCell - 1, zGridCell); } break; case "right": - if (xGridCell < xWalls - 1) { + if (xGridCell < xWalls - 1) + { return (xGridCell + 1, zGridCell); } break; case "bottom": - if (zGridCell < zWalls - 1) { + if (zGridCell < zWalls - 1) + { return (xGridCell, zGridCell + 1); } break; case "top": - if (zGridCell > 0) { + if (zGridCell > 0) + { return (xGridCell, zGridCell - 1); } break; @@ -173,18 +195,21 @@ public WallCell(bool visited, bool? left, bool? right, bool? top, bool? bottom) int xGridCell, int zGridCell, string orientation - ) { + ) + { (int, int)? neighbor = GetNeighbor( xGridCell: xGridCell, zGridCell: zGridCell, orientation: orientation ); - if (!neighbor.HasValue) { + if (!neighbor.HasValue) + { return null; } - switch (orientation) { + switch (orientation) + { case "left": wallCells[neighbor.Value.Item1, neighbor.Value.Item2].walls["right"] = false; break; @@ -205,12 +230,16 @@ string orientation * @param xGridCell is in [0:xWalls) * @param zGridCell is in [0:zWalls) */ - protected Vector3 GetWallGridPointCenter(int xGridCell, int zGridCell) { - if (xGridCell < 0 || xGridCell >= xWalls) { + protected Vector3 GetWallGridPointCenter(int xGridCell, int zGridCell) + { + if (xGridCell < 0 || xGridCell >= xWalls) + { throw new ArgumentOutOfRangeException( $"xGridCell must be in [0:xWalls), not {xGridCell}" ); - } else if (zGridCell < 0 || zGridCell >= zWalls) { + } + else if (zGridCell < 0 || zGridCell >= zWalls) + { throw new ArgumentOutOfRangeException( $"zGridCell must be in [0:zWalls), not {zGridCell}" ); @@ -234,12 +263,16 @@ protected Vector3 GetWallGridPointCenter(int xGridCell, int zGridCell) { * @param xGridCell is in [0:xWalls) * @param zGridCell is in [0:zWalls) */ - protected Vector3 GetAgentGridPointCenter(int xGridCell, int zGridCell) { - if (xGridCell < 0 || xGridCell >= xWalls) { + protected Vector3 GetAgentGridPointCenter(int xGridCell, int zGridCell) + { + if (xGridCell < 0 || xGridCell >= xWalls) + { throw new ArgumentOutOfRangeException( $"xGridCell must be in [0:xWalls), not {xGridCell}" ); - } else if (zGridCell < 0 || zGridCell >= zWalls) { + } + else if (zGridCell < 0 || zGridCell >= zWalls) + { throw new ArgumentOutOfRangeException( $"zGridCell must be in [0:zWalls), not {zGridCell}" ); @@ -271,10 +304,12 @@ protected Vector3 GetAgentGridPointCenter(int xGridCell, int zGridCell) { /** * Place a single wall at a position and orientation. */ - protected void PlaceWall(Vector3 gridPointCenter, string orientation) { + protected void PlaceWall(Vector3 gridPointCenter, string orientation) + { Quaternion rotation; Vector3 position = new Vector3(gridPointCenter.x, gridPointCenter.y, gridPointCenter.z); - switch (orientation) { + switch (orientation) + { case "top": rotation = Quaternion.Euler(0, 180, 0); break; @@ -306,7 +341,8 @@ 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) { + protected void PlaceWall(int xGridCell, int zGridCell, string orientation) + { Vector3 gridPointCenter = GetWallGridPointCenter( xGridCell: xGridCell, zGridCell: zGridCell @@ -317,27 +353,35 @@ protected void PlaceWall(int xGridCell, int zGridCell, string orientation) { /** * Place all the walls based on wallCells. */ - protected void PlaceWalls() { - for (int x = 0; x < xWalls; x++) { + protected void PlaceWalls() + { + for (int x = 0; x < xWalls; x++) + { PlaceWall(xGridCell: x, zGridCell: 0, orientation: "top"); } - for (int z = 0; z < zWalls; z++) { + for (int z = 0; z < zWalls; z++) + { PlaceWall(xGridCell: 0, zGridCell: z, orientation: "left"); } - for (int x = 0; x < xWalls; x++) { - for (int z = 0; z < zWalls; z++) { - if (wallCells[x, z].walls["right"] != false) { + for (int x = 0; x < xWalls; x++) + { + for (int z = 0; z < zWalls; z++) + { + if (wallCells[x, z].walls["right"] != false) + { PlaceWall(xGridCell: x, zGridCell: z, orientation: "right"); } - if (wallCells[x, z].walls["bottom"] != false) { + if (wallCells[x, z].walls["bottom"] != false) + { PlaceWall(xGridCell: x, zGridCell: z, orientation: "bottom"); } } } } - protected void AddOuterWalls() { + protected void AddOuterWalls() + { GameObject wall; // side 1 @@ -413,12 +457,15 @@ protected void AddOuterWalls() { ); } - protected void PlaceCeilings() { + protected void PlaceCeilings() + { int xCeilings = (int)Math.Ceiling((xWalls + 2 * boundaryPadding) / ceilingSizeX); int zCeilings = (int)Math.Ceiling((zWalls + 2 * boundaryPadding) / ceilingSizeZ); - for (int x = 0; x < xCeilings; x++) { - for (int z = 0; z < zCeilings; z++) { + for (int x = 0; x < xCeilings; x++) + { + for (int z = 0; z < zCeilings; z++) + { // Place ceilings Instantiate( original: ceilingPrefab, @@ -451,13 +498,16 @@ public void GenerateConfig( int xWalls = 16, int zWalls = 8, int boundaryPadding = 0 - ) { - if (xWalls <= 0 || zWalls <= 0) { + ) + { + if (xWalls <= 0 || zWalls <= 0) + { throw new ArgumentOutOfRangeException( $"Must use > 0 walls in each direction, not xWalls={xWalls}, zWalls={zWalls}." ); } - if (boundaryPadding < 0) { + if (boundaryPadding < 0) + { throw new ArgumentOutOfRangeException( $"boundaryPadding must be >= 0, not {boundaryPadding}" ); @@ -472,14 +522,17 @@ public void GenerateConfig( // There is a single floor tile under the agent at the start so that it // is caught by gravity. - for (int i = floorParent.childCount - 1; i >= 0; i--) { + for (int i = floorParent.childCount - 1; i >= 0; i--) + { Destroy(floorParent.GetChild(i).gameObject); } PlaceCeilings(); - for (int x = 0; x < xWalls + boundaryPadding * 2; x++) { - for (int z = 0; z < zWalls + boundaryPadding * 2; z++) { + for (int x = 0; x < xWalls + boundaryPadding * 2; x++) + { + for (int z = 0; z < zWalls + boundaryPadding * 2; z++) + { Instantiate( original: floorPrefab, parent: floorParent, @@ -498,7 +551,8 @@ public void GenerateConfig( // Only necessary because Initialize can be called within the // editor without calling Reset(). However, this is not supported // from the Python API. - for (int i = wallParent.childCount - 1; i >= 0; i--) { + for (int i = wallParent.childCount - 1; i >= 0; i--) + { Destroy(wallParent.GetChild(i).gameObject); } #endif @@ -507,8 +561,10 @@ public void GenerateConfig( cellsVisited = 0; // Start with walls everywhere! - for (int x = 0; x < xWalls; x++) { - for (int z = 0; z < zWalls; z++) { + for (int x = 0; x < xWalls; x++) + { + for (int z = 0; z < zWalls; z++) + { wallCells[x, z] = new WallCell( visited: false, left: x == 0 ? (bool?)null : true, @@ -523,12 +579,16 @@ public void GenerateConfig( Stack<(int, int)> stack = new Stack<(int, int)>(); (int, int) startingPosition = (Random.Range(0, xWalls), Random.Range(0, zWalls)); stack.Push(startingPosition); - while (cellsVisited != xWalls * zWalls) { + while (cellsVisited != xWalls * zWalls) + { (int xGridCell, int zGridCell) = stack.Peek(); (int, int)? neighbor = VisitCell(xGridCell: xGridCell, zGridCell: zGridCell); - if (neighbor.HasValue) { + if (neighbor.HasValue) + { stack.Push(neighbor.Value); - } else { + } + else + { stack.Pop(); } } diff --git a/unity/Assets/Scripts/GetAllScenesInstanceCount.cs b/unity/Assets/Scripts/GetAllScenesInstanceCount.cs index c6e5633e88..eebfb46c50 100644 --- a/unity/Assets/Scripts/GetAllScenesInstanceCount.cs +++ b/unity/Assets/Scripts/GetAllScenesInstanceCount.cs @@ -16,7 +16,8 @@ // public Dictionary objectTypeCountInScene = new Dictionary(); // } -public class GetAllScenesInstanceCount : MonoBehaviour { +public class GetAllScenesInstanceCount : MonoBehaviour +{ // [MenuItem("GameObject/Test")] // private static void TestGetPrefabInstanceHandle() // { diff --git a/unity/Assets/Scripts/GroupCommand.cs b/unity/Assets/Scripts/GroupCommand.cs index a1047ba412..4f9ab74992 100644 --- a/unity/Assets/Scripts/GroupCommand.cs +++ b/unity/Assets/Scripts/GroupCommand.cs @@ -2,17 +2,21 @@ using UnityEngine; #if UNITY_EDITOR -public static class GroupCommand { +public static class GroupCommand +{ [MenuItem("GameObject/Group Selected %g")] - private static void GroupSelected() { - if (!Selection.activeTransform) { + private static void GroupSelected() + { + if (!Selection.activeTransform) + { return; } var go = new GameObject(Selection.activeTransform.name + " Group"); Undo.RegisterCreatedObjectUndo(go, "Group Selected"); go.transform.SetParent(Selection.activeTransform.parent, false); - foreach (var transform in Selection.transforms) { + foreach (var transform in Selection.transforms) + { Undo.SetTransformParent(transform, go.transform, "Group Selected"); } diff --git a/unity/Assets/Scripts/HeatZone.cs b/unity/Assets/Scripts/HeatZone.cs index ada873db22..e5d9bb325e 100644 --- a/unity/Assets/Scripts/HeatZone.cs +++ b/unity/Assets/Scripts/HeatZone.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class HeatZone : MonoBehaviour { +public class HeatZone : MonoBehaviour +{ // in preparation for different kinds of cooking rather than a single abstracted cooked/uncooked state.... // this is to make sure that Microwaves don't switch bread slices into their toasted version, because microwaves can't do that public bool CanToastBread = true; @@ -13,13 +14,16 @@ void Start() { } // Update is called once per frame void Update() { } - public void OnTriggerStay(Collider other) { - if (other.GetComponentInParent()) { + public void OnTriggerStay(Collider other) + { + if (other.GetComponentInParent()) + { // Set temperature of object to HOT SimObjPhysics sop = other.GetComponentInParent(); sop.CurrentTemperature = Temperature.Hot; - if (sop.HowManySecondsUntilRoomTemp != sop.GetTimerResetValue()) { + if (sop.HowManySecondsUntilRoomTemp != sop.GetTimerResetValue()) + { sop.HowManySecondsUntilRoomTemp = sop.GetTimerResetValue(); } @@ -27,18 +31,23 @@ public void OnTriggerStay(Collider other) { // // now if the object is able to be cooked, automatically cook it - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeCooked)) { + if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeCooked)) + { CookObject sopcook = sop.GetComponent(); // if the object is bread... check if CanToastBread is true, and if so proceed to cook - if (sop.Type == SimObjType.BreadSliced && CanToastBread == true) { - if (!sopcook.IsCooked()) { + if (sop.Type == SimObjType.BreadSliced && CanToastBread == true) + { + if (!sopcook.IsCooked()) + { sopcook.Cook(); } } // oh it's not bread, no worries just cook it now - else if (sop.Type != SimObjType.BreadSliced) { - if (!sopcook.IsCooked()) { + else if (sop.Type != SimObjType.BreadSliced) + { + if (!sopcook.IsCooked()) + { sopcook.Cook(); } } diff --git a/unity/Assets/Scripts/HoleMetadata.cs b/unity/Assets/Scripts/HoleMetadata.cs index d62d5abcb5..a6afb1542b 100644 --- a/unity/Assets/Scripts/HoleMetadata.cs +++ b/unity/Assets/Scripts/HoleMetadata.cs @@ -3,7 +3,8 @@ using System.Linq; using UnityEngine; -public class HoleMetadata : MonoBehaviour { +public class HoleMetadata : MonoBehaviour +{ [DraggablePoint] public Vector3 Min; @@ -11,7 +12,8 @@ public class HoleMetadata : MonoBehaviour { public Vector3 Max; public Vector3 Margin; - void OnDrawGizmos() { + void OnDrawGizmos() + { // Box collider green //Gizmos.color = new Color(145.0f/255.0f, 245.0f/255.0f, 139/255.0f, 1.0f); @@ -52,14 +54,16 @@ void OnDrawGizmos() { corners.Skip(4).ToList() }; - foreach (var q in sides) { + 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); } } diff --git a/unity/Assets/Scripts/IK_Robot_Arm_Controller.cs b/unity/Assets/Scripts/IK_Robot_Arm_Controller.cs index d468cbadb3..d64ab0734a 100644 --- a/unity/Assets/Scripts/IK_Robot_Arm_Controller.cs +++ b/unity/Assets/Scripts/IK_Robot_Arm_Controller.cs @@ -5,7 +5,8 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public partial class IK_Robot_Arm_Controller : ArmController { +public partial class IK_Robot_Arm_Controller : ArmController +{ [SerializeField] private Transform armBase, elbowTarget, @@ -29,49 +30,60 @@ public partial class IK_Robot_Arm_Controller : ArmController { private const float extendedArmLength = 0.6325f; - public override GameObject GetArmTarget() { + public override GameObject GetArmTarget() + { return armTarget.gameObject; } - public override Transform pickupParent() { + public override Transform pickupParent() + { return magnetSphere.transform; } - public override Vector3 wristSpaceOffsetToWorldPos(Vector3 offset) { + public override Vector3 wristSpaceOffsetToWorldPos(Vector3 offset) + { return handCameraTransform.TransformPoint(offset) - handCameraTransform.TransformPoint(Vector3.zero); } - public override Vector3 armBaseSpaceOffsetToWorldPos(Vector3 offset) { + public override Vector3 armBaseSpaceOffsetToWorldPos(Vector3 offset) + { return this.transform.TransformPoint(offset) - this.transform.TransformPoint(Vector3.zero); } - public override Vector3 pointToWristSpace(Vector3 point) { + public override Vector3 pointToWristSpace(Vector3 point) + { return handCameraTransform.TransformPoint(point); } - public override Vector3 pointToArmBaseSpace(Vector3 point) { + public override Vector3 pointToArmBaseSpace(Vector3 point) + { return this.transform.Find("robot_arm_FK_IK_rig").transform.TransformPoint(point); } - public override void ContinuousUpdate(float fixedDeltaTime) { + public override void ContinuousUpdate(float fixedDeltaTime) + { Debug.Log("manipulate Arm called from IK_Robot_Arm_Controller"); solver.ManipulateArm(); } - public GameObject GetArmBase() { + public GameObject GetArmBase() + { return armBase.gameObject; } - public GameObject GetElbowTarget() { + public GameObject GetElbowTarget() + { return elbowTarget.gameObject; } - public GameObject GetMagnetSphere() { + public GameObject GetMagnetSphere() + { return magnetSphere.gameObject; } - protected override void lastStepCallback() { + protected override void lastStepCallback() + { Vector3 pos = handCameraTransform.transform.position; Quaternion rot = handCameraTransform.transform.rotation; armTarget.position = pos; @@ -84,7 +96,8 @@ protected override void lastStepCallback() { // } - void Start() { + 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, @@ -105,8 +118,10 @@ void Start() { // clean up arm colliders, removing triggers List cleanedCaps = new List(); - foreach (CapsuleCollider c in armCaps) { - if (!c.isTrigger) { + foreach (CapsuleCollider c in armCaps) + { + if (!c.isTrigger) + { cleanedCaps.Add(c); } } @@ -114,8 +129,10 @@ void Start() { ArmCapsuleColliders = cleanedCaps.ToArray(); List cleanedBoxes = new List(); - foreach (BoxCollider b in armBoxes) { - if (!b.isTrigger) { + foreach (BoxCollider b in armBoxes) + { + if (!b.isTrigger) + { cleanedBoxes.Add(b); } } @@ -124,8 +141,10 @@ void Start() { // TODO: Currently explicitly ignoring all arm self collisions (for efficiency)! var colliders = this.GetComponentsInChildren(); - foreach (Collider c0 in colliders) { - foreach (Collider c1 in colliders) { + foreach (Collider c0 in colliders) + { + foreach (Collider c1 in colliders) + { Physics.IgnoreCollision(c0, c1); } } @@ -133,7 +152,8 @@ void Start() { } // Restricts front hemisphere for arm movement - protected override bool validArmTargetPosition(Vector3 targetWorldPosition) { + protected override bool validArmTargetPosition(Vector3 targetWorldPosition) + { Vector3 targetShoulderSpace = ( this.transform.InverseTransformPoint(targetWorldPosition) - new Vector3(0, 0, originToShoulderLength) @@ -150,7 +170,8 @@ public IEnumerator rotateWristAroundPoint( float degreesPerSecond, float fixedDeltaTime, bool returnToStartPositionIfFailed = false - ) { + ) + { collisionListener.Reset(); return withLastStepCallback( ContinuousMovement.rotateAroundPoint( @@ -172,7 +193,8 @@ public IEnumerator rotateElbowRelative( float degreesPerSecond, float fixedDeltaTime, bool returnToStartPositionIfFailed = false - ) { + ) + { collisionListener.Reset(); GameObject poleManipulator = GameObject.Find("IK_pole_manipulator"); Quaternion rotation = Quaternion.Euler(0f, 0f, degrees); @@ -195,7 +217,8 @@ public IEnumerator rotateElbow( float degreesPerSecond, float fixedDeltaTime, bool returnToStartPositionIfFailed = false - ) { + ) + { GameObject poleManipulator = GameObject.Find("IK_pole_manipulator"); return rotateElbowRelative( controller: controller, @@ -206,7 +229,8 @@ public IEnumerator rotateElbow( ); } - public override ArmMetadata GenerateMetadata() { + public override ArmMetadata GenerateMetadata() + { ArmMetadata meta = new ArmMetadata(); // meta.handTarget = armTarget.position; Transform joint = transform; @@ -219,7 +243,8 @@ public override ArmMetadata GenerateMetadata() { Quaternion currentRotation; // Assign joint metadata to remaining joints, which all have identical hierarchies - for (int i = 1; i <= 4; i++) { + for (int i = 1; i <= 4; i++) + { joint = joint.Find("robot_arm_" + i + "_jnt"); JointMetadata jointMeta = new JointMetadata(); @@ -243,7 +268,8 @@ public override ArmMetadata GenerateMetadata() { currentRotation = joint.GetChild(0).rotation; // Check that world-relative rotation is angle-axis-notation-compatible - if (currentRotation != new Quaternion(0, 0, 0, -1)) { + if (currentRotation != new Quaternion(0, 0, 0, -1)) + { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); jointMeta.rotation = new Vector4( @@ -252,7 +278,9 @@ public override ArmMetadata GenerateMetadata() { vectorRot.z, ConvertAngleToZeroCentricRange(angleRot) ); - } else { + } + else + { jointMeta.rotation = new Vector4(1, 0, 0, 0); } @@ -263,7 +291,8 @@ public override ArmMetadata GenerateMetadata() { currentRotation = Quaternion.Inverse(armBase.rotation) * joint.GetChild(0).rotation; // Check that root-relative rotation is angle-axis-notation-compatible - if (currentRotation != new Quaternion(0, 0, 0, -1)) { + if (currentRotation != new Quaternion(0, 0, 0, -1)) + { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); jointMeta.rootRelativeRotation = new Vector4( vectorRot.x, @@ -271,12 +300,15 @@ public override ArmMetadata GenerateMetadata() { vectorRot.z, ConvertAngleToZeroCentricRange(angleRot) ); - } else { + } + else + { jointMeta.rootRelativeRotation = new Vector4(1, 0, 0, 0); } // PARENT-JOINT RELATIVE ROTATION - if (i != 1) { + if (i != 1) + { parentJoint = joint.parent; // Grab rotation of current joint's angler relative to parent joint's angler @@ -285,7 +317,8 @@ public override ArmMetadata GenerateMetadata() { * joint.GetChild(0).rotation; // Check that parent-relative rotation is angle-axis-notation-compatible - if (currentRotation != new Quaternion(0, 0, 0, -1)) { + if (currentRotation != new Quaternion(0, 0, 0, -1)) + { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); jointMeta.localRotation = new Vector4( vectorRot.x, @@ -293,10 +326,14 @@ public override ArmMetadata GenerateMetadata() { vectorRot.z, ConvertAngleToZeroCentricRange(angleRot) ); - } else { + } + else + { jointMeta.localRotation = new Vector4(1, 0, 0, 0); } - } else { + } + else + { // Special case for robot_arm_1_jnt because it has no parent-joint jointMeta.localRotation = jointMeta.rootRelativeRotation; @@ -313,8 +350,10 @@ public override ArmMetadata GenerateMetadata() { // note this is different from objects intersecting the hand's sphere, // there could be a case where an object is inside the sphere but not picked up by the hand List heldObjectIDs = new List(); - if (heldObjects != null) { - foreach (SimObjPhysics sop in heldObjects.Keys) { + if (heldObjects != null) + { + foreach (SimObjPhysics sop in heldObjects.Keys) + { heldObjectIDs.Add(sop.objectID); } } @@ -331,18 +370,22 @@ public override ArmMetadata GenerateMetadata() { return meta; } - float ConvertAngleToZeroCentricRange(float degrees) { - if (degrees < 0) { + float ConvertAngleToZeroCentricRange(float degrees) + { + if (degrees < 0) + { degrees = (degrees % 360f) + 360f; } - if (degrees > 180f) { + if (degrees > 180f) + { degrees = (degrees % 360f) - 360f; } return degrees; } #if UNITY_EDITOR - public class GizmoDrawCapsule { + public class GizmoDrawCapsule + { public Vector3 p0; public Vector3 p1; public float radius; @@ -350,9 +393,12 @@ public class GizmoDrawCapsule { List debugCapsules = new List(); - private void OnDrawGizmos() { - if (debugCapsules.Count > 0) { - foreach (GizmoDrawCapsule thing in debugCapsules) { + private void OnDrawGizmos() + { + if (debugCapsules.Count > 0) + { + foreach (GizmoDrawCapsule thing in debugCapsules) + { Gizmos.DrawWireSphere(thing.p0, thing.radius); Gizmos.DrawWireSphere(thing.p1, thing.radius); } diff --git a/unity/Assets/Scripts/IgnoreCollision.cs b/unity/Assets/Scripts/IgnoreCollision.cs index 31a92009b3..c7354b9093 100644 --- a/unity/Assets/Scripts/IgnoreCollision.cs +++ b/unity/Assets/Scripts/IgnoreCollision.cs @@ -3,36 +3,43 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public class IgnoreCollision : MonoBehaviour { +public class IgnoreCollision : MonoBehaviour +{ public Collider[] myColliders; public GameObject objectToIgnoreCollisionsWith = null; // Start is called before the first frame update - void Start() { + void Start() + { SetupIgnoreCollision(); } // Update is called once per frame void Update() { } - public void SetupIgnoreCollision() { - if (gameObject.GetComponentInParent() && myColliders.Length == 0) { + public void SetupIgnoreCollision() + { + if (gameObject.GetComponentInParent() && myColliders.Length == 0) + { myColliders = gameObject.GetComponentInParent().MyColliders; } Collider[] otherCollidersToIgnore = null; // if the object to ignore has been manually set already - if (objectToIgnoreCollisionsWith != null) { + if (objectToIgnoreCollisionsWith != null) + { // do this if we are ignoring a sim object like a dresser with drawers in it - if (objectToIgnoreCollisionsWith.GetComponent()) { + if (objectToIgnoreCollisionsWith.GetComponent()) + { otherCollidersToIgnore = objectToIgnoreCollisionsWith .GetComponent() .MyColliders; } // do this if we are ignoring the agent - if (objectToIgnoreCollisionsWith.GetComponent()) { + if (objectToIgnoreCollisionsWith.GetComponent()) + { otherCollidersToIgnore = new Collider[] { objectToIgnoreCollisionsWith @@ -42,7 +49,8 @@ public void SetupIgnoreCollision() { } } #if UNITY_EDITOR - else { + else + { Debug.LogError( "IgnoreCollision on " + gameObject.transform.name @@ -54,9 +62,11 @@ public void SetupIgnoreCollision() { // else // otherCollidersToIgnore = gameObject.GetComponentInParent().MyColliders; - foreach (Collider col in myColliders) { + foreach (Collider col in myColliders) + { // Physics.IgnoreCollision(col 1, col2, true) with all combinations? - foreach (Collider otherCol in otherCollidersToIgnore) { + foreach (Collider otherCol in otherCollidersToIgnore) + { Physics.IgnoreCollision(col, otherCol); } } diff --git a/unity/Assets/Scripts/ImageSynthesis/ColorEncoding.cs b/unity/Assets/Scripts/ImageSynthesis/ColorEncoding.cs index 0932090dcb..91258e86e8 100644 --- a/unity/Assets/Scripts/ImageSynthesis/ColorEncoding.cs +++ b/unity/Assets/Scripts/ImageSynthesis/ColorEncoding.cs @@ -1,23 +1,29 @@ using System.Security.Cryptography; using UnityEngine; -public class ColorEncoding { - public static byte ReverseBits(byte value) { +public class ColorEncoding +{ + public static byte ReverseBits(byte value) + { return (byte)((value * 0x0202020202 & 0x010884422010) % 1023); } - public static int SparsifyBits(byte value, int sparse) { + public static int SparsifyBits(byte value, int sparse) + { int retVal = 0; - for (int bits = 0; bits < 8; bits++, value >>= 1) { + for (int bits = 0; bits < 8; bits++, value >>= 1) + { retVal |= (value & 1); retVal <<= sparse; } return retVal >> sparse; } - public static Color EncodeIDAsColor(int instanceId) { + public static Color EncodeIDAsColor(int instanceId) + { var uid = instanceId * 2; - if (uid < 0) { + if (uid < 0) + { uid = -uid + 1; } @@ -35,15 +41,18 @@ public static Color EncodeIDAsColor(int instanceId) { return new Color32(r, g, b, 255); } - public static Color EncodeTagAsColor(string tag) { - using (MD5 md5 = MD5.Create()) { + 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) { + public static Color EncodeLayerAsColor(int layer) + { // Following value must be in the range (0.5 .. 1.0) // in order to avoid color overlaps when using 'divider' in this func var z = .7f; diff --git a/unity/Assets/Scripts/ImageSynthesis/ExampleUI.cs b/unity/Assets/Scripts/ImageSynthesis/ExampleUI.cs index 09ff92d09c..6e330a9104 100644 --- a/unity/Assets/Scripts/ImageSynthesis/ExampleUI.cs +++ b/unity/Assets/Scripts/ImageSynthesis/ExampleUI.cs @@ -4,13 +4,16 @@ using UnityEngine.SceneManagement; [RequireComponent(typeof(ImageSynthesis))] -public class ExampleUI : MonoBehaviour { +public class ExampleUI : MonoBehaviour +{ public int width = 320; public int height = 200; private int imageCounter = 1; - void OnGUI() { - if (GUILayout.Button("Captcha!!! (" + imageCounter + ")")) { + void OnGUI() + { + if (GUILayout.Button("Captcha!!! (" + imageCounter + ")")) + { 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) diff --git a/unity/Assets/Scripts/ImageSynthesis/ImageSynthesis.cs b/unity/Assets/Scripts/ImageSynthesis/ImageSynthesis.cs index e72c6f766b..889719df1f 100644 --- a/unity/Assets/Scripts/ImageSynthesis/ImageSynthesis.cs +++ b/unity/Assets/Scripts/ImageSynthesis/ImageSynthesis.cs @@ -18,7 +18,8 @@ // 2) rendering several cameras with different aspect ratios - vectors do stretch to the sides of the screen [RequireComponent(typeof(Camera))] -public class ImageSynthesis : MonoBehaviour { +public class ImageSynthesis : MonoBehaviour +{ private bool initialized = false; // pass configuration @@ -39,13 +40,15 @@ public class ImageSynthesis : MonoBehaviour { // new CapturePass() { name = "_position" }, }; - struct CapturePass { + struct CapturePass + { // configuration public string name; public bool supportsAntialiasing; public bool needsRescale; - public CapturePass(string name_) { + public CapturePass(string name_) + { name = name_; supportsAntialiasing = true; needsRescale = false; @@ -56,18 +59,24 @@ public CapturePass(string name_) { public Camera camera; }; - public bool hasCapturePass(string name) { - for (int i = 0; i < capturePasses.Length; i++) { - if (capturePasses[i].name == name) { + public bool hasCapturePass(string name) + { + for (int i = 0; i < capturePasses.Length; i++) + { + if (capturePasses[i].name == name) + { return true; } } return false; } - public void updateCameraStatuses(bool enabled) { - for (int i = 0; i < capturePasses.Length; i++) { - if (capturePasses[i].camera != null && capturePasses[i].name != "_img") { + public void updateCameraStatuses(bool enabled) + { + for (int i = 0; i < capturePasses.Length; i++) + { + if (capturePasses[i].camera != null && capturePasses[i].name != "_img") + { capturePasses[i].camera.enabled = enabled; } } @@ -94,10 +103,12 @@ public void updateCameraStatuses(bool enabled) { public Texture2D tex; - public void OnEnable() { + 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. - if (!initialized) { + if (!initialized) + { // XXXXXXXXXXX************ // Remember, adding any new Shaders requires them to be included in Project Settings->Graphics->Always Included Shaders // otherwise the standlone will build without the shaders and you will be sad @@ -105,17 +116,20 @@ public void OnEnable() { // default fallbacks, if shaders are unspecified - if (!uberReplacementShader) { + if (!uberReplacementShader) + { uberReplacementShader = Shader.Find("Hidden/UberReplacement"); } - if (!opticalFlowShader) { + if (!opticalFlowShader) + { opticalFlowShader = Shader.Find("Hidden/OpticalFlow"); } #if UNITY_EDITOR - if (!depthShader) { + if (!depthShader) + { depthShader = Shader.Find("Hidden/DepthBW"); } #else @@ -131,7 +145,8 @@ public void OnEnable() { // use real camera to capture final image capturePasses[0].camera = GetComponent(); - for (int q = 1; q < capturePasses.Length; q++) { + for (int q = 1; q < capturePasses.Length; q++) + { capturePasses[q].camera = CreateHiddenCamera(capturePasses[q].name); } md5 = System.Security.Cryptography.MD5.Create(); @@ -142,9 +157,11 @@ public void OnEnable() { initialized = true; } - void LateUpdate() { + void LateUpdate() + { #if UNITY_EDITOR - if (DetectPotentialSceneChangeInEditor()) { + if (DetectPotentialSceneChangeInEditor()) + { OnSceneChange(); } @@ -154,7 +171,8 @@ void LateUpdate() { // OnCameraChange(); } - private Camera CreateHiddenCamera(string name) { + 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; @@ -177,7 +195,8 @@ private Camera CreateHiddenCamera(string name) { return newCamera; } - private static 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); @@ -190,7 +209,8 @@ private static void SetupCameraWithReplacementShader( Camera cam, Shader shader, ReplacelementModes mode - ) { + ) + { SetupCameraWithReplacementShader(cam, shader, mode, Color.blue); } @@ -199,7 +219,8 @@ private static void SetupCameraWithReplacementShader( 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; @@ -214,14 +235,16 @@ 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); cam.depthTextureMode = depthTextureMode; } - enum ReplacelementModes { + enum ReplacelementModes + { ObjectId = 0, CatergoryId = 1, DepthCompressed = 2, @@ -232,8 +255,10 @@ enum ReplacelementModes { // Call this if the settings on the main camera ever change? But the main camera now uses slightly different layer masks and deffered/forward render settings than these image synth cameras // do, so maybe it's fine for now I dunno - public void OnCameraChange() { - if (tex != null) { + public void OnCameraChange() + { + if (tex != null) + { Destroy(tex); tex = null; } @@ -242,8 +267,10 @@ public void OnCameraChange() { // TODO: add tests, not needed when target display is different // mainCamera.depth = 9999; // This ensures the main camera is rendered on screen - foreach (var pass in capturePasses) { - if (pass.camera == mainCamera) { + foreach (var pass in capturePasses) + { + if (pass.camera == mainCamera) + { continue; } @@ -262,12 +289,14 @@ public void OnCameraChange() { } // cache materials and setup material properties - if (!opticalFlowMaterial || opticalFlowMaterial.shader != opticalFlowShader) { + if (!opticalFlowMaterial || opticalFlowMaterial.shader != opticalFlowShader) + { opticalFlowMaterial = new Material(opticalFlowShader); } opticalFlowMaterial.SetFloat("_Sensitivity", opticalFlowSensitivity); - if (!depthMaterial || depthMaterial.shader != depthShader) { + if (!depthMaterial || depthMaterial.shader != depthShader) + { depthMaterial = new Material(depthShader); } @@ -297,7 +326,8 @@ public void OnCameraChange() { ); #if UNITY_EDITOR - for (int i = 0; i < capturePasses.Length; i++) { + for (int i = 0; i < capturePasses.Length; i++) + { // Debug.Log("Setting camera " + capturePasses[i].camera.gameObject.name + " to display " + i); capturePasses[i].camera.targetDisplay = i; } @@ -308,25 +338,31 @@ public void OnCameraChange() { */ } - public string MD5Hash(string input) { + public string MD5Hash(string input) + { byte[] data = md5.ComputeHash(System.Text.Encoding.Default.GetBytes(input)); // Create string representation System.Text.StringBuilder sb = new System.Text.StringBuilder(); - for (int i = 0; i < data.Length; ++i) { + for (int i = 0; i < data.Length; ++i) + { sb.Append(data[i].ToString("x2")); } return sb.ToString(); } - private string getObjectId(GameObject gameObject) { + 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 // during a simulation. This forces the objectId to get generated once // on scene startup int key = gameObject.GetInstanceID(); - if (nonSimObjObjectIds.ContainsKey(key)) { + if (nonSimObjObjectIds.ContainsKey(key)) + { return nonSimObjObjectIds[key]; - } else { + } + else + { Transform t = gameObject.transform; string objectId = gameObject.name + "|" + t.position.x + "|" + t.position.y + "|" + t.position.z; @@ -335,13 +371,15 @@ private string getObjectId(GameObject gameObject) { } } - public void OnSceneChange() { + public void OnSceneChange() + { sentColorCorrespondence = false; var renderers = UnityEngine.Object.FindObjectsOfType(); colorIds = new Dictionary(); var mpb = new MaterialPropertyBlock(); - foreach (var r in renderers) { + foreach (var r in renderers) + { // var layer = r.gameObject.layer; // var tag = r.gameObject.tag; @@ -349,20 +387,24 @@ public void OnSceneChange() { string objTag = getObjectId(r.gameObject); StructureObject so = r.gameObject.GetComponent(); - if (so == null) { + if (so == null) + { so = r.gameObject.GetComponentInParent(); } SimObjPhysics sop = r.gameObject.GetComponent(); - if (sop == null) { + if (sop == null) + { sop = r.gameObject.GetComponentInParent(); } - if (so != null) { + if (so != null) + { classTag = "" + so.WhatIsMyStructureObjectTag; // objTag = so.gameObject.name; } - if (sop != null) { + if (sop != null) + { classTag = "" + sop.Type; objTag = sop.ObjectID; } @@ -372,10 +414,13 @@ public void OnSceneChange() { capturePasses[0].camera.WorldToScreenPoint(r.bounds.center); - if (so != null || sop != null) { + if (so != null || sop != null) + { colorIds[objColor] = objTag; colorIds[classColor] = classTag; - } else { + } + else + { colorIds[objColor] = r.gameObject.name; } @@ -384,7 +429,8 @@ public void OnSceneChange() { if ( r.gameObject.name.ToLower().Contains("lightray") && r.material.name.ToLower().Contains("lightray") - ) { + ) + { r.enabled = false; continue; } @@ -406,18 +452,23 @@ public byte[] Encode( int width = -1, int height = -1, bool jpg = false - ) { + ) + { // Must be called after end of Frame - if (width <= 0) { + if (width <= 0) + { width = Screen.width; } - if (height <= 0) { + if (height <= 0) + { height = Screen.height; } - foreach (var pass in capturePasses) { - if (pass.name == passName) { + foreach (var pass in capturePasses) + { + if (pass.name == passName) + { return Encode( pass.camera, width, @@ -434,14 +485,17 @@ public byte[] Encode( return (new byte[0]); } - public void Save(string filename, int width = -1, int height = -1, string path = "") { - if (width <= 0 || height <= 0) { + public void Save(string filename, int width = -1, int height = -1, string path = "") + { + if (width <= 0 || height <= 0) + { width = Screen.width; height = Screen.height; } var filenameExtension = System.IO.Path.GetExtension(filename); - if (filenameExtension == "") { + if (filenameExtension == "") + { filenameExtension = ".png"; } @@ -460,7 +514,8 @@ private IEnumerator WaitForEndOfFrameAndSave( string filenameExtension, int width, int height - ) { + ) + { yield return new WaitForEndOfFrame(); Save(filenameWithoutExtension, filenameExtension, width, height); } @@ -470,8 +525,10 @@ private void Save( string filenameExtension, int width, int height - ) { - foreach (var pass in capturePasses) { + ) + { + foreach (var pass in capturePasses) + { Save( pass.camera, filenameWithoutExtension + pass.name + filenameExtension, @@ -492,7 +549,8 @@ private byte[] Encode( bool jpg = false, RenderTextureFormat format = RenderTextureFormat.Default, RenderTextureReadWrite textureReadMode = RenderTextureReadWrite.Default - ) { + ) + { var mainCamera = GetComponent(); var depth = 32; var readWrite = textureReadMode; @@ -517,7 +575,8 @@ private byte[] Encode( readWrite, antiAliasing ); - if (tex == null) { + if (tex == null) + { tex = new Texture2D(width, height, TextureFormat.RGBA32, false); } @@ -530,7 +589,8 @@ private byte[] Encode( cam.Render(); - if (needsRescale) { + if (needsRescale) + { // blit to rescale (see issue with Motion Vectors in @KNOWN ISSUES) RenderTexture.active = finalRT; Graphics.Blit(renderRT, finalRT); @@ -548,9 +608,12 @@ private byte[] Encode( // encode texture into PNG/JPG byte[] bytes; - if (jpg) { + if (jpg) + { bytes = tex.EncodeToJPG(); - } else { + } + else + { bytes = tex.GetRawTextureData(); } @@ -573,7 +636,8 @@ private void Save( int height, bool supportsAntialiasing, bool needsRescale - ) { + ) + { byte[] bytes = Encode(cam, width, height, supportsAntialiasing, needsRescale); File.WriteAllBytes(filename, bytes); } @@ -583,22 +647,27 @@ bool needsRescale private int lastSelectedGOLayer = -1; private string lastSelectedGOTag = "unknown"; - private bool DetectPotentialSceneChangeInEditor() { + 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 // interesting for us (layer or tag) did not change since the last frame - if (UnityEditor.Selection.transforms.Length > 1) { + if (UnityEditor.Selection.transforms.Length > 1) + { // multiple objects are selected, all bets are off! // we have to assume these objects are being edited change = true; lastSelectedGO = null; - } else if (UnityEditor.Selection.activeGameObject) { + } + 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; - if (go == lastSelectedGO && potentialChangeHappened) { + if (go == lastSelectedGO && potentialChangeHappened) + { change = true; } diff --git a/unity/Assets/Scripts/InstantiatePrefabTest.cs b/unity/Assets/Scripts/InstantiatePrefabTest.cs index 8b539258cf..c193289fc9 100644 --- a/unity/Assets/Scripts/InstantiatePrefabTest.cs +++ b/unity/Assets/Scripts/InstantiatePrefabTest.cs @@ -6,7 +6,8 @@ using UnityStandardAssets.Characters.FirstPerson; // this script manages the spawning/placing of sim objects in the scene -public class InstantiatePrefabTest : MonoBehaviour { +public class InstantiatePrefabTest : MonoBehaviour +{ public GameObject[] prefabs = null; private int spawnCount = 0; @@ -23,15 +24,19 @@ public class InstantiatePrefabTest : MonoBehaviour { // spawn an object from the Array of prefabs. Used to spawn from a specific set of Prefabs // used for Hide and Seek stuff - public SimObjPhysics Spawn(string prefabType, string objectId, Vector3 position) { + public SimObjPhysics Spawn(string prefabType, string objectId, Vector3 position) + { GameObject topObject = GameObject.Find("Objects"); - foreach (GameObject prefab in prefabs) { - if (prefab.name.Contains(prefabType)) { + foreach (GameObject prefab in prefabs) + { + if (prefab.name.Contains(prefabType)) + { GameObject go = Instantiate(prefab, position, Quaternion.identity) as GameObject; go.transform.SetParent(topObject.transform); SimObjPhysics so = go.GetComponentInChildren(); - if (so == null) { + if (so == null) + { go.AddComponent(); so = go.GetComponentInChildren(); } @@ -51,7 +56,8 @@ public SimObjPhysics SpawnObject( Vector3 position, Vector3 rotation, bool spawningInHand - ) { + ) + { return SpawnObject( objectType, randomize, @@ -63,21 +69,26 @@ bool spawningInHand ); } - public Bounds BoundsOfObject(string objectType, int variation) { + public Bounds BoundsOfObject(string objectType, int variation) + { // GameObject topObject = GameObject.Find("Objects"); List candidates = new List(); - foreach (GameObject go in prefabs) { + foreach (GameObject go in prefabs) + { if ( go.GetComponent().Type == (SimObjType)Enum.Parse(typeof(SimObjType), objectType) - ) { + ) + { candidates.Add(go); } } Bounds objBounds = UtilityFunctions.CreateEmptyBounds(); - foreach (Renderer r in candidates[variation - 1].GetComponentsInChildren()) { - if (r.enabled) { + foreach (Renderer r in candidates[variation - 1].GetComponentsInChildren()) + { + if (r.enabled) + { objBounds.Encapsulate(r.bounds); } } @@ -102,17 +113,20 @@ public SimObjPhysics SpawnObject( Vector3 rotation, bool spawningInHand, bool ignoreChecks - ) { + ) + { GameObject topObject = GameObject.Find("Objects"); List candidates = new List(); - foreach (GameObject go in prefabs) { + 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) - ) { + ) + { candidates.Add(go); } } @@ -121,10 +135,12 @@ bool ignoreChecks SimObjPhysics simObj = null; // Figure out which variation to use, if no variation use first candidate found - if (randomize) { + if (randomize) + { variation = UnityEngine.Random.Range(1, candidates.Count); } - if (variation != 0) { + if (variation != 0) + { variation -= 1; } @@ -138,9 +154,11 @@ bool ignoreChecks quat, spawningInHand ) - ) { + ) + { GameObject prefab = Instantiate(candidates[variation], position, quat) as GameObject; - if (!ignoreChecks) { + if (!ignoreChecks) + { if ( UtilityFunctions.isObjectColliding( prefab, @@ -149,7 +167,8 @@ from agent in GameObject.FindObjectsOfType() select agent.gameObject ) ) - ) { + ) + { Debug.Log( "On spawning object the area was not clear despite CheckSpawnArea saying it was." ); @@ -160,12 +179,15 @@ select agent.gameObject prefab.transform.SetParent(topObject.transform); simObj = prefab.GetComponent(); spawnCount++; - } else { + } + else + { return null; } // ok make sure we did actually spawn something now, and give it an Id number - if (simObj) { + if (simObj) + { simObj.objectID = objectType + "|" + spawnCount.ToString(); return simObj; } @@ -184,8 +206,10 @@ public bool PlaceObjectReceptacle( int maxPlacementAttempts, int degreeIncrement, bool AlwaysPlaceUpright - ) { - if (rsps == null) { + ) + { + if (rsps == null) + { #if UNITY_EDITOR Debug.Log( "Null list of points to check, please pass in populated list of ?" @@ -193,33 +217,39 @@ bool AlwaysPlaceUpright #endif return false; // uh, there was nothing in the List for some reason, so failed to spawn } - if (rsps.Count == 0) { + if (rsps.Count == 0) + { return false; } List goodRsps = new List(); // 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) { + foreach (ReceptacleSpawnPoint p in rsps) + { if ( !p .ParentSimObjPhys.GetComponent() .DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.ObjectSpecificReceptacle ) - ) { + ) + { goodRsps.Add(p); } } // try a number of spawnpoints in this specific receptacle up to the maxPlacementAttempts int tries = 0; - foreach (ReceptacleSpawnPoint p in goodRsps) { - if (PlaceObject(sop, p, PlaceStationary, degreeIncrement, AlwaysPlaceUpright)) { + foreach (ReceptacleSpawnPoint p in goodRsps) + { + if (PlaceObject(sop, p, PlaceStationary, degreeIncrement, AlwaysPlaceUpright)) + { return true; } tries += 1; - if (maxPlacementAttempts > 0 && tries > maxPlacementAttempts) { + if (maxPlacementAttempts > 0 && tries > maxPlacementAttempts) + { break; } } @@ -238,8 +268,10 @@ public bool PlaceObjectReceptacleInViewport( int maxPlacementAttempts, int degreeIncrement, bool AlwaysPlaceUpright - ) { - if (rsps == null) { + ) + { + if (rsps == null) + { #if UNITY_EDITOR Debug.Log( "Null list of points to check, please pass in populated list of ?" @@ -248,38 +280,45 @@ bool AlwaysPlaceUpright return false; // uh, there was nothing in the List for some reason, so failed to spawn } - if (rsps.Count == 0) { + if (rsps.Count == 0) + { return false; } List goodRsps = new List(); - foreach (ReceptacleSpawnPoint p in rsps) { + foreach (ReceptacleSpawnPoint p in rsps) + { if ( !p .ParentSimObjPhys.GetComponent() .DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.ObjectSpecificReceptacle ) - ) { + ) + { goodRsps.Add(p); } } int tries = 0; - foreach (ReceptacleSpawnPoint p in goodRsps) { + foreach (ReceptacleSpawnPoint p in goodRsps) + { // if this is an Object Specific Receptacle, stop this check right now! I mean it! // Placing objects in/on an Object Specific Receptacle uses different logic to place the // object at the Attachemnet point rather than in the spawn area, so stop this right now! - if (PlaceObject(sop, p, PlaceStationary, degreeIncrement, AlwaysPlaceUpright)) { + if (PlaceObject(sop, p, PlaceStationary, degreeIncrement, AlwaysPlaceUpright)) + { // check to make sure the placed object is within the viewport - if (agent.objectIsOnScreen(sop)) { + if (agent.objectIsOnScreen(sop)) + { return true; } } tries += 1; - if (maxPlacementAttempts > 0 && tries > maxPlacementAttempts) { + if (maxPlacementAttempts > 0 && tries > maxPlacementAttempts) + { break; } } @@ -289,11 +328,13 @@ bool AlwaysPlaceUpright } // use this to keep track of a Rotation and Distance for use in PlaceObject - public class RotationAndDistanceValues { + public class RotationAndDistanceValues + { public float distance; public Quaternion rotation; - public RotationAndDistanceValues(float d, Quaternion r) { + public RotationAndDistanceValues(float d, Quaternion r) + { distance = d; rotation = r; } @@ -305,8 +346,10 @@ public bool PlaceObject( bool PlaceStationary, int degreeIncrement, bool AlwaysPlaceUpright - ) { - if (rsp.ParentSimObjPhys == sop) { + ) + { + if (rsp.ParentSimObjPhys == sop) + { #if UNITY_EDITOR Debug.Log("Can't place object inside itself!"); #endif @@ -336,10 +379,12 @@ bool AlwaysPlaceUpright // get rotations and distance values for 360/increment number of rotations around just the Y axis // we want to check all of these first so that the object is prioritized to be placed "upright" - for (int i = 0; i < HowManyRotationsToCheck; i++) { + for (int i = 0; i < HowManyRotationsToCheck; i++) + { oabb.enabled = true; - if (i > 0) { + if (i > 0) + { sop.transform.Rotate(new Vector3(0, degreeIncrement, 0), Space.Self); // ToCheck[i].rotation = sop.transform.rotation; @@ -358,7 +403,9 @@ bool AlwaysPlaceUpright sop.transform.rotation ) ); - } else { + } + else + { // no rotate change just yet, check the first position Vector3 Offset = oabb.ClosestPoint( @@ -382,18 +429,22 @@ bool AlwaysPlaceUpright } // continue to check rotations about the X and Z axes if the object doesn't have to be placed upright - if (!AlwaysPlaceUpright) { + if (!AlwaysPlaceUpright) + { // ok now try if the X and Z local axis are rotated if it'll fit // these values can cause the object to be placed at crazy angles, so we'll check these last - for (int i = 0; i < HowManyRotationsToCheck; i++) { + for (int i = 0; i < HowManyRotationsToCheck; i++) + { oabb.enabled = true; - if (i > 0) { + if (i > 0) + { sop.transform.Rotate(new Vector3(0, degreeIncrement, 0), Space.Self); Quaternion oldRotation = sop.transform.rotation; // now add more points by rotating the x axis at this current y rotation - for (int j = 0; j < HowManyRotationsToCheck; j++) { + for (int j = 0; j < HowManyRotationsToCheck; j++) + { sop.transform.Rotate(new Vector3(degreeIncrement, 0, 0), Space.Self); Vector3 Offset = oabb.ClosestPoint( @@ -416,7 +467,8 @@ bool AlwaysPlaceUpright sop.transform.rotation = oldRotation; // now add EVEN more points by rotating the z axis at this current y rotation - for (int j = 0; j < HowManyRotationsToCheck; j++) { + for (int j = 0; j < HowManyRotationsToCheck; j++) + { sop.transform.Rotate(new Vector3(0, 0, degreeIncrement), Space.Self); Vector3 Offset = oabb.ClosestPoint( @@ -443,7 +495,8 @@ bool AlwaysPlaceUpright } } - foreach (RotationAndDistanceValues quat in ToCheck) { + foreach (RotationAndDistanceValues quat in ToCheck) + { // if spawn area is clear, spawn it and return true that we spawned it if ( CheckSpawnArea( @@ -452,14 +505,16 @@ bool AlwaysPlaceUpright 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.rotation = quat.rotation; //ensure transforms are synced - if (!Physics.autoSyncTransforms) { + if (!Physics.autoSyncTransforms) + { Physics.SyncTransforms(); } @@ -469,12 +524,14 @@ bool AlwaysPlaceUpright // Check the ReceptacleBox's Sim Object component to see what Type it is. Then check to // see if the type is the kind where the Object placed must be completely contained or just the bottom 4 corners contained int HowManyCornersToCheck = 0; - if (ReceptacleRestrictions.OnReceptacles.Contains(rsp.ParentSimObjPhys.ObjType)) { + if (ReceptacleRestrictions.OnReceptacles.Contains(rsp.ParentSimObjPhys.ObjType)) + { // check that only the bottom 4 corners are in bounds HowManyCornersToCheck = 4; } - if (ReceptacleRestrictions.InReceptacles.Contains(rsp.ParentSimObjPhys.ObjType)) { + if (ReceptacleRestrictions.InReceptacles.Contains(rsp.ParentSimObjPhys.ObjType)) + { // check that all 8 corners are within bounds HowManyCornersToCheck = 8; } @@ -483,7 +540,8 @@ bool AlwaysPlaceUpright ReceptacleRestrictions.InReceptaclesThatOnlyCheckBottomFourCorners.Contains( rsp.ParentSimObjPhys.ObjType ) - ) { + ) + { // only check bottom 4 corners even though the action is PlaceIn HowManyCornersToCheck = 4; } @@ -495,7 +553,8 @@ 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) { + 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... @@ -513,14 +572,17 @@ bool AlwaysPlaceUpright // 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 - for (int i = 0; i < 8; i++) { - if (rsp.Script.CheckIfPointIsInsideReceptacleTriggerBox(SpawnCorners[i])) { + for (int i = 0; i < 8; i++) + { + if (rsp.Script.CheckIfPointIsInsideReceptacleTriggerBox(SpawnCorners[i])) + { CornerCount++; } } // if not enough corners are inside the receptacle, abort - if (CornerCount < HowManyCornersToCheck) { + if (CornerCount < HowManyCornersToCheck) + { sop.transform.rotation = originalRot; sop.transform.position = originalPos; return false; @@ -528,8 +590,10 @@ bool AlwaysPlaceUpright // one final check, make sure all corners of object are "above" the receptacle box in question, so we // dont spawn stuff half on a table and it falls over - foreach (Vector3 v in SpawnCorners) { - if (!rsp.Script.CheckIfPointIsAboveReceptacleTriggerBox(v)) { + foreach (Vector3 v in SpawnCorners) + { + if (!rsp.Script.CheckIfPointIsAboveReceptacleTriggerBox(v)) + { sop.transform.rotation = originalRot; sop.transform.position = originalPos; return false; @@ -538,12 +602,14 @@ bool AlwaysPlaceUpright // set true if we want objects to be stationary when placed. (if placed on uneven surface, object remains stationary) // if false, once placed the object will resolve with physics (if placed on uneven surface object might slide or roll) - if (PlaceStationary) { + 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 - ) { + ) + { rsp.ParentSimObjPhys.GetComponent().isKinematic = true; } @@ -561,12 +627,14 @@ bool AlwaysPlaceUpright 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 { + else + { // if not placing stationary, put all objects under Objects game object GameObject topObject = GameObject.Find("Objects"); // parent to the Objects transform @@ -580,7 +648,8 @@ bool AlwaysPlaceUpright sop.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.Receptacle ) - ) { + ) + { sop.DropContainedObjects( reparentContainedObjects: true, forceKinematic: false @@ -609,13 +678,15 @@ public Collider ColliderHitByObjectInSpawnArea( 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) { + if (spawningInHand) + { layermask = LayerMask.GetMask( "SimObjVisible", "Procedural1", @@ -623,7 +694,9 @@ bool spawningInHand "Procedural3", "Procedural0" ); - } else { + } + 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", @@ -638,16 +711,19 @@ bool spawningInHand // get list of all active colliders of sim object, then toggle them off for now // disable all colliders of the object being placed List colsToDisable = new List(); - foreach (Collider g in simObj.MyColliders) { + foreach (Collider g in simObj.MyColliders) + { // only track this collider if it's enabled by default // some objects, like houseplants, might have colliders in their simObj.MyColliders that are disabled - if (g.enabled) { + if (g.enabled) + { colsToDisable.Add(g); } } // disable collision before moving to check the spawn area - foreach (Collider c in colsToDisable) { + foreach (Collider c in colsToDisable) + { c.enabled = false; } @@ -732,7 +808,8 @@ bool spawningInHand simObj.transform.rotation = originalRot; // re-enable the collision after returning in place - foreach (Collider c in colsToDisable) { + foreach (Collider c in colsToDisable) + { c.enabled = true; } @@ -746,12 +823,17 @@ bool spawningInHand ); // if a collider was hit, then the space is not clear to spawn - if (hitColliders.Length > 0) { + if (hitColliders.Length > 0) + { // filter out any AgentTriggerBoxes because those should be ignored now - foreach (Collider c in hitColliders) { - if (c.isTrigger && c.GetComponentInParent()) { + foreach (Collider c in hitColliders) + { + if (c.isTrigger && c.GetComponentInParent()) + { continue; - } else { + } + else + { return c; } } @@ -766,7 +848,8 @@ public bool CheckSpawnArea( Vector3 position, Quaternion rotation, bool spawningInHand - ) { + ) + { var hitColliders = ColliderHitByObjectInSpawnArea( simObj, position, @@ -778,9 +861,11 @@ bool spawningInHand } #if UNITY_EDITOR - void OnDrawGizmos() { + void OnDrawGizmos() + { Gizmos.color = Color.red; - if (m_Started) { + if (m_Started) + { Matrix4x4 cubeTransform = Matrix4x4.TRS(gizmopos, gizmoquaternion, gizmoscale); Matrix4x4 oldGizmosMatrix = Gizmos.matrix; @@ -791,10 +876,13 @@ void OnDrawGizmos() { Gizmos.matrix = oldGizmosMatrix; } - if (SpawnCorners != null) { + if (SpawnCorners != null) + { int count = 0; - foreach (Vector3 point in SpawnCorners) { - if (count > 3) { + foreach (Vector3 point in SpawnCorners) + { + if (count > 3) + { Gizmos.color = Color.cyan; } diff --git a/unity/Assets/Scripts/JavaScriptInterface.cs b/unity/Assets/Scripts/JavaScriptInterface.cs index e4da39e082..11522266e3 100644 --- a/unity/Assets/Scripts/JavaScriptInterface.cs +++ b/unity/Assets/Scripts/JavaScriptInterface.cs @@ -3,7 +3,8 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public class JavaScriptInterface : MonoBehaviour { +public class JavaScriptInterface : MonoBehaviour +{ // IL2CPP throws exceptions about SendMetadata and Init not existing // so the body is only used for WebGL #if UNITY_WEBGL diff --git a/unity/Assets/Scripts/KinovaArmAgentController.cs b/unity/Assets/Scripts/KinovaArmAgentController.cs index 831dccb339..30143fc67d 100644 --- a/unity/Assets/Scripts/KinovaArmAgentController.cs +++ b/unity/Assets/Scripts/KinovaArmAgentController.cs @@ -6,15 +6,18 @@ using UnityEngine; using UnityEngine.AI; -namespace UnityStandardAssets.Characters.FirstPerson { - public partial class KinovaArmAgentController : ArmAgentController { +namespace UnityStandardAssets.Characters.FirstPerson +{ + public partial class KinovaArmAgentController : ArmAgentController + { public KinovaArmAgentController( BaseAgentComponent baseAgentComponent, AgentManager agentManager ) : base(baseAgentComponent, agentManager) { } - public override ActionFinished InitializeBody(ServerAction initializeAction) { + public override ActionFinished InitializeBody(ServerAction initializeAction) + { base.InitializeBody(initializeAction); Debug.Log("initializing arm"); IKArm.SetActive(true); @@ -33,9 +36,11 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { return ActionFinished.Success; } - private IK_Robot_Arm_Controller getArmImplementation() { + private IK_Robot_Arm_Controller getArmImplementation() + { IK_Robot_Arm_Controller arm = GetComponentInChildren(); - if (arm == null) { + 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." @@ -44,7 +49,8 @@ private IK_Robot_Arm_Controller getArmImplementation() { return arm; } - protected override ArmController getArm() { + protected override ArmController getArm() + { return getArmImplementation(); } @@ -55,7 +61,8 @@ public void TeleportArm( float? elbowOrientation = null, bool worldRelative = false, bool forceAction = false - ) { + ) + { GameObject heightManip = this.GetComponent().IKArm; GameObject posRotManip = this.GetComponent() .IKArm.GetComponent() @@ -76,19 +83,23 @@ public void TeleportArm( float oldElbowOrientation = elbowManip.transform.localEulerAngles.z; // establish defaults in the absence of inputs - if (position == null) { + if (position == null) + { position = new Vector3(0f, 0f, 0.4f); } - if (rotation == null) { + if (rotation == null) + { rotation = new Vector4(1f, 0f, 0f, 0f); } - if (armHeight == null) { + if (armHeight == null) + { armHeight = -0.003f; } - if (elbowOrientation == null) { + if (elbowOrientation == null) + { elbowOrientation = 0f; } @@ -100,13 +111,16 @@ public void TeleportArm( ); // teleport arm-elements - if (!worldRelative) { + 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) ); - } else { + } + else + { posRotManip.transform.position = (Vector3)position; posRotManip.transform.rotation = Quaternion.AngleAxis( ((Vector4)rotation).w % 360, @@ -120,7 +134,8 @@ public void TeleportArm( (float)elbowOrientation ); - if (Arm.IsArmColliding() && !forceAction) { + if (Arm.IsArmColliding() && !forceAction) + { errorMessage = "collision detected at desired transform, cannot teleport"; heightManip.transform.localPosition = new Vector3( heightManip.transform.localPosition.x, @@ -138,7 +153,9 @@ public void TeleportArm( oldElbowOrientation ); actionFinished(false); - } else { + } + else + { actionFinished(true); } } @@ -163,10 +180,12 @@ public void RotateWristAroundHeldObject( float roll = 0f, float speed = 10f, bool returnToStart = true - ) { + ) + { var arm = getArm(); - if (arm.heldObjects.Count == 1) { + if (arm.heldObjects.Count == 1) + { SimObjPhysics sop = arm.heldObjects.Keys.ToArray()[0]; RotateWristAroundPoint( point: sop.gameObject.transform.position, @@ -176,7 +195,9 @@ public void RotateWristAroundHeldObject( speed: speed, returnToStart: returnToStart ); - } else { + } + else + { actionFinished( success: false, errorMessage: $"Cannot RotateWristAroundHeldObject when holding" @@ -197,7 +218,8 @@ public void RotateWristAroundPoint( float roll = 0f, float speed = 10f, bool returnToStart = true - ) { + ) + { IK_Robot_Arm_Controller arm = getArmImplementation(); arm.rotateWristAroundPoint( @@ -220,7 +242,8 @@ 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( @@ -235,7 +258,8 @@ public void RotateElbowRelative(float degrees, float speed = 10f, bool returnToS /* 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 929b3270d5..469b412d8c 100644 --- a/unity/Assets/Scripts/Lamp.cs +++ b/unity/Assets/Scripts/Lamp.cs @@ -3,7 +3,8 @@ using UnityEngine; [ExecuteInEditMode] -public class Lamp : MonoBehaviour { +public class Lamp : MonoBehaviour +{ public SimObj ParentObj; public bool EditorOn = false; public bool OnByDefault = true; @@ -13,29 +14,38 @@ public class Lamp : MonoBehaviour { public Material OffMaterial; public Light[] Lights; - void OnEnable() { + void OnEnable() + { ParentObj = gameObject.GetComponent(); - if (ParentObj == null) { + if (ParentObj == null) + { ParentObj = gameObject.AddComponent(); } - if (!Application.isPlaying) { + if (!Application.isPlaying) + { Animator a = ParentObj.gameObject.GetComponent(); - if (a == null) { + if (a == null) + { a = ParentObj.gameObject.AddComponent(); a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; } - } else { - if (OnByDefault) { + } + else + { + if (OnByDefault) + { ParentObj.Animator.SetBool("AnimState1", true); } } } - void Update() { + void Update() + { bool on = EditorOn; - if (Application.isPlaying) { + if (Application.isPlaying) + { on = ParentObj.Animator.GetBool("AnimState1"); } @@ -45,7 +55,8 @@ void Update() { || OnMaterial == null || OffMaterial == null || Lights.Length == 0 - ) { + ) + { Debug.LogError("Required item null in lamp " + name); return; } @@ -53,7 +64,8 @@ void Update() { Material[] sharedMats = LampshadeRenderer.sharedMaterials; sharedMats[LampshadeMatIndex] = on ? OnMaterial : OffMaterial; LampshadeRenderer.sharedMaterials = sharedMats; - foreach (Light l in Lights) { + foreach (Light l in Lights) + { l.enabled = on; } } diff --git a/unity/Assets/Scripts/Laptop.cs b/unity/Assets/Scripts/Laptop.cs index 4d30401009..6e0cd7d868 100644 --- a/unity/Assets/Scripts/Laptop.cs +++ b/unity/Assets/Scripts/Laptop.cs @@ -3,7 +3,8 @@ using UnityEngine; [ExecuteInEditMode] -public class Laptop : MonoBehaviour { +public class Laptop : MonoBehaviour +{ public SimObj SimObjParent; public Transform[] PivotTransforms; public Renderer[] ScreenRenderers; @@ -24,24 +25,32 @@ public class Laptop : MonoBehaviour { bool displayedError; - void OnEnable() { + void OnEnable() + { Television = GameObject.FindObjectOfType(); } - void Update() { - if (Television != null) { + void Update() + { + if (Television != null) + { Television.SyncedScreenMat = OnScreenMat; } Vector3 rot = ClosedRot; Material mat = OffScreenMat; - if (!Application.isPlaying) { + if (!Application.isPlaying) + { rot = EditorOpen ? OpenRot : ClosedRot; mat = EditorOn ? OnScreenMat : OffScreenMat; - } else { - if (SimObjParent == null || OffScreenMat == null || OnScreenMat == null) { - if (!displayedError) { + } + else + { + if (SimObjParent == null || OffScreenMat == null || OnScreenMat == null) + { + if (!displayedError) + { Debug.LogError("Component null in latop " + name); displayedError = true; } @@ -53,7 +62,8 @@ void Update() { // 2 - Open, Off // 3 - Closed, On - switch (animState) { + switch (animState) + { case 1: default: rot = ClosedRot; @@ -72,7 +82,8 @@ void Update() { } } - for (int i = 0; i < ScreenRenderers.Length; i++) { + for (int i = 0; i < ScreenRenderers.Length; i++) + { Material[] sharedMats = ScreenRenderers[i].sharedMaterials; sharedMats[ScreenMatIndexes[i]] = mat; ScreenRenderers[i].sharedMaterials = sharedMats; diff --git a/unity/Assets/Scripts/LightSwitch.cs b/unity/Assets/Scripts/LightSwitch.cs index 5933a1e353..fad8d098ab 100644 --- a/unity/Assets/Scripts/LightSwitch.cs +++ b/unity/Assets/Scripts/LightSwitch.cs @@ -3,7 +3,8 @@ using UnityEngine; [ExecuteInEditMode] -public class LightSwitch : MonoBehaviour { +public class LightSwitch : MonoBehaviour +{ public SimObj ParentObj; public bool OnByDefault = true; public bool EditorOn = false; @@ -16,43 +17,54 @@ public class LightSwitch : MonoBehaviour { Color groundColor; Color skyColor; - void OnEnable() { + void OnEnable() + { equatorColor = RenderSettings.ambientEquatorColor; groundColor = RenderSettings.ambientGroundColor; skyColor = RenderSettings.ambientSkyColor; ParentObj = gameObject.GetComponent(); - if (ParentObj == null) { + if (ParentObj == null) + { ParentObj = gameObject.AddComponent(); } - if (!Application.isPlaying) { + if (!Application.isPlaying) + { Animator a = ParentObj.gameObject.GetComponent(); - if (a == null) { + if (a == null) + { a = ParentObj.gameObject.AddComponent(); a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; } - } else { - if (OnByDefault) { + } + else + { + if (OnByDefault) + { ParentObj.Animator.SetBool("AnimState1", true); } } } - void Update() { + void Update() + { // print(SourceRenderers.Length); bool on = EditorOn; - if (Application.isPlaying) { + if (Application.isPlaying) + { on = ParentObj.Animator.GetBool("AnimState1"); } - for (int i = 0; i < Lights.Length; i++) { + for (int i = 0; i < Lights.Length; i++) + { Lights[i].enabled = on; } - for (int i = 0; i < SourceRenderers.Length; i++) { + for (int i = 0; i < SourceRenderers.Length; i++) + { // print(i); Material[] sharedMats = SourceRenderers[i].sharedMaterials; sharedMats[SourceMatIndexes[i]] = on ? OnMaterial : OffMaterial; diff --git a/unity/Assets/Scripts/ListExtensions.cs b/unity/Assets/Scripts/ListExtensions.cs index f0b95d93f9..aa07b2ae55 100644 --- a/unity/Assets/Scripts/ListExtensions.cs +++ b/unity/Assets/Scripts/ListExtensions.cs @@ -26,14 +26,18 @@ using System.Linq; using UnityEngine; -public static class ListExtensions { - public static IList Shuffle(this IList list) { +public static class ListExtensions +{ + public static IList Shuffle(this IList list) + { return list.ShallowCopy().Shuffle_(); } - public static IList Shuffle_(this IList list) { + public static IList Shuffle_(this IList list) + { int n = list.Count; - while (n > 1) { + while (n > 1) + { n--; int k = UnityEngine.Random.Range(0, n + 1); T value = list[k]; @@ -43,14 +47,17 @@ public static IList Shuffle_(this IList list) { return list; } - public static IList Shuffle_(this IList list, int seed) { + public static IList Shuffle_(this IList list, int seed) + { // NOTE: this doesn't use systemRandom return list.Shuffle_(new System.Random(seed)); } - public static IList Shuffle_(this IList list, System.Random rng) { + public static IList Shuffle_(this IList list, System.Random rng) + { int n = list.Count; - while (n > 1) { + while (n > 1) + { n--; int k = rng.Next(n + 1); T value = list[k]; @@ -60,7 +67,8 @@ public static IList Shuffle_(this IList list, System.Random rng) { return list; } - public static IList ShallowCopy(this IList listToCopy) { + public static IList ShallowCopy(this IList listToCopy) + { return listToCopy.Select(item => item).ToList(); } } diff --git a/unity/Assets/Scripts/LocobotFPSAgentController.cs b/unity/Assets/Scripts/LocobotFPSAgentController.cs index 4d0048b96d..32860a5e3d 100644 --- a/unity/Assets/Scripts/LocobotFPSAgentController.cs +++ b/unity/Assets/Scripts/LocobotFPSAgentController.cs @@ -13,8 +13,10 @@ using UnityStandardAssets.ImageEffects; using UnityStandardAssets.Utility; -namespace UnityStandardAssets.Characters.FirstPerson { - public class LocobotFPSAgentController : BaseFPSAgentController { +namespace UnityStandardAssets.Characters.FirstPerson +{ + public class LocobotFPSAgentController : BaseFPSAgentController + { protected bool applyActionNoise = true; protected float movementGaussianMu = 0.001f; protected float movementGaussianSigma = 0.005f; @@ -28,7 +30,8 @@ AgentManager agentManager ) : base(baseAgentComponent, agentManager) { } - public override ActionFinished InitializeBody(ServerAction initializeAction) { + public override ActionFinished InitializeBody(ServerAction initializeAction) + { // toggle FirstPersonCharacterCull VisibilityCapsule = BotVisCap; @@ -56,36 +59,47 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { 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)) { + if (Mathf.Approximately(initializeAction.maxUpwardLookAngle, 0.0f)) + { this.maxUpwardLookAngle = 30f; - } else { + } + else + { this.maxUpwardLookAngle = initializeAction.maxUpwardLookAngle; } - if (Mathf.Approximately(initializeAction.maxDownwardLookAngle, 0.0f)) { + if (Mathf.Approximately(initializeAction.maxDownwardLookAngle, 0.0f)) + { this.maxDownwardLookAngle = 30f; - } else { + } + else + { this.maxDownwardLookAngle = initializeAction.maxDownwardLookAngle; } return ActionFinished.Success; } - public new void Initialize(ServerAction action) { + public new void Initialize(ServerAction action) + { this.applyActionNoise = action.applyActionNoise; - if (action.movementGaussianMu > 0.0f) { + if (action.movementGaussianMu > 0.0f) + { this.movementGaussianMu = action.movementGaussianMu; } - if (action.movementGaussianSigma > 0.0f) { + if (action.movementGaussianSigma > 0.0f) + { this.movementGaussianSigma = action.movementGaussianSigma; } - if (action.rotateGaussianMu > 0.0f) { + if (action.rotateGaussianMu > 0.0f) + { this.rotateGaussianMu = action.rotateGaussianMu; } - if (action.rotateGaussianSigma > 0.0f) { + if (action.rotateGaussianSigma > 0.0f) + { this.rotateGaussianSigma = action.rotateGaussianSigma; } @@ -103,7 +117,8 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { if ( UnityEngine.SceneManagement.SceneManager.GetActiveScene().name == "FloorPlan_Train_Generated" - ) { + ) + { GenerateRoboTHOR colorChangeComponent = physicsSceneManager.GetComponent(); colorChangeComponent.GenerateConfig(agentTransform: transform); @@ -111,7 +126,8 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { } // reset visible objects while in editor, for debug purposes only - private void LateUpdate() { + private void LateUpdate() + { #if UNITY_EDITOR || UNITY_WEBGL VisibleSimObjPhysics = VisibleSimObjs(); #endif @@ -123,14 +139,19 @@ public void MoveRelative( float z = 0f, float noise = 0f, bool forceAction = false - ) { - if (!moveMagnitude.HasValue) { + ) + { + if (!moveMagnitude.HasValue) + { moveMagnitude = gridSize; - } else if (moveMagnitude.Value <= 0f) { + } + else if (moveMagnitude.Value <= 0f) + { throw new InvalidOperationException("moveMagnitude must be null or >= 0."); } - if (!allowHorizontalMovement && Math.Abs(x) > 0) { + if (!allowHorizontalMovement && Math.Abs(x) > 0) + { throw new InvalidOperationException( "Controller does not support horizontal movement. Set AllowHorizontalMovement to true on the Controller." ); @@ -138,9 +159,11 @@ public void MoveRelative( var moveLocal = new Vector3(x, 0, z); float xzMag = moveLocal.magnitude; - if (xzMag > 1e-5f) { + if (xzMag > 1e-5f) + { // rotate a small amount with every movement since robot doesn't always move perfectly straight - if (this.applyActionNoise) { + if (this.applyActionNoise) + { var rotateNoise = (float) systemRandom.NextGaussian(rotateGaussianMu, rotateGaussianSigma / 2.0f); transform.rotation = @@ -159,23 +182,30 @@ public void MoveRelative( forceAction: forceAction ) ); - } else { + } + else + { errorMessage = "either x or z must be != 0 for the MoveRelative action"; actionFinished(false); } } // NOOP action to allow evaluation to know that the episode has finished - public void Stop() { + public void Stop() + { // i don't know why, but we have two no-op actions so here we go base.Pass(); } - public override void LookDown(ServerAction action) { + public override void LookDown(ServerAction action) + { // default degree increment to 30 - if (action.degrees == 0) { + if (action.degrees == 0) + { action.degrees = 30f; - } else { + } + else + { errorMessage = "Must have degrees == 0 for now."; actionFinished(false); return; @@ -185,7 +215,8 @@ public override void LookDown(ServerAction action) { // this is to prevent too small of a degree increment change that could cause float imprecision action.degrees = Mathf.Round(action.degrees * 10.0f) / 10.0f; - if (!checkForUpDownAngleLimit("down", action.degrees)) { + if (!checkForUpDownAngleLimit("down", action.degrees)) + { errorMessage = "can't look down beyond " + maxDownwardLookAngle @@ -199,11 +230,15 @@ public override void LookDown(ServerAction action) { return; } - public override void LookUp(ServerAction action) { + public override void LookUp(ServerAction action) + { // default degree increment to 30 - if (action.degrees == 0) { + if (action.degrees == 0) + { action.degrees = 30f; - } else { + } + else + { errorMessage = "Must have degrees == 0 for now."; actionFinished(false); return; @@ -213,7 +248,8 @@ public override void LookUp(ServerAction action) { // this is to prevent too small of a degree increment change that could cause float imprecision action.degrees = Mathf.Round(action.degrees * 10.0f) / 10.0f; - if (!checkForUpDownAngleLimit("up", action.degrees)) { + if (!checkForUpDownAngleLimit("up", action.degrees)) + { errorMessage = "can't look up beyond " + maxUpwardLookAngle @@ -227,13 +263,16 @@ public override void LookUp(ServerAction action) { } // NOTE: This is necessary to avoid an ambiguous action between base and stochastic. - public void Rotate(Vector3 rotation) { + public void Rotate(Vector3 rotation) + { Rotate(rotation: rotation, noise: 0); } - public void Rotate(Vector3 rotation, float noise, bool manualInteract = false) { + public void Rotate(Vector3 rotation, float noise, bool manualInteract = false) + { // only default hand if not manually Interacting with things - if (!manualInteract) { + if (!manualInteract) + { DefaultAgentHand(); } @@ -249,20 +288,24 @@ public void Rotate(Vector3 rotation, float noise, bool manualInteract = false) { actionFinished(true); } - public void RotateRight(ServerAction action) { + public void RotateRight(ServerAction action) + { float rotationAmount = this.rotateStepDegrees; - if (action.degrees != 0.0f) { + if (action.degrees != 0.0f) + { rotationAmount = action.degrees; } Rotate(rotation: new Vector3(0, rotationAmount, 0)); } - public void RotateLeft(ServerAction action) { + public void RotateLeft(ServerAction action) + { float rotationAmount = this.rotateStepDegrees; - if (action.degrees != 0.0f) { + if (action.degrees != 0.0f) + { rotationAmount = action.degrees; } @@ -284,7 +327,8 @@ public void Teleport( Vector3? rotation = null, float? horizon = null, bool forceAction = false - ) { + ) + { Teleport( position: new Vector3(x, y, z), rotation: rotation, @@ -298,7 +342,8 @@ public void Teleport( Vector3? rotation = null, float? horizon = null, bool forceAction = false - ) { + ) + { base.teleport( position: position, rotation: rotation, @@ -324,7 +369,8 @@ public void TeleportFull( Vector3? rotation, float? horizon, bool forceAction = false - ) { + ) + { TeleportFull( position: new Vector3(x, y, z), rotation: rotation, @@ -338,7 +384,8 @@ public void TeleportFull( Vector3? rotation, float? horizon, bool forceAction = false - ) { + ) + { base.teleportFull( position: position, rotation: rotation, @@ -353,7 +400,8 @@ public void MoveAhead( float? moveMagnitude = null, float noise = 0f, bool forceAction = false - ) { + ) + { MoveRelative( z: 1.0f, moveMagnitude: moveMagnitude, @@ -366,7 +414,8 @@ public void MoveBack( float? moveMagnitude = null, float noise = 0f, bool forceAction = false - ) { + ) + { MoveRelative( z: -1.0f, moveMagnitude: moveMagnitude, @@ -379,8 +428,10 @@ public void MoveRight( float? moveMagnitude = null, float noise = 0f, bool forceAction = false - ) { - if (!allowHorizontalMovement) { + ) + { + if (!allowHorizontalMovement) + { throw new InvalidOperationException( "Controller does not support horizontal movement by default. Set AllowHorizontalMovement to true on the Controller." ); @@ -397,8 +448,10 @@ public void MoveLeft( float? moveMagnitude = null, float noise = 0f, bool forceAction = false - ) { - if (!allowHorizontalMovement) { + ) + { + if (!allowHorizontalMovement) + { throw new InvalidOperationException( "Controller does not support horizontal movement by default. Set AllowHorizontalMovement to true on the Controller." ); @@ -411,14 +464,16 @@ public void MoveLeft( ); } - protected float GetMoveMagnitudeWithNoise(float moveMagnitude, float noise) { + protected float GetMoveMagnitudeWithNoise(float moveMagnitude, float noise) + { float internalNoise = applyActionNoise ? (float)systemRandom.NextGaussian(movementGaussianMu, movementGaussianSigma) : 0; return moveMagnitude + noise + (float)internalNoise; } - protected float GetRotateMagnitudeWithNoise(Vector3 rotation, float noise) { + protected float GetRotateMagnitudeWithNoise(Vector3 rotation, float noise) + { float internalNoise = applyActionNoise ? (float)systemRandom.NextGaussian(rotateGaussianMu, rotateGaussianSigma) : 0; diff --git a/unity/Assets/Scripts/Microwave.cs b/unity/Assets/Scripts/Microwave.cs index faca2ad2f9..1677ad3427 100644 --- a/unity/Assets/Scripts/Microwave.cs +++ b/unity/Assets/Scripts/Microwave.cs @@ -3,7 +3,8 @@ using UnityEngine; //[ExecuteInEditMode] -public class Microwave : MonoBehaviour { +public class Microwave : MonoBehaviour +{ public Transform Door; public Vector3 DoorOpenRot; public Vector3 DoorClosedRot; @@ -20,15 +21,21 @@ public class Microwave : MonoBehaviour { bool displayedError = false; - public void Update() { - if (!Application.isPlaying) { + public void Update() + { + if (!Application.isPlaying) + { Door.localEulerAngles = EditorOpen ? DoorOpenRot : DoorClosedRot; Material[] sharedMats = GlassRenderer.sharedMaterials; sharedMats[MatIndex] = EditorOn ? OnGlassMat : OffGlassMat; GlassRenderer.sharedMaterials = sharedMats; - } else { - if (SimObjParent == null || GlassRenderer == null || Door == null) { - if (!displayedError) { + } + else + { + if (SimObjParent == null || GlassRenderer == null || Door == null) + { + if (!displayedError) + { Debug.LogError("Component null in microwave " + name); displayedError = true; } @@ -41,7 +48,8 @@ public void Update() { // 3 - Closed, On Material[] sharedMats = GlassRenderer.sharedMaterials; bool waitForDoorToClose = false; - switch (animState) { + switch (animState) + { case 1: default: targetDoorRotation = DoorClosedRot; @@ -60,7 +68,8 @@ public void Update() { break; } - switch (SceneManager.Current.AnimationMode) { + switch (SceneManager.Current.AnimationMode) + { case SceneAnimationMode.Smooth: Quaternion doorStartRotation = Quaternion.identity; @@ -79,11 +88,13 @@ public void Update() { Door.localEulerAngles, targetDoorRotation ); - if (distanceToTarget >= 360f) { + if (distanceToTarget >= 360f) + { distanceToTarget -= 360f; } - if (!waitForDoorToClose || distanceToTarget < 0.005f) { + if (!waitForDoorToClose || distanceToTarget < 0.005f) + { GlassRenderer.sharedMaterials = sharedMats; } diff --git a/unity/Assets/Scripts/MinimalFPSController.cs b/unity/Assets/Scripts/MinimalFPSController.cs index d074dc0a22..f4e3fa5d49 100644 --- a/unity/Assets/Scripts/MinimalFPSController.cs +++ b/unity/Assets/Scripts/MinimalFPSController.cs @@ -12,16 +12,20 @@ using UnityStandardAssets.Utility; using Random = UnityEngine.Random; -namespace UnityStandardAssets.Characters.FirstPerson { +namespace UnityStandardAssets.Characters.FirstPerson +{ [RequireComponent(typeof(CharacterController))] - public class MinimalFPSController : DebugFPSAgentController { + public class MinimalFPSController : DebugFPSAgentController + { private GameObject BackgroundUI; private GameObject Crosshair; private GameObject TargetText; private GameObject ThrowForceBar; - MinimalFPSController() { - this.m_MouseLook = new MouseLook { + MinimalFPSController() + { + this.m_MouseLook = new MouseLook + { XSensitivity = 2, YSensitivity = 2, clampVerticalRotation = true, @@ -37,9 +41,11 @@ public class MinimalFPSController : DebugFPSAgentController { this.enableHighlightShader = false; } - public new void HideHUD() { + public new void HideHUD() + { InputMode_Text = GameObject.Find("DebugCanvasPhysics/InputModeText"); - if (InputMode_Text != null) { + if (InputMode_Text != null) + { InputMode_Text.SetActive(false); } // InputFieldObj.SetActive(false); @@ -59,14 +65,18 @@ public class MinimalFPSController : DebugFPSAgentController { TargetText.GetComponent().enabled = false; } - public void ShowHUD() { - if (InputMode_Text != null) { + public void ShowHUD() + { + if (InputMode_Text != null) + { InputMode_Text.SetActive(true); } - if (InputFieldObj != null) { + if (InputFieldObj != null) + { InputFieldObj.SetActive(true); } - if (BackgroundUI != null) { + if (BackgroundUI != null) + { BackgroundUI.SetActive(true); } @@ -78,14 +88,16 @@ public void ShowHUD() { TargetText.GetComponent().enabled = true; } - public new void OnEnable() { + public new void OnEnable() + { FPSEnabled = true; Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; InputMode_Text = GameObject.Find("DebugCanvasPhysics/InputModeText"); InputFieldObj = GameObject.Find("DebugCanvasPhysics/InputField"); - if (InputMode_Text) { + if (InputMode_Text) + { InputMode_Text.GetComponent().text = "FPS Mode"; } @@ -95,18 +107,21 @@ public void ShowHUD() { HideHUD(); } - public new void OnDisable() { + public new void OnDisable() + { DisableMouseControl(); ShowHUD(); } - public new void EnableMouseControl() { + public new void EnableMouseControl() + { FPSEnabled = true; Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; } - public new void DisableMouseControl() { + public new void DisableMouseControl() + { Debug.Log("Disabled mouse"); FPSEnabled = false; Cursor.visible = true; diff --git a/unity/Assets/Scripts/Mirror.cs b/unity/Assets/Scripts/Mirror.cs index 8359d471c0..aef9fa2ac7 100644 --- a/unity/Assets/Scripts/Mirror.cs +++ b/unity/Assets/Scripts/Mirror.cs @@ -3,21 +3,26 @@ using UnityEngine; [ExecuteInEditMode] -public class Mirror : MonoBehaviour { +public class Mirror : MonoBehaviour +{ public SimObj ParentObj; public bool EditorDirty = false; public GameObject DirtObject; - void OnEnable() { + void OnEnable() + { ParentObj = gameObject.GetComponent(); - if (ParentObj == null) { + if (ParentObj == null) + { ParentObj = gameObject.AddComponent(); } ParentObj.Type = SimObjType.Mirror; - if (!Application.isPlaying) { + if (!Application.isPlaying) + { Animator a = ParentObj.gameObject.GetComponent(); - if (a == null) { + if (a == null) + { a = ParentObj.gameObject.AddComponent(); a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; @@ -25,13 +30,16 @@ void OnEnable() { } } - void Update() { + void Update() + { bool dirty = EditorDirty; - if (Application.isPlaying) { + if (Application.isPlaying) + { dirty = !ParentObj.Animator.GetBool("AnimState1"); } - if (DirtObject == null) { + if (DirtObject == null) + { Debug.LogError("Dirt object is null in mirror"); return; } diff --git a/unity/Assets/Scripts/NavMeshSetup.cs b/unity/Assets/Scripts/NavMeshSetup.cs index ccb4baf4a0..1b2663af8d 100644 --- a/unity/Assets/Scripts/NavMeshSetup.cs +++ b/unity/Assets/Scripts/NavMeshSetup.cs @@ -9,7 +9,8 @@ using UnityEditor; #endif -public class NavMeshSetup : MonoBehaviour { +public class NavMeshSetup : MonoBehaviour +{ public Transform goal; private UnityEngine.AI.NavMeshAgent navMeshAgent; private Transform hitPos; @@ -21,22 +22,26 @@ void Start() { } #if UNITY_EDITOR [UnityEditor.MenuItem("NavMesh/Save Full Scene Prefabs (all houdini scenes)")] - public static void SaveHoudiniScenePrefabs() { + 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 trainSceneNames.ForEach((x) => saveSceneAsPrefab(x)); } - private static void saveSceneAsPrefab(string sceneName) { + private static void saveSceneAsPrefab(string sceneName) + { EditorSceneManager.OpenScene(sceneName); GameObject sceneParent = new GameObject(); sceneParent.name = "Scene"; - foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject))) { + foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject))) + { 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; @@ -56,7 +61,8 @@ private static void saveSceneAsPrefab(string sceneName) { DestroyImmediate(sceneParent); } - private static List houdiniScenes(string pathPrefix = "Assets/Scenes") { + private static List houdiniScenes(string pathPrefix = "Assets/Scenes") + { // list hand chosen from Winson // gets iTHOR scene names var scenes = new List(); @@ -100,7 +106,8 @@ private static List houdiniScenes(string pathPrefix = "Assets/Scenes") { } [UnityEditor.MenuItem("NavMesh/Build NavMeshes for All Scenes")] - public static void Build() { + public static void Build() + { // var testSceneNames = GetRoboSceneNames(3, 5, "Val"); // var trainSceneNames = GetRoboSceneNames(12, 5, "Train"); @@ -129,7 +136,8 @@ public static void Build() { } [UnityEditor.MenuItem("NavMesh/Build NavMesh for Active Scene")] - public static void BuildForCurrentActiveScene() { + public static void BuildForCurrentActiveScene() + { BuildNavmeshForScene(EditorSceneManager.GetActiveScene().path); } @@ -138,10 +146,13 @@ private static List GetRoboSceneNames( 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++) { + for (var i = 1; i <= lastIndex; i++) + { + for (var j = 1; j <= lastSubIndex; j++) + { var scene = pathPrefix + "/FloorPlan_" + nameTemplate + i + "_" + j + ".unity"; scenes.Add(scene); } @@ -154,24 +165,29 @@ private static List GetSceneNames( int lastIndex, string nameTemplate = "", string pathPrefix = "Assets/Scenes" - ) { + ) + { var scenes = new List(); - for (var i = startIndex; i <= lastIndex; i++) { + for (var i = startIndex; i <= lastIndex; i++) + { var scene = pathPrefix + "/FloorPlan" + nameTemplate + i + "_physics.unity"; scenes.Add(scene); } return scenes; } - private static void BuildNavMeshesForScenes(IEnumerable sceneNames) { - foreach (var sceneName in sceneNames) { + private static void BuildNavMeshesForScenes(IEnumerable sceneNames) + { + foreach (var sceneName in sceneNames) + { EditorSceneManager.OpenScene(sceneName); GameObject.Find("DebugCanvasPhysics/Object"); // FindObjectsOfType() } } - private static void BuildNavmeshForScene(string sceneName) { + private static void BuildNavmeshForScene(string sceneName) + { //EditorSceneManager.OpenScene(sceneName); SetNavMeshNotWalkable(GameObject.Find("Objects")); SetNavMeshNotWalkable(GameObject.Find("Structure")); @@ -189,7 +205,8 @@ private static void BuildNavmeshForScene(string sceneName) { navmeshAgent.enabled = true; // The Editor bake interface does not take with parameters and could not be modified as of 2018.3 //var buildSettings = - new NavMeshBuildSettings() { + new NavMeshBuildSettings() + { agentTypeID = navmeshAgent.agentTypeID, agentRadius = 0.2f, agentHeight = 1.8f, @@ -204,13 +221,16 @@ private static void BuildNavmeshForScene(string sceneName) { EditorSceneManager.SaveScene(EditorSceneManager.GetActiveScene()); } - public static void SetNavMeshNotWalkable(GameObject hierarchy) { - for (int i = 0; i < hierarchy.transform.childCount; i++) { + 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 => { + .ForEach(meshRenderer => + { Debug.Log("Mesh Renderer " + meshRenderer.gameObject.name + " layer "); UnityEditor.GameObjectUtility.SetStaticEditorFlags( meshRenderer.gameObject, @@ -225,12 +245,14 @@ public static void SetNavMeshNotWalkable(GameObject hierarchy) { } } - public static void SetNavMeshWalkable(GameObject hierarchy) { + public static void SetNavMeshWalkable(GameObject hierarchy) + { // var objectHierarchy = hirerarchy.transform.FirstChildOrDefault(x => x.name.Contains("Floor")); hierarchy .GetComponentsInChildren() .ToList() - .ForEach(meshRenderer => { + .ForEach(meshRenderer => + { Debug.Log("Mesh Renderer " + meshRenderer.gameObject.name + " layer "); UnityEditor.GameObjectUtility.SetStaticEditorFlags( meshRenderer.gameObject, @@ -243,14 +265,17 @@ public static void SetNavMeshWalkable(GameObject hierarchy) { }); } - private static GameObject SearchForSimObjectType(SimObjType sot, GameObject hierarchy) { + private static GameObject SearchForSimObjectType(SimObjType sot, GameObject hierarchy) + { GameObject go = null; hierarchy .GetComponentsInChildren() .ToList() - .ForEach(sop => { - if (sop.ObjType == sot) { + .ForEach(sop => + { + if (sop.ObjType == sot) + { go = sop.gameObject; } }); diff --git a/unity/Assets/Scripts/NavMeshSurfaceExtended.cs b/unity/Assets/Scripts/NavMeshSurfaceExtended.cs index c228c05f24..d6b779be49 100644 --- a/unity/Assets/Scripts/NavMeshSurfaceExtended.cs +++ b/unity/Assets/Scripts/NavMeshSurfaceExtended.cs @@ -8,7 +8,8 @@ using UnityEditor.SceneManagement; #endif -public class NavMeshSurfaceExtended : NavMeshSurface { +public class NavMeshSurfaceExtended : NavMeshSurface +{ public NavMeshBuildSettings buildSettings { get; private set; } // static readonly List s_NavMeshSurfaces = new List(); @@ -20,14 +21,16 @@ public class NavMeshSurfaceExtended : NavMeshSurface { // } // Dictionary navmeshes = new Dictionary(); - public void BuildNavMesh(NavMeshBuildSettings buildSettings) { + 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) { + if (collectObjects == CollectObjects.All || collectObjects == CollectObjects.Children) + { sourcesBounds = CalculateWorldBounds(sources); } @@ -39,11 +42,13 @@ public void BuildNavMesh(NavMeshBuildSettings buildSettings) { transform.rotation ); - if (data != null) { + if (data != null) + { data.name = gameObject.name; RemoveData(); navMeshData = data; - if (isActiveAndEnabled) { + if (isActiveAndEnabled) + { AddData(); } } @@ -78,24 +83,30 @@ public void BuildNavMesh(NavMeshBuildSettings buildSettings) { - static Vector3 Abs(Vector3 v) { + static Vector3 Abs(Vector3 v) + { return new Vector3(Mathf.Abs(v.x), Mathf.Abs(v.y), Mathf.Abs(v.z)); } - Bounds CalculateWorldBounds(List sources) { + 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: { + 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; @@ -106,12 +117,12 @@ Bounds CalculateWorldBounds(List sources) { ) ); #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; - } + break; + } case NavMeshBuildSourceShape.Box: case NavMeshBuildSourceShape.Sphere: case NavMeshBuildSourceShape.Capsule: @@ -130,7 +141,8 @@ Bounds CalculateWorldBounds(List sources) { return result; } - static Bounds GetWorldBounds(Matrix4x4 mat, Bounds bounds) { + 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)); @@ -140,34 +152,43 @@ static Bounds GetWorldBounds(Matrix4x4 mat, Bounds bounds) { return new Bounds(worldPosition, worldSize); } - void AppendModifierVolumes(ref List sources) { + void AppendModifierVolumes(ref List sources) + { #if UNITY_EDITOR var myStage = StageUtility.GetStageHandle(gameObject); - if (!myStage.IsValid()) { + if (!myStage.IsValid()) + { return; } #endif // Modifiers List modifiers; - if (collectObjects == CollectObjects.Children) { + if (collectObjects == CollectObjects.Children) + { modifiers = new List( GetComponentsInChildren() ); modifiers.RemoveAll(x => !x.isActiveAndEnabled); - } else { + } + else + { modifiers = NavMeshModifierVolume.activeModifiers; } - foreach (var m in modifiers) { - if ((layerMask & (1 << m.gameObject.layer)) == 0) { + foreach (var m in modifiers) + { + if ((layerMask & (1 << m.gameObject.layer)) == 0) + { continue; } - if (!m.AffectsAgentType(agentTypeID)) { + if (!m.AffectsAgentType(agentTypeID)) + { continue; } #if UNITY_EDITOR - if (!myStage.Contains(m.gameObject)) { + if (!myStage.Contains(m.gameObject)) + { continue; } #endif @@ -188,24 +209,31 @@ void AppendModifierVolumes(ref List sources) { } } - public List CollectSources() { + public List CollectSources() + { var sources = new List(); var markups = new List(); List modifiers; - if (collectObjects == CollectObjects.Children) { + if (collectObjects == CollectObjects.Children) + { modifiers = new List(GetComponentsInChildren()); modifiers.RemoveAll(x => !x.isActiveAndEnabled); - } else { + } + else + { modifiers = NavMeshModifier.activeModifiers; } - foreach (var m in modifiers) { - if ((layerMask & (1 << m.gameObject.layer)) == 0) { + foreach (var m in modifiers) + { + if ((layerMask & (1 << m.gameObject.layer)) == 0) + { continue; } - if (!m.AffectsAgentType(agentTypeID)) { + if (!m.AffectsAgentType(agentTypeID)) + { continue; } @@ -218,8 +246,10 @@ public List CollectSources() { } #if UNITY_EDITOR - if (!EditorApplication.isPlaying) { - if (collectObjects == CollectObjects.All) { + if (!EditorApplication.isPlaying) + { + if (collectObjects == CollectObjects.All) + { UnityEditor.AI.NavMeshBuilder.CollectSourcesInStage( null, layerMask, @@ -229,7 +259,9 @@ public List CollectSources() { gameObject.scene, sources ); - } else if (collectObjects == CollectObjects.Children) { + } + else if (collectObjects == CollectObjects.Children) + { UnityEditor.AI.NavMeshBuilder.CollectSourcesInStage( transform, layerMask, @@ -239,7 +271,9 @@ public List CollectSources() { gameObject.scene, sources ); - } else if (collectObjects == CollectObjects.Volume) { + } + else if (collectObjects == CollectObjects.Volume) + { Matrix4x4 localToWorld = Matrix4x4.TRS( transform.position, transform.rotation, @@ -258,10 +292,12 @@ public List CollectSources() { sources ); } - } else + } + else #endif { - if (collectObjects == CollectObjects.All) { + if (collectObjects == CollectObjects.All) + { NavMeshBuilder.CollectSources( null, layerMask, @@ -270,7 +306,9 @@ public List CollectSources() { markups, sources ); - } else if (collectObjects == CollectObjects.Children) { + } + else if (collectObjects == CollectObjects.Children) + { NavMeshBuilder.CollectSources( transform, layerMask, @@ -279,7 +317,9 @@ public List CollectSources() { markups, sources ); - } else if (collectObjects == CollectObjects.Volume) { + } + else if (collectObjects == CollectObjects.Volume) + { Matrix4x4 localToWorld = Matrix4x4.TRS( transform.position, transform.rotation, @@ -297,7 +337,8 @@ public List CollectSources() { } } - if (ignoreNavMeshAgent) { + if (ignoreNavMeshAgent) + { sources.RemoveAll( (x) => ( @@ -307,7 +348,8 @@ public List CollectSources() { ); } - if (ignoreNavMeshObstacle) { + if (ignoreNavMeshObstacle) + { sources.RemoveAll( (x) => ( diff --git a/unity/Assets/Scripts/ObjaverseAnnotation.cs b/unity/Assets/Scripts/ObjaverseAnnotation.cs index 25ffcc27cd..b1ff8c370c 100644 --- a/unity/Assets/Scripts/ObjaverseAnnotation.cs +++ b/unity/Assets/Scripts/ObjaverseAnnotation.cs @@ -1,14 +1,17 @@ using System; using UnityEngine; -namespace Thor.Objaverse { - public enum Dataset { +namespace Thor.Objaverse +{ + public enum Dataset + { Objaverse1_0, ObjaversePlus, ObjaverseXL } - public class ObjaverseAnnotation : MonoBehaviour { + public class ObjaverseAnnotation : MonoBehaviour + { [SerializeField] public string ObjectCategory; diff --git a/unity/Assets/Scripts/ObjectHighlightController.cs b/unity/Assets/Scripts/ObjectHighlightController.cs index f3496b65f3..7ab2326436 100644 --- a/unity/Assets/Scripts/ObjectHighlightController.cs +++ b/unity/Assets/Scripts/ObjectHighlightController.cs @@ -12,9 +12,11 @@ using UnityStandardAssets.Utility; using Random = UnityEngine.Random; -namespace UnityStandardAssets.Characters.FirstPerson { +namespace UnityStandardAssets.Characters.FirstPerson +{ [Serializable] - public class HighlightConfig { + public class HighlightConfig + { public Color TextStrongColor; public Color TextFaintColor; public Color SoftOutlineColor; @@ -23,7 +25,8 @@ public class HighlightConfig { public float WithinReachOutlineThickness; } - public class ObjectHighlightController { + public class ObjectHighlightController + { [SerializeField] private Text TargetText = null; @@ -43,7 +46,8 @@ public class ObjectHighlightController { private bool DisplayTargetText = true; [SerializeField] - private HighlightConfig HighlightParams = new HighlightConfig { + private HighlightConfig HighlightParams = new HighlightConfig + { TextStrongColor = new Color(1.0f, 1.0f, 1.0f, 1.0f), TextFaintColor = new Color(197.0f / 255, 197.0f / 255, 197.0f / 255, 228.0f / 255), SoftOutlineColor = new Color(0.66f, 0.66f, 0.66f, 0.1f), @@ -85,45 +89,54 @@ public ObjectHighlightController( float maxChargeThrowSeconds = 1.4f, bool highlightWhileHolding = false, HighlightConfig highlightConfig = null - ) { + ) + { this.PhysicsController = physicsController; this.MinHighlightDistance = minHighlightDistance; this.MaxThrowForce = maxThrowForce; this.withHighlightShader = highlightEnabled; this.MaxChargeThrowSeconds = maxChargeThrowSeconds; this.highlightWhileHolding = highlightWhileHolding; - if (highlightConfig != null) { + if (highlightConfig != null) + { this.HighlightParams = highlightConfig; } m_Camera = Camera.main; TargetText = GameObject.Find("DebugCanvasPhysics/TargetText").GetComponent(); CrosshairText = GameObject.Find("DebugCanvasPhysics/Crosshair").GetComponent(); var throwForceBar = GameObject.Find("DebugCanvasPhysics/ThrowForceBar"); - if (throwForceBar) { + if (throwForceBar) + { ThrowForceBarSlider = throwForceBar.GetComponent(); } this.ThrowEnabled = ThrowEnabled; this.highlightShader = Shader.Find("Custom/TransparentOutline"); } - public void SetDisplayTargetText(bool display) { + public void SetDisplayTargetText(bool display) + { this.DisplayTargetText = display; } - public void SetOnlyPickableId(string objectId, bool disableHighlightShaderForObject = false) { + public void SetOnlyPickableId(string objectId, bool disableHighlightShaderForObject = false) + { this.onlyPickableObjectId = objectId; this.disableHighlightShaderForObject = disableHighlightShaderForObject; } - public void MouseControls() { + public void MouseControls() + { // Interact action for mouse left-click when nothing is picked up - if (Input.GetKeyDown(KeyCode.Mouse0)) { + if (Input.GetKeyDown(KeyCode.Mouse0)) + { if ( this.PhysicsController.WhatAmIHolding() == null && this.PhysicsController.ReadyForCommand - ) { + ) + { var closestObj = this.highlightedObject; - if (closestObj != null) { + if (closestObj != null) + { var actionName = ""; if ( closestObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup @@ -131,27 +144,35 @@ public void MouseControls() { onlyPickableObjectId == null || onlyPickableObjectId == closestObj.objectID ) - ) { + ) + { pickupState = true; actionName = "PickupObject"; - } else if (closestObj.GetComponent()) { + } + else if (closestObj.GetComponent()) + { actionName = closestObj.GetComponent().isOpen ? "CloseObject" : "OpenObject"; - } else if (closestObj.GetComponent()) { + } + else if (closestObj.GetComponent()) + { actionName = closestObj.GetComponent().isOn ? "ToggleObjectOff" : "ToggleObjectOn"; } - if (actionName != "") { + if (actionName != "") + { Dictionary action = new Dictionary(); action["action"] = actionName; action["objectId"] = closestObj.objectID; this.PhysicsController.ProcessControlCommand(action); } } - } else if (this.PhysicsController.ReadyForCommand) { + } + else if (this.PhysicsController.ReadyForCommand) + { this.mouseDownThrow = true; this.timerAtPress = Time.time; } @@ -161,17 +182,21 @@ public void MouseControls() { && this.highlightedObject != null && this.PhysicsController.WhatAmIHolding() != this.highlightedObject.gameObject && this.PhysicsController.ReadyForCommand - ) { + ) + { var closestObj = this.highlightedObject; - if (closestObj != null) { + if (closestObj != null) + { var actionName = ""; - if (closestObj.GetComponent()) { + if (closestObj.GetComponent()) + { actionName = closestObj.GetComponent().isOpen ? "CloseObject" : "OpenObject"; } - if (actionName != "") { + if (actionName != "") + { Dictionary action = new Dictionary(); action["action"] = actionName; action["objectId"] = closestObj.objectID; @@ -187,7 +212,8 @@ public void MouseControls() { // simulate TouchThenApply for in-editor debugging stuff #if UNITY_EDITOR - if (Input.GetKeyDown(KeyCode.Mouse1) && !Input.GetKey(KeyCode.LeftShift)) { + if (Input.GetKeyDown(KeyCode.Mouse1) && !Input.GetKey(KeyCode.LeftShift)) + { Dictionary dothis = new Dictionary(); dothis["action"] = "TouchThenApplyForce"; @@ -202,7 +228,8 @@ public void MouseControls() { PhysicsController.ProcessControlCommand(dothis); } - if (Input.GetKeyDown(KeyCode.Mouse1) && Input.GetKey(KeyCode.LeftShift)) { + if (Input.GetKeyDown(KeyCode.Mouse1) && Input.GetKey(KeyCode.LeftShift)) + { Dictionary dothis = new Dictionary(); dothis["action"] = "TouchThenApplyForce"; @@ -219,12 +246,16 @@ public void MouseControls() { #endif // Sets throw bar value - if (ThrowEnabled && ThrowForceBarSlider != null) { - if (this.mouseDownThrow) { + if (ThrowEnabled && ThrowForceBarSlider != null) + { + if (this.mouseDownThrow) + { var diff = Time.time - this.timerAtPress; var clampedForceTime = Mathf.Min(diff * diff, MaxChargeThrowSeconds); ThrowForceBarSlider.value = clampedForceTime / MaxChargeThrowSeconds; - } else { + } + else + { ThrowForceBarSlider.value -= ThrowForceBarSlider.value > 0.0f ? Time.deltaTime / MaxChargeThrowSeconds @@ -233,9 +264,12 @@ public void MouseControls() { } // Throw action on left click release - if (Input.GetKeyUp(KeyCode.Mouse0)) { - if (!pickupState) { - if (this.PhysicsController.WhatAmIHolding() != null) { + if (Input.GetKeyUp(KeyCode.Mouse0)) + { + if (!pickupState) + { + if (this.PhysicsController.WhatAmIHolding() != null) + { var diff = Time.time - this.timerAtPress; var clampedForceTime = Mathf.Min(diff * diff, MaxChargeThrowSeconds); var force = clampedForceTime * MaxThrowForce / MaxChargeThrowSeconds; @@ -250,27 +284,34 @@ public void MouseControls() { == highlightedObject.gameObject ) ) - ) { + ) + { Dictionary action = new Dictionary(); action["forceAction"] = true; - if (ThrowEnabled) { + if (ThrowEnabled) + { action["action"] = "ThrowObject"; action["moveMagnitude"] = force; - } else { + } + else + { action["action"] = "DropHandObject"; } this.PhysicsController.ProcessControlCommand(action); this.mouseDownThrow = false; } } - } else { + } + else + { pickupState = false; } } } - public void UpdateHighlightedObject(Vector3 screenPosition) { + public void UpdateHighlightedObject(Vector3 screenPosition) + { RaycastHit hit = new RaycastHit(); var ray = m_Camera.GetComponent().ScreenPointToRay(screenPosition); int layerMask = LayerMask.GetMask( @@ -290,10 +331,12 @@ public void UpdateHighlightedObject(Vector3 screenPosition) { hit.transform != null && hit.transform.tag == "SimObjPhysics" && (this.PhysicsController.WhatAmIHolding() == null || this.highlightWhileHolding) - ) { + ) + { softHighlight = true; var simObj = hit.transform.GetComponent(); - Func validObjectLazy = () => { + Func validObjectLazy = () => + { return ( simObj.PrimaryProperty == SimObjPrimaryProperty.CanPickup && ( @@ -304,7 +347,8 @@ public void UpdateHighlightedObject(Vector3 screenPosition) { || simObj.GetComponent() || simObj.GetComponent(); }; - if (simObj != null && validObjectLazy()) { + if (simObj != null && validObjectLazy()) + { var withinReach = PhysicsController.FindObjectInVisibleSimObjPhysics(simObj.objectID) != null; setTargetText(simObj.name, withinReach); @@ -317,15 +361,18 @@ public void UpdateHighlightedObject(Vector3 screenPosition) { && simObj.objectID == this.onlyPickableObjectId ) && this.withHighlightShader; - if (mRenderer != null && useHighlightShader) { - if (this.highlightedObject != newHighlightedObject) { + if (mRenderer != null && useHighlightShader) + { + if (this.highlightedObject != newHighlightedObject) + { newPreviousShader = mRenderer.material.shader; this.previousRenderQueueValue = mRenderer.material.renderQueue; mRenderer.material.renderQueue = -1; mRenderer.material.shader = this.highlightShader; } - if (withinReach) { + if (withinReach) + { softHighlight = true; mRenderer.sharedMaterial.SetFloat( "_Outline", @@ -335,7 +382,9 @@ public void UpdateHighlightedObject(Vector3 screenPosition) { "_OutlineColor", this.HighlightParams.WithinReachOutlineColor ); - } else if (softHighlight) { + } + else if (softHighlight) + { softHighlight = false; mRenderer.sharedMaterial.SetFloat( "_Outline", @@ -348,11 +397,14 @@ public void UpdateHighlightedObject(Vector3 screenPosition) { } } } - } else { + } + else + { newHighlightedObject = null; } - if (this.highlightedObject != newHighlightedObject && this.highlightedObject != null) { + if (this.highlightedObject != newHighlightedObject && this.highlightedObject != null) + { var mRenderer = this.highlightedObject.GetComponentInChildren(); setTargetText(""); @@ -362,33 +414,40 @@ public void UpdateHighlightedObject(Vector3 screenPosition) { && highlightedObject.objectID == this.onlyPickableObjectId ) && this.withHighlightShader; - if (mRenderer != null && useHighlightShader) { + if (mRenderer != null && useHighlightShader) + { mRenderer.material.shader = this.previousShader; // TODO unity has a bug for transparent objects they disappear when shader swapping, so we reset the previous shader's render queue value to render it appropiately. mRenderer.material.renderQueue = this.previousRenderQueueValue; } } - if (newPreviousShader != null) { + if (newPreviousShader != null) + { this.previousShader = newPreviousShader; } this.highlightedObject = newHighlightedObject; } - private void setTargetText(string text, bool withinReach = false) { + private void setTargetText(string text, bool withinReach = false) + { var eps = 1e-5; - if (withinReach) { + 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 = "+"; } - if (DisplayTargetText && TargetText != null) { + if (DisplayTargetText && TargetText != null) + { // 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 179e9657a5..d3fd29f0c0 100644 --- a/unity/Assets/Scripts/ObjectSpawner.cs +++ b/unity/Assets/Scripts/ObjectSpawner.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class ObjectSpawner : MonoBehaviour { +public class ObjectSpawner : MonoBehaviour +{ public GameObject[] PrefabToSpawn = null; // Use this for initialization diff --git a/unity/Assets/Scripts/ObjectSpecificReceptacle.cs b/unity/Assets/Scripts/ObjectSpecificReceptacle.cs index 7a6b4fd80e..42f4d27dbd 100644 --- a/unity/Assets/Scripts/ObjectSpecificReceptacle.cs +++ b/unity/Assets/Scripts/ObjectSpecificReceptacle.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class ObjectSpecificReceptacle : MonoBehaviour { +public class ObjectSpecificReceptacle : MonoBehaviour +{ [Header("Only objects of these Types can be placed on this Receptacle")] public SimObjType[] SpecificTypes; @@ -12,11 +13,14 @@ public class ObjectSpecificReceptacle : MonoBehaviour { [Header("Is this Receptacle already holding a valid object?")] public bool full = false; - public bool HasSpecificType(SimObjType check) { + public bool HasSpecificType(SimObjType check) + { bool result = false; - foreach (SimObjType sot in SpecificTypes) { - if (sot == check) { + foreach (SimObjType sot in SpecificTypes) + { + if (sot == check) + { result = true; } } @@ -24,11 +28,14 @@ public bool HasSpecificType(SimObjType check) { return result; } - public bool isFull() { + public bool isFull() + { SimObjPhysics sop = gameObject.GetComponent(); - foreach (GameObject rtb in sop.ReceptacleTriggerBoxes) { - if (rtb.GetComponent().isOccupied()) { + foreach (GameObject rtb in sop.ReceptacleTriggerBoxes) + { + if (rtb.GetComponent().isOccupied()) + { full = true; return true; } @@ -39,7 +46,8 @@ public bool isFull() { } // Use this for initialization - void Start() { + void Start() + { #if UNITY_EDITOR if ( !gameObject @@ -47,7 +55,8 @@ void Start() { .DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.ObjectSpecificReceptacle ) - ) { + ) + { Debug.LogError( this.name + " is missing the Secondary Property ObjectSpecificReceptacle!" ); diff --git a/unity/Assets/Scripts/PenDraw.cs b/unity/Assets/Scripts/PenDraw.cs index 5abbbdf8ba..6fa526227b 100644 --- a/unity/Assets/Scripts/PenDraw.cs +++ b/unity/Assets/Scripts/PenDraw.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class PenDraw : MonoBehaviour { +public class PenDraw : MonoBehaviour +{ public GameObject penDecal; public GameObject raycastOrigin; @@ -14,8 +15,10 @@ void Start() { } // Update is called once per frame void Update() { } - void OnTriggerStay(Collider other) { - if (other.CompareTag("DecalSpawnPlane") && shouldSpawn) { + void OnTriggerStay(Collider other) + { + if (other.CompareTag("DecalSpawnPlane") && shouldSpawn) + { RaycastHit hit; //check if we hit the spawn plane below the pencil if ( @@ -26,15 +29,18 @@ void OnTriggerStay(Collider other) { 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") { + 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 { + else + { if ( Physics.Raycast( raycastOrigin.transform.position, @@ -43,11 +49,14 @@ void OnTriggerStay(Collider other) { Mathf.Infinity, LayerMask.GetMask("SimObjVisible") ) - ) { + ) + { Object.Instantiate(penDecal, hit.point, Quaternion.Euler(-90, 0, 0)); } } - } else { + } + else + { if ( Physics.Raycast( raycastOrigin.transform.position, @@ -56,7 +65,8 @@ void OnTriggerStay(Collider other) { 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 9f4424231e..0f0d3dcbe7 100644 --- a/unity/Assets/Scripts/PhysicsExtensions.cs +++ b/unity/Assets/Scripts/PhysicsExtensions.cs @@ -25,7 +25,8 @@ using System.Collections.Generic; using UnityEngine; -public static class PhysicsExtensions { +public static class PhysicsExtensions +{ // // Box // @@ -36,7 +37,8 @@ public static bool BoxCast( float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 center, halfExtents; Quaternion orientation; @@ -59,7 +61,8 @@ public static bool BoxCast( float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 center, halfExtents; Quaternion orientation; @@ -82,7 +85,8 @@ public static RaycastHit[] BoxCastAll( float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 center, halfExtents; Quaternion orientation; @@ -105,7 +109,8 @@ public static int BoxCastNonAlloc( float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 center, halfExtents; Quaternion orientation; @@ -126,7 +131,8 @@ public static bool CheckBox( BoxCollider box, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 center, halfExtents; Quaternion orientation; @@ -145,12 +151,14 @@ public static Collider[] OverlapBox( int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal, float expandBy = 0.0f - ) { + ) + { Vector3 center, halfExtents; Quaternion orientation; box.ToWorldSpaceBox(out center, out halfExtents, out orientation); - if (expandBy != 0.0f) { + if (expandBy != 0.0f) + { halfExtents = new Vector3( expandBy + halfExtents.x, expandBy + halfExtents.y, @@ -171,7 +179,8 @@ public static int OverlapBoxNonAlloc( Collider[] results, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 center, halfExtents; Quaternion orientation; @@ -191,7 +200,8 @@ public static void ToWorldSpaceBox( out Vector3 center, out Vector3 halfExtents, out Quaternion orientation - ) { + ) + { orientation = box.transform.rotation; center = box.transform.TransformPoint(box.center); var lossyScale = box.transform.lossyScale; @@ -210,7 +220,8 @@ public static bool SphereCast( float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); @@ -231,7 +242,8 @@ public static RaycastHit[] SphereCastAll( float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); @@ -252,7 +264,8 @@ public static int SphereCastNonAlloc( float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); @@ -271,7 +284,8 @@ public static bool CheckSphere( SphereCollider sphere, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); @@ -283,7 +297,8 @@ public static Collider[] OverlapSphere( int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal, float expandBy = 0.0f - ) { + ) + { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); @@ -296,7 +311,8 @@ public static int OverlapSphereNonAlloc( Collider[] results, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 center; float radius; sphere.ToWorldSpaceSphere(out center, out radius); @@ -313,7 +329,8 @@ 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)); } @@ -329,7 +346,8 @@ public static bool CapsuleCast( float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 point0, point1; float radius; @@ -352,7 +370,8 @@ public static RaycastHit[] CapsuleCastAll( float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 point0, point1; float radius; @@ -375,7 +394,8 @@ public static int CapsuleCastNonAlloc( float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 point0, point1; float radius; @@ -396,7 +416,8 @@ public static bool CheckCapsule( CapsuleCollider capsule, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 point0, point1; float radius; @@ -409,7 +430,8 @@ public static Collider[] OverlapCapsule( int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal, float expandBy = 0.0f - ) { + ) + { Vector3 point0, point1; float radius; @@ -428,7 +450,8 @@ public static int OverlapCapsuleNonAlloc( Collider[] results, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { Vector3 point0, point1; float radius; @@ -448,14 +471,16 @@ public static void ToWorldSpaceCapsule( out Vector3 point0, out Vector3 point1, out float radius - ) { + ) + { var center = capsule.transform.TransformPoint(capsule.center); radius = 0f; float height = 0f; Vector3 lossyScale = AbsVec3(capsule.transform.lossyScale); Vector3 dir = Vector3.zero; - switch (capsule.direction) { + switch (capsule.direction) + { case 0: // x radius = Mathf.Max(lossyScale.y, lossyScale.z) * capsule.radius; height = lossyScale.x * capsule.height; @@ -473,7 +498,8 @@ out float radius break; } - if (height < radius * 2f) { + if (height < radius * 2f) + { dir = Vector3.zero; } @@ -485,12 +511,15 @@ out float radius // Util // - public static void SortClosestToFurthest(RaycastHit[] hits, int hitCount = -1) { - if (hitCount == 0) { + public static void SortClosestToFurthest(RaycastHit[] hits, int hitCount = -1) + { + if (hitCount == 0) + { return; } - if (hitCount < 0) { + if (hitCount < 0) + { hitCount = hits.Length; } @@ -501,19 +530,23 @@ public static void SortClosestToFurthest(RaycastHit[] hits, int hitCount = -1) { // Private // - private class AscendingDistanceComparer : IComparer { - public int Compare(RaycastHit h1, RaycastHit h2) { + private class AscendingDistanceComparer : IComparer + { + public int Compare(RaycastHit h1, RaycastHit h2) + { return h1.distance < h2.distance ? -1 : (h1.distance > h2.distance ? 1 : 0); } } private static AscendingDistanceComparer ascendDistance = new AscendingDistanceComparer(); - private static Vector3 AbsVec3(Vector3 v) { + private static Vector3 AbsVec3(Vector3 v) + { return new Vector3(Mathf.Abs(v.x), Mathf.Abs(v.y), Mathf.Abs(v.z)); } - private static float MaxVec3(Vector3 v) { + private static float MaxVec3(Vector3 v) + { return Mathf.Max(v.x, Mathf.Max(v.y, v.z)); } } diff --git a/unity/Assets/Scripts/PhysicsRemoteFPSAgentController.cs b/unity/Assets/Scripts/PhysicsRemoteFPSAgentController.cs index a827d8200a..c5a0357c99 100644 --- a/unity/Assets/Scripts/PhysicsRemoteFPSAgentController.cs +++ b/unity/Assets/Scripts/PhysicsRemoteFPSAgentController.cs @@ -19,13 +19,16 @@ using UnityStandardAssets.ImageEffects; using UnityStandardAssets.Utility; -namespace UnityStandardAssets.Characters.FirstPerson { - public class OrientedPoint { +namespace UnityStandardAssets.Characters.FirstPerson +{ + public class OrientedPoint + { public Vector3 position = new Vector3(); public Quaternion orientation = new Quaternion(); } - public partial class PhysicsRemoteFPSAgentController : BaseFPSAgentController { + public partial class PhysicsRemoteFPSAgentController : BaseFPSAgentController + { protected Dictionary> maskedObjects = new Dictionary>(); bool transparentStructureObjectsHidden = false; @@ -36,11 +39,13 @@ public PhysicsRemoteFPSAgentController( BaseAgentComponent baseAgentComponent, AgentManager agentManager ) - : base(baseAgentComponent, agentManager) { + : base(baseAgentComponent, agentManager) + { standingLocalCameraPosition = m_Camera.transform.localPosition; } - public override ActionFinished InitializeBody(ServerAction initializeAction) { + public override ActionFinished InitializeBody(ServerAction initializeAction) + { VisibilityCapsule = TallVisCap; m_CharacterController.center = new Vector3(0, 0, 0); m_CharacterController.radius = 0.2f; @@ -71,34 +76,44 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { // protected float DownwardViewDistance = 2.0f; // forceVisible is true to activate, false to deactivate - public void ToggleHideAndSeekObjects(bool forceVisible = false) { - if (physicsSceneManager.ToggleHideAndSeek(forceVisible)) { + public void ToggleHideAndSeekObjects(bool forceVisible = false) + { + if (physicsSceneManager.ToggleHideAndSeek(forceVisible)) + { physicsSceneManager.ResetObjectIdToSimObjPhysics(); actionFinished(true); - } else { + } + else + { errorMessage = "No HideAndSeek object found"; actionFinished(false); } } - public Vector3 AgentHandLocation() { + public Vector3 AgentHandLocation() + { return AgentHand.transform.position; } - public GameObject WhatAmIHolding() { + public GameObject WhatAmIHolding() + { return ItemInHand; } - public void EnableTemperatureDecay() { - if (!physicsSceneManager.GetComponent().AllowDecayTemperature) { + public void EnableTemperatureDecay() + { + if (!physicsSceneManager.GetComponent().AllowDecayTemperature) + { physicsSceneManager.GetComponent().AllowDecayTemperature = true; } actionFinished(true); } - public void DisableTemperatureDecay() { - if (physicsSceneManager.GetComponent().AllowDecayTemperature) { + public void DisableTemperatureDecay() + { + if (physicsSceneManager.GetComponent().AllowDecayTemperature) + { physicsSceneManager.GetComponent().AllowDecayTemperature = false; } @@ -106,8 +121,10 @@ public void DisableTemperatureDecay() { } // sets temperature decay for a single object. - public void SetTemperatureDecayTime(string objectId, float decayTime) { - if (decayTime < 0) { + public void SetTemperatureDecayTime(string objectId, float decayTime) + { + if (decayTime < 0) + { throw new ArgumentOutOfRangeException( "decayTime must be >= 0. You gave " + decayTime ); @@ -121,34 +138,42 @@ public void SetTemperatureDecayTime(string objectId, float decayTime) { } // globally sets temperature decay for all objects. - public void SetTemperatureDecayTime(float decayTime) { - if (decayTime < 0) { + public void SetTemperatureDecayTime(float decayTime) + { + if (decayTime < 0) + { throw new ArgumentOutOfRangeException( "decayTime must be >= 0. You gave " + decayTime ); } SimObjPhysics[] simObjects = GameObject.FindObjectsOfType(); - foreach (SimObjPhysics sop in simObjects) { + foreach (SimObjPhysics sop in simObjects) + { sop.SetHowManySecondsUntilRoomTemp(decayTime); } actionFinished(true); } // change the mass/drag/angular drag values of a simobjphys that is pickupable or moveable - public void SetMassProperties(string objectId, float mass, float drag, float angularDrag) { - if (objectId == null) { + public void SetMassProperties(string objectId, float mass, float drag, float angularDrag) + { + if (objectId == null) + { errorMessage = "please give valid ObjectID for SetMassProperties() action"; actionFinished(false); return; } SimObjPhysics[] simObjects = GameObject.FindObjectsOfType(); - foreach (SimObjPhysics sop in simObjects) { - if (sop.objectID == objectId) { + foreach (SimObjPhysics sop in simObjects) + { + if (sop.objectID == objectId) + { if ( sop.PrimaryProperty == SimObjPrimaryProperty.Moveable || sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup - ) { + ) + { Rigidbody rb = sop.GetComponent(); rb.mass = mass; rb.drag = drag; @@ -173,19 +198,22 @@ public void SetMassProperties(string objectId, float mass, float drag, float ang return; } - public bool isStanding() { + public bool isStanding() + { return (m_Camera.transform.localPosition - standingLocalCameraPosition).magnitude < 0.1f; } - public override MetadataWrapper generateMetadataWrapper() { + public override MetadataWrapper generateMetadataWrapper() + { MetadataWrapper metaWrapper = base.generateMetadataWrapper(); metaWrapper.agent.isStanding = isStanding(); return metaWrapper; } // change the radius of the agent's capsule on the char controller component, and the capsule collider component - public void SetAgentRadius(float agentRadius = 2.0f) { + public void SetAgentRadius(float agentRadius = 2.0f) + { m_CharacterController.radius = agentRadius; CapsuleCollider cap = GetComponent(); cap.radius = agentRadius; @@ -197,11 +225,14 @@ public void SetAgentRadius(float agentRadius = 2.0f) { #if UNITY_EDITOR // return ID of closest CanPickup object by distance - public string ObjectIdOfClosestVisibleObject() { + public string ObjectIdOfClosestVisibleObject() + { string objectID = null; - foreach (SimObjPhysics o in VisibleSimObjPhysics) { - if (o.PrimaryProperty == SimObjPrimaryProperty.CanPickup) { + foreach (SimObjPhysics o in VisibleSimObjPhysics) + { + if (o.PrimaryProperty == SimObjPrimaryProperty.CanPickup) + { objectID = o.ObjectID; // print(objectID); break; @@ -211,14 +242,17 @@ public string ObjectIdOfClosestVisibleObject() { return objectID; } - public string ObjectIdOfClosestPickupableOrMoveableObject() { + public string ObjectIdOfClosestPickupableOrMoveableObject() + { string objectID = null; - foreach (SimObjPhysics o in VisibleSimObjPhysics) { + foreach (SimObjPhysics o in VisibleSimObjPhysics) + { if ( o.PrimaryProperty == SimObjPrimaryProperty.CanPickup || o.PrimaryProperty == SimObjPrimaryProperty.Moveable - ) { + ) + { objectID = o.ObjectID; // print(objectID); break; @@ -229,11 +263,14 @@ public string ObjectIdOfClosestPickupableOrMoveableObject() { } // return ID of closest CanOpen or CanOpen_Fridge object by distance - public string ObjectIdOfClosestVisibleOpenableObject() { + public string ObjectIdOfClosestVisibleOpenableObject() + { string objectID = null; - foreach (SimObjPhysics o in VisibleSimObjPhysics) { - if (o.GetComponent()) { + foreach (SimObjPhysics o in VisibleSimObjPhysics) + { + if (o.GetComponent()) + { objectID = o.ObjectID; break; } @@ -243,11 +280,14 @@ public string ObjectIdOfClosestVisibleOpenableObject() { } // return ID of closes toggleable object by distance - public string ObjectIdOfClosestToggleObject() { + public string ObjectIdOfClosestToggleObject() + { string objectID = null; - foreach (SimObjPhysics o in VisibleSimObjPhysics) { - if (o.GetComponent()) { + foreach (SimObjPhysics o in VisibleSimObjPhysics) + { + if (o.GetComponent()) + { objectID = o.ObjectID; break; } @@ -256,11 +296,14 @@ public string ObjectIdOfClosestToggleObject() { return objectID; } - public string ObjectIdOfClosestReceptacleObject() { + public string ObjectIdOfClosestReceptacleObject() + { string objectID = null; - foreach (SimObjPhysics o in VisibleSimObjPhysics) { - if (o.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { + foreach (SimObjPhysics o in VisibleSimObjPhysics) + { + if (o.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) + { objectID = o.ObjectID; break; } @@ -272,24 +315,31 @@ public string ObjectIdOfClosestReceptacleObject() { ///////////////////////////////////////////////////////// // return a reference to a SimObj that is Visible (in the VisibleSimObjPhysics array) and // matches the passed in objectID - public GameObject FindObjectInVisibleSimObjPhysics(string objectId) { - foreach (SimObjPhysics sop in VisibleSimObjs(false)) { - if (sop.ObjectID == objectId) { + public GameObject FindObjectInVisibleSimObjPhysics(string objectId) + { + foreach (SimObjPhysics sop in VisibleSimObjs(false)) + { + if (sop.ObjectID == objectId) + { return sop.gameObject; } } return null; } - protected Collider[] collidersWithinCapsuleCastOfAgent(float maxDistance) { + protected Collider[] collidersWithinCapsuleCastOfAgent(float maxDistance) + { CapsuleCollider agentCapsuleCollider = GetComponent(); Vector3 point0, point1; float radius; agentCapsuleCollider.ToWorldSpaceCapsule(out point0, out point1, out radius); - if (point0.y <= point1.y) { + if (point0.y <= point1.y) + { point1.y += maxDistance; - } else { + } + else + { point0.y += maxDistance; } return Physics.OverlapCapsule( @@ -308,16 +358,22 @@ protected Collider[] collidersWithinCapsuleCastOfAgent(float maxDistance) { } // checks if a float is a multiple of 0.1f - protected bool CheckIfFloatIsMultipleOfOneTenth(float f) { - if (((decimal)f % 0.1M == 0) == false) { + protected bool CheckIfFloatIsMultipleOfOneTenth(float f) + { + if (((decimal)f % 0.1M == 0) == false) + { return false; - } else { + } + else + { return true; } } - public override void LookDown(ServerAction action) { - if (action.degrees < 0) { + public override void LookDown(ServerAction action) + { + if (action.degrees < 0) + { errorMessage = "LookDown action requires positive degree value. Invalid value used: " + action.degrees; @@ -325,14 +381,16 @@ public override void LookDown(ServerAction action) { return; } - if (!CheckIfFloatIsMultipleOfOneTenth(action.degrees)) { + if (!CheckIfFloatIsMultipleOfOneTenth(action.degrees)) + { errorMessage = "LookDown action requires degree value to be a multiple of 0.1f"; actionFinished(false); return; } // default degree increment to 30 - if (action.degrees == 0) { + if (action.degrees == 0) + { action.degrees = 30f; } @@ -340,7 +398,8 @@ public override void LookDown(ServerAction action) { // this is to prevent too small of a degree increment change that could cause float imprecision action.degrees = Mathf.Round(action.degrees * 10.0f) / 10.0f; - if (!checkForUpDownAngleLimit("down", action.degrees)) { + if (!checkForUpDownAngleLimit("down", action.degrees)) + { errorMessage = "can't look down beyond " + maxDownwardLookAngle @@ -350,14 +409,18 @@ public override void LookDown(ServerAction action) { return; } - if (CheckIfAgentCanRotate("down", action.degrees)) { + if (CheckIfAgentCanRotate("down", action.degrees)) + { base.LookDown(action); // only default hand if not manually Interacting with things - if (!action.manualInteract) { + if (!action.manualInteract) + { DefaultAgentHand(); } - } else { + } + else + { errorMessage = "a held item: " + ItemInHand.transform.GetComponent().objectID @@ -368,8 +431,10 @@ public override void LookDown(ServerAction action) { } } - public override void LookUp(ServerAction action) { - if (action.degrees < 0) { + public override void LookUp(ServerAction action) + { + if (action.degrees < 0) + { errorMessage = "LookUp action requires positive degree value. Invalid value used: " + action.degrees; @@ -377,14 +442,16 @@ public override void LookUp(ServerAction action) { return; } - if (!CheckIfFloatIsMultipleOfOneTenth(action.degrees)) { + if (!CheckIfFloatIsMultipleOfOneTenth(action.degrees)) + { errorMessage = "LookUp action requires degree value to be a multiple of 0.1f"; actionFinished(false); return; } // default degree increment to 30 - if (action.degrees == 0) { + if (action.degrees == 0) + { action.degrees = 30f; } @@ -392,7 +459,8 @@ public override void LookUp(ServerAction action) { // this is to prevent too small of a degree increment change that could cause float imprecision action.degrees = Mathf.Round(action.degrees * 10.0f) / 10.0f; - if (!checkForUpDownAngleLimit("up", action.degrees)) { + if (!checkForUpDownAngleLimit("up", action.degrees)) + { errorMessage = "can't look up beyond " + maxUpwardLookAngle @@ -402,14 +470,18 @@ public override void LookUp(ServerAction action) { return; } - if (CheckIfAgentCanRotate("up", action.degrees)) { + if (CheckIfAgentCanRotate("up", action.degrees)) + { base.LookUp(action); // only default hand if not manually Interacting with things - if (!action.manualInteract) { + if (!action.manualInteract) + { DefaultAgentHand(); } - } else { + } + else + { errorMessage = "a held item: " + ItemInHand.transform.GetComponent().objectID @@ -429,25 +501,33 @@ public virtual void RotateRight( 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) { + ) + { + if (!degrees.HasValue) + { degrees = rotateStepDegrees; - } else if (degrees == 0f) { + } + else if (degrees == 0f) + { throw new InvalidOperationException( "Cannot rotate by 0 degrees as this previously defaulted to rotating by a diferent amount." ); } - if (CheckIfAgentCanRotate("right", degrees.Value) || forceAction) { + if (CheckIfAgentCanRotate("right", degrees.Value) || forceAction) + { transform.Rotate(0, degrees.Value, 0); // only default hand if not manually Interacting with things - if (!manualInteract) { + if (!manualInteract) + { DefaultAgentHand(); } actionFinished(true); - } else { + } + else + { errorMessage = $"a held item: {ItemInHand.transform.name} with something if agent rotates Right {degrees} degrees"; actionFinished(false); @@ -463,25 +543,33 @@ public virtual void RotateLeft( 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) { + ) + { + if (!degrees.HasValue) + { degrees = rotateStepDegrees; - } else if (degrees == 0f) { + } + else if (degrees == 0f) + { throw new InvalidOperationException( "Cannot rotate by 0 degrees as this previously defaulted to rotating by a diferent amount." ); } - if (CheckIfAgentCanRotate("left", degrees.Value) || forceAction) { + if (CheckIfAgentCanRotate("left", degrees.Value) || forceAction) + { transform.Rotate(0, -degrees.Value, 0); // only default hand if not manually Interacting with things - if (!manualInteract) { + if (!manualInteract) + { DefaultAgentHand(); } actionFinished(true); - } else { + } + else + { errorMessage = $"a held item: {ItemInHand.transform.name} with something if agent rotates Left {degrees} degrees"; actionFinished(false); @@ -494,7 +582,8 @@ private bool checkArcForCollisions( float degrees, int dirSign, Vector3 dirAxis - ) { + ) + { bool result = true; float arcIncrementDistance; Vector3 bbWorldCenter = bb.transform.TransformPoint(bb.center); @@ -514,7 +603,8 @@ Vector3 dirAxis 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 - for (int i = 0; i < pointsOnArc.Length - 1; i++) { + for (int i = 0; i < pointsOnArc.Length - 1; i++) + { RaycastHit hit; // do boxcasts from the first point, sequentially, to the last @@ -542,7 +632,8 @@ Vector3 dirAxis ), QueryTriggerInteraction.Ignore ) - ) { + ) + { // did we hit a sim obj? if ( ( @@ -550,7 +641,8 @@ Vector3 dirAxis && 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 continue; @@ -581,17 +673,21 @@ Vector3 dirAxis QueryTriggerInteraction.Ignore ); - foreach (Collider col in WhatDidWeHit) { - if (col.transform.GetComponentInParent()) { + foreach (Collider col in WhatDidWeHit) + { + if (col.transform.GetComponentInParent()) + { if ( col.transform.GetComponentInParent().transform == ItemInHand.transform - ) { + ) + { continue; } } - if (col.transform == this.transform) { + if (col.transform == this.transform) + { continue; } @@ -610,13 +706,15 @@ private OrientedPoint[] GenerateArcPoints( 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; // Calculate positions of all 10 OrientedPoints - for (int i = 0; i < arcPoints.Length; i++) { + for (int i = 0; i < arcPoints.Length; i++) + { currentIncrementAngle = i * dirSign * incrementAngle; // Move and orient the rotPoint to the bb's position and orientation rotPoint.transform.position = startingPoint; @@ -662,8 +760,10 @@ Vector3 dirAxis // } // 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) { + public bool CheckIfAgentCanRotate(string direction, float degrees) + { + if (ItemInHand == null) + { // Debug.Log("Rotation check passed: nothing in Agent Hand"); return true; } @@ -681,25 +781,29 @@ public bool CheckIfAgentCanRotate(string direction, float degrees) { Vector3 origin = m_CharacterController.transform.position; // Yawing left (Rotating negatively across XZ plane around CharacterController) - if (direction == "left") { + if (direction == "left") + { dirSign = -1; dirAxis = transform.up; origin = m_CharacterController.transform.position; } // Yawing right (Rotating positively across XZ plane around CharacterController) - else if (direction == "right") { + 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") { + 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") { + else if (direction == "down") + { dirSign = 1; dirAxis = transform.right; origin = m_Camera.transform.position; @@ -712,22 +816,26 @@ public bool CheckIfAgentCanRotate(string direction, float degrees) { } // 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) { + public void ChangeAgentColor(float x, float y, float z) + { agentManager.UpdateAgentColor(this, new Color(x, y, z, 1.0f)); actionFinished(true); } - protected Vector3 closestPointToObject(SimObjPhysics sop) { + protected Vector3 closestPointToObject(SimObjPhysics sop) + { float closestDist = 10000.0f; Vector3 closestPoint = new Vector3(0f, 0f, 0f); - foreach (Collider c in sop.GetComponentsInChildren()) { + foreach (Collider c in sop.GetComponentsInChildren()) + { Vector3 point = c.ClosestPointOnBounds(transform.position); float dist = Vector3.Distance( transform.position, c.ClosestPointOnBounds(transform.position) ); - if (dist < closestDist) { + if (dist < closestDist) + { closestDist = dist; closestPoint = point; } @@ -735,12 +843,14 @@ protected Vector3 closestPointToObject(SimObjPhysics sop) { return closestPoint; } - public void PointsOverTableWhereHandCanBe(string objectId, float x, float z) { + public void PointsOverTableWhereHandCanBe(string objectId, float x, float z) + { // Assumes InitializeTableSetting has been run before calling this string tableId = objectId; - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; @@ -753,12 +863,15 @@ public void PointsOverTableWhereHandCanBe(string objectId, float x, float z) { AgentHand.transform.position = AgentHand.transform.position; - if (ItemInHand != null) { + if (ItemInHand != null) + { ItemInHand.SetActive(false); } List goodPositions = new List(); - for (int i = -xSteps; i <= xSteps; i++) { - for (int j = zStart; j < 11; j++) { + for (int i = -xSteps; i <= xSteps; i++) + { + for (int j = zStart; j < 11; j++) + { DefaultAgentHand(); Vector3 testPosition = @@ -781,17 +894,20 @@ public void PointsOverTableWhereHandCanBe(string objectId, float x, float z) { "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 (hitSop && hitSop.ObjectID == tableId) { + if (hitSop && hitSop.ObjectID == tableId) + { goodPositions.Add(hit.point); #if UNITY_EDITOR Debug.Log("Point"); @@ -812,7 +928,8 @@ public void PointsOverTableWhereHandCanBe(string objectId, float x, float z) { } } - if (ItemInHand != null) { + if (ItemInHand != null) + { ItemInHand.SetActive(true); } @@ -820,8 +937,10 @@ public void PointsOverTableWhereHandCanBe(string objectId, float x, float z) { actionFinished(true, goodPositions); } - public void PlaceFixedReceptacleAtLocation(int objectVariation, float x, float y, float z) { - if (objectVariation < 0 || objectVariation > 4) { + public void PlaceFixedReceptacleAtLocation(int objectVariation, float x, float y, float z) + { + if (objectVariation < 0 || objectVariation > 4) + { errorMessage = "Invalid receptacle variation."; actionFinished(false); return; @@ -830,7 +949,8 @@ public void PlaceFixedReceptacleAtLocation(int objectVariation, float x, float y if ( physicsSceneManager.ManipulatorReceptacles == null || physicsSceneManager.ManipulatorReceptacles.Length == 0 - ) { + ) + { errorMessage = "Scene does not have manipulator receptacles set."; actionFinished(false); return; @@ -840,18 +960,22 @@ public void PlaceFixedReceptacleAtLocation(int objectVariation, float x, float y float[] yoffsets = { 0f, -0.0277601f, 0f, 0f, 0f }; string receptId = ""; - for (int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) + { GameObject recept = physicsSceneManager.ManipulatorReceptacles[i]; SimObjPhysics receptSop = recept.GetComponent(); - if (objectVariation == i) { + if (objectVariation == i) + { recept.SetActive(true); recept.GetComponent().isKinematic = true; recept.transform.position = new Vector3(x, y + yoffsets[i], z); recept.transform.rotation = transform.rotation; physicsSceneManager.AddToObjectsInScene(receptSop); receptId = receptSop.ObjectID; - } else if (recept.activeInHierarchy) { + } + else if (recept.activeInHierarchy) + { physicsSceneManager.RemoveFromObjectsInScene(receptSop); recept.SetActive(false); } @@ -866,17 +990,20 @@ public void PlaceBookWallAtLocation( float y, float z, Vector3 rotation - ) { + ) + { if ( physicsSceneManager.ManipulatorBooks == null || physicsSceneManager.ManipulatorBooks.Length == 0 - ) { + ) + { errorMessage = "Scene does not have manipulator books set."; actionFinished(false); return; } - if (objectVariation < 0) { + if (objectVariation < 0) + { errorMessage = "objectVariation must be >= 0"; actionFinished(false); return; @@ -886,10 +1013,14 @@ Vector3 rotation // uint which = (uint) Convert.ToUInt32(action.objectVariation); // List whichIncluded = new List(); - for (int i = 0; i < 5; i++) { - if (((objectVariation >> i) % 2) == 1) { + for (int i = 0; i < 5; i++) + { + if (((objectVariation >> i) % 2) == 1) + { physicsSceneManager.ManipulatorBooks[i].transform.gameObject.SetActive(true); - } else { + } + else + { physicsSceneManager.ManipulatorBooks[i].transform.gameObject.SetActive(false); } // whichIncluded.Add( @@ -913,34 +1044,47 @@ Vector3 rotation actionFinished(true); } - public void InitializeTableSetting(int objectVariation) { + public void InitializeTableSetting(int objectVariation) + { string scene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().name; Vector3 newPosition = transform.position; Quaternion newRotation = transform.rotation; - if (scene == "FloorPlan501_physics") { + if (scene == "FloorPlan501_physics") + { newPosition = new Vector3(0f, transform.position.y, 0.75f); newRotation = Quaternion.Euler(0f, 180f, 0f); - } else if (scene == "FloorPlan502_physics") { + } + else if (scene == "FloorPlan502_physics") + { newPosition = new Vector3(-0.5f, transform.position.y, 0.75f); newRotation = Quaternion.Euler(0f, 90f, 0f); - } else if (scene == "FloorPlan503_physics") { + } + else if (scene == "FloorPlan503_physics") + { newPosition = new Vector3(-0.5f, transform.position.y, -0.25f); newRotation = Quaternion.Euler(0f, 0f, 0f); - } else if (scene == "FloorPlan504_physics") { + } + else if (scene == "FloorPlan504_physics") + { newPosition = new Vector3(0f, transform.position.y, 0.5f); newRotation = Quaternion.Euler(0f, 180f, 0f); - } else if (scene == "FloorPlan505_physics") { + } + else if (scene == "FloorPlan505_physics") + { newPosition = new Vector3(0f, transform.position.y, 1.25f); newRotation = Quaternion.Euler(0f, 180f, 0f); - } else { + } + else + { errorMessage = "Cannot initialize table in scene " + scene; actionFinished(false); return; } - if (objectVariation < 0 || objectVariation > 4) { + if (objectVariation < 0 || objectVariation > 4) + { errorMessage = "Invalid table variation."; actionFinished(false); return; @@ -949,35 +1093,43 @@ public void InitializeTableSetting(int objectVariation) { transform.position = newPosition; transform.rotation = newRotation; - if (m_Camera.fieldOfView != 90f) { + if (m_Camera.fieldOfView != 90f) + { m_Camera.fieldOfView = 90f; } m_Camera.transform.localEulerAngles = new Vector3(30f, 0.0f, 0.0f); string tableId = ""; - for (int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) + { GameObject table = physicsSceneManager.ManipulatorTables[i]; SimObjPhysics tableSop = table.GetComponent(); - if (objectVariation == i) { + if (objectVariation == i) + { table.SetActive(true); physicsSceneManager.AddToObjectsInScene(tableSop); tableId = tableSop.ObjectID; - } else if (table.activeInHierarchy) { + } + else if (table.activeInHierarchy) + { physicsSceneManager.RemoveFromObjectsInScene(tableSop); table.SetActive(false); } GameObject recept = physicsSceneManager.ManipulatorReceptacles[i]; SimObjPhysics receptSop = recept.GetComponent(); - if (recept.activeInHierarchy) { + if (recept.activeInHierarchy) + { physicsSceneManager.RemoveFromObjectsInScene(receptSop); recept.SetActive(false); } } - if (physicsSceneManager.ManipulatorBooks != null) { - foreach (GameObject book in physicsSceneManager.ManipulatorBooks) { + if (physicsSceneManager.ManipulatorBooks != null) + { + foreach (GameObject book in physicsSceneManager.ManipulatorBooks) + { book.SetActive(false); } } @@ -985,18 +1137,22 @@ public void InitializeTableSetting(int objectVariation) { actionFinished(true, tableId); } - public float GetXZRadiusOfObject(SimObjPhysics sop) { + public float GetXZRadiusOfObject(SimObjPhysics sop) + { BoxCollider bc = sop.BoundingBox.GetComponent(); return (new Vector3(bc.size.x, 0f, bc.size.z) * 0.5f).magnitude; } - public void GetUnreachableSilhouetteForObject(string objectId, float z) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void GetUnreachableSilhouetteForObject(string objectId, float z) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; } - if (z <= 0.0f) { + if (z <= 0.0f) + { errorMessage = "Interactable distance (z) must be > 0"; actionFinished(false); return; @@ -1016,21 +1172,29 @@ public void GetUnreachableSilhouetteForObject(string objectId, float z) { var sb = new System.Text.StringBuilder(); int halfWidth = 1 + ((int)Math.Round((objectRad + z + m_CharacterController.radius) / gridSize)); - for (int i = 2 * halfWidth; i >= 0; i--) { + for (int i = 2 * halfWidth; i >= 0; i--) + { float zOffset = ((i - halfWidth) * gridSize); - for (int j = 0; j < 2 * halfWidth + 1; j++) { + for (int j = 0; j < 2 * halfWidth + 1; j++) + { float xOffset = ((j - halfWidth) * gridSize); - if (j != 0) { + if (j != 0) + { sb.Append(" "); } transform.position = targetObject.transform.position + new Vector3(xOffset, 0f, zOffset); - if (isAgentCapsuleCollidingWith(targetObject.gameObject)) { + if (isAgentCapsuleCollidingWith(targetObject.gameObject)) + { sb.Append("1"); - } else if (distanceToObject(targetObject) <= z) { + } + else if (distanceToObject(targetObject) <= z) + { sb.Append("2"); - } else { + } + else + { sb.Append("0"); } } @@ -1049,13 +1213,16 @@ public void GetUnreachableSilhouetteForObject(string objectId, float z) { actionFinished(true, mat); } - public void RandomlyCreateLiftedFurniture(ServerAction action) { - if (action.z < 0.25f) { + public void RandomlyCreateLiftedFurniture(ServerAction action) + { + if (action.z < 0.25f) + { errorMessage = "z must be at least 0.25"; actionFinished(false); return; } - if (action.y == 0.0f) { + if (action.y == 0.0f) + { errorMessage = "y must be non-zero"; actionFinished(false); return; @@ -1064,21 +1231,26 @@ public void RandomlyCreateLiftedFurniture(ServerAction action) { List oldAgentPositions = new List(); List oldAgentRotations = new List(); - foreach (BaseFPSAgentController agent in this.agentManager.agents) { + foreach (BaseFPSAgentController agent in this.agentManager.agents) + { oldAgentPositions.Add(agent.transform.position); agent.transform.position = new Vector3(50f, 50f, 50f); oldAgentRotations.Add(agent.transform.rotation); } SimObjPhysics objectCreated = null; - try { + try + { objectCreated = randomlyCreateAndPlaceObjectOnFloor( action.objectType, action.objectVariation, reachablePositions ); - } catch (Exception) { } - if (objectCreated == null) { - for (int i = 0; i < this.agentManager.agents.Count; i++) { + } + catch (Exception) { } + if (objectCreated == null) + { + for (int i = 0; i < this.agentManager.agents.Count; i++) + { var agent = this.agentManager.agents[i]; agent.transform.position = oldAgentPositions[i]; agent.transform.rotation = oldAgentRotations[i]; @@ -1098,77 +1270,98 @@ public void RandomlyCreateLiftedFurniture(ServerAction action) { List rotations = rotationsArr.ToList(); bool placementSuccess = false; - for (int i = 0; i < 10; i++) { - if (objectFloating) { + for (int i = 0; i < 10; i++) + { + if (objectFloating) + { List candidatePositionsList = new List(); - foreach (Vector3 p in reachablePositions) { + foreach (Vector3 p in reachablePositions) + { transform.position = p; - if (isAgentCapsuleColliding(collidersToIgnoreDuringMovement)) { + if (isAgentCapsuleColliding(collidersToIgnoreDuringMovement)) + { continue; } - if (distanceToObject(objectCreated) <= action.z) { + if (distanceToObject(objectCreated) <= action.z) + { candidatePositionsList.Add(p); } } transform.position = new Vector3(50f, 50f, 50f); - if (candidatePositionsList.Count >= agentManager.agents.Count) { + if (candidatePositionsList.Count >= agentManager.agents.Count) + { candidatePositionsList.Shuffle_(); foreach ( Vector3[] candidatePositions in UtilityFunctions.Combinations( candidatePositionsList.ToArray(), agentManager.agents.Count ) - ) { + ) + { bool candidatesBad = false; - for (int j = 0; j < candidatePositions.Length - 1; j++) { + for (int j = 0; j < candidatePositions.Length - 1; j++) + { Vector3 p0 = candidatePositions[j]; - for (int k = j + 1; k < candidatePositions.Length; k++) { + 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 - ) { + ) + { candidatesBad = true; } - if (candidatesBad) { + if (candidatesBad) + { break; } } - if (candidatesBad) { + if (candidatesBad) + { break; } } - if (candidatesBad) { + if (candidatesBad) + { continue; } placementSuccess = true; - for (int j = 0; j < agentManager.agents.Count; j++) { + for (int j = 0; j < agentManager.agents.Count; j++) + { var agent = (PhysicsRemoteFPSAgentController)agentManager.agents[j]; agent.transform.position = candidatePositions[j]; - foreach (float r in rotations.Shuffle_()) { + foreach (float r in rotations.Shuffle_()) + { agent.transform.rotation = Quaternion.Euler( new Vector3(0f, r, 0f) ); - if (agent.objectIsCurrentlyVisible(objectCreated, 100f)) { + if (agent.objectIsCurrentlyVisible(objectCreated, 100f)) + { break; } } } break; } - if (placementSuccess) { + if (placementSuccess) + { break; } } } - if (placementSuccess) { + if (placementSuccess) + { break; - } else { - foreach (BaseFPSAgentController agent in this.agentManager.agents) { + } + else + { + foreach (BaseFPSAgentController agent in this.agentManager.agents) + { agent.transform.position = new Vector3(50f, 50f, 50f); } randomlyPlaceObjectOnFloor(objectCreated, reachablePositions); @@ -1179,8 +1372,10 @@ Vector3[] candidatePositions in UtilityFunctions.Combinations( } } - if (!placementSuccess) { - for (int i = 0; i < this.agentManager.agents.Count; i++) { + if (!placementSuccess) + { + for (int i = 0; i < this.agentManager.agents.Count; i++) + { var agent = this.agentManager.agents[i]; agent.transform.position = oldAgentPositions[i]; agent.transform.rotation = oldAgentRotations[i]; @@ -1199,11 +1394,13 @@ protected bool moveObject( Vector3 targetPosition, bool snapToGrid = false, HashSet ignoreCollisionWithTransforms = null - ) { + ) + { Vector3 lastPosition = sop.transform.position; // Rigidbody ItemRB = sop.gameObject.GetComponent(); no longer needs rb reference - if (snapToGrid) { + if (snapToGrid) + { float mult = 1.0f / gridSize; float gridX = Convert.ToSingle(Math.Round(targetPosition.x * mult) / mult); float gridZ = Convert.ToSingle(Math.Round(targetPosition.z * mult) / mult); @@ -1226,12 +1423,15 @@ protected bool moveObject( QueryTriggerInteraction.Ignore ); - if (sweepResults.Length > 0) { - foreach (RaycastHit hit in sweepResults) { + 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; return false; @@ -1246,21 +1446,27 @@ protected bool moveLiftedObjectHelper( string objectId, Vector3 relativeDir, float maxAgentsDistance = -1.0f - ) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + ) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; return false; } SimObjPhysics objectToMove = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; Vector3 oldPosition = objectToMove.transform.position; - if (moveObject(objectToMove, objectToMove.transform.position + relativeDir, true)) { - if (maxAgentsDistance > 0.0f) { - for (int i = 0; i < agentManager.agents.Count; i++) { + 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 - ) { + ) + { objectToMove.transform.position = oldPosition; errorMessage = "Would move object beyond max distance from agent " + i.ToString(); @@ -1269,20 +1475,25 @@ protected bool moveLiftedObjectHelper( } } return true; - } else { + } + else + { return false; } } - public void CollidersObjectCollidingWith(string objectId) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void CollidersObjectCollidingWith(string objectId) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; } List collidingWithNames = new List(); GameObject go = physicsSceneManager.ObjectIdToSimObjPhysics[objectId].gameObject; - foreach (Collider c in UtilityFunctions.collidersObjectCollidingWith(go)) { + foreach (Collider c in UtilityFunctions.collidersObjectCollidingWith(go)) + { collidingWithNames.Add(c.name); #if UNITY_EDITOR Debug.Log(c.name); @@ -1295,10 +1506,12 @@ protected bool moveObjectWithTeleport( SimObjPhysics sop, Vector3 targetPosition, bool snapToGrid = false - ) { + ) + { Vector3 lastPosition = sop.transform.position; - if (snapToGrid) { + if (snapToGrid) + { float mult = 1.0f / gridSize; float gridX = Convert.ToSingle(Math.Round(targetPosition.x * mult) / mult); float gridZ = Convert.ToSingle(Math.Round(targetPosition.z * mult) / mult); @@ -1308,13 +1521,15 @@ protected bool moveObjectWithTeleport( Vector3 oldPosition = sop.transform.position; sop.transform.position = targetPosition; - if (UtilityFunctions.isObjectColliding(sop.gameObject)) { + if (UtilityFunctions.isObjectColliding(sop.gameObject)) + { sop.transform.position = oldPosition; errorMessage = sop.ObjectID + " is colliding after teleport."; return false; } - foreach (BaseFPSAgentController agent in agentManager.agents) { + foreach (BaseFPSAgentController agent in agentManager.agents) + { // 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. @@ -1322,7 +1537,8 @@ protected bool moveObjectWithTeleport( ((PhysicsRemoteFPSAgentController)agent).isAgentCapsuleCollidingWith( sop.gameObject ) - ) { + ) + { sop.transform.position = oldPosition; errorMessage = sop.ObjectID + " is colliding with an agent after movement."; return false; @@ -1332,7 +1548,8 @@ protected bool moveObjectWithTeleport( return true; } - public void MoveLiftedObjectAhead(ServerAction action) { + public void MoveLiftedObjectAhead(ServerAction action) + { float mag = action.moveMagnitude > 0 ? action.moveMagnitude : gridSize; actionFinished( moveLiftedObjectHelper( @@ -1343,7 +1560,8 @@ public void MoveLiftedObjectAhead(ServerAction action) { ); } - public void MoveLiftedObjectRight(ServerAction action) { + public void MoveLiftedObjectRight(ServerAction action) + { float mag = action.moveMagnitude > 0 ? action.moveMagnitude : gridSize; actionFinished( moveLiftedObjectHelper( @@ -1354,7 +1572,8 @@ public void MoveLiftedObjectRight(ServerAction action) { ); } - public void MoveLiftedObjectLeft(ServerAction action) { + public void MoveLiftedObjectLeft(ServerAction action) + { float mag = action.moveMagnitude > 0 ? action.moveMagnitude : gridSize; actionFinished( moveLiftedObjectHelper( @@ -1365,7 +1584,8 @@ public void MoveLiftedObjectLeft(ServerAction action) { ); } - public void MoveLiftedObjectBack(ServerAction action) { + public void MoveLiftedObjectBack(ServerAction action) + { float mag = action.moveMagnitude > 0 ? action.moveMagnitude : gridSize; actionFinished( moveLiftedObjectHelper( @@ -1376,15 +1596,20 @@ public void MoveLiftedObjectBack(ServerAction action) { ); } - public void RotateLiftedObjectRight(ServerAction action) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void RotateLiftedObjectRight(ServerAction action) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { errorMessage = "Cannot find object with id " + action.objectId; Debug.Log(errorMessage); actionFinished(false); return; - } else { + } + else + { SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId]; - if (ItemInHand != null && sop == ItemInHand.GetComponent()) { + if (ItemInHand != null && sop == ItemInHand.GetComponent()) + { errorMessage = "Cannot rotate lifted object in hand."; Debug.Log(errorMessage); actionFinished(false); @@ -1399,14 +1624,18 @@ public void RotateLiftedObjectRight(ServerAction action) { ) ); ; - if (!action.forceAction) { - if (action.maxAgentsDistance > 0.0f) { - for (int i = 0; i < agentManager.agents.Count; i++) { + 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 - ) { + ) + { sop.transform.rotation = oldRotation; errorMessage = "Would move object beyond max distance from agent " @@ -1416,13 +1645,15 @@ public void RotateLiftedObjectRight(ServerAction action) { } } } - if (UtilityFunctions.isObjectColliding(sop.gameObject, null, 0.0f)) { + if (UtilityFunctions.isObjectColliding(sop.gameObject, null, 0.0f)) + { sop.transform.rotation = oldRotation; errorMessage = sop.ObjectID + " is colliding after teleport."; actionFinished(false); return; } - foreach (BaseFPSAgentController agent in agentManager.agents) { + foreach (BaseFPSAgentController agent in agentManager.agents) + { // 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. @@ -1430,7 +1661,8 @@ public void RotateLiftedObjectRight(ServerAction action) { ((PhysicsRemoteFPSAgentController)agent).isAgentCapsuleCollidingWith( sop.gameObject ) - ) { + ) + { sop.transform.rotation = oldRotation; errorMessage = sop.ObjectID + " is colliding with an agent after rotation."; @@ -1447,10 +1679,12 @@ public bool moveAgentsWithObject( SimObjPhysics objectToMove, Vector3 d, bool snapToGrid = true - ) { + ) + { List startAgentPositions = new List(); var agentMovePQ = new SimplePriorityQueue(); - foreach (BaseFPSAgentController agent in agentManager.agents) { + foreach (BaseFPSAgentController agent in agentManager.agents) + { var p = agent.transform.position; startAgentPositions.Add(p); agentMovePQ.Enqueue(agent, -(d.x * p.x + d.z * p.z)); @@ -1460,19 +1694,24 @@ public bool moveAgentsWithObject( bool objectMoved = false; HashSet agentsAndObjColliders = new HashSet(); - foreach (BaseFPSAgentController agent in agentManager.agents) { - foreach (Collider c in agent.GetComponentsInChildren()) { + foreach (BaseFPSAgentController agent in agentManager.agents) + { + foreach (Collider c in agent.GetComponentsInChildren()) + { agentsAndObjColliders.Add(c); } } - foreach (Collider c in objectToMove.GetComponentsInChildren()) { + foreach (Collider c in objectToMove.GetComponentsInChildren()) + { agentsAndObjColliders.Add(c); } bool success = true; Physics.autoSimulation = false; - while (agentMovePQ.Count > 0 || !objectMoved) { - if (agentMovePQ.Count == 0) { + while (agentMovePQ.Count > 0 || !objectMoved) + { + if (agentMovePQ.Count == 0) + { success = moveObjectWithTeleport( objectToMove, objectToMove.transform.position + d, @@ -1480,12 +1719,15 @@ public bool moveAgentsWithObject( ); PhysicsSceneManager.PhysicsSimulateTHOR(0.04f); break; - } else { + } + else + { PhysicsRemoteFPSAgentController nextAgent = (PhysicsRemoteFPSAgentController) agentMovePQ.First; float agentPriority = -agentMovePQ.GetPriority(nextAgent); - if (!objectMoved && agentPriority < objectPriority) { + if (!objectMoved && agentPriority < objectPriority) + { // Debug.Log("Object"); success = moveObjectWithTeleport( objectToMove, @@ -1494,7 +1736,9 @@ public bool moveAgentsWithObject( ); PhysicsSceneManager.PhysicsSimulateTHOR(0.04f); objectMoved = true; - } else { + } + else + { // Debug.Log(nextAgent); agentMovePQ.Dequeue(); success = nextAgent.moveInDirection( @@ -1508,13 +1752,16 @@ public bool moveAgentsWithObject( PhysicsSceneManager.PhysicsSimulateTHOR(0.04f); } } - if (!success) { + if (!success) + { break; } } Physics.autoSimulation = true; - if (!success) { - for (int i = 0; i < agentManager.agents.Count; i++) { + if (!success) + { + for (int i = 0; i < agentManager.agents.Count; i++) + { agentManager.agents[i].transform.position = startAgentPositions[i]; } objectToMove.transform.position = startObjectPosition; @@ -1522,8 +1769,10 @@ public bool moveAgentsWithObject( return success; } - public void MoveAgentsAheadWithObject(ServerAction action) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void MoveAgentsAheadWithObject(ServerAction action) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { errorMessage = "Cannot find object with id " + action.objectId; actionFinished(false); return; @@ -1537,8 +1786,10 @@ public void MoveAgentsAheadWithObject(ServerAction action) { ); } - public void MoveAgentsLeftWithObject(ServerAction action) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void MoveAgentsLeftWithObject(ServerAction action) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { errorMessage = "Cannot find object with id " + action.objectId; actionFinished(false); return; @@ -1552,8 +1803,10 @@ public void MoveAgentsLeftWithObject(ServerAction action) { ); } - public void MoveAgentsRightWithObject(ServerAction action) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void MoveAgentsRightWithObject(ServerAction action) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { errorMessage = "Cannot find object with id " + action.objectId; actionFinished(false); return; @@ -1567,8 +1820,10 @@ public void MoveAgentsRightWithObject(ServerAction action) { ); } - public void MoveAgentsBackWithObject(ServerAction action) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void MoveAgentsBackWithObject(ServerAction action) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { errorMessage = "Cannot find object with id " + action.objectId; actionFinished(false); return; @@ -1582,32 +1837,41 @@ public void MoveAgentsBackWithObject(ServerAction action) { ); } - public void TeleportObjectToFloor(ServerAction action) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void TeleportObjectToFloor(ServerAction action) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { errorMessage = "Cannot find object with id " + action.objectId; actionFinished(false); return; - } else { + } + else + { SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId]; - if (ItemInHand != null && sop == ItemInHand.GetComponent()) { + if (ItemInHand != null && sop == ItemInHand.GetComponent()) + { errorMessage = "Cannot teleport object in hand."; actionFinished(false); return; } Bounds objBounds = UtilityFunctions.CreateEmptyBounds(); - foreach (Renderer r in sop.GetComponentsInChildren()) { - if (r.enabled) { + foreach (Renderer r in sop.GetComponentsInChildren()) + { + if (r.enabled) + { objBounds.Encapsulate(r.bounds); } } - if (objBounds.min.x == float.PositiveInfinity) { + if (objBounds.min.x == float.PositiveInfinity) + { errorMessage = "Could not get bounds of " + action.objectId + "."; actionFinished(false); return; } float y = getFloorY(action.x, action.z); - if (errorMessage != "") { + if (errorMessage != "") + { actionFinished(false); return; } @@ -1654,7 +1918,8 @@ public void TeleportFull( float? horizon, bool? standing, bool forceAction = false - ) { + ) + { TeleportFull( position: new Vector3(x, y, z), rotation: rotation, @@ -1688,7 +1953,8 @@ public virtual void TeleportFull( float? horizon, bool? standing, bool forceAction = false - ) { + ) + { Debug.Log($"------- Teleport Full physicsFPS type {this.GetType()}"); // cache old values in case there's a failure bool wasStanding = isStanding(); @@ -1698,12 +1964,14 @@ public virtual void TeleportFull( Vector3 oldLocalHandPosition = new Vector3(); Quaternion oldLocalHandRotation = new Quaternion(); - if (ItemInHand != null) { + if (ItemInHand != null) + { oldLocalHandPosition = ItemInHand.transform.localPosition; oldLocalHandRotation = ItemInHand.transform.localRotation; } - try { + try + { // default high level hand when teleporting DefaultAgentHand(); base.teleportFull( @@ -1713,39 +1981,54 @@ public virtual void TeleportFull( forceAction: forceAction ); - if (standing.HasValue) { - if (standing.Value) { + if (standing.HasValue) + { + if (standing.Value) + { stand(); - } else { + } + else + { crouch(); } } // add arm value cases - if (!forceAction) { - if (isHandObjectColliding(ignoreAgent: true)) { + if (!forceAction) + { + if (isHandObjectColliding(ignoreAgent: true)) + { throw new InvalidOperationException( "Cannot teleport due to hand object collision." ); } - if (Arm != null && Arm.IsArmColliding()) { + 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." ); } base.assertTeleportedNearGround(targetPosition: position); } - } catch (InvalidOperationException e) { - if (wasStanding) { + } + catch (InvalidOperationException e) + { + if (wasStanding) + { stand(); - } else { + } + else + { crouch(); } - if (ItemInHand != null) { + if (ItemInHand != null) + { ItemInHand.transform.localPosition = oldLocalHandPosition; ItemInHand.transform.localRotation = oldLocalHandRotation; } @@ -1792,7 +2075,8 @@ public void Teleport( float? horizon = null, bool? standing = null, bool forceAction = false - ) { + ) + { Teleport( position: new Vector3(x, y, z), rotation: rotation, @@ -1826,7 +2110,8 @@ public void Teleport( float? horizon = null, bool? standing = null, bool forceAction = false - ) { + ) + { TeleportFull( position: position == null ? transform.position : (Vector3)position, rotation: rotation == null ? transform.eulerAngles : (Vector3)rotation, @@ -1836,22 +2121,29 @@ public void Teleport( ); } - public void ToggleArmColliders(IK_Robot_Arm_Controller arm, bool value) { - if (arm != null) { - foreach (CapsuleCollider c in arm.ArmCapsuleColliders) { + public void ToggleArmColliders(IK_Robot_Arm_Controller arm, bool value) + { + if (arm != null) + { + foreach (CapsuleCollider c in arm.ArmCapsuleColliders) + { c.isTrigger = value; } - foreach (BoxCollider b in arm.ArmBoxColliders) { + foreach (BoxCollider b in arm.ArmBoxColliders) + { b.isTrigger = value; } } } - protected HashSet allAgentColliders() { + protected HashSet allAgentColliders() + { HashSet colliders = null; colliders = new HashSet(); - foreach (BaseFPSAgentController agent in agentManager.agents) { - foreach (Collider c in agent.GetComponentsInChildren()) { + foreach (BaseFPSAgentController agent in agentManager.agents) + { + foreach (Collider c in agent.GetComponentsInChildren()) + { colliders.Add(c); } } @@ -1869,10 +2161,14 @@ public virtual void MoveLeft( 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 - ) { - if (!moveMagnitude.HasValue) { + ) + { + if (!moveMagnitude.HasValue) + { moveMagnitude = gridSize; - } else if (moveMagnitude <= 0f) { + } + else if (moveMagnitude <= 0f) + { throw new InvalidOperationException("moveMagnitude must be > 0"); } @@ -1895,11 +2191,15 @@ public virtual void MoveRight( bool forceAction = false, bool manualInteract = false, bool allowAgentsToIntersect = false - ) { + ) + { Debug.Log("MoveRight at physics fps? call "); - if (!moveMagnitude.HasValue) { + if (!moveMagnitude.HasValue) + { moveMagnitude = gridSize; - } else if (moveMagnitude <= 0f) { + } + else if (moveMagnitude <= 0f) + { throw new InvalidOperationException("moveMagnitude must be > 0"); } @@ -1922,10 +2222,14 @@ public virtual void MoveAhead( bool forceAction = false, bool manualInteract = false, bool allowAgentsToIntersect = false - ) { - if (!moveMagnitude.HasValue) { + ) + { + if (!moveMagnitude.HasValue) + { moveMagnitude = gridSize; - } else if (moveMagnitude <= 0f) { + } + else if (moveMagnitude <= 0f) + { throw new InvalidOperationException("moveMagnitude must be > 0"); } @@ -1952,10 +2256,14 @@ public virtual void MoveBack( 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 - ) { - if (!moveMagnitude.HasValue) { + ) + { + if (!moveMagnitude.HasValue) + { moveMagnitude = gridSize; - } else if (moveMagnitude <= 0f) { + } + else if (moveMagnitude <= 0f) + { throw new InvalidOperationException("moveMagnitude must be > 0"); } @@ -1972,15 +2280,18 @@ public virtual void MoveBack( } // 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 - public void NoOp() { + public void NoOp() + { actionFinished(true); } - public void PushObject(ServerAction action) { + public void PushObject(ServerAction action) + { 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); @@ -1996,11 +2307,13 @@ public void PushObject(ServerAction action) { ApplyForceObject(action); } - public void PullObject(ServerAction action) { + public void PullObject(ServerAction action) + { 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); @@ -2017,11 +2330,13 @@ 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) { + public void DirectionalPush(ServerAction action) + { 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); @@ -2033,22 +2348,27 @@ public void DirectionalPush(ServerAction action) { action.pushAngle %= 360; // converts negative rotations to be positive - if (action.pushAngle < 360) { + if (action.pushAngle < 360) + { action.pushAngle += 360; } - if (action.forceAction) { + if (action.forceAction) + { action.forceVisible = true; } SimObjPhysics target = null; - if (action.objectId == null) { + if (action.objectId == null) + { target = getInteractableSimObjectFromXY( x: action.x, y: action.y, forceAction: action.forceAction ); - } else { + } + else + { target = getInteractableSimObjectFromId( objectId: action.objectId, forceAction: action.forceAction @@ -2068,13 +2388,15 @@ public void DirectionalPush(ServerAction action) { if ( target.PrimaryProperty != SimObjPrimaryProperty.CanPickup && target.PrimaryProperty != SimObjPrimaryProperty.Moveable - ) { + ) + { throw new InvalidOperationException( "Target Primary Property type incompatible with push/pull" ); } - if (!action.forceAction && !IsInteractable(target)) { + if (!action.forceAction && !IsInteractable(target)) + { errorMessage = "Target is not interactable and is probably occluded by something!"; actionFinished(false); return; @@ -2108,19 +2430,24 @@ public void DirectionalPush(ServerAction action) { // actionFinished(true); } - public void ApplyForceObject(ServerAction action) { - if (action.forceAction) { + public void ApplyForceObject(ServerAction action) + { + if (action.forceAction) + { action.forceVisible = true; } SimObjPhysics target = null; - if (action.objectId == null) { + if (action.objectId == null) + { target = getInteractableSimObjectFromXY( x: action.x, y: action.y, forceAction: action.forceAction ); - } else { + } + else + { target = getInteractableSimObjectFromId( objectId: action.objectId, forceAction: action.forceAction @@ -2132,18 +2459,21 @@ public void ApplyForceObject(ServerAction action) { if ( target.PrimaryProperty == SimObjPrimaryProperty.CanPickup || target.PrimaryProperty == SimObjPrimaryProperty.Moveable - ) { + ) + { canbepushed = true; } - if (!canbepushed) { + if (!canbepushed) + { errorMessage = "Target Sim Object cannot be moved. It's primary property must be Pickupable or Moveable"; actionFinished(false); return; } - if (!action.forceAction && !IsInteractable(target)) { + if (!action.forceAction && !IsInteractable(target)) + { errorMessage = "Target:" + target.objectID @@ -2159,11 +2489,13 @@ public void ApplyForceObject(ServerAction action) { Vector3 dir = Vector3.zero; - if (action.z == 1) { + if (action.z == 1) + { dir = gameObject.transform.forward; } - if (action.z == -1) { + if (action.z == -1) + { dir = -gameObject.transform.forward; } // Vector3 dir = gameObject.transform.forward; @@ -2177,21 +2509,27 @@ public void ApplyForceObject(ServerAction action) { // actionFinished(true); } - public IEnumerator SimulatePhysics(int steps) { - for (var i = 0; i < steps; i++) { + public IEnumerator SimulatePhysics(int steps) + { + for (var i = 0; i < steps; i++) + { yield return new WaitForFixedUpdate(); } yield return ActionFinished.Success; } - protected void sopApplyForce(ServerAction action, SimObjPhysics sop, float length) { + protected void sopApplyForce(ServerAction action, SimObjPhysics sop, float length) + { // print("running sopApplyForce"); // apply force, return action finished immediately - if (physicsSceneManager.physicsSimulationPaused) { + if (physicsSceneManager.physicsSimulationPaused) + { // print("autosimulation off"); sop.ApplyForce(action); - if (length >= 0.00001f) { - WhatDidITouch feedback = new WhatDidITouch() { + if (length >= 0.00001f) + { + WhatDidITouch feedback = new WhatDidITouch() + { didHandTouchSomething = true, objectId = sop.objectID, armsLength = length @@ -2204,12 +2542,14 @@ protected void sopApplyForce(ServerAction action, SimObjPhysics sop, float lengt actionFinished(true, feedback); } // why is this here? - else { + else + { actionFinished(true); } } // if physics is automatically being simulated, use coroutine rather than returning actionFinished immediately - else { + else + { // print("autosimulation true"); sop.ApplyForce(action); StartCoroutine(checkIfObjectHasStoppedMoving(sop: sop, length: length)); @@ -2223,23 +2563,28 @@ protected IEnumerator checkIfObjectHasStoppedMoving( SimObjPhysics sop, float length, bool useTimeout = false - ) { + ) + { // yield for the physics update to make sure this yield is consistent regardless of framerate yield return new WaitForFixedUpdate(); float startTime = Time.time; float waitTime = TimeToWaitForObjectsToComeToRest; - if (useTimeout) { + if (useTimeout) + { waitTime = 1.0f; } - if (sop != null) { + if (sop != null) + { Rigidbody rb = sop.GetComponentInChildren(); bool stoppedMoving = false; - while (Time.time - startTime < waitTime) { - if (sop == null) { + while (Time.time - startTime < waitTime) + { + if (sop == null) + { break; } @@ -2249,20 +2594,24 @@ protected IEnumerator checkIfObjectHasStoppedMoving( float accel = (currentVelocity - sop.lastVelocity) / Time.fixedDeltaTime; // ok the accel is basically zero, so it has stopped moving - if (Mathf.Abs(accel) <= 0.001f) { + if (Mathf.Abs(accel) <= 0.001f) + { // force the rb to stop moving just to be safe rb.velocity = Vector3.zero; rb.angularVelocity = Vector3.zero; rb.Sleep(); stoppedMoving = true; break; - } else { + } + else + { yield return new WaitForFixedUpdate(); } } // so we never stopped moving and we are using the timeout - if (!stoppedMoving && useTimeout) { + if (!stoppedMoving && useTimeout) + { errorMessage = "object couldn't come to rest"; // print(errorMessage); actionFinished(false); @@ -2270,7 +2619,8 @@ protected IEnumerator checkIfObjectHasStoppedMoving( } // return to metadatawrapper.actionReturn if an object was touched during this interaction - WhatDidITouch feedback = new WhatDidITouch() { + WhatDidITouch feedback = new WhatDidITouch() + { didHandTouchSomething = true, objectId = sop.objectID, armsLength = length @@ -2289,14 +2639,17 @@ protected IEnumerator checkIfObjectHasStoppedMoving( rb.Sleep(); actionFinished(true, feedback); - } else { + } + else + { errorMessage = "null reference sim obj in checkIfObjectHasStoppedMoving call"; actionFinished(false); } } // wrapping the SimObjPhysics.ApplyForce function since lots of things use it.... - protected void sopApplyForce(ServerAction action, SimObjPhysics sop) { + protected void sopApplyForce(ServerAction action, SimObjPhysics sop) + { sopApplyForce(action, sop, 0.0f); } @@ -2304,23 +2657,28 @@ private IEnumerator checkIfAllObjectsHaveStoppedMoving( float length, double squaredAccelerationEpsilon = 1e-3, bool useTimeout = false - ) { + ) + { // yield for the physics update to make sure this yield is consistent regardless of framerate yield return new WaitForFixedUpdate(); float startTime = Time.time; float waitTime = TimeToWaitForObjectsToComeToRest; - if (useTimeout) { + if (useTimeout) + { waitTime = 1.0f; } - foreach (var sop in GameObject.FindObjectsOfType()) { + foreach (var sop in GameObject.FindObjectsOfType()) + { Rigidbody rb = sop.GetComponentInChildren(); bool stoppedMoving = false; - while (Time.time - startTime < waitTime) { - if (sop == null) { + while (Time.time - startTime < waitTime) + { + if (sop == null) + { break; } @@ -2331,20 +2689,24 @@ private IEnumerator checkIfAllObjectsHaveStoppedMoving( / (Time.fixedDeltaTime * Time.fixedDeltaTime); // ok the accel is basically zero, so it has stopped moving - if (Mathf.Abs(squaredAccel) <= squaredAccelerationEpsilon) { + if (Mathf.Abs(squaredAccel) <= squaredAccelerationEpsilon) + { // force the rb to stop moving just to be safe rb.velocity = Vector3.zero; rb.angularVelocity = Vector3.zero; rb.Sleep(); stoppedMoving = true; break; - } else { + } + else + { yield return new WaitForFixedUpdate(); } } // so we never stopped moving and we are using the timeout - if (!stoppedMoving && useTimeout) { + if (!stoppedMoving && useTimeout) + { errorMessage = "object couldn't come to rest"; // print(errorMessage); actionFinished(false); @@ -2357,8 +2719,10 @@ private IEnumerator checkIfAllObjectsHaveStoppedMoving( // rb.Sleep(); // return to metadatawrapper.actionReturn if an object was touched during this interaction - if (length != 0.0f) { - WhatDidITouch feedback = new WhatDidITouch() { + if (length != 0.0f) + { + WhatDidITouch feedback = new WhatDidITouch() + { didHandTouchSomething = true, objectId = sop.objectID, armsLength = length @@ -2379,7 +2743,8 @@ private IEnumerator checkIfAllObjectsHaveStoppedMoving( actionFinished(true, feedback); } // if passed in length is 0, don't return feedback cause not all actions need that - else { + else + { DefaultAgentHand(); actionFinished(true, sop.transform.position); } @@ -2387,21 +2752,27 @@ private IEnumerator checkIfAllObjectsHaveStoppedMoving( } // Sweeptest to see if the object Agent is holding will prohibit movement - public bool CheckIfItemBlocksAgentStandOrCrouch() { + public bool CheckIfItemBlocksAgentStandOrCrouch() + { bool result = false; // if there is nothing in our hand, we are good, return! - if (ItemInHand == null) { + if (ItemInHand == null) + { result = true; return result; } // otherwise we are holding an object and need to do a sweep using that object's rb - else { + else + { Vector3 dir = new Vector3(); - if (isStanding()) { + if (isStanding()) + { dir = new Vector3(0.0f, -1f, 0.0f); - } else { + } + else + { dir = new Vector3(0.0f, 1f, 0.0f); } @@ -2412,16 +2783,21 @@ public bool CheckIfItemBlocksAgentStandOrCrouch() { standingLocalCameraPosition.y, QueryTriggerInteraction.Ignore ); - if (sweepResults.Length > 0) { - foreach (RaycastHit res in sweepResults) { + if (sweepResults.Length > 0) + { + foreach (RaycastHit res in sweepResults) + { // did the item in the hand touch the agent? if so, ignore it's fine // also ignore Untagged because the Transparent_RB of transparent objects need to be ignored for movement // the actual rigidbody of the SimObjPhysics parent object of the transparent_rb should block correctly by having the // checkMoveAction() in the BaseFPSAgentController fail when the agent collides and gets shoved back - if (res.transform.tag == "Player" || res.transform.tag == "Untagged") { + if (res.transform.tag == "Player" || res.transform.tag == "Untagged") + { result = true; break; - } else { + } + else + { errorMessage = res.transform.name + " is blocking the Agent from moving " @@ -2435,7 +2811,8 @@ public bool CheckIfItemBlocksAgentStandOrCrouch() { } } // if the array is empty, nothing was hit by the sweeptest so we are clear to move - else { + else + { result = true; } @@ -2449,8 +2826,10 @@ protected IEnumerator moveHandToTowardsXYZWithForce( float y, float z, float maxDistance - ) { - if (ItemInHand == null) { + ) + { + if (ItemInHand == null) + { errorMessage = "Agent can only move hand if holding an item"; actionFinished(false); yield break; @@ -2483,10 +2862,12 @@ float maxDistance Physics.autoSimulation = false; List seenPositions = new List(); List seenRotations = new List(); - for (int i = 0; i < 100; i++) { + for (int i = 0; i < 100; i++) + { seenPositions.Add(rb.transform.position); seenRotations.Add(rb.transform.rotation); - if (rb.velocity.magnitude < 1) { + if (rb.velocity.magnitude < 1) + { rb.AddForce(forceDirection, ForceMode.Force); } rb.angularVelocity = rb.angularVelocity * 0.96f; @@ -2496,21 +2877,25 @@ float maxDistance yield return null; #endif - if (i >= 5) { + if (i >= 5) + { bool repeatedPosition = false; 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) { + if (distance <= 0.001f && angle <= 3f) + { repeatedPosition = true; break; } } - if (repeatedPosition) { + if (repeatedPosition) + { break; } } @@ -2522,7 +2907,8 @@ float maxDistance Vector3 forceDir = Vector3.Project(newPosition - initialPosition, forceDirection); Vector3 perpDir = delta - forceDir; float perpNorm = perpDir.magnitude; - if (perpNorm > 0.1f * maxDistance) { + if (perpNorm > 0.1f * maxDistance) + { newPosition = initialPosition + forceDir + (0.1f * maxDistance) * perpDir / perpNorm; rb.transform.position = newPosition; @@ -2538,15 +2924,19 @@ float maxDistance leavingViewport = !objectIsWithinViewport(simObjInHand); // leavingViewport = !objectIsCurrentlyVisible(simObjInHand, 1000f); - if (hitMaxDistance) { + if (hitMaxDistance) + { rb.velocity = new Vector3(0f, 0f, 0f); rb.angularVelocity = 0.0f * rb.angularVelocity; break; } - if (beyondVisibleDistance || leavingViewport) { + if (beyondVisibleDistance || leavingViewport) + { break; - } else { + } + else + { positions.Add(rb.transform.position); rotations.Add(rb.transform.rotation); lastPosition = rb.transform.position; @@ -2559,14 +2949,17 @@ float maxDistance int count = 0; foreach ( KeyValuePair pair in simObjInHand.contactPointsDictionary - ) { - foreach (ContactPoint cp in pair.Value) { + ) + { + foreach (ContactPoint cp in pair.Value) + { normalSum += cp.normal; count += 1; } } - if (count != 0) { + if (count != 0) + { aveCollisionsNormal = normalSum / count; aveCollisionsNormal.Normalize(); } @@ -2582,8 +2975,10 @@ KeyValuePair pair in simObjInHand.contactPointsDiction PhysicsSceneManager.PhysicsSimulateTHOR(0.1f); bool handObjectIsColliding = isHandObjectColliding(true); - if (count != 0) { - for (int j = 0; handObjectIsColliding && j < 5; j++) { + if (count != 0) + { + for (int j = 0; handObjectIsColliding && j < 5; j++) + { AgentHand.transform.position = AgentHand.transform.position + 0.01f * aveCollisionsNormal; PhysicsSceneManager.PhysicsSimulateTHOR(0.1f); @@ -2598,7 +2993,8 @@ KeyValuePair pair in simObjInHand.contactPointsDiction rb.isKinematic = true; rb.collisionDetectionMode = oldCollisionDetectionMode; - if (handObjectIsColliding) { + if (handObjectIsColliding) + { AgentHand.transform.position = initialPosition; rb.transform.rotation = initialRotation; errorMessage = "Hand object was colliding with: "; @@ -2607,38 +3003,53 @@ KeyValuePair pair in simObjInHand.contactPointsDiction Collider, ContactPoint[] > pair in simObjInHand.contactPointsDictionary - ) { + ) + { SimObjPhysics sop = ancestorSimObjPhysics(pair.Key.gameObject); - if (sop != null) { + if (sop != null) + { errorMessage += "" + sop.ObjectID + ", "; - } else { + } + else + { errorMessage += "" + pair.Key.gameObject.name + ", "; } } errorMessage += " object(s) after movement."; actionFinished(false); - } else if ( - Vector3.Distance(initialPosition, lastPosition) < 0.001f - && Quaternion.Angle(initialRotation, lastRotation) < 0.001f - ) { - if (beyondVisibleDistance) { + } + 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) { + } + else if (leavingViewport) + { errorMessage = "Hand at viewport constraints."; - } else { + } + else + { errorMessage = "Hand object did not move, perhaps its being blocked."; } actionFinished(false); - } else { + } + else + { actionFinished(true); } } - public void OpenWithHand(ServerAction action) { + public void OpenWithHand(ServerAction action) + { Vector3 direction = transform.forward * action.z + transform.right * action.x + transform.up * action.y; direction.Normalize(); - if (ItemInHand != null) { + if (ItemInHand != null) + { ItemInHand.SetActive(false); } RaycastHit hit; @@ -2657,33 +3068,44 @@ public void OpenWithHand(ServerAction action) { 10f, layerMask ); - if (ItemInHand != null) { + if (ItemInHand != null) + { ItemInHand.SetActive(true); } - if (!raycastDidHit) { + if (!raycastDidHit) + { errorMessage = "No openable objects in direction."; actionFinished(false); return; } SimObjPhysics so = ancestorSimObjPhysics(hit.transform.gameObject); - if (so != null) { + if (so != null) + { OpenObject(objectId: so.ObjectID, forceAction: true); - } else { + } + else + { errorMessage = hit.transform.gameObject.name + " is not interactable."; actionFinished(false); } } - public void MoveHandForce(float x, float y, float z) { + 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; - if (ItemInHand == null) { + if (ItemInHand == null) + { Debug.Log("Agent can only move hand if holding an item"); actionFinished(false); - } else if (moveHandToXYZ(target.x, target.y, target.z)) { + } + else if (moveHandToXYZ(target.x, target.y, target.z)) + { actionFinished(true); - } else { + } + else + { errorMessage = ""; StartCoroutine( moveHandToTowardsXYZWithForce(target.x, target.y, target.z, direction.magnitude) @@ -2691,7 +3113,8 @@ public void MoveHandForce(float x, float y, float z) { } } - public void TouchThenApplyForce(ServerAction action) { + public void TouchThenApplyForce(ServerAction action) + { float x = action.x; float y = 1.0f - action.y; // reverse the y so that the origin (0, 0) can be passed in as the top left of the screen @@ -2716,21 +3139,27 @@ public void TouchThenApplyForce(ServerAction action) { ), QueryTriggerInteraction.Ignore ) - ) { - if (hit.transform.GetComponent()) { + ) + { + if (hit.transform.GetComponent()) + { // 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 { + try + { assertPosInView( targetPosition: hit.point, inMaxVisibleDistance: true, inViewport: true ); - } catch (InvalidOperationException e) { + } + catch (InvalidOperationException e) + { actionFinished( success: false, errorMessage: "Object successfully hit, but it is outside of the Agent's interaction range", - actionReturn: new WhatDidITouch() { + actionReturn: new WhatDidITouch() + { didHandTouchSomething = false, objectId = "", armsLength = action.handDistance @@ -2746,13 +3175,16 @@ public void TouchThenApplyForce(ServerAction action) { if ( target.PrimaryProperty == SimObjPrimaryProperty.CanPickup || target.PrimaryProperty == SimObjPrimaryProperty.Moveable - ) { + ) + { canbepushed = true; } - if (!canbepushed) { + if (!canbepushed) + { // the sim object hit was not moveable or pickupable - WhatDidITouch feedback = new WhatDidITouch() { + WhatDidITouch feedback = new WhatDidITouch() + { didHandTouchSomething = true, objectId = target.objectID, armsLength = hit.distance @@ -2780,8 +3212,10 @@ 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() { + else + { + WhatDidITouch feedback = new WhatDidITouch() + { didHandTouchSomething = true, objectId = "not a sim object, a structure was touched", armsLength = hit.distance @@ -2797,21 +3231,26 @@ public void TouchThenApplyForce(ServerAction action) { } } // raycast didn't hit anything - else { + 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 { + try + { assertPosInView( targetPosition: testPosition, inMaxVisibleDistance: true, inViewport: true ); - } catch (InvalidOperationException e) { + } + catch (InvalidOperationException e) + { actionFinished( success: false, errorMessage: "Object successfully hit, but it is outside of the Agent's interaction range", - actionReturn: new WhatDidITouch() { + actionReturn: new WhatDidITouch() + { didHandTouchSomething = false, objectId = "", armsLength = action.handDistance @@ -2821,7 +3260,8 @@ public void TouchThenApplyForce(ServerAction action) { } // the nothing hit was not out of range, but still nothing was hit - WhatDidITouch feedback = new WhatDidITouch() { + WhatDidITouch feedback = new WhatDidITouch() + { didHandTouchSomething = false, objectId = "", armsLength = action.handDistance @@ -2837,18 +3277,21 @@ public void TouchThenApplyForce(ServerAction action) { } // for use with TouchThenApplyForce feedback return - public struct WhatDidITouch { + 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 } // checks if agent hand that is holding an object can move to a target location. Returns false if any obstructions - public bool CheckIfAgentCanMoveHand(Vector3 targetPosition, bool mustBeVisible = false) { + public bool CheckIfAgentCanMoveHand(Vector3 targetPosition, bool mustBeVisible = false) + { bool result = false; // first check if we have anything in our hand, if not then no reason to move hand - if (ItemInHand == null) { + if (ItemInHand == null) + { errorMessage = "Agent can only move hand if currently holding an item"; result = false; return result; @@ -2858,7 +3301,8 @@ public bool CheckIfAgentCanMoveHand(Vector3 targetPosition, bool mustBeVisible = Vector3 tmp = m_Camera.transform.position; tmp.y = targetPosition.y; - if (Vector3.Distance(tmp, targetPosition) > maxVisibleDistance) { + if (Vector3.Distance(tmp, targetPosition) > maxVisibleDistance) + { errorMessage = "The target position is out of range- object cannot move outside of max visibility distance."; result = false; @@ -2871,7 +3315,8 @@ public bool CheckIfAgentCanMoveHand(Vector3 targetPosition, bool mustBeVisible = 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())) { + 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."; @@ -2884,11 +3329,13 @@ public bool CheckIfAgentCanMoveHand(Vector3 targetPosition, bool mustBeVisible = // by default this is ignored, but pass this as true to force hand manipulation // such that objects will always remain visible to the agent and not occluded - if (mustBeVisible) { + if (mustBeVisible) + { // quickly move object to proposed target position and see if target is still visible lastPosition = AgentHand.transform.position; AgentHand.transform.position = targetPosition; - if (!objectIsCurrentlyVisible(ItemInHand.GetComponent(), 1000f)) { + if (!objectIsCurrentlyVisible(ItemInHand.GetComponent(), 1000f)) + { errorMessage = "The target position is not in the Area of the Agent's Viewport!"; result = false; @@ -2909,15 +3356,19 @@ public bool CheckIfAgentCanMoveHand(Vector3 targetPosition, bool mustBeVisible = ); // did we hit anything? - if (sweepResults.Length > 0) { - foreach (RaycastHit hit in sweepResults) { + if (sweepResults.Length > 0) + { + foreach (RaycastHit hit in sweepResults) + { // hit the player? it's cool, no problem - if (hit.transform.tag == "Player") { + if (hit.transform.tag == "Player") + { result = true; break; } // oh we hit something else? oh boy, that's blocking! - else { + else + { errorMessage = hit.transform.name + " is in Object In Hand's Path! Can't Move Hand holding " @@ -2928,7 +3379,8 @@ public bool CheckIfAgentCanMoveHand(Vector3 targetPosition, bool mustBeVisible = } } // didnt hit anything in sweep, we are good to go - else { + else + { result = true; } @@ -2936,23 +3388,29 @@ public bool CheckIfAgentCanMoveHand(Vector3 targetPosition, bool mustBeVisible = } // moves hand to the x, y, z coordinate, not constrained by any axis, if within range - protected bool moveHandToXYZ(float x, float y, float z, bool mustBeVisible = false) { + protected bool moveHandToXYZ(float x, float y, float z, bool mustBeVisible = false) + { Vector3 targetPosition = new Vector3(x, y, z); - if (CheckIfAgentCanMoveHand(targetPosition, mustBeVisible)) { + if (CheckIfAgentCanMoveHand(targetPosition, mustBeVisible)) + { // Debug.Log("Movement of Agent Hand holding " + ItemInHand.name + " succesful!"); Vector3 oldPosition = AgentHand.transform.position; AgentHand.transform.position = targetPosition; IsHandDefault = false; return true; - } else { + } + else + { // error messages are set up in CheckIfAgentCanMoveHand return false; } } // coroutine to yield n frames before returning - protected IEnumerator waitForNFramesAndReturn(int n, bool actionSuccess) { - for (int i = 0; i < n; i++) { + protected IEnumerator waitForNFramesAndReturn(int n, bool actionSuccess) + { + for (int i = 0; i < n; i++) + { yield return null; } actionFinished(actionSuccess); @@ -2961,7 +3419,8 @@ protected IEnumerator waitForNFramesAndReturn(int n, bool actionSuccess) { // Moves hand relative the agent (but not relative the camera, i.e. up is up) // x, y, z coordinates should specify how far to move in that direction, so // 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) { + 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 @@ -2975,7 +3434,8 @@ public void MoveHand(float x, float y, float z) { 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) { + public void MoveHandDelta(float x, float y, float z, bool forceVisible = false) + { MoveHeldObject(right: x, up: y, ahead: z); } @@ -2985,7 +3445,8 @@ public void MoveHeldObject( float up = 0, float ahead = 0, bool forceVisible = false - ) { + ) + { Vector3 newPos = AgentHand.transform.position; newPos += ( m_Camera.transform.forward * ahead @@ -2999,11 +3460,13 @@ public void MoveHeldObject( message: "This action is deprecated. Call MoveHeldObjectAhead() instead.", error: false )] - public void MoveHandAhead(float moveMagnitude, bool forceVisible = false) { + public void MoveHandAhead(float moveMagnitude, bool forceVisible = false) + { MoveHeldObjectAhead(moveMagnitude: moveMagnitude, forceVisible: forceVisible); } - public void MoveHeldObjectAhead(float moveMagnitude, bool forceVisible = false) { + public void MoveHeldObjectAhead(float moveMagnitude, bool forceVisible = false) + { Vector3 newPos = AgentHand.transform.position; newPos = newPos + (m_Camera.transform.forward * moveMagnitude); actionFinished(moveHandToXYZ(newPos.x, newPos.y, newPos.z, forceVisible)); @@ -3013,11 +3476,13 @@ public void MoveHeldObjectAhead(float moveMagnitude, bool forceVisible = false) message: "This action is deprecated. Call MoveHeldObjectLeft() instead.", error: false )] - public void MoveHandLeft(float moveMagnitude, bool forceVisible = false) { + public void MoveHandLeft(float moveMagnitude, bool forceVisible = false) + { MoveHeldObjectLeft(moveMagnitude: moveMagnitude, forceVisible: forceVisible); } - public void MoveHeldObjectLeft(float moveMagnitude, bool forceVisible = false) { + public void MoveHeldObjectLeft(float moveMagnitude, bool forceVisible = false) + { Vector3 newPos = AgentHand.transform.position; newPos = newPos + (-m_Camera.transform.right * moveMagnitude); actionFinished(moveHandToXYZ(newPos.x, newPos.y, newPos.z, forceVisible)); @@ -3027,11 +3492,13 @@ public void MoveHeldObjectLeft(float moveMagnitude, bool forceVisible = false) { message: "This action is deprecated. Call MoveHeldObjectDown() instead.", error: false )] - public void MoveHandDown(float moveMagnitude, bool forceVisible = false) { + public void MoveHandDown(float moveMagnitude, bool forceVisible = false) + { MoveHeldObjectDown(moveMagnitude: moveMagnitude, forceVisible: forceVisible); } - public void MoveHeldObjectDown(float moveMagnitude, bool forceVisible = false) { + public void MoveHeldObjectDown(float moveMagnitude, bool forceVisible = false) + { Vector3 newPos = AgentHand.transform.position; newPos = newPos + (-m_Camera.transform.up * moveMagnitude); actionFinished(moveHandToXYZ(newPos.x, newPos.y, newPos.z, forceVisible)); @@ -3041,11 +3508,13 @@ public void MoveHeldObjectDown(float moveMagnitude, bool forceVisible = false) { message: "This action is deprecated. Call MoveHeldObjectUp() instead.", error: false )] - public void MoveHandUp(float moveMagnitude, bool forceVisible = false) { + public void MoveHandUp(float moveMagnitude, bool forceVisible = false) + { MoveHeldObjectUp(moveMagnitude: moveMagnitude, forceVisible: forceVisible); } - public void MoveHeldObjectUp(float moveMagnitude, bool forceVisible = false) { + public void MoveHeldObjectUp(float moveMagnitude, bool forceVisible = false) + { Vector3 newPos = AgentHand.transform.position; newPos = newPos + (m_Camera.transform.up * moveMagnitude); actionFinished(moveHandToXYZ(newPos.x, newPos.y, newPos.z, forceVisible)); @@ -3055,11 +3524,13 @@ public void MoveHeldObjectUp(float moveMagnitude, bool forceVisible = false) { message: "This action is deprecated. Call MoveHeldObjectRight() instead.", error: false )] - public void MoveHandRight(float moveMagnitude, bool forceVisible = false) { + public void MoveHandRight(float moveMagnitude, bool forceVisible = false) + { MoveHeldObjectRight(moveMagnitude: moveMagnitude, forceVisible: forceVisible); } - public void MoveHeldObjectRight(float moveMagnitude, bool forceVisible = false) { + public void MoveHeldObjectRight(float moveMagnitude, bool forceVisible = false) + { Vector3 newPos = AgentHand.transform.position; newPos = newPos + (m_Camera.transform.right * moveMagnitude); actionFinished(moveHandToXYZ(newPos.x, newPos.y, newPos.z, forceVisible)); @@ -3069,11 +3540,13 @@ public void MoveHeldObjectRight(float moveMagnitude, bool forceVisible = false) message: "This action is deprecated. Call MoveHeldObjectBack() instead.", error: false )] - public void MoveHandBack(float moveMagnitude, bool forceVisible = false) { + public void MoveHandBack(float moveMagnitude, bool forceVisible = false) + { MoveHeldObjectBack(moveMagnitude: moveMagnitude, forceVisible: forceVisible); } - public void MoveHeldObjectBack(float moveMagnitude, bool forceVisible = false) { + public void MoveHeldObjectBack(float moveMagnitude, bool forceVisible = false) + { Vector3 newPos = AgentHand.transform.position; newPos = newPos + (-m_Camera.transform.forward * moveMagnitude); actionFinished(moveHandToXYZ(newPos.x, newPos.y, newPos.z, forceVisible)); @@ -3086,51 +3559,63 @@ public void MoveHandMagnitude( 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 - if (x > 0) { + if (x > 0) + { newPos = newPos + (m_Camera.transform.right * moveMagnitude); } - if (x < 0) { + if (x < 0) + { newPos = newPos + (-m_Camera.transform.right * moveMagnitude); } - if (y > 0) { + if (y > 0) + { newPos = newPos + (m_Camera.transform.up * moveMagnitude); } - if (y < 0) { + if (y < 0) + { newPos = newPos + (-m_Camera.transform.up * moveMagnitude); } - if (z > 0) { + if (z > 0) + { newPos = newPos + (m_Camera.transform.forward * moveMagnitude); } - if (z < 0) { + if (z < 0) + { newPos = newPos + (-m_Camera.transform.forward * moveMagnitude); } actionFinished(moveHandToXYZ(newPos.x, newPos.y, newPos.z)); } - public bool IsInArray(Collider collider, GameObject[] arrayOfCol) { - for (int i = 0; i < arrayOfCol.Length; i++) { - if (collider == arrayOfCol[i].GetComponent()) { + public bool IsInArray(Collider collider, GameObject[] arrayOfCol) + { + for (int i = 0; i < arrayOfCol.Length; i++) + { + if (collider == arrayOfCol[i].GetComponent()) + { return true; } } return false; } - public bool CheckIfAgentCanRotateHand() { + public bool CheckIfAgentCanRotateHand() + { bool result = false; // make sure there is a box collider - if (ItemInHand.GetComponent().BoundingBox.GetComponent()) { + if (ItemInHand.GetComponent().BoundingBox.GetComponent()) + { Vector3 sizeOfBox = ItemInHand .GetComponent() .BoundingBox.GetComponent() @@ -3152,27 +3637,33 @@ public bool CheckIfAgentCanRotateHand() { ); // did we even hit anything? - if (hitColliders.Length > 0) { - foreach (Collider col in hitColliders) { + if (hitColliders.Length > 0) + { + foreach (Collider col in hitColliders) + { // is this a sim object? - if (col.GetComponentInParent()) { + 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; return false; } // oh it is the item we are holding, it's fine - else { + 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") { + else if (col.tag != "Player") + { errorMessage = "Rotating the object results in it colliding with an agent."; return false; @@ -3180,10 +3671,13 @@ public bool CheckIfAgentCanRotateHand() { } } // nothing hit by sphere, so we are safe to rotate - else { + else + { result = true; } - } else { + } + else + { Debug.Log("item in hand is missing a collider box for some reason! Oh nooo!"); } @@ -3194,19 +3688,23 @@ public bool CheckIfAgentCanRotateHand() { message: "This action is deprecated. Call RotateHeldObject() instead.", error: false )] - public void RotateHand(float x, float y, float z) { + public void RotateHand(float x, float y, float z) + { RotateHeldObject(rotation: new Vector3(x, y, z)); } // rotate the held object if there is an object in it - public void RotateHeldObject(Vector3 rotation) { - if (ItemInHand == null) { + public void RotateHeldObject(Vector3 rotation) + { + if (ItemInHand == null) + { throw new InvalidOperationException( "Can't rotate held object since no object is being held." ); } - if (!CheckIfAgentCanRotateHand()) { + if (!CheckIfAgentCanRotateHand()) + { throw new InvalidOperationException( "Object is unable to rotate in its current state!" ); @@ -3216,7 +3714,8 @@ public void RotateHeldObject(Vector3 rotation) { // SetUpRotationBoxChecks(); // 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) { + if (Vector3.Angle(ItemInHand.transform.up, Vector3.up) > 95) + { ItemInHand .GetComponent() .DropContainedObjects(reparentContainedObjects: true, forceKinematic: false); @@ -3226,8 +3725,10 @@ 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) { + 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." ); @@ -3242,7 +3743,8 @@ public void RotateHeldObject(float pitch = 0, float yaw = 0, float roll = 0) { AgentHand.transform.Rotate(new Vector3(pitch, yaw, -roll), Space.World); transform.rotation = agentRot; - if (isHandObjectColliding(true)) { + if (isHandObjectColliding(true)) + { AgentHand.transform.rotation = agentHandStartRot; throw new InvalidOperationException("Held object is coliding after rotation."); } @@ -3251,7 +3753,8 @@ public void RotateHeldObject(float pitch = 0, float yaw = 0, float roll = 0) { } // rotate the hand if there is an object in it - public void RotateHandRelative(float x = 0, float y = 0, float z = 0) { + public void RotateHandRelative(float x = 0, float y = 0, float z = 0) + { // NOTE: -z is used for backwards compatibility. RotateHeldObject(pitch: x, yaw: y, roll: -z); } @@ -3263,7 +3766,8 @@ public void SpawnObjectInReceptacleRandomly( string prefabName, string targetReceptacle, FlexibleRotation rotation - ) { + ) + { SimObjPhysics target = getInteractableSimObjectFromId(targetReceptacle, true); var spawnedObj = ProceduralTools.spawnObjectInReceptacleRandomly( this, @@ -3275,7 +3779,8 @@ FlexibleRotation rotation ); bool result = false; //object succesfully spawned, wait for it to settle, then actionReturn success and the object's position - if (spawnedObj != null) { + if (spawnedObj != null) + { result = true; StartCoroutine( checkIfObjectHasStoppedMoving( @@ -3283,7 +3788,9 @@ FlexibleRotation rotation useTimeout: false ) ); - } else { + } + else + { 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 @@ -3298,7 +3805,8 @@ public void SpawnObjectInReceptacle( string targetReceptacle, Vector3 position, FlexibleRotation rotation - ) { + ) + { SimObjPhysics target = getInteractableSimObjectFromId(targetReceptacle, true); var spawnedObj = ProceduralTools.spawnObjectInReceptacle( this, @@ -3311,7 +3819,8 @@ FlexibleRotation rotation ); bool result = false; //object succesfully spawned, wait for it to settle, then actionReturn success and the object's position - if (spawnedObj != null) { + if (spawnedObj != null) + { result = true; StartCoroutine( checkIfObjectHasStoppedMoving( @@ -3319,7 +3828,9 @@ FlexibleRotation rotation useTimeout: false ) ); - } else { + } + else + { 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 @@ -3328,7 +3839,8 @@ FlexibleRotation rotation } //generic spawn object in scene, no physics resoultion or bounds/collision check - public void SpawnObjectInScene(HouseObject ho) { + public void SpawnObjectInScene(HouseObject ho) + { CollisionDetectionMode collDet = CollisionDetectionMode.ContinuousSpeculative; Enum.TryParse(ho.collisionDetectionMode, true, out collDet); var spawnedObj = ProceduralTools.spawnHouseObject( @@ -3341,11 +3853,13 @@ public void SpawnObjectInScene(HouseObject ho) { //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) { + public bool placeNewObjectAtPoint(SimObjPhysics t, Vector3 position) + { SimObjPhysics target = t; // make sure point we are moving the object to is valid - if (!agentManager.SceneBounds.Contains(position)) { + if (!agentManager.SceneBounds.Contains(position)) + { return false; } @@ -3369,7 +3883,8 @@ public bool placeNewObjectAtPoint(SimObjPhysics t, Vector3 position) { //check spawn area, if its clear, then place object at finalPos InstantiatePrefabTest ipt = physicsSceneManager.GetComponent(); - if (ipt.CheckSpawnArea(target, finalPos, target.transform.rotation, false)) { + if (ipt.CheckSpawnArea(target, finalPos, target.transform.rotation, false)) + { target.transform.position = finalPos; return true; } @@ -3382,7 +3897,8 @@ public void ScaleObject( float scale, float scaleOverSeconds = 1.0f, bool forceAction = false - ) { + ) + { // if object is in the scene and visible, assign it to 'target' SimObjPhysics target = getInteractableSimObjectFromId( objectId: objectId, @@ -3390,11 +3906,14 @@ public void ScaleObject( ); // neither objectId nor coordinates found an object - if (target == null) { + if (target == null) + { errorMessage = $"Object with ID {objectId} does not appear to be interactable."; actionFinished(false); return; - } else { + } + else + { StartCoroutine( scaleObject(gameObject.transform.localScale * scale, target, scaleOverSeconds) ); @@ -3407,7 +3926,8 @@ public void ScaleObject( float scale, float scaleOverSeconds = 1.0f, bool forceAction = false - ) { + ) + { SimObjPhysics target = getInteractableSimObjectFromXY( x: x, y: y, @@ -3423,7 +3943,8 @@ private IEnumerator scaleObject( SimObjPhysics target, float scaleOverSeconds, bool skipActionFinished = false - ) { + ) + { return scaleObject( targetScale: this.transform.localScale * scale, target: target, @@ -3437,15 +3958,20 @@ private IEnumerator scaleObject( SimObjPhysics target, float scaleOverSeconds, bool skipActionFinished = false - ) { + ) + { Vector3 originalScale = target.transform.localScale; float currentTime = 0.0f; - if (scaleOverSeconds <= 0f) { + if (scaleOverSeconds <= 0f) + { target.transform.localScale = targetScale; - } else { + } + else + { yield return new WaitForFixedUpdate(); - do { + do + { target.transform.localScale = Vector3.Lerp( originalScale, targetScale, @@ -3459,7 +3985,8 @@ private IEnumerator scaleObject( // store reference to all children Transform[] children = new Transform[target.transform.childCount]; - for (int i = 0; i < target.transform.childCount; i++) { + for (int i = 0; i < target.transform.childCount; i++) + { children[i] = target.transform.GetChild(i); } @@ -3468,7 +3995,8 @@ private IEnumerator scaleObject( // zero out object transform to be 1, 1, 1 target.transform.transform.localScale = Vector3.one; // reparent all children - foreach (Transform t in children) { + foreach (Transform t in children) + { t.SetParent(target.transform); } @@ -3476,7 +4004,8 @@ private IEnumerator scaleObject( target.ContextSetUpBoundingBox(forceCacheReset: true); - if (!skipActionFinished) { + if (!skipActionFinished) + { actionFinished(true); } } @@ -3487,8 +4016,10 @@ private IEnumerator scaleObject( // return a bunch of vector3 points above a target receptacle // if forceVisible = true, return points regardless of where receptacle is // if forceVisible = false, only return points that are also within view of the Agent camera - public void GetSpawnCoordinatesAboveReceptacle(ServerAction action) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void GetSpawnCoordinatesAboveReceptacle(ServerAction action) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { errorMessage = "Object ID appears to be invalid."; actionFinished(false); return; @@ -3498,16 +4029,22 @@ public void GetSpawnCoordinatesAboveReceptacle(ServerAction action) { // find our target receptacle // if action.anywhere False (default) this should only return objects that are visible // if action.anywhere true, return for any object no matter where it is - foreach (SimObjPhysics sop in VisibleSimObjs(action.anywhere)) { - if (action.objectId == sop.ObjectID) { + foreach (SimObjPhysics sop in VisibleSimObjs(action.anywhere)) + { + if (action.objectId == sop.ObjectID) + { target = sop; } } - if (target == null) { - if (action.anywhere) { + if (target == null) + { + if (action.anywhere) + { errorMessage = "No valid Receptacle found in scene"; - } else { + } + else + { errorMessage = "No valid Receptacle found in view"; } @@ -3521,17 +4058,22 @@ public void GetSpawnCoordinatesAboveReceptacle(ServerAction action) { // by default, action.anywhere = false, so remove all targetPoints that are outside of agent's view // if anywhere true, don't do this and just return all points we got from above - if (!action.anywhere) { + if (!action.anywhere) + { List filteredTargetPoints = new List(); - foreach (Vector3 v in targetPoints) { - try { + foreach (Vector3 v in targetPoints) + { + try + { assertPosInView( targetPosition: v, inMaxVisibleDistance: true, inViewport: true ); filteredTargetPoints.Add(v); - } catch (Exception e) { + } + catch (Exception e) + { continue; } } @@ -3552,7 +4094,8 @@ public void GetSpawnCoordinatesAboveReceptacle(ServerAction action) { public List getSpawnCoordinatesAboveReceptacle( SimObjPhysics t, bool fromReceptacleTop = true - ) { + ) + { SimObjPhysics target = t; // ok now get spawn points from target List targetPoints = new List(); @@ -3565,15 +4108,18 @@ public void MakeReceptacleDirty( float density, int seed = 0, Vector3? scale = null - ) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + ) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { actionFinished( success: false, errorMessage: $"Object ID {objectId} appears to be invalid." ); } SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; - if (!sop.IsReceptacle) { + if (!sop.IsReceptacle) + { actionFinished( success: false, errorMessage: $"Object ID {objectId} is not a Receptacle." @@ -3597,7 +4143,8 @@ public void MakeReceptacleDirty( var selectedCoords = spawnCoordinates .Shuffle_(new System.Random(seed)) .Take(coordinateCount); - foreach (var coord in selectedCoords) { + foreach (var coord in selectedCoords) + { dc.SpawnDecal( position: coord, scale: scale, @@ -3609,8 +4156,10 @@ public void MakeReceptacleDirty( // 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) { + 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"; actionFinished(false); @@ -3628,20 +4177,25 @@ public void SpawnTargetCircle(ServerAction action) { InstantiatePrefabTest ipt = physicsSceneManager.GetComponent(); // this is the default, only spawn circles in objects that are in view - if (!action.anywhere) { + if (!action.anywhere) + { // check every sim object and see if it is within the viewport - foreach (SimObjPhysics sop in VisibleSimObjs(true)) { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { if ( sop.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.Receptacle ) - ) { + ) + { /// one more check, make sure this receptacle if ( ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(sop.ObjType) - ) { + ) + { // ok now check if the object is for real in the viewport - if (objectIsWithinViewport(sop)) { + if (objectIsWithinViewport(sop)) + { targetReceptacles.Add(sop); } } @@ -3649,20 +4203,26 @@ public void SpawnTargetCircle(ServerAction action) { } } // spawn target circle in any valid "outside" receptacle in the scene even if not in veiw - else { + else + { // targetReceptacles.AddRange(physicsSceneManager.ReceptaclesInScene); - foreach (SimObjPhysics sop in physicsSceneManager.GatherAllReceptaclesInScene()) { - if (ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(sop.ObjType)) { + foreach (SimObjPhysics sop in physicsSceneManager.GatherAllReceptaclesInScene()) + { + if (ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(sop.ObjType)) + { targetReceptacles.Add(sop); } } } // if we passed in a objectId, see if it is in the list of targetReceptacles found so far - if (action.objectId != null) { + if (action.objectId != null) + { List filteredTargetReceptacleList = new List(); - foreach (SimObjPhysics sop in targetReceptacles) { - if (sop.objectID == action.objectId) { + foreach (SimObjPhysics sop in targetReceptacles) + { + if (sop.objectID == action.objectId) + { filteredTargetReceptacleList.Add(sop); } } @@ -3677,7 +4237,8 @@ public void SpawnTargetCircle(ServerAction action) { bool succesfulSpawn = false; - if (targetReceptacles.Count <= 0) { + if (targetReceptacles.Count <= 0) + { errorMessage = "for some reason, no receptacles were found in the scene!"; Destroy(targetCircle); actionFinished(false); @@ -3685,7 +4246,8 @@ public void SpawnTargetCircle(ServerAction action) { } // ok we have a shuffled list of receptacles that is picked based on the seed.... - foreach (SimObjPhysics sop in targetReceptacles) { + foreach (SimObjPhysics sop in targetReceptacles) + { // for every receptacle, we will get a returned list of receptacle spawn points, and then try placeObjectReceptacle List rsps = new List(); @@ -3694,8 +4256,10 @@ public void SpawnTargetCircle(ServerAction action) { 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) { + 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, @@ -3704,14 +4268,16 @@ public void SpawnTargetCircle(ServerAction action) { ); Vector3 normalizedPoint = new Vector3(p.Point.x, 0, p.Point.z); - if (action.minDistance == 0 && action.maxDistance > 0) { + if (action.minDistance == 0 && action.maxDistance > 0) + { // check distance from agent's transform to spawnpoint if ( ( Vector3.Distance(normalizedPoint, normalizedPosition) <= action.maxDistance ) - ) { + ) + { editedRsps.Add(p); } @@ -3719,19 +4285,23 @@ public void SpawnTargetCircle(ServerAction action) { } // min distance passed in, no max distance - if (action.maxDistance == 0 && action.minDistance > 0) { + if (action.maxDistance == 0 && action.minDistance > 0) + { // check distance from agent's transform to spawnpoint if ( ( Vector3.Distance(normalizedPoint, normalizedPosition) >= action.minDistance ) - ) { + ) + { editedRsps.Add(p); } constraintsUsed = true; - } else { + } + else + { // these are default so don't filter by distance // check distance from agent's transform to spawnpoint if ( @@ -3741,7 +4311,8 @@ public void SpawnTargetCircle(ServerAction action) { && Vector3.Distance(normalizedPoint, normalizedPosition) <= action.maxDistance ) - ) { + ) + { editedRsps.Add(p); } @@ -3750,14 +4321,16 @@ public void SpawnTargetCircle(ServerAction action) { } } - if (constraintsUsed) { + if (constraintsUsed) + { rsps = editedRsps; } rsps.Shuffle_(action.randomSeed); // only place in viewport - if (!action.anywhere) { + if (!action.anywhere) + { if ( ipt.PlaceObjectReceptacleInViewport( this, @@ -3768,14 +4341,16 @@ public void SpawnTargetCircle(ServerAction action) { 90, true ) - ) { + ) + { // make sure target circle is within viewport succesfulSpawn = true; break; } } // place anywhere - else { + else + { if ( ipt.PlaceObjectReceptacle( rsps, @@ -3785,7 +4360,8 @@ public void SpawnTargetCircle(ServerAction action) { 90, true ) - ) { + ) + { // make sure target circle is within viewport succesfulSpawn = true; break; @@ -3793,14 +4369,17 @@ public void SpawnTargetCircle(ServerAction action) { } } - if (succesfulSpawn) { + 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; - if (primaryAgent.imageSynthesis) { - if (primaryAgent.imageSynthesis.enabled) { + if (primaryAgent.imageSynthesis) + { + if (primaryAgent.imageSynthesis.enabled) + { primaryAgent.imageSynthesis.OnSceneChange(); } } @@ -3809,29 +4388,37 @@ public void SpawnTargetCircle(ServerAction action) { physicsSceneManager.Generate_ObjectID(targetSOP); physicsSceneManager.AddToObjectsInScene(targetSOP); actionFinished(true, targetSOP.objectID); // return the objectID of circle spawned for easy reference - } else { + } + else + { Destroy(targetCircle); errorMessage = "circle failed to spawn"; actionFinished(false); } } - public void MakeObjectsOfTypeUnbreakable(string objectType) { - if (objectType == null) { + public void MakeObjectsOfTypeUnbreakable(string objectType) + { + if (objectType == null) + { errorMessage = "no object type specified for MakeOBjectsOfTypeUnbreakable()"; actionFinished(false); } SimObjPhysics[] simObjs = GameObject.FindObjectsOfType(typeof(SimObjPhysics)) as SimObjPhysics[]; - if (simObjs != null) { - foreach (SimObjPhysics sop in simObjs) { - if (sop.Type.ToString() == objectType) { + if (simObjs != null) + { + foreach (SimObjPhysics sop in simObjs) + { + if (sop.Type.ToString() == objectType) + { if ( sop.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.CanBreak ) - ) { + ) + { //look both in this object and children so things like Windows don't FREAK OUT sop.GetComponentInChildren().Unbreakable = true; } @@ -3842,12 +4429,15 @@ public void MakeObjectsOfTypeUnbreakable(string objectType) { actionFinished(true); } - public void MakeObjectBreakable(string objectId) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void MakeObjectBreakable(string objectId) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { throw new ArgumentException($"Object ID {objectId} appears to be invalid."); } SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; - if (sop.GetComponent()) { + if (sop.GetComponent()) + { sop.GetComponent().Unbreakable = false; } actionFinishedEmit(true); @@ -3855,8 +4445,10 @@ public void MakeObjectBreakable(string objectId) { // 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) { - if (action.SetObjectStates == null) { + public void SetObjectStates(ServerAction action) + { + if (action.SetObjectStates == null) + { errorMessage = "action.SetObjectStates is null or not initialized!"; actionFinished(false); return; @@ -3866,7 +4458,8 @@ public void SetObjectStates(ServerAction action) { 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); @@ -3877,7 +4470,8 @@ public void SetObjectStates(ServerAction action) { 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); @@ -3888,40 +4482,49 @@ public void SetObjectStates(ServerAction action) { 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 { + else + { SetStateOfObjectsThatDontHaveAnimationTime(action.SetObjectStates); } } // find all objects in scene of type specified by SetObjectStates.objectType // toggle them to the bool if applicable: isOpen, isToggled, isBroken etc. - protected IEnumerator SetStateOfAnimatedObjects(SetObjectStates SetObjectStates) { + protected IEnumerator SetStateOfAnimatedObjects(SetObjectStates SetObjectStates) + { List animating = new List(); 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 (SetObjectStates.objectType == null) + { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { + if (SetObjectStates.stateChange == "toggleable") + { if ( sop.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.CanToggleOnOff ) && sop.GetComponent() - ) { + ) + { StartCoroutine(toggleObject(sop, SetObjectStates.isToggled)); animating.Add(sop); animatingType[sop] = "toggleable"; } } - if (SetObjectStates.stateChange == "openable") { - if (sop.GetComponent()) { + if (SetObjectStates.stateChange == "openable") + { + if (sop.GetComponent()) + { openObject( target: sop, openness: SetObjectStates.isOpen ? 1 : 0, @@ -3933,29 +4536,37 @@ protected IEnumerator SetStateOfAnimatedObjects(SetObjectStates SetObjectStates) } } } - } else { + } + 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); // for every sim obj in scene, find objects of type specified first - foreach (SimObjPhysics sop in VisibleSimObjs(true)) { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { // ok we found an object with type specified, now toggle it - if (sop.ObjType == sot) { - if (SetObjectStates.stateChange == "toggleable") { + if (sop.ObjType == sot) + { + if (SetObjectStates.stateChange == "toggleable") + { if ( sop.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.CanToggleOnOff ) && sop.GetComponent() - ) { + ) + { StartCoroutine(toggleObject(sop, SetObjectStates.isToggled)); animating.Add(sop); animatingType[sop] = "toggleable"; } } - if (SetObjectStates.stateChange == "openable") { - if (sop.GetComponent()) { + if (SetObjectStates.stateChange == "openable") + { + if (sop.GetComponent()) + { openObject( target: sop, openness: SetObjectStates.isOpen ? 1 : 0, @@ -3970,11 +4581,14 @@ protected IEnumerator SetStateOfAnimatedObjects(SetObjectStates SetObjectStates) } } - if (animating.Count > 0) { + if (animating.Count > 0) + { // we have now started the toggle for all objects in the ObjectStates array int numStillGoing = animating.Count; - while (numStillGoing > 0) { - foreach (SimObjPhysics sop in animating) { + while (numStillGoing > 0) + { + foreach (SimObjPhysics sop in animating) + { if ( animatingType.ContainsKey(sop) && ( @@ -3984,12 +4598,14 @@ protected IEnumerator SetStateOfAnimatedObjects(SetObjectStates SetObjectStates) || animatingType[sop] == "openable" ) && sop.GetComponent().GetIsCurrentlyLerping() == false - ) { + ) + { numStillGoing--; } } // someone is still animating - if (numStillGoing > 0) { + if (numStillGoing > 0) + { numStillGoing = animating.Count; } @@ -4003,273 +4619,345 @@ 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) { + 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 - ) - ) { - // 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 - ) - ) { - b.BreakObject(null); - } else { - continue; - } - } else { + switch (SetObjectStates.stateChange) + { + case "breakable": + { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { + 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 + ) + ) + { b.BreakObject(null); } + else + { + continue; + } + } + else + { + b.BreakObject(null); } } } - - break; } - case "canFillWithLiquid": { - foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - // only proceed if the sop is fillable - if ( - sop.DoesThisObjectHaveThisSecondaryProperty( - SimObjSecondaryProperty.CanBeFilled - ) - ) { - Fill fil = sop.GetComponent(); - - // object is empty and trying to fill it - 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 - ) - ) { - fil.FillObject("water"); - } - // doesn't match objectType, continue to next object - else { - continue; - } - } else { + break; + } + + case "canFillWithLiquid": + { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { + // only proceed if the sop is fillable + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBeFilled + ) + ) + { + Fill fil = sop.GetComponent(); + + // object is empty and trying to fill it + 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 + ) + ) + { fil.FillObject("water"); } + // doesn't match objectType, continue to next object + else + { + continue; + } + } + else + { + 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 - ) - ) { - fil.EmptyObject(); - } - // doesn't match objectType, continue to next object - else { - continue; - } - } else { + } + // 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 + ) + ) + { fil.EmptyObject(); } + // doesn't match objectType, continue to next object + else + { + continue; + } + } + else + { + fil.EmptyObject(); } } } - - break; } - case "dirtyable": { - foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - // only proceed if the sop is dirtyable - if ( - sop.DoesThisObjectHaveThisSecondaryProperty( - SimObjSecondaryProperty.CanBeDirty - ) - ) { - Dirty deedsDoneDirtCheap = sop.GetComponent(); - - // object is clean and we are trying to dirty it - 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 - ) - ) { - deedsDoneDirtCheap.ToggleCleanOrDirty(); - } - // doesn't match objectType, continue to next object - else { - continue; - } - } else { + break; + } + + case "dirtyable": + { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { + // only proceed if the sop is dirtyable + if ( + sop.DoesThisObjectHaveThisSecondaryProperty( + SimObjSecondaryProperty.CanBeDirty + ) + ) + { + Dirty deedsDoneDirtCheap = sop.GetComponent(); + + // object is clean and we are trying to dirty it + 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 + ) + ) + { deedsDoneDirtCheap.ToggleCleanOrDirty(); } + // doesn't match objectType, continue to next object + else + { + continue; + } + } + else + { + 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 - ) - ) { - deedsDoneDirtCheap.ToggleCleanOrDirty(); - } - // doesn't match objectType, continue to next object - else { - continue; - } - } else { + } + // 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 + ) + ) + { deedsDoneDirtCheap.ToggleCleanOrDirty(); } + // doesn't match objectType, continue to next object + else + { + continue; + } + } + else + { + deedsDoneDirtCheap.ToggleCleanOrDirty(); } } } - - break; } + break; + } + // one way - case "cookable": { - foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - 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 - ) - ) { - c.Cook(); - } else { - continue; - } - } else { + case "cookable": + { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { + 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 + ) + ) + { c.Cook(); } + else + { + continue; + } + } + else + { + c.Cook(); } } } - - break; } + break; + } + // one way - case "sliceable": { - foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - 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 - ) - ) { - s.Slice(); - } else { - continue; - } - } else { + case "sliceable": + { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { + 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 + ) + ) + { s.Slice(); } + else + { + continue; + } + } + else + { + s.Slice(); } } } - - break; } + break; + } + // one way - case "canBeUsedUp": { - foreach (SimObjPhysics sop in VisibleSimObjs(true)) { - 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 - ) - ) { - u.UseUp(); - } else { - continue; - } - } else { + case "canBeUsedUp": + { + foreach (SimObjPhysics sop in VisibleSimObjs(true)) + { + 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 + ) + ) + { u.UseUp(); } + else + { + continue; + } + } + else + { + u.UseUp(); } } } - - break; } + + break; + } } actionFinished(true); @@ -4282,7 +4970,8 @@ public void PutObject( bool placeStationary = true, int randomSeed = 0, bool putNearXY = false - ) { + ) + { PlaceHeldObject( x: x, y: y, @@ -4299,7 +4988,8 @@ public void PutObject( bool forceAction = false, bool placeStationary = true, int randomSeed = 0 - ) { + ) + { PlaceHeldObject( objectId: objectId, forceAction: forceAction, @@ -4320,7 +5010,8 @@ public void PlaceHeldObject( bool placeStationary = true, int randomSeed = 0, bool putNearXY = false - ) { + ) + { SimObjPhysics targetReceptacle = null; RaycastHit hit = new RaycastHit(); @@ -4351,7 +5042,8 @@ public void PlaceHeldObject( bool forceAction = false, bool placeStationary = true, int randomSeed = 0 - ) { + ) + { // get the target receptacle based on the action object ID SimObjPhysics targetReceptacle = null; @@ -4376,7 +5068,8 @@ private void placeHeldObject( bool placeStationary, int randomSeed, float maxDistance - ) { + ) + { RaycastHit hit = new RaycastHit(); placeHeldObject( @@ -4398,19 +5091,22 @@ private void placeHeldObject( float maxDistance, bool putNearXY, RaycastHit hit - ) { + ) + { // #if UNITY_EDITOR // var watch = System.Diagnostics.Stopwatch.StartNew(); // #endif // check if we are even holding anything - if (ItemInHand == null) { + if (ItemInHand == null) + { errorMessage = "Can't place an object if Agent isn't holding anything"; actionFinished(false); return; } - if (targetReceptacle == null) { + if (targetReceptacle == null) + { errorMessage = "No valid Receptacle found"; Debug.Log(errorMessage); actionFinished(false); @@ -4421,7 +5117,8 @@ RaycastHit hit !targetReceptacle.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.Receptacle ) - ) { + ) + { errorMessage = "This target object is NOT a receptacle!"; Debug.Log(errorMessage); actionFinished(false); @@ -4433,13 +5130,16 @@ RaycastHit hit targetReceptacle.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.CanOpen ) - ) { + ) + { if ( ReceptacleRestrictions.MustBeOpenToPlaceObjectsIn.Contains( targetReceptacle.ObjType ) - ) { - if (!targetReceptacle.GetComponent().isOpen) { + ) + { + if (!targetReceptacle.GetComponent().isOpen) + { errorMessage = "Target openable Receptacle is CLOSED, can't place if target is not open!"; Debug.Log(errorMessage); @@ -4455,16 +5155,19 @@ RaycastHit hit 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) { + if (osr.GetComponent().Type == SimObjType.StoveBurner) + { // PhysicsSceneManager psm = GameObject.Find("PhysicsSceneManager").GetComponent(); if ( physicsSceneManager.StoveTopCheckSpawnArea( @@ -4473,7 +5176,8 @@ RaycastHit hit osr.attachPoint.transform.rotation, false ) == false - ) { + ) + { errorMessage = "another object's collision is blocking held object from being placed"; actionFinished(false); @@ -4490,10 +5194,15 @@ RaycastHit hit DefaultAgentHand(); actionFinished(true); return; - } else { - if (osr.attachPoint.transform.childCount > 0 || osr.isFull()) { + } + else + { + if (osr.attachPoint.transform.childCount > 0 || osr.isFull()) + { errorMessage = targetReceptacle.name + " is full right now"; - } else { + } + else + { errorMessage = ItemInHand.name + " is not a valid Object Type to be placed in " @@ -4507,17 +5216,21 @@ RaycastHit hit SimObjPhysics handSOP = ItemInHand.GetComponent(); - if (!forceAction) { + if (!forceAction) + { // check if the item we are holding can even be placed in the action.ObjectID target at all 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)) { + if (res.Key == handSOP.ObjType) + { + if (!res.Value.Contains(targetReceptacle.ObjType)) + { errorMessage = ItemInHand.name + " cannot be placed in " @@ -4533,13 +5246,15 @@ RaycastHit hit bool onlyPointsCloseToAgent = !forceAction; // if the target is something like a pot or bowl on a table, return all valid points instead of ONLY visible points since // the Agent can't see the bottom of the receptacle if it's placed too high on a table - if (ReceptacleRestrictions.ReturnAllPoints.Contains(targetReceptacle.ObjType)) { + if (ReceptacleRestrictions.ReturnAllPoints.Contains(targetReceptacle.ObjType)) + { onlyPointsCloseToAgent = false; } bool placeUpright = false; // check if the object should be forced to only check upright placement angles (this prevents things like Pots being placed sideways) - if (ReceptacleRestrictions.AlwaysPlaceUpright.Contains(handSOP.ObjType)) { + if (ReceptacleRestrictions.AlwaysPlaceUpright.Contains(handSOP.ObjType)) + { placeUpright = true; } @@ -4550,11 +5265,13 @@ RaycastHit hit List spawnPoints = targetReceptacle.ReturnMySpawnPoints( onlyPointsCloseToAgent ? this : null ); - if (randomSeed != 0 || putNearXY) { + if (randomSeed != 0 || putNearXY) + { List> distSpawnPoints = new List>(); - foreach (ReceptacleSpawnPoint sp in spawnPoints) { + 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 @@ -4563,9 +5280,11 @@ RaycastHit hit sp.Point.y, transform.position.z ); - if (Vector3.Distance(sp.Point, tmp) < maxDistance) { + if (Vector3.Distance(sp.Point, tmp) < maxDistance) + { float dist = 0; - if (putNearXY) { + if (putNearXY) + { dist = Vector3.Distance(sp.Point, hit.point); } distSpawnPoints.Add( @@ -4575,14 +5294,18 @@ RaycastHit hit } // actually sort by distance closest to raycast hit if needed here, otherwise leave random - if (putNearXY) { + if (putNearXY) + { distSpawnPoints.Sort((x, y) => (x.Value.CompareTo(y.Value))); - } else { + } + else + { distSpawnPoints.Shuffle_(randomSeed); } spawnPoints = new List(); // populate a new spawnPoints list with sorted keys - foreach (KeyValuePair pair in distSpawnPoints) { + foreach (KeyValuePair pair in distSpawnPoints) + { spawnPoints.Add(pair.Key); } } @@ -4596,11 +5319,14 @@ RaycastHit hit 90, placeUpright ) - ) { + ) + { ItemInHand = null; DefaultAgentHand(); actionFinished(true); - } else { + } + else + { errorMessage = "No valid positions to place object found"; actionFinished(false); } @@ -4617,25 +5343,30 @@ protected void pickupObject( bool forceAction, bool manualInteract, bool markActionFinished - ) { - if (target == null) { + ) + { + if (target == null) + { throw new ArgumentNullException(); } // found non-pickupable object - if (target.PrimaryProperty != SimObjPrimaryProperty.CanPickup) { + if (target.PrimaryProperty != SimObjPrimaryProperty.CanPickup) + { throw new InvalidOperationException( target.objectID + " must have the property CanPickup to be picked up." ); } // agent is holding something - if (ItemInHand != null) { + if (ItemInHand != null) + { throw new InvalidOperationException( "Agent hand has something in it already! Can't pick up anything else" ); } - if (!IsHandDefault) { + if (!IsHandDefault) + { throw new InvalidOperationException( "Must reset Hand to default position before attempting to Pick Up objects" ); @@ -4656,18 +5387,22 @@ bool markActionFinished // run this to pickup any contained objects if object is a receptacle // if the target is rotated too much, don't try to pick up any contained objects since they would fall out - if (Vector3.Angle(target.transform.up, Vector3.up) < 60) { + if (Vector3.Angle(target.transform.up, Vector3.up) < 60) + { PickupContainedObjects(target); } - if (!manualInteract) { + if (!manualInteract) + { // by default, abstract agent hand pickup so that object teleports to hand and changes orientation to match agent // agent's hand is in default position in front of camera, teleport object into agent's hand target.transform.position = AgentHand.transform.position; // target.transform.rotation = AgentHand.transform.rotation; - keep this line if we ever want to change the pickup position to be constant relative to the Agent Hand and Agent Camera rather than aligned by world axis target.transform.rotation = transform.rotation; - } else { + } + else + { // in manualInteract mode, move the hand to the object, and require agent hand manipulation to move object around // or move closer to agent @@ -4678,7 +5413,8 @@ bool markActionFinished target.transform.SetParent(AgentHand.transform); ItemInHand = target.gameObject; - if (!forceAction && isHandObjectColliding(true) && !manualInteract) { + if (!forceAction && isHandObjectColliding(true) && !manualInteract) + { // Undo picking up the object if the object is colliding with something after picking it up target.GetComponent().isKinematic = wasKinematic; target.transform.position = savedPos; @@ -4693,12 +5429,14 @@ bool markActionFinished // we have successfully picked up something! target.isInAgentHand = true; - if (markActionFinished) { + if (markActionFinished) + { actionFinished(success: true, actionReturn: target.ObjectID); } } - public void GetDoorHandle(string objectId) { + public void GetDoorHandle(string objectId) + { SimObjPhysics target = getInteractableSimObjectFromId( objectId: objectId, forceAction: true @@ -4706,14 +5444,17 @@ public void GetDoorHandle(string objectId) { List doorHandlePositions = new List(); - foreach (Transform child in target.transform.GetComponentsInChildren()) { - if (child.CompareTag("Handle")) { + foreach (Transform child in target.transform.GetComponentsInChildren()) + { + if (child.CompareTag("Handle")) + { doorHandlePositions.Add(child.transform.position); } } #if UNITY_EDITOR - foreach (Vector3 v in doorHandlePositions) { + foreach (Vector3 v in doorHandlePositions) + { Debug.Log(v); } #endif @@ -4721,7 +5462,8 @@ public void GetDoorHandle(string objectId) { actionFinished(true, doorHandlePositions); } - public void GetDoorHinge(string objectId) { + public void GetDoorHinge(string objectId) + { SimObjPhysics target = getInteractableSimObjectFromId( objectId: objectId, forceAction: true @@ -4729,14 +5471,17 @@ public void GetDoorHinge(string objectId) { List hingePositions = new List(); - foreach (Transform child in target.transform.GetComponentsInChildren()) { - if (child.CompareTag("Hinge")) { + foreach (Transform child in target.transform.GetComponentsInChildren()) + { + if (child.CompareTag("Hinge")) + { hingePositions.Add(child.transform.position); } } #if UNITY_EDITOR - foreach (Vector3 v in hingePositions) { + foreach (Vector3 v in hingePositions) + { Debug.Log(v); } #endif @@ -4749,7 +5494,8 @@ public virtual void PickupObject( float y, bool forceAction = false, bool manualInteract = false - ) { + ) + { SimObjPhysics target = getInteractableSimObjectFromXY( x: x, y: y, @@ -4767,7 +5513,8 @@ public virtual void PickupObject( string objectId, bool forceAction = false, bool manualInteract = false - ) { + ) + { SimObjPhysics target = getInteractableSimObjectFromId( objectId: objectId, forceAction: forceAction @@ -4781,20 +5528,26 @@ public virtual void PickupObject( } // make sure not to pick up any sliced objects because those should remain uninteractable i they have been sliced - public void PickupContainedObjects(SimObjPhysics target) { - if (target.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { - foreach (SimObjPhysics sop in target.SimObjectsContainedByReceptacle) { + public void PickupContainedObjects(SimObjPhysics target) + { + if (target.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) + { + foreach (SimObjPhysics sop in target.SimObjectsContainedByReceptacle) + { // for every object that is contained by this object...first make sure it's pickupable so we don't like, grab a Chair if it happened to be in the receptacle box or something // 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) { + if (sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup) + { // wait! check if this object is sliceable and is sliced, if so SKIP! if ( sop.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.CanBeSliced ) - ) { + ) + { // if this object is sliced, don't pick it up because it is effectively disabled - if (sop.GetComponent().IsSliced()) { + if (sop.GetComponent().IsSliced()) + { target.RemoveFromContainedObjectReferences(sop); break; } @@ -4848,13 +5601,16 @@ public void PickupContainedObjects(SimObjPhysics target) { // actionFinished(true); // } - private IEnumerator checkDropHeldObjectActionFast(SimObjPhysics currentHandSimObj) { - if (currentHandSimObj != null) { + private IEnumerator checkDropHeldObjectActionFast(SimObjPhysics currentHandSimObj) + { + if (currentHandSimObj != null) + { Rigidbody rb = currentHandSimObj.GetComponentInChildren(); Physics.autoSimulation = false; yield return null; - for (int i = 0; i < 100; i++) { + for (int i = 0; i < 100; i++) + { PhysicsSceneManager.PhysicsSimulateTHOR(0.04f); #if UNITY_EDITOR yield return null; @@ -4862,7 +5618,8 @@ private IEnumerator checkDropHeldObjectActionFast(SimObjPhysics currentHandSimOb if ( Math.Abs(rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude) < 0.00001 - ) { + ) + { break; } } @@ -4873,15 +5630,18 @@ private IEnumerator checkDropHeldObjectActionFast(SimObjPhysics currentHandSimOb actionFinished(true); } - public void DropHeldObject(bool forceAction = false, bool autoSimulation = true) { + public void DropHeldObject(bool forceAction = false, bool autoSimulation = true) + { // make sure something is actually in our hands - if (ItemInHand == null) { + if (ItemInHand == null) + { throw new InvalidOperationException("Nothing is in the agent's hand to drop!"); } // we do need this to check if the item is currently colliding with the agent, otherwise // dropping an object while it is inside the agent will cause it to shoot out weirdly - if (!forceAction && isHandObjectColliding(false)) { + 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." @@ -4898,9 +5658,12 @@ public void DropHeldObject(bool forceAction = false, bool autoSimulation = true) rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; GameObject topObject = GameObject.Find("Objects"); - if (topObject != null) { + if (topObject != null) + { ItemInHand.transform.parent = topObject.transform; - } else { + } + else + { ItemInHand.transform.parent = null; } ItemInHand @@ -4909,21 +5672,27 @@ public void DropHeldObject(bool forceAction = false, bool autoSimulation = true) // if physics simulation has been paused by the PausePhysicsAutoSim() action, // don't do any coroutine checks - if (!physicsSceneManager.physicsSimulationPaused) { + if (!physicsSceneManager.physicsSimulationPaused) + { // this is true by default - if (autoSimulation) { + if (autoSimulation) + { StartCoroutine( checkIfObjectHasStoppedMoving( sop: ItemInHand.GetComponent(), useTimeout: false ) ); - } else { + } + else + { StartCoroutine( checkDropHeldObjectActionFast(ItemInHand.GetComponent()) ); } - } else { + } + else + { DefaultAgentHand(); actionFinished(true); } @@ -4935,7 +5704,8 @@ public void DropHeldObject(bool forceAction = false, bool autoSimulation = true) message: "This action is deprecated. Call DropHeldObject instead.", error: false )] - public void DropHandObject(bool forceAction = false, bool autoSimulation = true) { + public void DropHandObject(bool forceAction = false, bool autoSimulation = true) + { DropHeldObject(forceAction: forceAction, autoSimulation: autoSimulation); } @@ -4945,8 +5715,10 @@ public void ThrowObject( float moveMagnitude, bool forceAction = false, bool autoSimulation = true - ) { - if (ItemInHand == null) { + ) + { + if (ItemInHand == null) + { throw new InvalidOperationException("Nothing in Hand to Throw!"); } @@ -4962,27 +5734,32 @@ public void ThrowObject( } // Hide and Seek helper function, makes overlap box at x,z coordinates - protected HashSet objectsInBox(float x, float z) { + protected HashSet objectsInBox(float x, float z) + { Collider[] colliders = Physics.OverlapBox( new Vector3(x, 0f, z), new Vector3(0.125f, 10f, 0.125f), Quaternion.identity ); HashSet toReturn = new HashSet(); - foreach (Collider c in colliders) { + foreach (Collider c in colliders) + { SimObjPhysics so = ancestorSimObjPhysics(c.transform.gameObject); - if (so != null) { + if (so != null) + { toReturn.Add(so); } } return toReturn; } - public void ObjectsInBox(float x, float z) { + public void ObjectsInBox(float x, float z) + { HashSet objects = objectsInBox(x, z); objectIdsInBox = new string[objects.Count]; int i = 0; - foreach (SimObjPhysics so in objects) { + foreach (SimObjPhysics so in objects) + { objectIdsInBox[i] = so.ObjectID; i++; #if UNITY_EDITOR @@ -4993,17 +5770,22 @@ public void ObjectsInBox(float x, float z) { } // try and close all visible objects - public void CloseVisibleObjects(bool simplifyPhysics = false) { + public void CloseVisibleObjects(bool simplifyPhysics = false) + { OpenVisibleObjects(simplifyPhysics: simplifyPhysics, openness: 0); } // try and open all visible objects - public void OpenVisibleObjects(bool simplifyPhysics = false, float openness = 1) { - foreach (SimObjPhysics so in GetAllVisibleSimObjPhysics(m_Camera, maxVisibleDistance)) { + public void OpenVisibleObjects(bool simplifyPhysics = false, float openness = 1) + { + foreach (SimObjPhysics so in GetAllVisibleSimObjPhysics(m_Camera, maxVisibleDistance)) + { CanOpen_Object coo = so.GetComponent(); - if (coo) { + if (coo) + { // if object is open, add it to be closed. - if (!coo.isOpen) { + if (!coo.isOpen) + { openObject( target: so, openness: openness, @@ -5028,7 +5810,8 @@ public void CloseObject( bool stopAtNonStaticCol = false, float? physicsInterval = null, bool useGripper = false - ) { + ) + { OpenObject( objectId: objectId, openness: 0, @@ -5042,7 +5825,8 @@ public void CloseObject( } // 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); } @@ -5052,7 +5836,8 @@ protected SimObjPhysics getOpenableOrCloseableObjectNearLocation( float y, float radius, bool forceAction - ) { + ) + { y = 1.0f - y; RaycastHit hit; @@ -5064,20 +5849,25 @@ bool forceAction "Procedural0", "SimObjInvisible" ); - if (ItemInHand != null) { - foreach (Collider c in ItemInHand.GetComponentsInChildren()) { + if (ItemInHand != null) + { + foreach (Collider c in ItemInHand.GetComponentsInChildren()) + { c.enabled = false; } } - for (int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) + { float r = radius * (i / 9.0f); int n = 2 * i + 1; - for (int j = 0; j < n; j++) { + for (int j = 0; j < n; j++) + { float thetak = 2 * j * ((float)Math.PI) / n; float newX = x + (float)(r * Math.Cos(thetak)); float newY = y + (float)(r * Math.Sin(thetak)); - if (x < 0 || x > 1.0 || y < 0 || y > 1.0) { + if (x < 0 || x > 1.0 || y < 0 || y > 1.0) + { continue; } @@ -5085,25 +5875,31 @@ bool forceAction bool raycastDidHit = Physics.Raycast(ray, out hit, 10f, layerMask); #if UNITY_EDITOR - if (raycastDidHit) { + if (raycastDidHit) + { Debug.DrawLine(ray.origin, hit.point, Color.red, 10f); } #endif - if (raycastDidHit) { + if (raycastDidHit) + { SimObjPhysics sop = ancestorSimObjPhysics(hit.transform.gameObject); if ( sop != null && sop.GetComponent() && (forceAction || objectIsCurrentlyVisible(sop, maxVisibleDistance)) - ) { + ) + { CanOpen_Object coo = sop.GetComponent(); - if (open != coo.isOpen) { - if (ItemInHand != null) { + if (open != coo.isOpen) + { + if (ItemInHand != null) + { foreach ( Collider c in ItemInHand.GetComponentsInChildren() - ) { + ) + { c.enabled = true; } } @@ -5113,8 +5909,10 @@ Collider c in ItemInHand.GetComponentsInChildren() } } } - if (ItemInHand != null) { - foreach (Collider c in ItemInHand.GetComponentsInChildren()) { + if (ItemInHand != null) + { + foreach (Collider c in ItemInHand.GetComponentsInChildren()) + { c.enabled = true; } } @@ -5122,7 +5920,8 @@ Collider c in ItemInHand.GetComponentsInChildren() } // H&S action - private void OpenOrCloseObjectAtLocation(bool open, ServerAction action) { + private void OpenOrCloseObjectAtLocation(bool open, ServerAction action) + { float x = action.x; float y = 1.0f - action.y; Ray ray = m_Camera.ViewportPointToRay(new Vector3(x, y, 0.0f)); @@ -5135,18 +5934,23 @@ private void OpenOrCloseObjectAtLocation(bool open, ServerAction action) { "Procedural0", "SimObjInvisible" ); - if (ItemInHand != null) { - foreach (Collider c in ItemInHand.GetComponentsInChildren()) { + if (ItemInHand != null) + { + foreach (Collider c in ItemInHand.GetComponentsInChildren()) + { c.enabled = false; } } bool raycastDidHit = Physics.Raycast(ray, out hit, 10f, layerMask); - if (ItemInHand != null) { - foreach (Collider c in ItemInHand.GetComponentsInChildren()) { + if (ItemInHand != null) + { + foreach (Collider c in ItemInHand.GetComponentsInChildren()) + { c.enabled = true; } } - if (!raycastDidHit) { + if (!raycastDidHit) + { Debug.Log("There don't seem to be any objects in that area."); errorMessage = "No openable object at location."; actionFinished(false); @@ -5156,24 +5960,34 @@ private void OpenOrCloseObjectAtLocation(bool open, ServerAction action) { if ( so != null && (action.forceAction || objectIsCurrentlyVisible(so, maxVisibleDistance)) - ) { - if (open) { + ) + { + if (open) + { OpenObject(objectId: so.ObjectID, forceAction: true); - } else { + } + else + { CloseObject(objectId: so.ObjectID, forceAction: true); } - } else if (so == null) { + } + else if (so == null) + { errorMessage = "Object at location is not interactable."; actionFinished(false); - } else { + } + else + { errorMessage = so.ObjectID + " is too far away."; actionFinished(false); } } // H&S action - public void OpenObjectAtLocation(ServerAction action) { - if (action.z > 0) { + public void OpenObjectAtLocation(ServerAction action) + { + if (action.z > 0) + { SimObjPhysics sop = getOpenableOrCloseableObjectNearLocation( true, action.x, @@ -5181,56 +5995,71 @@ public void OpenObjectAtLocation(ServerAction action) { action.z, false ); - if (sop != null) { + if (sop != null) + { OpenObject(objectId: sop.ObjectID, forceAction: true); - } else { + } + else + { errorMessage = "No openable object found within a radius about given point."; actionFinished(false); } - } else { + } + else + { OpenOrCloseObjectAtLocation(true, action); } } // H&S action - public void CloseObjectAtLocation(ServerAction action) { + 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) { + public void CookObject(ServerAction action) + { // specify target to pickup via objectId or coordinates - if (action.forceAction) { + if (action.forceAction) + { action.forceVisible = true; } SimObjPhysics target = null; - if (action.objectId == null) { + if (action.objectId == null) + { target = getInteractableSimObjectFromXY( x: action.x, y: action.y, forceAction: action.forceAction ); - } else { + } + else + { target = getInteractableSimObjectFromId( objectId: action.objectId, forceAction: action.forceAction ); } - if (target) { - if (!action.forceAction && !IsInteractable(target)) { + if (target) + { + if (!action.forceAction && !IsInteractable(target)) + { actionFinished(false); errorMessage = "object is visible but occluded by something: " + action.objectId; return; } - if (target.GetComponent()) { + if (target.GetComponent()) + { CookObject to = target.GetComponent(); // is this toasted already? if not, good to go - if (to.IsCooked()) { + if (to.IsCooked()) + { actionFinished(false); errorMessage = action.objectId + " is already Toasted!"; return; @@ -5239,14 +6068,17 @@ public void CookObject(ServerAction action) { to.Cook(); actionFinished(true); - } else { + } + else + { errorMessage = "target object is not cookable"; actionFinished(false); return; } } // target not found in currently visible objects, report not found - else { + else + { actionFinished(false); errorMessage = "object not found: " + action.objectId; } @@ -5254,7 +6086,8 @@ public void CookObject(ServerAction action) { // face change the agent's face screen to demonstrate different "emotion" states // for use with multi agent implicit communication - public void ChangeAgentFaceToNeutral() { + public void ChangeAgentFaceToNeutral() + { Material[] currentmats = MyFaceMesh.materials; currentmats[2] = ScreenFaces[0]; @@ -5264,7 +6097,8 @@ public void ChangeAgentFaceToNeutral() { actionFinished(true); } - public void ChangeAgentFaceToHappy() { + public void ChangeAgentFaceToHappy() + { Material[] currentmats = MyFaceMesh.materials; currentmats[2] = ScreenFaces[1]; @@ -5274,7 +6108,8 @@ public void ChangeAgentFaceToHappy() { actionFinished(true); } - public void ChangeAgentFaceToMad() { + public void ChangeAgentFaceToMad() + { Material[] currentmats = MyFaceMesh.materials; currentmats[2] = ScreenFaces[2]; @@ -5284,7 +6119,8 @@ public void ChangeAgentFaceToMad() { actionFinished(true); } - public void ChangeAgentFaceToSuperMad() { + public void ChangeAgentFaceToSuperMad() + { Material[] currentmats = MyFaceMesh.materials; currentmats[2] = ScreenFaces[3]; @@ -5294,23 +6130,28 @@ public void ChangeAgentFaceToSuperMad() { actionFinished(true); } - public void ToggleObjectOn(string objectId, bool forceAction = false) { + public void ToggleObjectOn(string objectId, bool forceAction = false) + { toggleObject(objectId, true, forceAction); } - public void ToggleObjectOff(string objectId, bool forceAction = false) { + public void ToggleObjectOff(string objectId, bool forceAction = false) + { toggleObject(objectId, false, forceAction); } - public void ToggleObjectOn(float x, float y, bool forceAction = false) { + public void ToggleObjectOn(float x, float y, bool forceAction = false) + { toggleObject(x, y, true, forceAction); } - public void ToggleObjectOff(float x, float y, bool forceAction = false) { + public void ToggleObjectOff(float x, float y, bool forceAction = false) + { toggleObject(x, y, false, forceAction); } - private void toggleObject(float x, float y, bool toggleOn, bool forceAction) { + private void toggleObject(float x, float y, bool toggleOn, bool forceAction) + { SimObjPhysics target = getInteractableSimObjectFromXY( x: x, y: y, @@ -5319,13 +6160,15 @@ private void toggleObject(float x, float y, bool toggleOn, bool forceAction) { toggleObject(target, toggleOn, forceAction); } - private void toggleObject(string objectId, bool toggleOn, bool forceAction) { + private void toggleObject(string objectId, bool toggleOn, bool forceAction) + { SimObjPhysics target = null; // if object is in the scene and visible, assign it to 'target' target = getInteractableSimObjectFromId(objectId: objectId, forceAction: forceAction); - if (!target) { + if (!target) + { // target not found in currently visible objects, report not found errorMessage = "object not found: " + objectId; actionFinished(false); @@ -5336,24 +6179,30 @@ private void toggleObject(string objectId, bool toggleOn, bool forceAction) { } // specific ToggleObject that is used for SetObjectStatesForLotsOfObjects - private IEnumerator toggleObject(SimObjPhysics target, bool toggleOn) { - if (target.GetComponent()) { + private IEnumerator toggleObject(SimObjPhysics target, bool toggleOn) + { + if (target.GetComponent()) + { // get CanToggleOnOff component from target CanToggleOnOff ctof = target.GetComponent(); - if (!ctof.ReturnSelfControlled()) { + if (!ctof.ReturnSelfControlled()) + { yield break; } // if the object is already in the state specified by the toggleOn bool, do nothing - if (ctof.isOn == toggleOn) { + if (ctof.isOn == toggleOn) + { yield break; } // if object needs to be closed to turn on... - if (toggleOn && ctof.ReturnMustBeClosedToTurnOn().Contains(target.Type)) { + if (toggleOn && ctof.ReturnMustBeClosedToTurnOn().Contains(target.Type)) + { // if the object is open and we are trying to turn it on, do nothing because it can't - if (target.GetComponent().isOpen) { + if (target.GetComponent().isOpen) + { yield break; } } @@ -5362,17 +6211,21 @@ private IEnumerator toggleObject(SimObjPhysics target, bool toggleOn) { } } - private bool toggleObject(SimObjPhysics target, bool toggleOn, bool forceAction) { - if (!forceAction && !IsInteractable(target)) { + private bool toggleObject(SimObjPhysics target, bool toggleOn, bool forceAction) + { + if (!forceAction && !IsInteractable(target)) + { errorMessage = "object is visible but occluded by something: " + target.ObjectID; actionFinished(false); return false; } - if (target.GetComponent()) { + if (target.GetComponent()) + { CanToggleOnOff ctof = target.GetComponent(); - if (!ctof.ReturnSelfControlled()) { + if (!ctof.ReturnSelfControlled()) + { errorMessage = "target object is controlled by another sim object. target object cannot be turned on/off directly"; actionFinished(false); @@ -5380,10 +6233,14 @@ private bool toggleObject(SimObjPhysics target, bool toggleOn, bool forceAction) } // check to make sure object is in other state - if (ctof.isOn == toggleOn) { - if (ctof.isOn) { + if (ctof.isOn == toggleOn) + { + if (ctof.isOn) + { errorMessage = "can't toggle object on if it's already on!"; - } else { + } + else + { errorMessage = "can't toggle object off if it's already off!"; } @@ -5391,8 +6248,10 @@ private bool toggleObject(SimObjPhysics target, bool toggleOn, bool forceAction) return false; } // check if this object needs to be closed in order to turn on - if (toggleOn && ctof.ReturnMustBeClosedToTurnOn().Contains(target.Type)) { - if (target.GetComponent().isOpen) { + if (toggleOn && ctof.ReturnMustBeClosedToTurnOn().Contains(target.Type)) + { + if (target.GetComponent().isOpen) + { errorMessage = "Target must be closed to Toggle On!"; actionFinished(false); return false; @@ -5405,9 +6264,11 @@ private bool toggleObject(SimObjPhysics target, bool toggleOn, bool forceAction) && target.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.CanBreak ) - ) { + ) + { // if this breakable object is broken, we can't turn it on - if (target.IsBroken) { + if (target.IsBroken) + { errorMessage = "Target is broken and cannot be Toggled On!"; actionFinished(false); return false; @@ -5417,17 +6278,21 @@ private bool toggleObject(SimObjPhysics target, bool toggleOn, bool forceAction) // interact then wait StartCoroutine(ToggleAndWait(ctof)); return true; - } else { + } + else + { errorMessage = "object is not toggleable."; actionFinished(false); return false; } } - protected IEnumerator ToggleAndWait(CanToggleOnOff ctof) { + protected IEnumerator ToggleAndWait(CanToggleOnOff ctof) + { bool ctofInitialState = ctof.isOn; - if (ctof != null) { + if (ctof != null) + { ctof.Toggle(); } @@ -5443,7 +6308,8 @@ protected IEnumerator ToggleAndWait(CanToggleOnOff ctof) { ); success = true; - if (!success) { + if (!success) + { errorMessage = "object could not be toggled on/off succesfully"; } @@ -5453,8 +6319,10 @@ protected IEnumerator ToggleAndWait(CanToggleOnOff ctof) { } // XXX: This will return contained objects, but should not be used. Likely depracate this later - public void Contains(ServerAction action) { - if (action.objectId == null) { + public void Contains(ServerAction action) + { + if (action.objectId == null) + { errorMessage = "Hey, actually give me an object ID check containment for, yeah?"; actionFinished(false); return; @@ -5465,17 +6333,21 @@ public void Contains(ServerAction action) { forceAction: action.forceAction ); - if (target) { + if (target) + { List ids = target.GetAllSimObjectsInReceptacleTriggersByObjectID(); #if UNITY_EDITOR - foreach (string s in ids) { + foreach (string s in ids) + { Debug.Log(s); } #endif actionFinished(true, ids.ToArray()); - } else { + } + else + { errorMessage = "object not found: " + action.objectId; actionFinished(false); } @@ -5494,35 +6366,44 @@ public void Contains(ServerAction action) { private Dictionary maskedGameObjectDict = new Dictionary(); - private void maskGameObject(GameObject go, Material mat) { - if (go.name == "Objects" || go.name == "Structure") { + private void maskGameObject(GameObject go, Material mat) + { + if (go.name == "Objects" || go.name == "Structure") + { return; } - foreach (MeshRenderer r in go.GetComponentsInChildren() as MeshRenderer[]) { + foreach (MeshRenderer r in go.GetComponentsInChildren() as MeshRenderer[]) + { int id = r.GetInstanceID(); - if (!maskedGameObjectDict.ContainsKey(id)) { + if (!maskedGameObjectDict.ContainsKey(id)) + { maskedGameObjectDict[id] = r.materials; } Material[] newMaterials = new Material[r.materials.Length]; - for (int i = 0; i < newMaterials.Length; i++) { + for (int i = 0; i < newMaterials.Length; i++) + { newMaterials[i] = new Material(mat); } r.materials = newMaterials; } } - private void unmaskGameObject(GameObject go) { - foreach (MeshRenderer r in go.GetComponentsInChildren() as MeshRenderer[]) { + private void unmaskGameObject(GameObject go) + { + foreach (MeshRenderer r in go.GetComponentsInChildren() as MeshRenderer[]) + { int id = r.GetInstanceID(); - if (maskedGameObjectDict.ContainsKey(id)) { + if (maskedGameObjectDict.ContainsKey(id)) + { r.materials = maskedGameObjectDict[id]; maskedGameObjectDict.Remove(id); } } } - public void MaskMovingParts() { + public void MaskMovingParts() + { Material openMaterial = new Material(Shader.Find("Unlit/Color")); openMaterial.color = Color.magenta; Material closedMaterial = new Material(Shader.Find("Unlit/Color")); @@ -5530,26 +6411,34 @@ public void MaskMovingParts() { Material otherMaterial = new Material(Shader.Find("Unlit/Color")); otherMaterial.color = Color.green; - foreach (GameObject go in GameObject.FindObjectsOfType()) { + foreach (GameObject go in GameObject.FindObjectsOfType()) + { maskGameObject(go, otherMaterial); } - foreach (CanOpen_Object coo in GameObject.FindObjectsOfType()) { + foreach (CanOpen_Object coo in GameObject.FindObjectsOfType()) + { Material m; - if (coo.isOpen) { + if (coo.isOpen) + { m = openMaterial; - } else { + } + else + { m = closedMaterial; } - foreach (GameObject go in coo.MovingParts) { + foreach (GameObject go in coo.MovingParts) + { maskGameObject(go, m); } } actionFinished(true); } - public void UnmaskMovingParts() { - foreach (GameObject go in GameObject.FindObjectsOfType()) { + public void UnmaskMovingParts() + { + foreach (GameObject go in GameObject.FindObjectsOfType()) + { unmaskGameObject(go); } // foreach (CanOpen_Object coo in GameObject.FindObjectsOfType()) { @@ -5560,27 +6449,35 @@ public void UnmaskMovingParts() { actionFinished(true); } - private void HideAll() { - foreach (GameObject go in GameObject.FindObjectsOfType()) { + private void HideAll() + { + foreach (GameObject go in GameObject.FindObjectsOfType()) + { UpdateDisplayGameObject(go, false); } } - private void UnhideAll() { - foreach (GameObject go in GameObject.FindObjectsOfType()) { + private void UnhideAll() + { + foreach (GameObject go in GameObject.FindObjectsOfType()) + { UpdateDisplayGameObject(go, true); } // Making sure the agents visibility capsules are not incorrectly unhidden - foreach (BaseFPSAgentController agent in this.agentManager.agents) { + foreach (BaseFPSAgentController agent in this.agentManager.agents) + { agent.IsVisible = agent.IsVisible; } } - public void HideAllObjectsExcept(ServerAction action) { - foreach (GameObject go in UnityEngine.Object.FindObjectsOfType()) { + public void HideAllObjectsExcept(ServerAction action) + { + foreach (GameObject go in UnityEngine.Object.FindObjectsOfType()) + { UpdateDisplayGameObject(go, false); } - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { UpdateDisplayGameObject( physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId].gameObject, true @@ -5589,37 +6486,45 @@ public void HideAllObjectsExcept(ServerAction action) { actionFinished(true); } - public void HideTranslucentObjects() { - foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) { + public void HideTranslucentObjects() + { + foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) + { if ( sop.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.CanSeeThrough ) - ) { + ) + { UpdateDisplayGameObject(sop.gameObject, false); } } actionFinished(true); } - public void HideTransparentStructureObjects() { + public void HideTransparentStructureObjects() + { transparentStructureObjectsHidden = true; GameObject structObj = GameObject.Find("Structure"); GameObject lightObj = GameObject.Find("Lighting"); List renderers = new List(); - if (structObj != null) { + if (structObj != null) + { renderers.AddRange(structObj.GetComponentsInChildren()); } - if (lightObj != null) { + if (lightObj != null) + { renderers.AddRange(lightObj.GetComponentsInChildren()); } // renderers.AddRange(GameObject.FindObjectsOfType()); - foreach (Renderer r in renderers) { + foreach (Renderer r in renderers) + { bool transparent = true; - foreach (Material m in r.materials) { + foreach (Material m in r.materials) + { if ( !( m.IsKeywordEnabled("_ALPHATEST_ON") @@ -5627,59 +6532,74 @@ public void HideTransparentStructureObjects() { || m.IsKeywordEnabled("_ALPHAPREMULTIPLY_ON") ) || m.color.a == 1.0f - ) { + ) + { transparent = false; break; } } - if (transparent) { + if (transparent) + { UpdateDisplayGameObject(r.gameObject, false); } } } - public void UnhideStructureObjects() { + public void UnhideStructureObjects() + { transparentStructureObjectsHidden = false; GameObject structObj = GameObject.Find("Structure"); GameObject lightObj = GameObject.Find("Lighting"); List transforms = new List(); - if (structObj != null) { + if (structObj != null) + { transforms.AddRange(structObj.GetComponentsInChildren()); } - if (lightObj != null) { + if (lightObj != null) + { transforms.AddRange(lightObj.GetComponentsInChildren()); } - foreach (Transform transform in transforms) { + foreach (Transform transform in transforms) + { UpdateDisplayGameObject(transform.gameObject, true); } } - public void HideBlueObjects(ServerAction action) { - foreach (Renderer r in UnityEngine.Object.FindObjectsOfType()) { - foreach (Material m in r.materials) { - if (m.name.Contains("BLUE")) { + public void HideBlueObjects(ServerAction action) + { + foreach (Renderer r in UnityEngine.Object.FindObjectsOfType()) + { + foreach (Material m in r.materials) + { + if (m.name.Contains("BLUE")) + { r.enabled = false; break; } } } - foreach (GameObject go in Resources.FindObjectsOfTypeAll()) { - if (go.name.Contains("BlueCube")) { + foreach (GameObject go in Resources.FindObjectsOfTypeAll()) + { + if (go.name.Contains("BlueCube")) + { UpdateDisplayGameObject(go, true); } } actionFinished(true); } - public void GetAwayFromObject(ServerAction action) { - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void GetAwayFromObject(ServerAction action) + { + if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId]; int k = 0; - while (isAgentCapsuleCollidingWith(sop.gameObject) && k < 20) { + while (isAgentCapsuleCollidingWith(sop.gameObject) && k < 20) + { k++; Vector3[] dirs = { @@ -5694,44 +6614,58 @@ public void GetAwayFromObject(ServerAction action) { moveInDirection(dirs[0] * gridSize); sop.gameObject.SetActive(true); } - if (isAgentCapsuleCollidingWith(sop.gameObject)) { + if (isAgentCapsuleCollidingWith(sop.gameObject)) + { errorMessage = "Could not get away from " + sop.ObjectID; actionFinished(false); return; } actionFinished(true); - } else { + } + else + { errorMessage = "No object with given id could be found to disable collisions with."; actionFinished(false); } } - public void DisableObjectCollisionWithAgent(ServerAction action) { - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void DisableObjectCollisionWithAgent(ServerAction action) + { + if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId]; - foreach (Collider c0 in this.GetComponentsInChildren()) { - foreach (Collider c1 in sop.GetComponentsInChildren()) { + foreach (Collider c0 in this.GetComponentsInChildren()) + { + foreach (Collider c1 in sop.GetComponentsInChildren()) + { Physics.IgnoreCollision(c0, c1); } } - foreach (Collider c1 in sop.GetComponentsInChildren()) { + foreach (Collider c1 in sop.GetComponentsInChildren()) + { collidersToIgnoreDuringMovement.Add(c1); } actionFinished(true); - } else { + } + else + { errorMessage = "No object with given id could be found to disable collisions with."; actionFinished(false); } } - public void HideObject(string objectId, bool hideContained = true) { - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + 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) - ) { - foreach (SimObjPhysics containedSop in sop.SimObjectsContainedByReceptacle) { + ) + { + foreach (SimObjPhysics containedSop in sop.SimObjectsContainedByReceptacle) + { UpdateDisplayGameObject(containedSop.gameObject, false); } } @@ -5739,50 +6673,65 @@ public void HideObject(string objectId, bool hideContained = true) { sop.GetAllSimObjectsInReceptacleTriggersByObjectID(); actionFinished(true); - } else { + } + else + { errorMessage = "No object with given id could be found to hide."; actionFinished(false); } } - public void UnhideObject(string objectId, bool unhideContained = true) { - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + 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) - ) { - foreach (SimObjPhysics containedSop in sop.SimObjectsContainedByReceptacle) { + ) + { + foreach (SimObjPhysics containedSop in sop.SimObjectsContainedByReceptacle) + { UpdateDisplayGameObject(containedSop.gameObject, true); } } UpdateDisplayGameObject(sop.gameObject, true); actionFinished(true); - } else { + } + else + { errorMessage = "No object with given id could be found to unhide."; actionFinished(false); } } - public void HideAllObjects(ServerAction action) { + public void HideAllObjects(ServerAction action) + { HideAll(); actionFinished(true); } - public void UnhideAllObjects(ServerAction action) { + public void UnhideAllObjects(ServerAction action) + { transparentStructureObjectsHidden = false; UnhideAll(); actionFinished(true); } - protected void MaskSimObj(SimObjPhysics so, Material mat) { - if (!transparentStructureObjectsHidden) { + protected void MaskSimObj(SimObjPhysics so, Material mat) + { + if (!transparentStructureObjectsHidden) + { HideTransparentStructureObjects(); } HashSet renderersToSkip = new HashSet(); - foreach (SimObjPhysics childSo in so.GetComponentsInChildren()) { - if (so.ObjectID != childSo.ObjectID) { - foreach (MeshRenderer mr in childSo.GetComponentsInChildren()) { + foreach (SimObjPhysics childSo in so.GetComponentsInChildren()) + { + if (so.ObjectID != childSo.ObjectID) + { + foreach (MeshRenderer mr in childSo.GetComponentsInChildren()) + { renderersToSkip.Add(mr); } } @@ -5791,23 +6740,29 @@ protected void MaskSimObj(SimObjPhysics so, Material mat) { foreach ( MeshRenderer r in so.gameObject.GetComponentsInChildren() as MeshRenderer[] - ) { - if (!renderersToSkip.Contains(r)) { + ) + { + if (!renderersToSkip.Contains(r)) + { dict[r.GetInstanceID()] = r.materials; Material[] newMaterials = new Material[r.materials.Length]; - for (int i = 0; i < newMaterials.Length; i++) { + for (int i = 0; i < newMaterials.Length; i++) + { newMaterials[i] = new Material(mat); } r.materials = newMaterials; } } - if (!maskedObjects.ContainsKey(so.ObjectID)) { + if (!maskedObjects.ContainsKey(so.ObjectID)) + { maskedObjects[so.ObjectID] = dict; } } - protected void MaskSimObj(SimObjPhysics so, Color color) { - if (!transparentStructureObjectsHidden) { + protected void MaskSimObj(SimObjPhysics so, Color color) + { + if (!transparentStructureObjectsHidden) + { HideTransparentStructureObjects(); } Material material = new Material(Shader.Find("Unlit/Color")); @@ -5815,18 +6770,24 @@ protected void MaskSimObj(SimObjPhysics so, Color color) { MaskSimObj(so, material); } - protected void UnmaskSimObj(SimObjPhysics so) { - if (transparentStructureObjectsHidden) { + protected void UnmaskSimObj(SimObjPhysics so) + { + if (transparentStructureObjectsHidden) + { UnhideStructureObjects(); } - if (maskedObjects.ContainsKey(so.ObjectID)) { + if (maskedObjects.ContainsKey(so.ObjectID)) + { foreach ( MeshRenderer r in so.gameObject.GetComponentsInChildren() as MeshRenderer[] - ) { - if (r != null) { - if (maskedObjects[so.ObjectID].ContainsKey(r.GetInstanceID())) { + ) + { + if (r != null) + { + if (maskedObjects[so.ObjectID].ContainsKey(r.GetInstanceID())) + { r.materials = maskedObjects[so.ObjectID][r.GetInstanceID()]; } } @@ -5835,20 +6796,23 @@ as MeshRenderer[] } } - public void EmphasizeObject(ServerAction action) { + public void EmphasizeObject(ServerAction action) + { #if UNITY_EDITOR foreach ( KeyValuePair< string, SimObjPhysics > entry in physicsSceneManager.ObjectIdToSimObjPhysics - ) { + ) + { Debug.Log(entry.Key); Debug.Log(entry.Key == action.objectId); } #endif - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { HideAll(); UpdateDisplayGameObject( physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId].gameObject, @@ -5859,38 +6823,50 @@ public void EmphasizeObject(ServerAction action) { Color.magenta ); actionFinished(true); - } else { + } + else + { errorMessage = "No object with id: " + action.objectId; actionFinished(false); } } - public void UnemphasizeAll() { + public void UnemphasizeAll() + { UnhideAll(); - foreach (SimObjPhysics so in GameObject.FindObjectsOfType()) { + foreach (SimObjPhysics so in GameObject.FindObjectsOfType()) + { UnmaskSimObj(so); } actionFinished(true); } - public void MaskObject(ServerAction action) { - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void MaskObject(ServerAction action) + { + if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { MaskSimObj( physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId], Color.magenta ); actionFinished(true); - } else { + } + else + { errorMessage = "No such object with id: " + action.objectId; actionFinished(false); } } - public void UnmaskObject(ServerAction action) { - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void UnmaskObject(ServerAction action) + { + if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { UnmaskSimObj(physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId]); actionFinished(true); - } else { + } + else + { errorMessage = "No such object with id: " + action.objectId; actionFinished(false); } @@ -5900,11 +6876,13 @@ public void UnmaskObject(ServerAction action) { ///// GETTING DISTANCES, NORMALS, ETC ///// /////////////////////////////////////////// - private bool NormalIsApproximatelyUp(Vector3 normal, float tol = 10f) { + private bool NormalIsApproximatelyUp(Vector3 normal, float tol = 10f) + { return Vector3.Angle(transform.up, normal) < tol; } - private bool AnythingAbovePosition(Vector3 position, float distance) { + private bool AnythingAbovePosition(Vector3 position, float distance) + { Vector3 up = new Vector3(0.0f, 1.0f, 0.0f); RaycastHit hit; return Physics.Raycast(position, up, out hit, distance); @@ -5915,22 +6893,29 @@ private bool AnythingAbovePositionIgnoreObject( float distance, int layerMask, 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) { - if (hit.collider.transform.gameObject != toIgnore) { + foreach (RaycastHit hit in hits) + { + if (hit.collider.transform.gameObject != toIgnore) + { return true; } } return false; } - private float[,,] initializeFlatSurfacesOnGrid(int yGridSize, int xGridSize) { + private float[,,] initializeFlatSurfacesOnGrid(int yGridSize, int xGridSize) + { float[,,] flatSurfacesOnGrid = new float[2, yGridSize, xGridSize]; - for (int i = 0; i < 2; i++) { - for (int j = 0; j < yGridSize; j++) { - for (int k = 0; k < xGridSize; k++) { + for (int i = 0; i < 2; i++) + { + for (int j = 0; j < yGridSize; j++) + { + for (int k = 0; k < xGridSize; k++) + { flatSurfacesOnGrid[i, j, k] = float.PositiveInfinity; } } @@ -5938,18 +6923,22 @@ GameObject toIgnore return flatSurfacesOnGrid; } - private void toggleColliders(IEnumerable colliders) { - foreach (Collider c in colliders) { + private void toggleColliders(IEnumerable colliders) + { + foreach (Collider c in colliders) + { c.enabled = !c.enabled; } } - public void FlatSurfacesOnGrid(ServerAction action) { + public void FlatSurfacesOnGrid(ServerAction action) + { int xGridSize = (int)Math.Round(action.x, 0); int yGridSize = (int)Math.Round(action.y, 0); flatSurfacesOnGrid = initializeFlatSurfacesOnGrid(yGridSize, xGridSize); - if (ItemInHand != null) { + if (ItemInHand != null) + { toggleColliders(ItemInHand.GetComponentsInChildren()); } @@ -5960,26 +6949,35 @@ public void FlatSurfacesOnGrid(ServerAction action) { "Procedural3", "Procedural0" ); - for (int i = 0; i < yGridSize; i++) { - for (int j = 0; j < xGridSize; j++) { + for (int i = 0; i < yGridSize; i++) + { + for (int j = 0; j < xGridSize; j++) + { float x = j * (1.0f / xGridSize) + (0.5f / xGridSize); float y = (1.0f - (0.5f / yGridSize)) - i * (1.0f / yGridSize); Ray ray = m_Camera.ViewportPointToRay(new Vector3(x, y, 0)); RaycastHit[] hits = Physics.RaycastAll(ray, 10f, layerMask); float minHitDistance = float.PositiveInfinity; - foreach (RaycastHit hit in hits) { - if (hit.distance < minHitDistance) { + foreach (RaycastHit hit in hits) + { + if (hit.distance < minHitDistance) + { minHitDistance = hit.distance; } } - foreach (RaycastHit hit in hits) { + foreach (RaycastHit hit in hits) + { if ( NormalIsApproximatelyUp(hit.normal) && !AnythingAbovePosition(hit.point, 0.1f) - ) { - if (hit.distance == minHitDistance) { + ) + { + if (hit.distance == minHitDistance) + { flatSurfacesOnGrid[0, i, j] = minHitDistance; - } else { + } + else + { flatSurfacesOnGrid[1, i, j] = Math.Min( flatSurfacesOnGrid[1, i, j], hit.distance @@ -5989,20 +6987,23 @@ public void FlatSurfacesOnGrid(ServerAction action) { } } } - if (ItemInHand != null) { + if (ItemInHand != null) + { toggleColliders(ItemInHand.GetComponentsInChildren()); } actionFinished(true); } - public void GetMetadataOnGrid(ServerAction action) { + public void GetMetadataOnGrid(ServerAction action) + { int xGridSize = (int)Math.Round(action.x, 0); int yGridSize = (int)Math.Round(action.y, 0); distances = new float[yGridSize, xGridSize]; normals = new float[3, yGridSize, xGridSize]; isOpenableGrid = new bool[yGridSize, xGridSize]; - if (ItemInHand != null) { + if (ItemInHand != null) + { toggleColliders(ItemInHand.GetComponentsInChildren()); } @@ -6013,20 +7014,25 @@ public void GetMetadataOnGrid(ServerAction action) { "Procedural3", "Procedural0" ); - for (int i = 0; i < yGridSize; i++) { - for (int j = 0; j < xGridSize; j++) { + for (int i = 0; i < yGridSize; i++) + { + for (int j = 0; j < xGridSize; j++) + { float x = j * (1.0f / xGridSize) + (0.5f / xGridSize); float y = (1.0f - (0.5f / yGridSize)) - i * (1.0f / yGridSize); Ray ray = m_Camera.ViewportPointToRay(new Vector3(x, y, 0)); RaycastHit hit; - if (Physics.Raycast(ray, out hit, 10f, layerMask)) { + if (Physics.Raycast(ray, out hit, 10f, layerMask)) + { distances[i, j] = hit.distance; normals[0, i, j] = Vector3.Dot(transform.right, hit.normal); normals[1, i, j] = Vector3.Dot(transform.up, hit.normal); normals[2, i, j] = Vector3.Dot(transform.forward, hit.normal); SimObjPhysics so = hit.transform.gameObject.GetComponent(); isOpenableGrid[i, j] = so != null && (so.GetComponent()); - } else { + } + else + { distances[i, j] = float.PositiveInfinity; normals[0, i, j] = float.NaN; normals[1, i, j] = float.NaN; @@ -6036,20 +7042,24 @@ public void GetMetadataOnGrid(ServerAction action) { } } - if (ItemInHand != null) { + if (ItemInHand != null) + { toggleColliders(ItemInHand.GetComponentsInChildren()); } actionFinished(true); } - public void SegmentVisibleObjects() { - if (ItemInHand != null) { + public void SegmentVisibleObjects() + { + if (ItemInHand != null) + { toggleColliders(ItemInHand.GetComponentsInChildren()); } int k = 0; List objectIds = new List(); - foreach (SimObjPhysics so in GetAllVisibleSimObjPhysics(m_Camera, 100f)) { + foreach (SimObjPhysics so in GetAllVisibleSimObjPhysics(m_Camera, 100f)) + { int i = (10 * k) / 256; int j = (10 * k) % 256; MaskSimObj(so, new Color32(Convert.ToByte(i), Convert.ToByte(j), 255, 255)); @@ -6058,7 +7068,8 @@ public void SegmentVisibleObjects() { } segmentedObjectIds = objectIds.ToArray(); - if (ItemInHand != null) { + if (ItemInHand != null) + { toggleColliders(ItemInHand.GetComponentsInChildren()); } actionFinished(true); @@ -6067,7 +7078,8 @@ public void SegmentVisibleObjects() { //////////////////////////// ///// Crouch and Stand ///// //////////////////////////// - virtual public void crouch() { + virtual public void crouch() + { m_Camera.transform.localPosition = new Vector3( standingLocalCameraPosition.x, crouchingLocalCameraPosition.y, @@ -6075,29 +7087,42 @@ virtual public void crouch() { ); } - public virtual void stand() { + public virtual void stand() + { m_Camera.transform.localPosition = standingLocalCameraPosition; } - public void Crouch() { - if (!isStanding()) { + public void Crouch() + { + if (!isStanding()) + { errorMessage = "Already crouching."; actionFinished(false); - } else if (!CheckIfItemBlocksAgentStandOrCrouch()) { + } + else if (!CheckIfItemBlocksAgentStandOrCrouch()) + { actionFinished(false); - } else { + } + else + { crouch(); actionFinished(true); } } - public void Stand() { - if (isStanding()) { + public void Stand() + { + if (isStanding()) + { errorMessage = "Already standing."; actionFinished(false); - } else if (!CheckIfItemBlocksAgentStandOrCrouch()) { + } + else if (!CheckIfItemBlocksAgentStandOrCrouch()) + { actionFinished(false); - } else { + } + else + { stand(); actionFinished(true); } @@ -6107,17 +7132,23 @@ public void Stand() { ///// MISC ///// //////////////// - public void RotateUniverseAroundAgent(ServerAction action) { + public void RotateUniverseAroundAgent(ServerAction action) + { agentManager.RotateAgentsByRotatingUniverse(action.rotation.y); actionFinished(true); } - public void ChangeFOV(float fieldOfView, string camera = "") { - if (fieldOfView > 0 && fieldOfView < 180) { - if (string.IsNullOrEmpty(camera)) { + public void ChangeFOV(float fieldOfView, string camera = "") + { + if (fieldOfView > 0 && fieldOfView < 180) + { + if (string.IsNullOrEmpty(camera)) + { m_Camera.fieldOfView = fieldOfView; actionFinished(true); - } else { + } + else + { var cameraTuples = new List<(Camera camera, bool isThirdPartyCamera, int id)>() { (camera: m_Camera, isThirdPartyCamera: false, id: -1) @@ -6127,29 +7158,39 @@ public void ChangeFOV(float fieldOfView, string camera = "") { ) ); var matches = cameraTuples; - if (camera != "*") { + 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) { + 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'."; actionFinished(false); - } else { - foreach (var tuple in matches) { - if (tuple.isThirdPartyCamera) { + } + else + { + foreach (var tuple in matches) + { + if (tuple.isThirdPartyCamera) + { agentManager.UpdateThirdPartyCamera( tuple.id, fieldOfView: fieldOfView ); - } else { + } + else + { tuple.camera.fieldOfView = fieldOfView; } } actionFinished(true); } } - } else { + } + else + { errorMessage = "fov must be in (0, 180) noninclusive."; Debug.Log(errorMessage); actionFinished(false); @@ -6157,11 +7198,15 @@ public void ChangeFOV(float fieldOfView, string camera = "") { } // in case you want to change the timescale - public void ChangeTimeScale(ServerAction action) { - if (action.timeScale > 0) { + public void ChangeTimeScale(ServerAction action) + { + if (action.timeScale > 0) + { Time.timeScale = action.timeScale; actionFinished(true); - } else { + } + else + { errorMessage = "Time scale must be >0"; actionFinished(false); } @@ -6174,11 +7219,14 @@ public void ChangeTimeScale(ServerAction action) { // this is a combination of objectIsWithinViewport and objectIsCurrentlyVisible, specifically to check // if a single sim object is on screen regardless of agent visibility maxDistance // DO NOT USE THIS FOR ALL OBJECTS cause it's going to be soooo expensive - public bool objectIsOnScreen(SimObjPhysics sop) { + public bool objectIsOnScreen(SimObjPhysics sop) + { bool result = false; - if (sop.VisibilityPoints.Length > 0) { + if (sop.VisibilityPoints.Length > 0) + { Transform[] visPoints = sop.VisibilityPoints; - foreach (Transform point in visPoints) { + foreach (Transform point in visPoints) + { Vector3 viewPoint = m_Camera.WorldToViewportPoint(point.position); float ViewPointRangeHigh = 1.0f; float ViewPointRangeLow = 0.0f; @@ -6191,7 +7239,8 @@ public bool objectIsOnScreen(SimObjPhysics sop) { && // 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); // raycast from agentcamera to point, ignore triggers, use layers 8 and 10 @@ -6212,10 +7261,14 @@ public bool objectIsOnScreen(SimObjPhysics sop) { "Agent" ) ) - ) { - if (hit.transform != sop.transform) { + ) + { + if (hit.transform != sop.transform) + { result = false; - } else { + } + else + { result = true; break; } @@ -6225,23 +7278,29 @@ public bool objectIsOnScreen(SimObjPhysics sop) { updateAllAgentCollidersForVisibilityCheck(true); return result; - } else { + } + else + { Debug.Log("Error! Set at least 1 visibility point on SimObjPhysics prefab!"); } return false; } - public bool objectIsCurrentlyVisible(SimObjPhysics sop, float maxDistance) { + public bool objectIsCurrentlyVisible(SimObjPhysics sop, float maxDistance) + { Debug.Log("trying to check if objectIsCurrentlyVisible"); - if (sop.VisibilityPoints.Length > 0) { + if (sop.VisibilityPoints.Length > 0) + { Transform[] visPoints = sop.VisibilityPoints; updateAllAgentCollidersForVisibilityCheck(false); - foreach (Transform point in visPoints) { + foreach (Transform point in visPoints) + { Vector3 tmp = point.position; tmp.y = transform.position.y; // Debug.Log(Vector3.Distance(tmp, transform.position)); - if (Vector3.Distance(tmp, transform.position) < maxDistance) { + if (Vector3.Distance(tmp, transform.position) < maxDistance) + { // if this particular point is in view... if ( ( @@ -6258,20 +7317,24 @@ public bool objectIsCurrentlyVisible(SimObjPhysics sop, float maxDistance) { true ).visible ) - ) { + ) + { updateAllAgentCollidersForVisibilityCheck(true); return true; } } } - } else { + } + else + { Debug.Log("Error! Set at least 1 visibility point on SimObjPhysics prefab!"); } updateAllAgentCollidersForVisibilityCheck(true); return false; } - protected int xzManhattanDistance(Vector3 p0, Vector3 p1, float gridSize) { + 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)) @@ -6279,8 +7342,10 @@ protected int xzManhattanDistance(Vector3 p0, Vector3 p1, float gridSize) { } // hide and seek action. - public void ExhaustiveSearchForItem(ServerAction action) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void ExhaustiveSearchForItem(ServerAction action) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { errorMessage = "Object ID appears to be invalid."; actionFinished(false); return; @@ -6288,16 +7353,20 @@ public void ExhaustiveSearchForItem(ServerAction action) { SimObjPhysics theObject = physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId]; Vector3[] positions = null; - if (action.positions != null && action.positions.Count != 0) { + if (action.positions != null && action.positions.Count != 0) + { positions = action.positions.ToArray(); - } else { + } + else + { positions = getReachablePositions(); } bool wasStanding = isStanding(); Vector3 oldPosition = transform.position; Quaternion oldRotation = transform.rotation; - if (ItemInHand != null) { + if (ItemInHand != null) + { ItemInHand.gameObject.SetActive(false); } @@ -6306,7 +7375,8 @@ public void ExhaustiveSearchForItem(ServerAction action) { SimplePriorityQueue pq = new SimplePriorityQueue(); Vector3 agentPos = transform.position; - foreach (Vector3 p in positions) { + foreach (Vector3 p in positions) + { pq.Enqueue(p, xzManhattanDistance(p, agentPos, gridSize)); } @@ -6315,35 +7385,46 @@ public void ExhaustiveSearchForItem(ServerAction action) { #endif bool objectSeen = false; int positionsTried = 0; - while (pq.Count != 0 && !objectSeen) { + while (pq.Count != 0 && !objectSeen) + { positionsTried += 1; Vector3 p = pq.Dequeue(); transform.position = p; Collider[] colliders = collidersWithinCapsuleCastOfAgent(maxVisibleDistance); HashSet openableObjectsNearby = new HashSet(); - foreach (Collider c in colliders) { + foreach (Collider c in colliders) + { SimObjPhysics sop = ancestorSimObjPhysics(c.gameObject); - if (sop != null && sop.GetComponent() != null) { + if (sop != null && sop.GetComponent() != null) + { openableObjectsNearby.Add(sop); } } - foreach (SimObjPhysics openable in openableObjectsNearby) { - foreach (GameObject go in openable.GetComponent().MovingParts) { + foreach (SimObjPhysics openable in openableObjectsNearby) + { + foreach (GameObject go in openable.GetComponent().MovingParts) + { go.SetActive(false); } } - for (int j = 0; j < 2; j++) { // Standing / Crouching - if (j == 0) { + for (int j = 0; j < 2; j++) + { // Standing / Crouching + if (j == 0) + { stand(); - } else { + } + else + { crouch(); } - for (int i = 0; i < 4; i++) { // 4 rotations + for (int i = 0; i < 4; i++) + { // 4 rotations transform.rotation = Quaternion.Euler(new Vector3(0.0f, 90.0f * i, 0.0f)); - if (objectIsCurrentlyVisible(theObject, 1000f)) { + if (objectIsCurrentlyVisible(theObject, 1000f)) + { objectSeen = true; #if UNITY_EDITOR visiblePosition = p; @@ -6351,24 +7432,30 @@ public void ExhaustiveSearchForItem(ServerAction action) { break; } } - if (objectSeen) { + if (objectSeen) + { break; } } - foreach (SimObjPhysics openable in openableObjectsNearby) { - foreach (GameObject go in openable.GetComponent().MovingParts) { + foreach (SimObjPhysics openable in openableObjectsNearby) + { + foreach (GameObject go in openable.GetComponent().MovingParts) + { go.SetActive(true); } } } #if UNITY_EDITOR - if (objectSeen) { + if (objectSeen) + { Debug.Log("Object found."); Debug.Log("Manhattan distance:"); Debug.Log(xzManhattanDistance(visiblePosition, oldPosition, gridSize)); - } else { + } + else + { Debug.Log("Object not found."); } Debug.Log("BFS steps taken:"); @@ -6384,18 +7471,23 @@ public void ExhaustiveSearchForItem(ServerAction action) { actionFinished(true, toReturn); } - protected HashSet getAllItemsVisibleFromPositions(Vector3[] positions) { + protected HashSet getAllItemsVisibleFromPositions(Vector3[] positions) + { bool wasStanding = isStanding(); Vector3 oldPosition = transform.position; Quaternion oldRotation = transform.rotation; - if (ItemInHand != null) { + if (ItemInHand != null) + { ItemInHand.gameObject.SetActive(false); } List movingPartsDisabled = new List(); - foreach (SimObjPhysics sop in physicsSceneManager.ObjectIdToSimObjPhysics.Values) { - if (sop.GetComponent() != null) { - foreach (GameObject go in sop.GetComponent().MovingParts) { + foreach (SimObjPhysics sop in physicsSceneManager.ObjectIdToSimObjPhysics.Values) + { + if (sop.GetComponent() != null) + { + foreach (GameObject go in sop.GetComponent().MovingParts) + { movingPartsDisabled.Add(go); go.SetActive(false); } @@ -6404,14 +7496,20 @@ protected HashSet getAllItemsVisibleFromPositions(Vector3[] posit HashSet allVisible = new HashSet(); float[] rotations = { 0f, 90f, 180f, 270f }; - foreach (Vector3 p in positions) { + foreach (Vector3 p in positions) + { transform.position = p; - foreach (float rotation in rotations) { + foreach (float rotation in rotations) + { transform.rotation = Quaternion.Euler(new Vector3(0f, rotation, 0f)); - for (int i = 0; i < 2; i++) { - if (i == 0) { + for (int i = 0; i < 2; i++) + { + if (i == 0) + { stand(); - } else { + } + else + { crouch(); } foreach ( @@ -6419,25 +7517,31 @@ SimObjPhysics sop in GetAllVisibleSimObjPhysics( m_Camera, 1.0f + maxVisibleDistance ) - ) { + ) + { allVisible.Add(sop); } } } } - foreach (GameObject go in movingPartsDisabled) { + foreach (GameObject go in movingPartsDisabled) + { go.SetActive(true); } - if (wasStanding) { + if (wasStanding) + { stand(); - } else { + } + else + { crouch(); } transform.position = oldPosition; transform.rotation = oldRotation; - if (ItemInHand != null) { + if (ItemInHand != null) + { ItemInHand.gameObject.SetActive(true); } @@ -6449,25 +7553,33 @@ public void SetTransform( Transform transform, Vector3? position = null, Quaternion? rotation = null - ) { - if (!transform.GetComponent()) { - if (position != null) { + ) + { + if (!transform.GetComponent()) + { + if (position != null) + { transform.position = (Vector3)position; } - if (rotation != null) { + 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 { + 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) { + } + 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}" @@ -6476,7 +7588,9 @@ public void SetTransform( (Vector3)position, articulationBody.transform.rotation ); - } else if (position == null && rotation != null) { + } + else if (position == null && rotation != null) + { Debug.Log("Teleporting rotation, default position"); articulationBody.TeleportRoot( articulationBody.transform.position, @@ -6497,29 +7611,37 @@ public virtual List> getInteractablePoses( bool[] standings = null, float? maxDistance = null, int maxPoses = int.MaxValue // works like infinity - ) { + ) + { Debug.Log( $"Position of agent at start of GetInteractablePoses: {this.transform.position}" ); - if (360 % rotateStepDegrees != 0 && rotations != null) { + if (360 % rotateStepDegrees != 0 && rotations != null) + { throw new InvalidOperationException( $"360 % rotateStepDegrees (360 % {rotateStepDegrees} != 0) must be 0, unless 'rotations: float[]' is overwritten." ); } - if (maxPoses <= 0) { + if (maxPoses <= 0) + { throw new ArgumentOutOfRangeException("maxPoses must be > 0."); } // default "visibility" distance float maxDistanceFloat; - if (maxDistance == null) { + if (maxDistance == null) + { maxDistanceFloat = maxVisibleDistance; - } else if ((float)maxDistance <= 0) { + } + else if ((float)maxDistance <= 0) + { throw new ArgumentOutOfRangeException( "maxDistance must be >= 0 meters from the object." ); - } else { + } + else + { maxDistanceFloat = (float)maxDistance; } @@ -6530,17 +7652,23 @@ public virtual List> getInteractablePoses( // Populate default standings. Note that these are boolean because that's // the most natural integration with Teleport - if (standings == null) { + if (standings == null) + { standings = new bool[] { false, true }; } // populate default horizons - if (horizons == null) { + if (horizons == null) + { horizons = new float[] { -30, 0, 30, 60 }; - } else { - foreach (float horizon in horizons) { + } + else + { + foreach (float horizon in horizons) + { // recall that horizon=60 is look down 60 degrees and horizon=-30 is look up 30 degrees - if (horizon > maxDownwardLookAngle || horizon < -maxUpwardLookAngle) { + if (horizon > maxDownwardLookAngle || horizon < -maxUpwardLookAngle) + { throw new ArgumentException( $"Each horizon must be in [{-maxUpwardLookAngle}:{maxDownwardLookAngle}]. You gave {horizon}." ); @@ -6549,12 +7677,14 @@ public virtual List> getInteractablePoses( } // populate the positions by those that are reachable - if (positions == null) { + if (positions == null) + { positions = getReachablePositions(); } // populate the rotations based on rotateStepDegrees - if (rotations == null) { + if (rotations == null) + { // Consider the case where one does not want to move on a perfect grid, and is currently moving // with an offsetted set of rotations like {10, 100, 190, 280} instead of the default {0, 90, 180, 270}. // This may happen if the agent starts by teleports with the rotation of 10 degrees. @@ -6569,7 +7699,8 @@ public virtual List> getInteractablePoses( float rotation = offset; rotation < 360 + offset; rotation += rotateStepDegrees - ) { + ) + { rotations[i++] = rotation; } } @@ -6579,7 +7710,8 @@ public virtual List> getInteractablePoses( || rotations.Length == 0 || positions.Length == 0 || standings.Length == 0 - ) { + ) + { throw new InvalidOperationException( "Every degree of freedom must have at least 1 valid value." ); @@ -6590,7 +7722,8 @@ public virtual List> getInteractablePoses( Vector3 oldPosition = transform.position; Quaternion oldRotation = transform.rotation; Vector3 oldHorizon = m_Camera.transform.localEulerAngles; - if (ItemInHand != null) { + if (ItemInHand != null) + { ItemInHand.gameObject.SetActive(false); } @@ -6599,7 +7732,8 @@ public virtual List> getInteractablePoses( // which is then used to filter the set of all reachable positions to just those plausible positions. Bounds objectBounds = UtilityFunctions.CreateEmptyBounds(); objectBounds.Encapsulate(theObject.transform.position); - foreach (Transform vp in theObject.VisibilityPoints) { + foreach (Transform vp in theObject.VisibilityPoints) + { objectBounds.Encapsulate(vp.position); } float fudgeFactor = objectBounds.extents.magnitude; @@ -6621,17 +7755,23 @@ public virtual List> getInteractablePoses( // iterate over each reasonable agent pose bool stopEarly = false; - foreach (float horizon in horizons) { + foreach (float horizon in horizons) + { m_Camera.transform.localEulerAngles = new Vector3(horizon, 0f, 0f); Debug.Log($"setting horizon to: {m_Camera.transform.localEulerAngles.x}"); - foreach (bool standing in standings) { - if (standing) { + foreach (bool standing in standings) + { + if (standing) + { stand(); - } else { + } + else + { crouch(); } - foreach (float rotation in rotations) { + foreach (float rotation in rotations) + { Vector3 rotationVector = new Vector3(x: 0, y: rotation, z: 0); //Debug.Log($"initial rotation: {transform.rotation}"); SetTransform( @@ -6640,7 +7780,8 @@ public virtual List> getInteractablePoses( ); //Debug.Log($"Rotation after SetTransform(): {transform.rotation}"); - foreach (Vector3 position in filteredPositions) { + foreach (Vector3 position in filteredPositions) + { Debug.Log("////////////////////"); Debug.Log($"position Before SetTransform: {transform.position}"); Debug.Log( @@ -6652,9 +7793,11 @@ public virtual List> getInteractablePoses( // Each of these values is directly compatible with TeleportFull // and should be used with .step(action='TeleportFull', **interactable_positions[0]) - if (objectIsCurrentlyVisible(theObject, maxDistanceFloat)) { + if (objectIsCurrentlyVisible(theObject, maxDistanceFloat)) + { validAgentPoses.Add( - new Dictionary { + new Dictionary + { ["x"] = position.x, ["y"] = position.y, ["z"] = position.z, @@ -6664,7 +7807,8 @@ public virtual List> getInteractablePoses( } ); - if (validAgentPoses.Count >= maxPoses) { + if (validAgentPoses.Count >= maxPoses) + { stopEarly = true; break; } @@ -6680,23 +7824,29 @@ public virtual List> getInteractablePoses( #endif } } - if (stopEarly) { + if (stopEarly) + { break; } } - if (stopEarly) { + if (stopEarly) + { break; } } - if (stopEarly) { + if (stopEarly) + { break; } } // restore old agent pose - if (wasStanding) { + if (wasStanding) + { stand(); - } else { + } + else + { crouch(); } SetTransform( @@ -6705,7 +7855,8 @@ public virtual List> getInteractablePoses( rotation: (Quaternion?)oldRotation ); m_Camera.transform.localEulerAngles = oldHorizon; - if (ItemInHand != null) { + if (ItemInHand != null) + { ItemInHand.gameObject.SetActive(true); } @@ -6714,7 +7865,8 @@ public virtual List> getInteractablePoses( Debug.Log(validAgentPoses); #endif - if (markActionFinished) { + if (markActionFinished) + { actionFinishedEmit(success: true, actionReturn: validAgentPoses); } @@ -6731,7 +7883,8 @@ public virtual void GetInteractablePoses( bool[] standings = null, float? maxDistance = null, int maxPoses = int.MaxValue // works like infinity - ) { + ) + { getInteractablePoses( objectId: objectId, markActionFinished: true, @@ -6752,10 +7905,12 @@ 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) { + for (float h = -maxUpwardLookAngle; h <= maxDownwardLookAngle; h += horizon) + { horizons.Add(h); } List> interactablePoses = getInteractablePoses( @@ -6770,15 +7925,21 @@ public void PositionsFromWhichItemIsInteractable( // where the latter is cleaner in python. Dictionary> d = new Dictionary>(); string[] keys = { "x", "y", "z", "rotation", "standing", "horizon" }; - foreach (string key in keys) { + foreach (string key in keys) + { d[key] = new List(); } - foreach (Dictionary pose in interactablePoses) { - foreach (string key in keys) { - if (key == "standing") { + foreach (Dictionary pose in interactablePoses) + { + foreach (string key in keys) + { + if (key == "standing") + { // standing is converted from true => 1 to false => 0, for backwards compatibility d[key].Add((bool)pose[key] ? 1 : 0); - } else { + } + else + { // all other keys have float outputs d[key].Add((float)pose[key]); } @@ -6793,7 +7954,8 @@ private int numVisiblePositions( bool markActionFinished, Vector3[] positions = null, int maxPoses = int.MaxValue - ) { + ) + { List> interactablePoses = getInteractablePoses( objectId: objectId, positions: positions, @@ -6804,7 +7966,8 @@ private int numVisiblePositions( ); // object id might have been invalid, causing failure - if (markActionFinished) { + if (markActionFinished) + { actionFinishedEmit(success: true, actionReturn: interactablePoses.Count); } return interactablePoses.Count; @@ -6814,36 +7977,44 @@ private int numVisiblePositions( public void NumberOfPositionsFromWhichItemIsVisible( string objectId, Vector3[] positions = null - ) { + ) + { numVisiblePositions(objectId: objectId, positions: positions, markActionFinished: true); } - public void TogglePhysics() { + public void TogglePhysics() + { Physics.autoSimulation = !Physics.autoSimulation; actionFinished(true); } - public void ChangeOpenSpeed(ServerAction action) { - foreach (CanOpen_Object coo in GameObject.FindObjectsOfType()) { + public void ChangeOpenSpeed(ServerAction action) + { + foreach (CanOpen_Object coo in GameObject.FindObjectsOfType()) + { coo.animationTime = action.x; } actionFinished(true); } // to ignore the agent in this collision check, set ignoreAgent to true - protected bool isHandObjectColliding(bool ignoreAgent = false, float expandBy = 0.0f) { - if (ItemInHand == null) { + protected bool isHandObjectColliding(bool ignoreAgent = false, float expandBy = 0.0f) + { + if (ItemInHand == null) + { return false; } List ignoreGameObjects = new List(); // Ignore the agent when determining if the hand object is colliding - if (ignoreAgent) { + if (ignoreAgent) + { ignoreGameObjects.Add(this.gameObject); } return UtilityFunctions.isObjectColliding(ItemInHand, ignoreGameObjects, expandBy); } - protected bool isAgentCapsuleCollidingWith(GameObject otherGameObject) { + protected bool isAgentCapsuleCollidingWith(GameObject otherGameObject) + { int layerMask = LayerMask.GetMask( "SimObjVisible", "Procedural1", @@ -6857,8 +8028,10 @@ Collider c in PhysicsExtensions.OverlapCapsule( layerMask, QueryTriggerInteraction.Ignore ) - ) { - if (hasAncestor(c.transform.gameObject, otherGameObject)) { + ) + { + if (hasAncestor(c.transform.gameObject, otherGameObject)) + { return true; } } @@ -6954,19 +8127,25 @@ Collider c in PhysicsExtensions.OverlapCapsule( // return false; // } - public float roundToGridSize(float x, float gridSize, bool roundUp) { + public float roundToGridSize(float x, float gridSize, bool roundUp) + { int mFactor = Convert.ToInt32(1.0f / gridSize); - if (Math.Abs(mFactor - 1.0f / gridSize) > 1e-3) { + if (Math.Abs(mFactor - 1.0f / gridSize) > 1e-3) + { throw new Exception("1.0 / gridSize should be an integer."); } - if (roundUp) { + if (roundUp) + { return (float)Math.Ceiling(mFactor * x) / mFactor; - } else { + } + else + { return (float)Math.Floor(mFactor * x) / mFactor; } } - public void RandomlyMoveAgent(int randomSeed = 0) { + public void RandomlyMoveAgent(int randomSeed = 0) + { #if UNITY_EDITOR randomSeed = UnityEngine.Random.Range(0, 1000000); #endif @@ -6976,9 +8155,12 @@ public void RandomlyMoveAgent(int randomSeed = 0) { reachablePositions.Shuffle_(randomSeed); bool success = false; - foreach (Vector3 position in reachablePositions) { - foreach (float rotation in orientations) { - if (handObjectCanFitInPosition(position, rotation)) { + foreach (Vector3 position in reachablePositions) + { + foreach (float rotation in orientations) + { + if (handObjectCanFitInPosition(position, rotation)) + { this.transform.position = position; this.transform.rotation = Quaternion.Euler(0.0f, rotation, 0.0f); success = true; @@ -6987,18 +8169,25 @@ public void RandomlyMoveAgent(int randomSeed = 0) { } } - if (errorMessage != "") { + if (errorMessage != "") + { actionFinished(false); - } else if (!success) { + } + else if (!success) + { errorMessage = "Could not find a position in which the agent and object fit."; actionFinished(false); - } else { + } + else + { actionFinished(true, reachablePositions); } } - public void GetReachablePositionsForObject(ServerAction action) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void GetReachablePositionsForObject(ServerAction action) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { errorMessage = "Object " + action.objectId + " does not seem to exist."; actionFinished(false); return; @@ -7009,14 +8198,18 @@ public void GetReachablePositionsForObject(ServerAction action) { Quaternion startRot = sop.transform.rotation; Vector3[] positions = null; - if (action.positions != null && action.positions.Count != 0) { + if (action.positions != null && action.positions.Count != 0) + { positions = action.positions.ToArray(); - } else { + } + else + { positions = getReachablePositions(); } Bounds b = UtilityFunctions.CreateEmptyBounds(); - foreach (Vector3 p in positions) { + foreach (Vector3 p in positions) + { b.Encapsulate(p); } @@ -7030,14 +8223,17 @@ public void GetReachablePositionsForObject(ServerAction action) { // Debug.Log(zMax); List agentGameObjects = new List(); - foreach (BaseFPSAgentController agent in agentManager.agents) { + foreach (BaseFPSAgentController agent in agentManager.agents) + { agentGameObjects.Add(agent.gameObject); } // List reachable = new List(); List enabledColliders = new List(); - foreach (Collider c in sop.GetComponentsInChildren()) { - if (c.enabled) { + foreach (Collider c in sop.GetComponentsInChildren()) + { + if (c.enabled) + { c.enabled = false; enabledColliders.Add(c); } @@ -7046,12 +8242,15 @@ public void GetReachablePositionsForObject(ServerAction action) { Dictionary> reachablePerRotation = new Dictionary>(); - for (int k = 0; k < 4; k++) { + 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++) { + 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, @@ -7065,7 +8264,8 @@ public void GetReachablePositionsForObject(ServerAction action) { 0.0f, true ) - ) { + ) + { // #if UNITY_EDITOR // Debug.Log(p); // #endif @@ -7083,7 +8283,8 @@ public void GetReachablePositionsForObject(ServerAction action) { } } sop.BoundingBox.GetComponent().enabled = false; - foreach (Collider c in enabledColliders) { + foreach (Collider c in enabledColliders) + { c.enabled = true; } @@ -7099,24 +8300,33 @@ public void GetReachablePositionsForObject(ServerAction action) { actionFinished(true, reachablePerRotation); } - private bool stringInSomeAncestorName(GameObject go, string[] strs) { - foreach (string str in strs) { - if (go.name.Contains(str)) { + private bool stringInSomeAncestorName(GameObject go, string[] strs) + { + foreach (string str in strs) + { + if (go.name.Contains(str)) + { return true; } } - if (go.transform.parent != null) { + if (go.transform.parent != null) + { return stringInSomeAncestorName(go.transform.parent.gameObject, strs); - } else { + } + else + { return false; } } - public void HideObscuringObjects(ServerAction action) { + public void HideObscuringObjects(ServerAction action) + { string objType = ""; - if (action.objectId != null && action.objectId != "") { + if (action.objectId != null && action.objectId != "") + { string[] split = action.objectId.Split('|'); - if (split.Length != 0) { + if (split.Length != 0) + { objType = action.objectId.Split('|')[0]; } } @@ -7129,14 +8339,18 @@ public void HideObscuringObjects(ServerAction action) { "Procedural3", "Procedural0" ); - for (int i = 0; i < yGridSize; i++) { - for (int j = 0; j < xGridSize; j++) { + for (int i = 0; i < yGridSize; i++) + { + for (int j = 0; j < xGridSize; j++) + { float x = j * (1.0f / xGridSize) + (0.5f / xGridSize); float y = (1.0f - (0.5f / yGridSize)) - i * (1.0f / yGridSize); Ray ray = m_Camera.ViewportPointToRay(new Vector3(x, y, 0)); RaycastHit hit; - while (true) { - if (Physics.Raycast(ray, out hit, 10f, layerMask)) { + while (true) + { + if (Physics.Raycast(ray, out hit, 10f, layerMask)) + { UpdateDisplayGameObject(hit.transform.gameObject, false); SimObjPhysics hitObj = hit.transform.gameObject.GetComponentInChildren(); @@ -7144,12 +8358,17 @@ public void HideObscuringObjects(ServerAction action) { hitObj != null && objType != "" && hitObj.ObjectID.Contains(objType) - ) { + ) + { ray.origin = hit.point + ray.direction / 100f; - } else { + } + else + { break; } - } else { + } + else + { break; } } @@ -7159,15 +8378,18 @@ 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) { + public void CreateObject(ServerAction action) + { + if (ItemInHand != null) + { errorMessage = "Already have an object in hand, can't create a new one to put there."; actionFinished(false); return; } - if (action.objectType == null) { + if (action.objectType == null) + { errorMessage = "Please give valid Object Type from SimObjType enum list"; actionFinished(false); return; @@ -7186,7 +8408,8 @@ public void CreateObject(ServerAction action) { action.forceAction ); - if (so == null) { + if (so == null) + { throw new InvalidOperationException( "Failed to create object, are you sure it can be spawned?" ); @@ -7198,17 +8421,20 @@ public void CreateObject(ServerAction action) { PickupObject(objectId: so.objectID, forceAction: true); } - public void CreateObjectAtLocation(ServerAction action) { + public void CreateObjectAtLocation(ServerAction action) + { Vector3 targetPosition = action.position; Vector3 targetRotation = action.rotation; - if (!action.forceAction && !agentManager.SceneBounds.Contains(targetPosition)) { + if (!action.forceAction && !agentManager.SceneBounds.Contains(targetPosition)) + { errorMessage = "Target position is out of bounds!"; actionFinished(false); return; } - if (action.objectType == null) { + if (action.objectType == null) + { errorMessage = "Please give valid Object Type from SimObjType enum list"; actionFinished(false); return; @@ -7227,11 +8453,14 @@ public void CreateObjectAtLocation(ServerAction action) { action.forceAction ); - if (so == null) { + if (so == null) + { errorMessage = "Failed to create object, are you sure it can be spawned?"; actionFinished(false); return; - } else { + } + else + { // also update the PHysics Scene Manager with this new object physicsSceneManager.AddToObjectsInScene(so); } @@ -7244,13 +8473,16 @@ protected SimObjPhysics createObjectAtLocation( Vector3 targetPosition, Vector3 targetRotation, int objectVariation = 1 - ) { - if (!agentManager.SceneBounds.Contains(targetPosition)) { + ) + { + if (!agentManager.SceneBounds.Contains(targetPosition)) + { errorMessage = "Target position is out of bounds!"; return null; } - if (objectType == null) { + if (objectType == null) + { errorMessage = "Please give valid Object Type from SimObjType enum list"; return null; } @@ -7267,10 +8499,13 @@ protected SimObjPhysics createObjectAtLocation( false ); - if (so == null) { + if (so == null) + { errorMessage = "Failed to create object, are you sure it can be spawned?"; return null; - } else { + } + else + { // also update the PHysics Scene Manager with this new object physicsSceneManager.AddToObjectsInScene(so); } @@ -7278,28 +8513,35 @@ protected SimObjPhysics createObjectAtLocation( return so; } - public void CreateObjectOnFloor(ServerAction action) { + public void CreateObjectOnFloor(ServerAction action) + { InstantiatePrefabTest script = physicsSceneManager.GetComponent(); Bounds b = script.BoundsOfObject(action.objectType, 1); - if (b.min.x == float.PositiveInfinity) { + if (b.min.x == float.PositiveInfinity) + { errorMessage = "Could not get bounds for the object to be created on the floor"; actionFinished(false); - } else { + } + else + { action.y = b.extents.y + getFloorY(action.x, action.z) + 0.1f; action.position = new Vector3(action.x, action.y, action.z); CreateObjectAtLocation(action); } } - protected bool randomlyPlaceObjectOnFloor(SimObjPhysics sop, Vector3[] candidatePositions) { + protected bool randomlyPlaceObjectOnFloor(SimObjPhysics sop, Vector3[] candidatePositions) + { var oldPosition = sop.transform.position; var oldRotation = sop.transform.rotation; sop.transform.rotation = Quaternion.identity; Bounds b = UtilityFunctions.CreateEmptyBounds(); - foreach (Renderer r in sop.GetComponentsInChildren()) { - if (r.enabled) { + foreach (Renderer r in sop.GetComponentsInChildren()) + { + if (r.enabled) + { b.Encapsulate(r.bounds); } } @@ -7309,21 +8551,26 @@ protected bool randomlyPlaceObjectOnFloor(SimObjPhysics sop, Vector3[] candidate float[] rotations = { 0f, 90f, 180f, 270f }; List shuffledRotations = (List)rotations.ToList().Shuffle_(); bool objectColliding = true; - foreach (Vector3 position in shuffledCurrentlyReachable) { + foreach (Vector3 position in shuffledCurrentlyReachable) + { float y = b.extents.y + getFloorY(position.x, position.y, position.z) + 0.1f; - foreach (float r in shuffledRotations) { + foreach (float r in shuffledRotations) + { sop.transform.position = new Vector3(position.x, y, position.z); sop.transform.rotation = Quaternion.Euler(new Vector3(0.0f, r, 0.0f)); objectColliding = UtilityFunctions.isObjectColliding(sop.gameObject); - if (!objectColliding) { + if (!objectColliding) + { break; } } - if (!objectColliding) { + if (!objectColliding) + { break; } } - if (objectColliding) { + if (objectColliding) + { sop.transform.position = oldPosition; sop.transform.rotation = oldRotation; } @@ -7334,11 +8581,13 @@ 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) { + if (b.min.x != float.PositiveInfinity) + { errorMessage = "Could not get bounds of object with type " + objectType; } @@ -7348,20 +8597,24 @@ Vector3[] candidatePositions float[] rotations = { 0f, 90f, 180f, 270f }; float[] shuffledRotations = rotations.OrderBy(x => systemRandom.Next()).ToArray(); SimObjPhysics objectCreated = null; - foreach (Vector3 position in shuffledCurrentlyReachable) { + foreach (Vector3 position in shuffledCurrentlyReachable) + { float y = b.extents.y + getFloorY(position.x, position.y, position.z) + 0.01f; - foreach (float r in shuffledRotations) { + foreach (float r in shuffledRotations) + { objectCreated = createObjectAtLocation( objectType, new Vector3(position.x, y, position.z), new Vector3(0.0f, r, 0.0f), objectVariation ); - if (objectCreated) { + if (objectCreated) + { break; } } - if (objectCreated) { + if (objectCreated) + { errorMessage = ""; break; } @@ -7372,7 +8625,8 @@ Vector3[] candidatePositions protected SimObjPhysics randomlyCreateAndPlaceObjectOnFloor( string objectType, int objectVariation - ) { + ) + { return randomlyCreateAndPlaceObjectOnFloor( objectType, objectVariation, @@ -7380,22 +8634,28 @@ int objectVariation ); } - public void RandomlyCreateAndPlaceObjectOnFloor(string objectType, int objectVariation = 0) { + public void RandomlyCreateAndPlaceObjectOnFloor(string objectType, int objectVariation = 0) + { SimObjPhysics objectCreated = randomlyCreateAndPlaceObjectOnFloor( objectType, objectVariation ); - if (!objectCreated) { + if (!objectCreated) + { errorMessage = "Failed to randomly create object. " + errorMessage; actionFinished(false); - } else { + } + else + { errorMessage = ""; actionFinished(true, objectCreated.ObjectID); } } - public void GetPositionsObjectVisibleFrom(ServerAction action) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void GetPositionsObjectVisibleFrom(ServerAction action) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { errorMessage = "Object " + action.objectId + " does not seem to exist."; actionFinished(false); return; @@ -7411,20 +8671,27 @@ public void GetPositionsObjectVisibleFrom(ServerAction action) { List goodRotations = new List(); Vector3[] positions = null; - if (action.positions != null && action.positions.Count != 0) { + if (action.positions != null && action.positions.Count != 0) + { positions = action.positions.ToArray(); - } else { + } + else + { positions = getReachablePositions(); } - foreach (Vector3 position in positions) { + foreach (Vector3 position in positions) + { Vector3 tmp = position; tmp.y = sop.transform.position.y; - if (Vector3.Distance(tmp, sop.transform.position) <= 2 * maxVisibleDistance) { - foreach (float r in rotations) { + if (Vector3.Distance(tmp, sop.transform.position) <= 2 * maxVisibleDistance) + { + foreach (float r in rotations) + { transform.position = position; transform.rotation = Quaternion.Euler(new Vector3(0f, r, 0f)); - if (objectIsCurrentlyVisible(sop, maxVisibleDistance)) { + if (objectIsCurrentlyVisible(sop, maxVisibleDistance)) + { #if UNITY_EDITOR Debug.Log(position); Debug.Log(r); @@ -7445,9 +8712,11 @@ public void GetPositionsObjectVisibleFrom(ServerAction action) { actionFinished(true); } - public void WorldToViewportPoint(Vector3 position) { + public void WorldToViewportPoint(Vector3 position) + { Vector3 point = m_Camera.WorldToViewportPoint(position); - if (point.x < 0f || point.x > 1.0f || point.y < 0f || point.y > 1.0f) { + if (point.x < 0f || point.x > 1.0f || point.y < 0f || point.y > 1.0f) + { errorMessage = "Point not in viewport."; actionFinished(false); return; @@ -7460,21 +8729,26 @@ public void WorldToViewportPoint(Vector3 position) { protected float approxPercentScreenObjectOccupies( SimObjPhysics sop, bool updateVisibilityColliders = true - ) { + ) + { float percent = 0.0f; - if (sop.VisibilityPoints != null && sop.VisibilityPoints.Length > 0) { + if (sop.VisibilityPoints != null && sop.VisibilityPoints.Length > 0) + { float minX = 1.0f; float maxX = 0.0f; float minY = 1.0f; float maxY = 0.0f; - if (updateVisibilityColliders) { + if (updateVisibilityColliders) + { updateAllAgentCollidersForVisibilityCheck(false); } - foreach (Transform point in sop.VisibilityPoints) { + foreach (Transform point in sop.VisibilityPoints) + { Vector3 viewPoint = m_Camera.WorldToViewportPoint(point.position); - if (CheckIfVisibilityPointInViewport(sop, point, m_Camera, false).visible) { + if (CheckIfVisibilityPointInViewport(sop, point, m_Camera, false).visible) + { minX = Math.Min(viewPoint.x, minX); maxX = Math.Max(viewPoint.x, maxX); minY = Math.Min(viewPoint.y, minY); @@ -7482,7 +8756,8 @@ protected float approxPercentScreenObjectOccupies( } } percent = Math.Max(0f, maxX - minX) * Math.Max(0f, maxY - minY); - if (updateVisibilityColliders) { + if (updateVisibilityColliders) + { updateAllAgentCollidersForVisibilityCheck(true); } } @@ -7492,8 +8767,10 @@ protected float approxPercentScreenObjectOccupies( return percent; } - public void ApproxPercentScreenObjectOccupies(string objectId) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void ApproxPercentScreenObjectOccupies(string objectId) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; actionFinishedEmit(false); return; @@ -7502,8 +8779,10 @@ public void ApproxPercentScreenObjectOccupies(string objectId) { actionFinishedEmit(true, approxPercentScreenObjectOccupies(sop)); } - public void ApproxPercentScreenObjectFromPositions(ServerAction action) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) { + public void ApproxPercentScreenObjectFromPositions(ServerAction action) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(action.objectId)) + { errorMessage = "Cannot find object with id " + action.objectId; actionFinished(false); return; @@ -7511,9 +8790,12 @@ public void ApproxPercentScreenObjectFromPositions(ServerAction action) { SimObjPhysics sop = physicsSceneManager.ObjectIdToSimObjPhysics[action.objectId]; Vector3[] positions = null; - if (action.positions != null && action.positions.Count != 0) { + if (action.positions != null && action.positions.Count != 0) + { positions = action.positions.ToArray(); - } else { + } + else + { positions = getReachablePositions(); } @@ -7524,12 +8806,15 @@ public void ApproxPercentScreenObjectFromPositions(ServerAction action) { List positionAndApproxAmountVisible = new List(); updateAllAgentCollidersForVisibilityCheck(false); - foreach (Vector3 position in positions) { + foreach (Vector3 position in positions) + { transform.position = position; - foreach (float rotation in rotations) { + foreach (float rotation in rotations) + { transform.rotation = Quaternion.Euler(0f, rotation, 0f); float approxVisible = approxPercentScreenObjectOccupies(sop, false); - if (approxVisible > 0.0f) { + if (approxVisible > 0.0f) + { float[] tuple = { position.x, @@ -7548,13 +8833,17 @@ public void ApproxPercentScreenObjectFromPositions(ServerAction action) { actionFinishedEmit(true, positionAndApproxAmountVisible); } - public void GetVisibilityPointsOfObjects() { + public void GetVisibilityPointsOfObjects() + { Dictionary> objectIdToVisibilityPoints = new Dictionary>(); - foreach (SimObjPhysics sop in physicsSceneManager.ObjectIdToSimObjPhysics.Values) { + foreach (SimObjPhysics sop in physicsSceneManager.ObjectIdToSimObjPhysics.Values) + { objectIdToVisibilityPoints[sop.ObjectID] = new List(); - if (sop.VisibilityPoints != null) { - foreach (Transform t in sop.VisibilityPoints) { + if (sop.VisibilityPoints != null) + { + foreach (Transform t in sop.VisibilityPoints) + { objectIdToVisibilityPoints[sop.ObjectID].Add(t.position); } } @@ -7562,11 +8851,15 @@ public void GetVisibilityPointsOfObjects() { actionFinished(true, objectIdToVisibilityPoints); } - public void ObjectsVisibleFromPositions(ServerAction action) { + public void ObjectsVisibleFromPositions(ServerAction action) + { Vector3[] positions = null; - if (action.positions != null && action.positions.Count != 0) { + if (action.positions != null && action.positions.Count != 0) + { positions = action.positions.ToArray(); - } else { + } + else + { positions = getReachablePositions(); } @@ -7577,17 +8870,21 @@ public void ObjectsVisibleFromPositions(ServerAction action) { Dictionary> objectIdToVisiblePositions = new Dictionary>(); - foreach (Vector3 position in positions) { + foreach (Vector3 position in positions) + { transform.position = position; - foreach (float rotation in rotations) { + foreach (float rotation in rotations) + { transform.rotation = Quaternion.Euler(0f, rotation, 0f); foreach ( SimObjPhysics sop in GetAllVisibleSimObjPhysics( m_Camera, maxVisibleDistance ) - ) { - if (!objectIdToVisiblePositions.ContainsKey(sop.ObjectID)) { + ) + { + if (!objectIdToVisiblePositions.ContainsKey(sop.ObjectID)) + { objectIdToVisiblePositions[sop.ObjectID] = new List(); } List l = objectIdToVisiblePositions[sop.ObjectID]; @@ -7609,28 +8906,34 @@ SimObjPhysics sop in GetAllVisibleSimObjPhysics( actionFinished(true, objectIdToVisiblePositions); } - public void StackBooks() { + public void StackBooks() + { GameObject topLevelObject = GameObject.Find("HideAndSeek"); SimObjPhysics[] hideSeekObjects = topLevelObject.GetComponentsInChildren(); HashSet seenBooks = new HashSet(); List> groups = new List>(); - foreach (SimObjPhysics sop in hideSeekObjects) { + foreach (SimObjPhysics sop in hideSeekObjects) + { HashSet group = new HashSet(); - if (sop.ObjectID.StartsWith("Book|")) { - if (!seenBooks.Contains(sop.ObjectID)) { + if (sop.ObjectID.StartsWith("Book|")) + { + if (!seenBooks.Contains(sop.ObjectID)) + { HashSet objectsNearBook = objectsInBox( sop.transform.position.x, sop.transform.position.z ); group.Add(sop); seenBooks.Add(sop.ObjectID); - foreach (SimObjPhysics possibleBook in objectsNearBook) { + foreach (SimObjPhysics possibleBook in objectsNearBook) + { if ( possibleBook.ObjectID.StartsWith("Book|") && !seenBooks.Contains(possibleBook.ObjectID) - ) { + ) + { group.Add(possibleBook); seenBooks.Add(possibleBook.ObjectID); } @@ -7640,14 +8943,17 @@ public void StackBooks() { } } - foreach (HashSet group in groups) { + foreach (HashSet group in groups) + { SimObjPhysics topBook = null; GameObject topMesh = null; GameObject topColliders = null; GameObject topTrigColliders = null; GameObject topVisPoints = null; - foreach (SimObjPhysics so in group) { - if (topBook == null) { + foreach (SimObjPhysics so in group) + { + if (topBook == null) + { topBook = so; topMesh = so.gameObject.transform.Find("mesh").gameObject; topColliders = so.gameObject.transform.Find("Colliders").gameObject; @@ -7655,13 +8961,17 @@ public void StackBooks() { .gameObject.transform.Find("TriggerColliders") .gameObject; topVisPoints = so.gameObject.transform.Find("VisibilityPoints").gameObject; - } else { + } + else + { GameObject mesh = so.gameObject.transform.Find("mesh").gameObject; mesh.transform.parent = topMesh.transform; GameObject colliders = so.gameObject.transform.Find("Colliders").gameObject; - foreach (Transform t in colliders.GetComponentsInChildren()) { - if (t != colliders.transform) { + foreach (Transform t in colliders.GetComponentsInChildren()) + { + if (t != colliders.transform) + { t.parent = topColliders.transform; } } @@ -7669,8 +8979,10 @@ public void StackBooks() { GameObject trigColliders = so .gameObject.transform.Find("TriggerColliders") .gameObject; - foreach (Transform t in trigColliders.GetComponentsInChildren()) { - if (t != colliders.transform) { + foreach (Transform t in trigColliders.GetComponentsInChildren()) + { + if (t != colliders.transform) + { t.parent = topTrigColliders.transform; } } @@ -7678,8 +8990,10 @@ public void StackBooks() { GameObject visPoints = so .gameObject.transform.Find("VisibilityPoints") .gameObject; - foreach (Transform t in visPoints.GetComponentsInChildren()) { - if (t != visPoints.transform) { + foreach (Transform t in visPoints.GetComponentsInChildren()) + { + if (t != visPoints.transform) + { t.parent = topVisPoints.transform; } } @@ -7693,17 +9007,20 @@ public void StackBooks() { } // hide and seek action - public void RandomizeHideSeekObjects(int randomSeed, float removeProb) { + public void RandomizeHideSeekObjects(int randomSeed, float removeProb) + { // NOTE: this does not use systemRandom var rnd = new System.Random(randomSeed); - if (!physicsSceneManager.ToggleHideAndSeek(true)) { + if (!physicsSceneManager.ToggleHideAndSeek(true)) + { errorMessage = "Hide and Seek object reference not set, nothing to randomize."; actionFinished(false); return; } - foreach (Transform child in physicsSceneManager.HideAndSeek.transform) { + foreach (Transform child in physicsSceneManager.HideAndSeek.transform) + { child.gameObject.SetActive(rnd.NextDouble() > removeProb); } physicsSceneManager.SetupScene(); @@ -7759,11 +9076,15 @@ public void RandomlyOpenCloseObjects( bool simplifyPhysics = false, float pOpen = 0.5f, bool randOpenness = true - ) { - foreach (SimObjPhysics so in GameObject.FindObjectsOfType()) { - if (so.GetComponent()) { + ) + { + foreach (SimObjPhysics so in GameObject.FindObjectsOfType()) + { + if (so.GetComponent()) + { // randomly opens an object to a random openness - if (UnityEngine.Random.value < pOpen) { + if (UnityEngine.Random.value < pOpen) + { openObject( target: so, openness: randOpenness ? UnityEngine.Random.value : 1, @@ -7777,20 +9098,25 @@ public void RandomlyOpenCloseObjects( actionFinished(true); } - public void GetApproximateVolume(string objectId) { - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void GetApproximateVolume(string objectId) + { + if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { SimObjPhysics so = physicsSceneManager.ObjectIdToSimObjPhysics[objectId]; Quaternion oldRotation = so.transform.rotation; so.transform.rotation = Quaternion.identity; Bounds objBounds = UtilityFunctions.CreateEmptyBounds(); bool hasActiveRenderer = false; - foreach (Renderer r in so.GetComponentsInChildren()) { - if (r.enabled) { + foreach (Renderer r in so.GetComponentsInChildren()) + { + if (r.enabled) + { hasActiveRenderer = true; objBounds.Encapsulate(r.bounds); } } - if (!hasActiveRenderer) { + if (!hasActiveRenderer) + { errorMessage = "Cannot get bounds for " + objectId @@ -7805,27 +9131,34 @@ public void GetApproximateVolume(string objectId) { Debug.Log("Volume is " + actionFloatReturn); #endif actionFinished(true); - } else { + } + else + { errorMessage = "Invalid objectId " + objectId; actionFinished(false); } } - public void GetVolumeOfAllObjects() { + public void GetVolumeOfAllObjects() + { List objectIds = new List(); List volumes = new List(); - foreach (SimObjPhysics so in GameObject.FindObjectsOfType()) { + foreach (SimObjPhysics so in GameObject.FindObjectsOfType()) + { Quaternion oldRotation = so.transform.rotation; so.transform.rotation = Quaternion.identity; Bounds objBounds = UtilityFunctions.CreateEmptyBounds(); bool hasActiveRenderer = false; - foreach (Renderer r in so.GetComponentsInChildren()) { - if (r.enabled) { + foreach (Renderer r in so.GetComponentsInChildren()) + { + if (r.enabled) + { hasActiveRenderer = true; objBounds.Encapsulate(r.bounds); } } - if (!hasActiveRenderer) { + if (!hasActiveRenderer) + { continue; } so.transform.rotation = oldRotation; @@ -7843,15 +9176,19 @@ protected void changeObjectBlendMode( SimObjPhysics so, StandardShaderUtils.BlendMode bm, float alpha - ) { + ) + { HashSet renderersToSkip = new HashSet(); - foreach (SimObjPhysics childSo in so.GetComponentsInChildren()) { + foreach (SimObjPhysics childSo in so.GetComponentsInChildren()) + { if ( !childSo.ObjectID.StartsWith("Drawer") && !childSo.ObjectID.Split('|')[0].EndsWith("Door") && so.ObjectID != childSo.ObjectID - ) { - foreach (MeshRenderer mr in childSo.GetComponentsInChildren()) { + ) + { + foreach (MeshRenderer mr in childSo.GetComponentsInChildren()) + { renderersToSkip.Add(mr); } } @@ -7860,10 +9197,13 @@ float alpha foreach ( MeshRenderer r in so.gameObject.GetComponentsInChildren() as MeshRenderer[] - ) { - if (!renderersToSkip.Contains(r)) { + ) + { + if (!renderersToSkip.Contains(r)) + { Material[] newMaterials = new Material[r.materials.Length]; - for (int i = 0; i < newMaterials.Length; i++) { + for (int i = 0; i < newMaterials.Length; i++) + { newMaterials[i] = new Material(r.materials[i]); StandardShaderUtils.ChangeRenderMode(newMaterials[i], bm); Color color = newMaterials[i].color; @@ -7875,60 +9215,77 @@ as MeshRenderer[] } } - public void MakeObjectTransparent(string objectId) { - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void MakeObjectTransparent(string objectId) + { + if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { changeObjectBlendMode( physicsSceneManager.ObjectIdToSimObjPhysics[objectId], StandardShaderUtils.BlendMode.Fade, 0.4f ); actionFinished(true); - } else { + } + else + { errorMessage = "Invalid objectId " + objectId; actionFinished(false); } } - public void MakeObjectOpaque(string objectId) { - if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + public void MakeObjectOpaque(string objectId) + { + if (physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { changeObjectBlendMode( physicsSceneManager.ObjectIdToSimObjPhysics[objectId], StandardShaderUtils.BlendMode.Opaque, 1.0f ); actionFinished(true); - } else { + } + else + { errorMessage = "Invalid objectId " + objectId; actionFinished(false); } } - public void UnmaskWalkable() { + public void UnmaskWalkable() + { GameObject walkableParent = GameObject.Find("WalkablePlanes"); - if (walkableParent != null) { - foreach (GameObject go in GameObject.FindObjectsOfType()) { + if (walkableParent != null) + { + foreach (GameObject go in GameObject.FindObjectsOfType()) + { unmaskGameObject(go); } - foreach (Renderer r in walkableParent.GetComponentsInChildren()) { + foreach (Renderer r in walkableParent.GetComponentsInChildren()) + { r.enabled = false; } } actionFinished(true); } - public void MaskWalkable() { + public void MaskWalkable() + { Material backgroundMaterial = new Material(Shader.Find("Unlit/Color")); backgroundMaterial.color = Color.green; - foreach (GameObject go in GameObject.FindObjectsOfType()) { - if (!ancestorHasName(go, "WalkablePlanes")) { + foreach (GameObject go in GameObject.FindObjectsOfType()) + { + if (!ancestorHasName(go, "WalkablePlanes")) + { maskGameObject(go, backgroundMaterial); } } GameObject walkableParent = GameObject.Find("WalkablePlanes"); - if (walkableParent != null) { - foreach (Renderer r in walkableParent.GetComponentsInChildren()) { + if (walkableParent != null) + { + foreach (Renderer r in walkableParent.GetComponentsInChildren()) + { r.enabled = true; } actionFinished(true); @@ -7939,7 +9296,8 @@ public void MaskWalkable() { walkableParent = new GameObject(); walkableParent.name = "WalkablePlanes"; GameObject topLevelObject = GameObject.Find("Objects"); - if (topLevelObject != null) { + if (topLevelObject != null) + { walkableParent.transform.parent = topLevelObject.transform; } @@ -7950,28 +9308,36 @@ public void MaskWalkable() { "Procedural3", "Procedural0" ); - foreach (Vector3 p in reachablePositions) { + 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++) { + 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 ); - if (Physics.Raycast(p + offset, -transform.up, out hit, 10f, layerMask)) { - if (!somethingHit) { + if (Physics.Raycast(p + offset, -transform.up, out hit, 10f, layerMask)) + { + if (!somethingHit) + { y = hit.point.y; - } else { + } + else + { y = Math.Max(y, hit.point.y); } somethingHit = true; } } } - if (somethingHit) { + if (somethingHit) + { y += 0.01f; y = Math.Max(y, 0.05f); GameObject plane = @@ -7996,21 +9362,27 @@ private IEnumerator CoverSurfacesWithHelper( int n, List newObjects, Vector3[] reachablePositions - ) { + ) + { Vector3[] initialPositions = new Vector3[newObjects.Count]; int k = 0; bool[] deleted = new bool[newObjects.Count]; - foreach (SimObjPhysics so in newObjects) { + foreach (SimObjPhysics so in newObjects) + { initialPositions[k] = so.transform.position; deleted[k] = false; k++; } - for (int i = 0; i < n; i++) { + for (int i = 0; i < n; i++) + { k = 0; - foreach (SimObjPhysics so in newObjects) { - if (!deleted[k]) { + foreach (SimObjPhysics so in newObjects) + { + if (!deleted[k]) + { float dist = Vector3.Distance(initialPositions[k], so.transform.position); - if (dist > 0.5f) { + if (dist > 0.5f) + { deleted[k] = true; so.gameObject.SetActive(false); } @@ -8021,9 +9393,12 @@ Vector3[] reachablePositions } HashSet objectIdsContained = new HashSet(); - foreach (SimObjPhysics so in physicsSceneManager.ObjectIdToSimObjPhysics.Values) { - if (objectIsOfIntoType(so)) { - foreach (string id in so.GetAllSimObjectsInReceptacleTriggersByObjectID()) { + foreach (SimObjPhysics so in physicsSceneManager.ObjectIdToSimObjPhysics.Values) + { + if (objectIsOfIntoType(so)) + { + foreach (string id in so.GetAllSimObjectsInReceptacleTriggersByObjectID()) + { objectIdsContained.Add(id); } } @@ -8035,17 +9410,24 @@ Vector3[] reachablePositions .Find("FPSController") .GetComponentsInChildren(); k = 0; - foreach (SimObjPhysics so in newObjects) { - if (!deleted[k]) { + foreach (SimObjPhysics so in newObjects) + { + if (!deleted[k]) + { so.GetComponentInChildren().isKinematic = true; - foreach (Collider c1 in so.GetComponentsInChildren()) { - foreach (Collider c in fpsControllerColliders) { + foreach (Collider c1 in so.GetComponentsInChildren()) + { + foreach (Collider c in fpsControllerColliders) + { Physics.IgnoreCollision(c, c1); } } - if (objectIdsContained.Contains(so.ObjectID)) { + if (objectIdsContained.Contains(so.ObjectID)) + { MaskSimObj(so, greenMaterial); - } else { + } + else + { MaskSimObj(so, redMaterial); } physicsSceneManager.AddToObjectsInScene(so); @@ -8056,8 +9438,10 @@ Vector3[] reachablePositions HashSet visibleObjects = getAllItemsVisibleFromPositions( reachablePositions ); - foreach (SimObjPhysics so in newObjects) { - if (so.gameObject.activeSelf && !visibleObjects.Contains(so)) { + foreach (SimObjPhysics so in newObjects) + { + if (so.gameObject.activeSelf && !visibleObjects.Contains(so)) + { so.gameObject.SetActive(false); physicsSceneManager.ObjectIdToSimObjPhysics.Remove(so.ObjectID); } @@ -8066,7 +9450,8 @@ Vector3[] reachablePositions actionFinished(true); } - private void createCubeSurrounding(Bounds bounds) { + private void createCubeSurrounding(Bounds bounds) + { Vector3 center = bounds.center; Vector3 max = bounds.max; Vector3 min = bounds.min; @@ -8160,11 +9545,13 @@ private List RaycastWithRepeatHits( Vector3 direction, float maxDistance, int layerMask - ) { + ) + { List hits = new List(); RaycastHit hit; bool didHit = Physics.Raycast(origin, direction, out hit, maxDistance, layerMask); - while (didHit) { + while (didHit) + { hits.Add(hit); origin = hit.point + direction / 100f; hit = new RaycastHit(); @@ -8173,47 +9560,60 @@ int layerMask return hits; } - public void setAllObjectsToMaterial(Material material) { + public void setAllObjectsToMaterial(Material material) + { GameObject go = GameObject.Find("Lighting"); - if (go != null) { + if (go != null) + { go.SetActive(false); } - foreach (Renderer r in GameObject.FindObjectsOfType()) { + foreach (Renderer r in GameObject.FindObjectsOfType()) + { bool disableRenderer = false; - foreach (Material m in r.materials) { - if (m.name.Contains("LightRay")) { + foreach (Material m in r.materials) + { + if (m.name.Contains("LightRay")) + { disableRenderer = true; break; } } - if (disableRenderer) { + if (disableRenderer) + { r.enabled = false; - } else { + } + else + { Material[] newMaterials = new Material[r.materials.Length]; - for (int i = 0; i < newMaterials.Length; i++) { + for (int i = 0; i < newMaterials.Length; i++) + { newMaterials[i] = material; } r.materials = newMaterials; } } - foreach (Light l in GameObject.FindObjectsOfType()) { + foreach (Light l in GameObject.FindObjectsOfType()) + { l.enabled = false; } RenderSettings.ambientMode = AmbientMode.Flat; RenderSettings.ambientLight = Color.white; } - public void SetAllObjectsToBlueUnlit() { + public void SetAllObjectsToBlueUnlit() + { setAllObjectsToMaterial((Material)Resources.Load("BLUE", typeof(Material))); actionFinished(true); } - public void SetAllObjectsToBlueStandard() { + public void SetAllObjectsToBlueStandard() + { setAllObjectsToMaterial((Material)Resources.Load("BLUE_standard", typeof(Material))); actionFinished(true); } - public void EnableFog(float z) { + public void EnableFog(float z) + { GlobalFog gf = m_Camera.GetComponent(); gf.enabled = true; gf.heightFog = false; @@ -8226,19 +9626,24 @@ public void EnableFog(float z) { actionFinished(true); } - public void DisableFog() { + public void DisableFog() + { m_Camera.GetComponent().enabled = false; RenderSettings.fog = false; actionFinished(true); } - public void ColorSurfaceColorObjectsByDistance(float z) { + public void ColorSurfaceColorObjectsByDistance(float z) + { GameObject surfaceCoverObjects = GameObject.Find("SurfaceCoverObjects"); HashSet objectIdsContained = new HashSet(); - foreach (SimObjPhysics so in physicsSceneManager.ObjectIdToSimObjPhysics.Values) { - if (objectIsOfIntoType(so)) { - foreach (string id in so.GetAllSimObjectsInReceptacleTriggersByObjectID()) { + foreach (SimObjPhysics so in physicsSceneManager.ObjectIdToSimObjPhysics.Values) + { + if (objectIsOfIntoType(so)) + { + foreach (string id in so.GetAllSimObjectsInReceptacleTriggersByObjectID()) + { objectIdsContained.Add(id); } } @@ -8246,14 +9651,18 @@ public void ColorSurfaceColorObjectsByDistance(float z) { foreach ( SimObjPhysics sop in surfaceCoverObjects.GetComponentsInChildren() - ) { + ) + { Material newMaterial; float minRed = 0.0f; float minGreen = 0.0f; newMaterial = new Material(Shader.Find("Unlit/Color")); - if (objectIdsContained.Contains(sop.ObjectID)) { + if (objectIdsContained.Contains(sop.ObjectID)) + { minGreen = 1.0f; - } else { + } + else + { minRed = 1.0f; } @@ -8274,7 +9683,8 @@ SimObjPhysics sop in surfaceCoverObjects.GetComponentsInChildren( actionFinished(true); } - public void CoverSurfacesWith(ServerAction action) { + public void CoverSurfacesWith(ServerAction action) + { string prefab = action.objectType; int objectVariation = action.objectVariation; Vector3[] reachablePositions = getReachablePositions(); @@ -8310,7 +9720,8 @@ public void CoverSurfacesWith(ServerAction action) { ); Bounds objBounds = UtilityFunctions.CreateEmptyBounds(); - foreach (Renderer r in objForBounds.GetComponentsInChildren()) { + foreach (Renderer r in objForBounds.GetComponentsInChildren()) + { objBounds.Encapsulate(r.bounds); } Vector3 objCenterRelPos = objBounds.center - objForBounds.transform.position; @@ -8336,16 +9747,20 @@ public void CoverSurfacesWith(ServerAction action) { var zsToTry = new List(); // xsToTry.Add(-0.1253266f); // zsToTry.Add(1.159979f); - foreach (GameObject go in Resources.FindObjectsOfTypeAll()) { - if (go.name == "ReceptacleTriggerBox") { + foreach (GameObject go in Resources.FindObjectsOfTypeAll()) + { + if (go.name == "ReceptacleTriggerBox") + { Vector3 receptCenter = go.transform.position; xsToTry.Add(receptCenter.x); zsToTry.Add(receptCenter.z); } } - for (int i = 0; i < numXSteps; i++) { + for (int i = 0; i < numXSteps; i++) + { float x = b.min.x + (0.5f + i) * xStepSize; - for (int j = 0; j < numZSteps; j++) { + for (int j = 0; j < numZSteps; j++) + { float z = b.min.z + (0.5f + j) * zStepSize; xsToTry.Add(x); zsToTry.Add(z); @@ -8361,7 +9776,8 @@ public void CoverSurfacesWith(ServerAction action) { "Procedural3", "Procedural0" ); - for (int i = 0; i < xsToTryArray.Length; i++) { + for (int i = 0; i < xsToTryArray.Length; i++) + { float xPos = xsToTryArray[i]; float zPos = zsToTryArray[i]; @@ -8372,7 +9788,8 @@ public void CoverSurfacesWith(ServerAction action) { layerMask ); int k = -1; - foreach (RaycastHit hit in hits) { + foreach (RaycastHit hit in hits) + { if ( b.Contains(hit.point) && hit.point.y < transform.position.y + 1.2f @@ -8383,10 +9800,12 @@ public void CoverSurfacesWith(ServerAction action) { layerMask, hit.collider.transform.gameObject ) - ) { + ) + { SimObjPhysics hitSimObj = hit.transform.gameObject.GetComponent(); - if (hitSimObj == null || hitSimObj.ObjectID.Split('|')[0] != prefab) { + if (hitSimObj == null || hitSimObj.ObjectID.Split('|')[0] != prefab) + { Vector3 halfExtents = new Vector3( xExtent / 2.1f, yExtent / 2.1f, @@ -8399,7 +9818,8 @@ public void CoverSurfacesWith(ServerAction action) { Quaternion.identity, layerMask ); - if (colliders.Length == 0) { + if (colliders.Length == 0) + { k++; SimObjPhysics newObj = script.SpawnObject( prefab, @@ -8410,10 +9830,12 @@ public void CoverSurfacesWith(ServerAction action) { false, true ); - if (prefab == "Cup") { + if (prefab == "Cup") + { foreach ( Collider c in newObj.GetComponentsInChildren() - ) { + ) + { c.enabled = false; } newObj @@ -8429,7 +9851,8 @@ Collider c in newObj.GetComponentsInChildren() GameObject topLevelObject = GameObject.Find("Objects"); GameObject newTopLevelObject = new GameObject("SurfaceCoverObjects"); newTopLevelObject.transform.parent = topLevelObject.transform; - foreach (SimObjPhysics sop in newObjects) { + foreach (SimObjPhysics sop in newObjects) + { sop.gameObject.transform.parent = newTopLevelObject.transform; } StartCoroutine(CoverSurfacesWithHelper(100, newObjects, reachablePositions)); @@ -8438,32 +9861,40 @@ Collider c in newObj.GetComponentsInChildren() public void NumberOfPositionsObjectsOfTypeAreVisibleFrom( string objectType, Vector3[] positions - ) { + ) + { #if UNITY_EDITOR - if (positions == null || positions.Length == 0) { + if (positions == null || positions.Length == 0) + { List toReEnable = new List(); - foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) { - if (sop.Type.ToString().ToLower() == objectType.ToLower()) { + foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) + { + if (sop.Type.ToString().ToLower() == objectType.ToLower()) + { toReEnable.Add(sop); sop.gameObject.SetActive(false); } } - foreach (SimObjPhysics sop in toReEnable) { + foreach (SimObjPhysics sop in toReEnable) + { sop.gameObject.SetActive(true); } } #endif List objectsOfType = new List(); - foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) { - if (sop.Type.ToString().ToLower() == objectType.ToLower()) { + foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) + { + if (sop.Type.ToString().ToLower() == objectType.ToLower()) + { objectsOfType.Add(sop); sop.gameObject.SetActive(false); } } Dictionary objectIdToPositionsVisibleFrom = new Dictionary(); - foreach (SimObjPhysics sop in objectsOfType) { + foreach (SimObjPhysics sop in objectsOfType) + { sop.gameObject.SetActive(true); objectIdToPositionsVisibleFrom.Add( sop.ObjectID, @@ -8481,25 +9912,31 @@ Vector3[] positions sop.gameObject.SetActive(false); } - foreach (SimObjPhysics sop in objectsOfType) { + foreach (SimObjPhysics sop in objectsOfType) + { sop.gameObject.SetActive(true); } actionFinished(true, objectIdToPositionsVisibleFrom); } - private IEnumerator SpamObjectsInRoomHelper(int n, List newObjects) { - for (int i = 0; i < n; i++) { + private IEnumerator SpamObjectsInRoomHelper(int n, List newObjects) + { + for (int i = 0; i < n; i++) + { yield return null; } Collider[] fpsControllerColliders = GameObject .Find("FPSController") .GetComponentsInChildren(); - foreach (SimObjPhysics so in newObjects) { + foreach (SimObjPhysics so in newObjects) + { so.GetComponentInChildren().isKinematic = true; - foreach (Collider c1 in so.GetComponentsInChildren()) { - foreach (Collider c in fpsControllerColliders) { + foreach (Collider c1 in so.GetComponentsInChildren()) + { + foreach (Collider c in fpsControllerColliders) + { Physics.IgnoreCollision(c, c1); } } @@ -8509,7 +9946,8 @@ private IEnumerator SpamObjectsInRoomHelper(int n, List newObject actionFinished(true); } - public void SpamObjectsInRoom(int randomSeed = 0) { + public void SpamObjectsInRoom(int randomSeed = 0) + { UnityEngine.Random.InitState(randomSeed); string[] objectTypes = { "Bread", "Cup", "Footstool", "Knife", "Plunger", "Tomato", }; @@ -8537,8 +9975,10 @@ public void SpamObjectsInRoom(int randomSeed = 0) { List objsCenterRelPos = new List(); List yOffsets = new List(); float offset = 10f; - foreach (string objType in objectTypes) { - for (int i = 1; i < numObjectVariations; i++) { + foreach (string objType in objectTypes) + { + for (int i = 1; i < numObjectVariations; i++) + { SimObjPhysics objForBounds = script.SpawnObject( objType, false, @@ -8551,7 +9991,8 @@ public void SpamObjectsInRoom(int randomSeed = 0) { offset += 1.0f; Bounds objBounds = UtilityFunctions.CreateEmptyBounds(); - foreach (Renderer r in objForBounds.GetComponentsInChildren()) { + foreach (Renderer r in objForBounds.GetComponentsInChildren()) + { objBounds.Encapsulate(r.bounds); } @@ -8570,19 +10011,23 @@ public void SpamObjectsInRoom(int randomSeed = 0) { var xsToTry = new List(); var zsToTry = new List(); - foreach (GameObject go in Resources.FindObjectsOfTypeAll()) { - if (go.name == "ReceptacleTriggerBox") { + foreach (GameObject go in Resources.FindObjectsOfTypeAll()) + { + if (go.name == "ReceptacleTriggerBox") + { BoxCollider bc = go.GetComponent(); Bounds bcb = bc.bounds; xsToTry.Add(bcb.center.x); zsToTry.Add(bcb.center.z); - for (int i = 0; i < 5; i++) { + for (int i = 0; i < 5; i++) + { xsToTry.Add((bcb.max.x - bcb.min.x) * UnityEngine.Random.value + bcb.min.x); zsToTry.Add((bcb.max.z - bcb.min.z) * UnityEngine.Random.value + bcb.min.z); } } } - for (int i = 0; i < 1000; i++) { + for (int i = 0; i < 1000; i++) + { xsToTry.Add((b.max.x - b.min.x) * UnityEngine.Random.value + b.min.x); zsToTry.Add((b.max.z - b.min.z) * UnityEngine.Random.value + b.min.z); } @@ -8598,8 +10043,10 @@ public void SpamObjectsInRoom(int randomSeed = 0) { "Procedural0" ); // int attempts = 0; - for (int i = 0; i < xsToTryArray.Length; i++) { - if (newObjects.Count >= 100) { + for (int i = 0; i < xsToTryArray.Length; i++) + { + if (newObjects.Count >= 100) + { break; } float xPos = (b.max.x - b.min.x) * UnityEngine.Random.value + b.min.x; @@ -8615,10 +10062,12 @@ public void SpamObjectsInRoom(int randomSeed = 0) { layerMask ); - foreach (RaycastHit hit in hits) { + foreach (RaycastHit hit in hits) + { Bounds ob = objsBounds[objectInd]; Vector3 randRotation = new Vector3(0.0f, 0.0f, 0.0f); - if (UnityEngine.Random.value < 0.5f) { + if (UnityEngine.Random.value < 0.5f) + { randRotation = new Vector3( UnityEngine.Random.value * 360f, UnityEngine.Random.value * 360f, @@ -8640,7 +10089,8 @@ public void SpamObjectsInRoom(int randomSeed = 0) { false, false ); - if (newObj == null) { + if (newObj == null) + { newObj = script.SpawnObject( objectTypes[objectInd], false, @@ -8660,11 +10110,14 @@ public void SpamObjectsInRoom(int randomSeed = 0) { false ); } - if (newObj != null) { + if (newObj != null) + { newObjects.Add(newObj); } - if (newObj != null && objectTypes[objectInd] == "Cup") { - foreach (Collider c in newObj.GetComponentsInChildren()) { + if (newObj != null && objectTypes[objectInd] == "Cup") + { + foreach (Collider c in newObj.GetComponentsInChildren()) + { c.enabled = false; } newObj @@ -8677,8 +10130,10 @@ public void SpamObjectsInRoom(int randomSeed = 0) { StartCoroutine(SpamObjectsInRoomHelper(100, newObjects)); } - public void ChangeLightSet(ServerAction action) { - if (action.objectVariation > 10 || action.objectVariation < 1) { + public void ChangeLightSet(ServerAction action) + { + if (action.objectVariation > 10 || action.objectVariation < 1) + { errorMessage = "Please use value between 1 and 10"; actionFinished(false); return; @@ -8689,19 +10144,24 @@ public void ChangeLightSet(ServerAction action) { actionFinished(true); } - public void SliceObject(ServerAction action) { - if (action.forceAction) { + public void SliceObject(ServerAction action) + { + if (action.forceAction) + { action.forceVisible = true; } SimObjPhysics target = null; - if (action.objectId == null) { + if (action.objectId == null) + { target = getInteractableSimObjectFromXY( x: action.x, y: action.y, forceAction: action.forceAction ); - } else { + } + else + { target = getInteractableSimObjectFromId( objectId: action.objectId, forceAction: action.forceAction @@ -8709,9 +10169,12 @@ public void SliceObject(ServerAction action) { } // we found it! - if (target) { - if (ItemInHand != null) { - if (target.transform == ItemInHand.transform) { + if (target) + { + if (ItemInHand != null) + { + if (target.transform == ItemInHand.transform) + { errorMessage = "target object cannot be sliced if it is in the agent's hand"; actionFinished(false); @@ -8725,11 +10188,14 @@ public void SliceObject(ServerAction action) { .DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.CanBeSliced ) - ) { + ) + { target.GetComponent().Slice(); actionFinished(true); return; - } else { + } + else + { errorMessage = target.transform.name + " Does not have the CanBeSliced property!"; actionFinished(false); @@ -8737,25 +10203,31 @@ public void SliceObject(ServerAction action) { } } // target not found in currently visible objects, report not found - else { + else + { errorMessage = "object not found: " + action.objectId; actionFinished(false); } } - public void BreakObject(ServerAction action) { - if (action.forceAction) { + public void BreakObject(ServerAction action) + { + if (action.forceAction) + { action.forceVisible = true; } SimObjPhysics target = null; - if (action.objectId == null) { + if (action.objectId == null) + { target = getInteractableSimObjectFromXY( x: action.x, y: action.y, forceAction: action.forceAction ); - } else { + } + else + { target = getInteractableSimObjectFromId( objectId: action.objectId, forceAction: action.forceAction @@ -8763,21 +10235,25 @@ public void BreakObject(ServerAction action) { } // we found it! - if (target) { + if (target) + { 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 (targetsop.isInAgentHand) + { // if the target is also a Receptacle, drop contained objects first if ( targetsop.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.Receptacle ) - ) { + ) + { // drop contained objects as well targetsop.DropContainedObjects( reparentContainedObjects: true, @@ -8794,14 +10270,17 @@ public void BreakObject(ServerAction action) { target.GetComponentInChildren().BreakObject(null); actionFinished(true); return; - } else { + } + else + { errorMessage = target.transform.name + " does not have the CanBreak property!!"; actionFinished(false); return; } } // target not found in currently visible objects, report not found - else { + else + { errorMessage = "object not found: " + action.objectId; actionFinished(false); } @@ -8813,17 +10292,20 @@ public void SpawnDirt( bool forceAction = true, int randomSeed = 0, DirtSpawnPosition[] spawnPositions = null - ) { + ) + { SimObjPhysics target = getInteractableSimObjectFromId( objectId: objectId, forceAction: forceAction ); - if (target == null) { + if (target == null) + { throw new ArgumentNullException(); } - if (target) { + if (target) + { target.SpawnDirtOnReceptacle(howManyDirt, randomSeed, spawnPositions); } @@ -8831,141 +10313,179 @@ public void SpawnDirt( } //currently only to be used with the Cleaning Table prefab - public void GetDirtCoordinateBounds(string objectId) { + public void GetDirtCoordinateBounds(string objectId) + { DirtCoordinateBounds toReturn = null; SimObjPhysics target = getInteractableSimObjectFromId(objectId: objectId, true); - if (target == null) { + if (target == null) + { throw new ArgumentNullException(); } - if (target) { + if (target) + { toReturn = target.GetDirtCoordinateBounds(); } actionFinished(true, toReturn); } - public void DirtyObject(ServerAction action) { - if (action.forceAction) { + public void DirtyObject(ServerAction action) + { + if (action.forceAction) + { action.forceVisible = true; } SimObjPhysics target = null; - if (action.objectId == null) { + if (action.objectId == null) + { target = getInteractableSimObjectFromXY( x: action.x, y: action.y, forceAction: action.forceAction ); - } else { + } + else + { target = getInteractableSimObjectFromId( objectId: action.objectId, forceAction: action.forceAction ); } - if (target) { + if (target) + { if ( target .GetComponent() .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeDirty) - ) { + ) + { Dirty dirt = target.GetComponent(); - if (dirt.IsDirty() == false) { + if (dirt.IsDirty() == false) + { dirt.ToggleCleanOrDirty(); actionFinished(true); return; - } else { + } + else + { errorMessage = target.transform.name + " is already dirty!"; actionFinished(false); return; } - } else { + } + else + { errorMessage = target.transform.name + " does not have CanBeDirty property!"; actionFinished(false); return; } - } else { + } + else + { errorMessage = "object not found: " + action.objectId; actionFinished(false); } } - public void CleanObject(ServerAction action) { - if (action.forceAction) { + public void CleanObject(ServerAction action) + { + if (action.forceAction) + { action.forceVisible = true; } SimObjPhysics target = null; - if (action.objectId == null) { + if (action.objectId == null) + { target = getInteractableSimObjectFromXY( x: action.x, y: action.y, forceAction: action.forceAction ); - } else { + } + else + { target = getInteractableSimObjectFromId( objectId: action.objectId, forceAction: action.forceAction ); } - if (target) { + if (target) + { if ( target .GetComponent() .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeDirty) - ) { + ) + { Dirty dirt = target.GetComponent(); - if (dirt.IsDirty()) { + if (dirt.IsDirty()) + { dirt.ToggleCleanOrDirty(); actionFinished(true); return; - } else { + } + else + { errorMessage = target.transform.name + " is already Clean!"; actionFinished(false); return; } - } else { + } + else + { errorMessage = target.transform.name + " does not have dirtyable property!"; actionFinished(false); return; } - } else { + } + else + { errorMessage = "object not found: " + action.objectId; actionFinished(false); } } // fill an object with a liquid specified by action.fillLiquid - coffee, water, soap, wine, etc - public void FillObjectWithLiquid(ServerAction action) { - if (action.forceAction) { + public void FillObjectWithLiquid(ServerAction action) + { + if (action.forceAction) + { action.forceVisible = true; } SimObjPhysics target = null; - if (action.objectId == null) { + if (action.objectId == null) + { target = getInteractableSimObjectFromXY( x: action.x, y: action.y, forceAction: action.forceAction ); - } else { + } + else + { target = getInteractableSimObjectFromId( objectId: action.objectId, forceAction: action.forceAction ); } - if (action.fillLiquid == null) { + if (action.fillLiquid == null) + { throw new InvalidOperationException("Missing Liquid string for FillObject action"); } // ignore casing action.fillLiquid = action.fillLiquid.ToLower(); - if (!target) { + if (!target) + { throw new ArgumentException("object not found: " + action.objectId); } @@ -8973,7 +10493,8 @@ public void FillObjectWithLiquid(ServerAction action) { !target .GetComponent() .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeFilled) - ) { + ) + { throw new ArgumentException( target.transform.name + " does not have CanBeFilled property!" ); @@ -8982,11 +10503,13 @@ public void FillObjectWithLiquid(ServerAction action) { Fill fil = target.GetComponent(); // if the passed in liquid string is not valid - if (!fil.Liquids.ContainsKey(action.fillLiquid)) { + if (!fil.Liquids.ContainsKey(action.fillLiquid)) + { throw new ArgumentException(action.fillLiquid + " is not a valid Liquid Type"); } - if (fil.IsFilled()) { + if (fil.IsFilled()) + { throw new InvalidOperationException(target.transform.name + " is already Filled!"); } @@ -8994,111 +10517,141 @@ public void FillObjectWithLiquid(ServerAction action) { actionFinished(true); } - public void EmptyLiquidFromObject(ServerAction action) { - if (action.forceAction) { + public void EmptyLiquidFromObject(ServerAction action) + { + if (action.forceAction) + { action.forceVisible = true; } SimObjPhysics target = null; - if (action.objectId == null) { + if (action.objectId == null) + { target = getInteractableSimObjectFromXY( x: action.x, y: action.y, forceAction: action.forceAction ); - } else { + } + else + { target = getInteractableSimObjectFromId( objectId: action.objectId, forceAction: action.forceAction ); } - if (target) { + if (target) + { if ( target .GetComponent() .DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.CanBeFilled ) - ) { + ) + { Fill fil = target.GetComponent(); - if (fil.IsFilled()) { + if (fil.IsFilled()) + { fil.EmptyObject(); actionFinished(true); return; - } else { + } + else + { errorMessage = "object already empty"; actionFinished(false); return; } - } else { + } + else + { errorMessage = target.transform.name + " does not have CanBeFilled property!"; actionFinished(false); return; } - } else { + } + else + { errorMessage = "object not found: " + action.objectId; actionFinished(false); } } // use up the contents of this object (toilet paper, paper towel, tissue box, etc). - public void UseUpObject(ServerAction action) { - if (action.forceAction) { + public void UseUpObject(ServerAction action) + { + if (action.forceAction) + { action.forceVisible = true; } SimObjPhysics target = null; - if (action.objectId == null) { + if (action.objectId == null) + { target = getInteractableSimObjectFromXY( x: action.x, y: action.y, forceAction: action.forceAction ); - } else { + } + else + { target = getInteractableSimObjectFromId( objectId: action.objectId, forceAction: action.forceAction ); } - if (target) { + if (target) + { if ( target .GetComponent() .DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.CanBeUsedUp ) - ) { + ) + { UsedUp u = target.GetComponent(); // make sure object is not already used up - if (!u.isUsedUp) { + if (!u.isUsedUp) + { u.UseUp(); actionFinished(true); return; - } else { + } + else + { errorMessage = "object already used up!"; // Debug.Log(errorMessage); actionFinished(false); return; } - } else { + } + else + { errorMessage = target.transform.name + " does not have CanBeUsedUp property!"; actionFinished(false); return; } - } else { + } + else + { errorMessage = "object not found: " + action.objectId; actionFinished(false); } } - public void GetScenesInBuild() { + public void GetScenesInBuild() + { int sceneCount = UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; string[] scenes = new string[sceneCount]; - for (int i = 0; i < sceneCount; i++) { + for (int i = 0; i < sceneCount; i++) + { scenes[i] = System.IO.Path.GetFileNameWithoutExtension( UnityEngine.SceneManagement.SceneUtility.GetScenePathByBuildIndex(i) ); @@ -9106,7 +10659,8 @@ public void GetScenesInBuild() { actionFinished(true, scenes); } - protected bool objectIsOfIntoType(SimObjPhysics so) { + protected bool objectIsOfIntoType(SimObjPhysics so) + { return so.ReceptacleTriggerBoxes != null && so.ReceptacleTriggerBoxes.Length != 0 && !so.ObjectID.Contains("Table") @@ -9120,10 +10674,13 @@ protected bool objectIsOfIntoType(SimObjPhysics so) { && !so.ObjectID.Contains("Ottoman"); } - public void ToggleColorIntoTypeReceptacleFloors() { + public void ToggleColorIntoTypeReceptacleFloors() + { GameObject go = GameObject.Find("IntoObjectFloorPlanes"); - if (go != null) { - foreach (Renderer r in go.GetComponentsInChildren()) { + if (go != null) + { + foreach (Renderer r in go.GetComponentsInChildren()) + { r.enabled = !r.enabled; } actionFinished(true); @@ -9133,7 +10690,8 @@ public void ToggleColorIntoTypeReceptacleFloors() { GameObject newParent = new GameObject(); newParent.name = "IntoObjectFloorPlanes"; GameObject topLevelObject = GameObject.Find("Objects"); - if (topLevelObject != null) { + if (topLevelObject != null) + { newParent.transform.parent = topLevelObject.transform; } @@ -9144,9 +10702,12 @@ public void ToggleColorIntoTypeReceptacleFloors() { "Procedural3", "Procedural0" ); - foreach (SimObjPhysics so in physicsSceneManager.ObjectIdToSimObjPhysics.Values) { - if (objectIsOfIntoType(so)) { - foreach (GameObject rtb in so.ReceptacleTriggerBoxes) { + 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; @@ -9159,8 +10720,10 @@ public void ToggleColorIntoTypeReceptacleFloors() { HashSet yOffsets = new HashSet(); yOffsets.Add(b.extents.y - 0.01f); - for (int i = -1; i <= 1; i++) { - for (int j = -1; j <= 1; j++) { + for (int i = -1; i <= 1; i++) + { + for (int j = -1; j <= 1; j++) + { Vector3 start = b.center + new Vector3( @@ -9175,11 +10738,13 @@ RaycastHit hit in Physics.RaycastAll( 10f, layerMask ) - ) { + ) + { if ( NormalIsApproximatelyUp(hit.normal) && ancestorSimObjPhysics(hit.transform.gameObject) == so - ) { + ) + { yOffsets.Add( (float) Math.Round(hit.distance - b.extents.y - 0.005f, 3) @@ -9189,7 +10754,8 @@ RaycastHit hit in Physics.RaycastAll( } } - foreach (float yOffset in yOffsets) { + foreach (float yOffset in yOffsets) + { GameObject plane = Instantiate( Resources.Load("BluePlane") as GameObject, diff --git a/unity/Assets/Scripts/PhysicsSceneManager.cs b/unity/Assets/Scripts/PhysicsSceneManager.cs index 5f90056326..c736fd4916 100644 --- a/unity/Assets/Scripts/PhysicsSceneManager.cs +++ b/unity/Assets/Scripts/PhysicsSceneManager.cs @@ -10,7 +10,8 @@ using UnityStandardAssets.ImageEffects; [ExecuteInEditMode] -public class PhysicsSimulationParams { +public class PhysicsSimulationParams +{ public bool autoSimulation = false; public float fixedDeltaTime = 0.02f; public float minSimulateTimeSeconds = 0; @@ -19,14 +20,18 @@ public class PhysicsSimulationParams { // public int maxActionPhysicsSteps = int.MaxValue; - public override bool Equals(object p) { - if (p is null) { + public override bool Equals(object p) + { + 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; @@ -38,7 +43,8 @@ public override bool Equals(object p) { } } -public class PhysicsSceneManager : MonoBehaviour { +public class PhysicsSceneManager : MonoBehaviour +{ // public static PhysicsSceneManager Instance { get; private set; } public bool ProceduralMode = false; public List RequiredObjects = new List(); @@ -89,16 +95,19 @@ public class PhysicsSceneManager : MonoBehaviour { public static PhysicsSimulationParams physicsSimulationParams { get; private set; } - public static float fixedDeltaTime { + public static float fixedDeltaTime + { get { return physicsSimulationParams.fixedDeltaTime; } private set { return; } } - void Awake() { + void Awake() + { SetDefaultSimulationParams(new PhysicsSimulationParams()); } - private void OnEnable() { + private void OnEnable() + { // must do this here instead of Start() since OnEnable gets triggered prior to Start // when the component is enabled. agentManager = GameObject @@ -108,17 +117,20 @@ private void OnEnable() { // clear this on start so that the CheckForDuplicates function doesn't check pre-existing lists SetupScene(); - if (GameObject.Find("HideAndSeek")) { + if (GameObject.Find("HideAndSeek")) + { HideAndSeek = GameObject.Find("HideAndSeek"); } - if (!GameObject.Find("Objects")) { + if (!GameObject.Find("Objects")) + { GameObject c = new GameObject("Objects"); Debug.Log(c.transform.name + " was missing and is now added"); } } - public void SetupScene(bool generateObjectIds = true) { + public void SetupScene(bool generateObjectIds = true) + { Debug.Log("------- Setup Scene called " + (generateObjectIds && !ProceduralMode)); ObjectIdToSimObjPhysics.Clear(); GatherSimObjPhysInScene(generateObjectIds && !ProceduralMode); @@ -126,24 +138,28 @@ public void SetupScene(bool generateObjectIds = true) { } // Use this for initialization - void Start() { + void Start() + { PhysicsSceneManager.PhysicsSimulateCallCount = 0; GatherAllRBsInScene(); } public static void SetDefaultSimulationParams( PhysicsSimulationParams defaultPhysicsSimulationParams - ) { + ) + { PhysicsSceneManager.defaultPhysicsSimulationParams = defaultPhysicsSimulationParams; // ?? new PhysicsSimulationParams(); PhysicsSceneManager.physicsSimulationParams = PhysicsSceneManager.defaultPhysicsSimulationParams; } - public static void SetPhysicsSimulationParams(PhysicsSimulationParams physicsSimulationParams) { + public static void SetPhysicsSimulationParams(PhysicsSimulationParams physicsSimulationParams) + { PhysicsSceneManager.physicsSimulationParams = physicsSimulationParams; } - public static void PhysicsSimulateTHOR(float deltaTime) { + public static void PhysicsSimulateTHOR(float deltaTime) + { Physics.Simulate(deltaTime); PhysicsSceneManager.PhysicsSimulateTimeSeconds += deltaTime; PhysicsSceneManager.PhysicsSimulateCallCount++; @@ -152,16 +168,20 @@ public static void PhysicsSimulateTHOR(float deltaTime) { public static ActionFinished ExpandIEnumerator( IEnumerator enumerator, PhysicsSimulationParams physicsSimulationParams - ) { + ) + { ActionFinished actionFinished = null; - while (enumerator.MoveNext()) { - if (enumerator.Current == null) { + while (enumerator.MoveNext()) + { + if (enumerator.Current == null) + { continue; } // ActionFinished was found but enumerator keeps moving forward, throw error - if (actionFinished != null) { + if (actionFinished != null) + { // Premature ActionFinished, same as yield break, stops iterator evaluation break; } @@ -169,22 +189,28 @@ PhysicsSimulationParams physicsSimulationParams if ( enumerator.Current.GetType() == typeof(WaitForFixedUpdate) && !physicsSimulationParams.autoSimulation - ) { + ) + { // TODO: is this still used? - if (physicsSimulationParams.fixedDeltaTime == 0f) { + if (physicsSimulationParams.fixedDeltaTime == 0f) + { Physics.SyncTransforms(); - } else { + } + else + { PhysicsSceneManager.PhysicsSimulateTHOR(physicsSimulationParams.fixedDeltaTime); } } // else if (enumerator.Current.GetType() == typeof) - else if (enumerator.Current.GetType() == typeof(ActionFinished)) { + else if (enumerator.Current.GetType() == typeof(ActionFinished)) + { actionFinished = (ActionFinished)(enumerator.Current as ActionFinished); } // For recursive ienumerators, unity StartCoroutine must do something for cases when (yield return (yield return value)) // 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())) { + else if (typeof(IEnumerator).IsAssignableFrom(enumerator.Current.GetType())) + { actionFinished = PhysicsSceneManager.ExpandIEnumerator( enumerator.Current as IEnumerator, physicsSimulationParams @@ -198,7 +224,8 @@ PhysicsSimulationParams physicsSimulationParams public static ActionFinished RunSimulatePhysicsForAction( IEnumerator enumerator, PhysicsSimulationParams physicsSimulationParams - ) { + ) + { var fixedDeltaTime = physicsSimulationParams.fixedDeltaTime; var previousAutoSimulate = Physics.autoSimulation; Physics.autoSimulation = physicsSimulationParams.autoSimulation; @@ -210,7 +237,8 @@ PhysicsSimulationParams physicsSimulationParams // Recursive expansion of IEnumerator ActionFinished actionFinished = ExpandIEnumerator(enumerator, physicsSimulationParams); - if (actionFinished == null) { + if (actionFinished == null) + { throw new MissingActionFinishedException(); } @@ -220,18 +248,21 @@ PhysicsSimulationParams physicsSimulationParams if ( !physicsSimulationParams.autoSimulation && physicsSimulationParams.minSimulateTimeSeconds > 0.0f - ) { + ) + { // Because of floating point precision const float eps = 1e-5f; while ( PhysicsSceneManager.PhysicsSimulateTimeSeconds <= (physicsSimulationParams.minSimulateTimeSeconds - eps) - ) { + ) + { PhysicsSceneManager.PhysicsSimulateTHOR(fixedDeltaTime); } } - if (physicsSimulationParams.syncTransformsAfterAction) { + if (physicsSimulationParams.syncTransformsAfterAction) + { Physics.SyncTransforms(); } @@ -243,21 +274,28 @@ public static IEnumerator RunActionForCoroutine( ActionInvokable target, IEnumerator action, PhysicsSimulationParams physicsSimulationParams - ) { + ) + { var fixedDeltaTime = physicsSimulationParams.fixedDeltaTime; var previousFixedDeltaTime = Time.fixedDeltaTime; Time.fixedDeltaTime = fixedDeltaTime; var startFixedTimeSeconds = Time.fixedTime; ActionFinished actionFinished = null; - while (true) { + while (true) + { // Adds Exception handling for Coroutines! - try { - if (!action.MoveNext()) { + try + { + 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 @@ -272,7 +310,8 @@ PhysicsSimulationParams physicsSimulationParams break; } - if (action.Current != null && typeof(ActionFinished) == action.Current.GetType()) { + if (action.Current != null && typeof(ActionFinished) == action.Current.GetType()) + { actionFinished = (ActionFinished)(action.Current as ActionFinished); break; } @@ -285,7 +324,8 @@ PhysicsSimulationParams physicsSimulationParams // throw new MissingActionFinishedException(); // } - actionFinished ??= new ActionFinished() { + actionFinished ??= new ActionFinished() + { success = false, errorMessage = "Action did not return an `ActionFinished`.", errorCode = ServerActionErrorCode.MissingActionFinished @@ -294,12 +334,14 @@ PhysicsSimulationParams physicsSimulationParams 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) { + if (physicsSimulationParams.syncTransformsAfterAction) + { Physics.SyncTransforms(); } @@ -311,31 +353,38 @@ PhysicsSimulationParams physicsSimulationParams // Returns previous parameters public static PhysicsSimulationParams applyPhysicsSimulationParams( PhysicsSimulationParams physicsSimulationParams - ) { - return new PhysicsSimulationParams() { + ) + { + return new PhysicsSimulationParams() + { autoSimulation = Physics.autoSimulation, fixedDeltaTime = Time.fixedDeltaTime }; } - private void GatherAllRBsInScene() { + private void GatherAllRBsInScene() + { // cache all rigidbodies that are in the scene by default // NOTE: any rigidbodies created from actions such as Slice/Break or spawned in should be added to this! rbsInScene = new HashSet(FindObjectsOfType()); } // disabling LateUpdate to experiment with determinism - void LateUpdate() { + void LateUpdate() + { // check what objects in the scene are currently in motion // Rigidbody[] rbs = FindObjectsOfType(typeof(Rigidbody)) as Rigidbody[]; - foreach (Rigidbody rb in rbsInScene) { - if (rb == null) { + foreach (Rigidbody rb in rbsInScene) + { + if (rb == null) + { return; } // if this rigidbody is part of a SimObject, calculate rest using lastVelocity/currentVelocity comparisons // make sure the object is actually active, otherwise skip the check - if (rb.GetComponentInParent() && rb.transform.gameObject.activeSelf) { + if (rb.GetComponentInParent() && rb.transform.gameObject.activeSelf) + { SimObjPhysics sop = rb.GetComponentInParent(); float currentVelocity = Math.Abs( @@ -343,11 +392,14 @@ void LateUpdate() { ); float accel = (currentVelocity - sop.lastVelocity) / Time.fixedDeltaTime; - if (Mathf.Abs(accel) <= 0.0001f) { + if (Mathf.Abs(accel) <= 0.0001f) + { sop.inMotion = false; // print(sop.transform.name + " should be sleeping"); // rb.Sleep(); maybe do something to ensure object has stopped moving, and reduce jitter - } else { + } + else + { // the rb's velocities are not 0, so it is in motion and the scene is not at rest rb.GetComponentInParent().inMotion = true; isSceneAtRest = false; @@ -356,13 +408,17 @@ void LateUpdate() { // #endif } // only apply drag if autosimulation is on - } else if (Physics.autoSimulation) { + } + else if (Physics.autoSimulation) + { // 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) { + 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 - ) { + ) + { isSceneAtRest = false; // make sure the rb's drag values are not at 0 exactly // if (rb.drag < 0.1f) @@ -375,14 +431,17 @@ void LateUpdate() { #if UNITY_EDITOR //print(rb.transform.name + " is still in motion!"); #endif - } else { + } + else + { // the velocities are small enough, assume object has come to rest and force this one to sleep rb.drag = 1.0f; rb.angularDrag = 1.0f; } // if the shard/broken piece gets out of bounds somehow and begins falling forever, get rid of it with this check - if (rb.transform.position.y < -50f) { + if (rb.transform.position.y < -50f) + { rb.transform.gameObject.SetActive(false); // note: we might want to remove these from the list of rbs at some point but for now it'll be fine } @@ -392,17 +451,22 @@ void LateUpdate() { } // used to add a reference to a rigidbody created after the scene was started - public void AddToRBSInScene(Rigidbody rb) { + public void AddToRBSInScene(Rigidbody rb) + { rbsInScene.Add(rb); } - public void RemoveFromRBSInScene(Rigidbody rb) { + public void RemoveFromRBSInScene(Rigidbody rb) + { rbsInScene.Remove(rb); } - public bool ToggleHideAndSeek(bool hide) { - if (HideAndSeek) { - if (HideAndSeek.activeSelf != hide) { + public bool ToggleHideAndSeek(bool hide) + { + if (HideAndSeek) + { + if (HideAndSeek.activeSelf != hide) + { HideAndSeek.SetActive(hide); SetupScene(); } @@ -415,23 +479,29 @@ public bool ToggleHideAndSeek(bool hide) { return false; } - public void ResetObjectIdToSimObjPhysics() { + public void ResetObjectIdToSimObjPhysics() + { ObjectIdToSimObjPhysics.Clear(); - foreach (SimObjPhysics so in GameObject.FindObjectsOfType()) { + foreach (SimObjPhysics so in GameObject.FindObjectsOfType()) + { ObjectIdToSimObjPhysics[so.ObjectID] = so; } } - public void MakeAllObjectsMoveable() { - foreach (SimObjPhysics sop in GameObject.FindObjectsOfType()) { + 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 this object is actively hung on its corresponding object specific receptacle... skip it so it doesn't fall on the floor - if (sop.GetComponentInParent()) { + if (sop.GetComponentInParent()) + { continue; } } @@ -439,7 +509,8 @@ public void MakeAllObjectsMoveable() { if ( sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup || sop.PrimaryProperty == SimObjPrimaryProperty.Moveable - ) { + ) + { Rigidbody rb = sop.GetComponent(); rb.isKinematic = false; rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; @@ -447,27 +518,33 @@ public void MakeAllObjectsMoveable() { } } - public void GatherSimObjPhysInScene(bool generateObjectIds = true) { + public void GatherSimObjPhysInScene(bool generateObjectIds = true) + { List allPhysObjects = new List(); allPhysObjects.AddRange(FindObjectsOfType()); allPhysObjects.Sort((x, y) => (x.Type.ToString().CompareTo(y.Type.ToString()))); - foreach (SimObjPhysics o in allPhysObjects) { - if (generateObjectIds) { + foreach (SimObjPhysics o in allPhysObjects) + { + if (generateObjectIds) + { Generate_ObjectID(o); } // debug in editor, make sure no two object share ids for some reason #if UNITY_EDITOR - if (CheckForDuplicateObjectIDs(o)) { + if (CheckForDuplicateObjectIDs(o)) + { Debug.Log( "Yo there are duplicate ObjectIDs! Check" + o.ObjectID + "in scene " + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name ); - } else { + } + else + { AddToObjectsInScene(o); continue; } @@ -476,24 +553,31 @@ public void GatherSimObjPhysInScene(bool generateObjectIds = true) { AddToObjectsInScene(o); } - foreach (var agent in this.agentManager.agents) { - if (agent.imageSynthesis != null) { + foreach (var agent in this.agentManager.agents) + { + if (agent.imageSynthesis != null) + { agent.imageSynthesis.OnSceneChange(); } } } - public List GatherAllReceptaclesInScene() { + public List GatherAllReceptaclesInScene() + { List ReceptaclesInScene = new List(); - foreach (SimObjPhysics sop in ObjectIdToSimObjPhysics.Values) { - if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { + foreach (SimObjPhysics sop in ObjectIdToSimObjPhysics.Values) + { + if (sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) + { ReceptaclesInScene.Add(sop); #if UNITY_EDITOR // debug if some of these receptacles were not set up correctly - foreach (GameObject go in sop.ReceptacleTriggerBoxes) { - if (go == null) { + foreach (GameObject go in sop.ReceptacleTriggerBoxes) + { + if (go == null) + { Debug.LogWarning( sop.gameObject + " has non-empty receptacle trigger boxes but contains a null value." @@ -504,14 +588,16 @@ public List GatherAllReceptaclesInScene() { // c.CurrentlyContainedObjects().Clear(); // c.GetComponent().enabled = false; // c.GetComponent().enabled = true; - if (c == null) { + if (c == null) + { Debug.LogWarning( sop.gameObject + " is missing a contains script on one of its receptacle boxes." ); continue; } - if (go.GetComponent().myParent == null) { + if (go.GetComponent().myParent == null) + { go.GetComponent().myParent = sop.transform.gameObject; } } @@ -525,11 +611,14 @@ public List GatherAllReceptaclesInScene() { return ReceptaclesInScene; } - public void Generate_ObjectID(SimObjPhysics o) { + public void Generate_ObjectID(SimObjPhysics o) + { // check if this object requires it's parent simObjs ObjectID as a prefix - if (ReceptacleRestrictions.UseParentObjectIDasPrefix.Contains(o.Type)) { + if (ReceptacleRestrictions.UseParentObjectIDasPrefix.Contains(o.Type)) + { SimObjPhysics parent = o.transform.parent.GetComponent(); - if (parent == null) { + if (parent == null) + { Debug.LogWarning( "Object " + o @@ -540,7 +629,8 @@ public void Generate_ObjectID(SimObjPhysics o) { return; } - if (parent.ObjectID == null) { + if (parent.ObjectID == null) + { Vector3 ppos = parent.transform.position; string xpPos = (ppos.x >= 0 ? "+" : "") + ppos.x.ToString("00.00"); string ypPos = (ppos.y >= 0 ? "+" : "") + ppos.y.ToString("00.00"); @@ -564,38 +654,47 @@ public void Generate_InheritedObjectID( SimObjPhysics sourceObject, SimObjPhysics createdObject, int count - ) { + ) + { createdObject.ObjectID = sourceObject.ObjectID + "|" + createdObject.ObjType + "_" + count; AddToObjectsInScene(createdObject); } - private bool CheckForDuplicateObjectIDs(SimObjPhysics sop) { + private bool CheckForDuplicateObjectIDs(SimObjPhysics sop) + { return ObjectIdToSimObjPhysics.ContainsKey(sop.ObjectID); } - public void AddToObjectsInScene(SimObjPhysics sop) { + public void AddToObjectsInScene(SimObjPhysics sop) + { ObjectIdToSimObjPhysics[sop.ObjectID] = sop; - if (sop.GetComponent()) { + if (sop.GetComponent()) + { Rigidbody rb = sop.GetComponent(); AddToRBSInScene(rb); } } - public void RemoveFromObjectsInScene(SimObjPhysics sop) { - if (ObjectIdToSimObjPhysics.ContainsKey(sop.ObjectID)) { + public void RemoveFromObjectsInScene(SimObjPhysics sop) + { + if (ObjectIdToSimObjPhysics.ContainsKey(sop.ObjectID)) + { ObjectIdToSimObjPhysics.Remove(sop.ObjectID); - if (sop.GetComponent()) { + if (sop.GetComponent()) + { Rigidbody rb = sop.GetComponent(); RemoveFromRBSInScene(rb); } } } - public void RemoveFromSpawnedObjects(SimObjPhysics sop) { + public void RemoveFromSpawnedObjects(SimObjPhysics sop) + { SpawnedObjects.Remove(sop.gameObject); } - public void RemoveFromRequiredObjects(SimObjPhysics sop) { + public void RemoveFromRequiredObjects(SimObjPhysics sop) + { RequiredObjects.Remove(sop.gameObject); } @@ -603,12 +702,14 @@ public bool SetObjectPoses( ObjectPose[] objectPoses, out string errorMessage, bool placeStationary - ) { + ) + { SetupScene(); errorMessage = ""; bool shouldFail = false; GameObject topObject = GameObject.Find("Objects"); - if (objectPoses != null && objectPoses.Length > 0) { + if (objectPoses != null && objectPoses.Length > 0) + { // Perform object location sets SimObjPhysics[] sceneObjects = FindObjectsOfType(); @@ -619,25 +720,30 @@ bool placeStationary 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) { + foreach (SimObjPhysics sop in sceneObjects) + { // 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) { + if (sop.IsPickupable || sop.IsMoveable) + { sop.gameObject.SetActive(false); // sop.gameObject.GetComponent().IsDisabled = true; nameToObject[sop.name] = sop; } // track all static sim objects as well for reference later - if (sop.isStatic) { + if (sop.isStatic) + { isStaticNameToObject[sop.name] = sop; } } HashSet placedOriginal = new HashSet(); - for (int ii = 0; ii < objectPoses.Length; ii++) { + for (int ii = 0; ii < objectPoses.Length; ii++) + { ObjectPose objectPose = objectPoses[ii]; - if (!nameToObject.ContainsKey(objectPose.objectName)) { + if (!nameToObject.ContainsKey(objectPose.objectName)) + { errorMessage = "No Pickupable or Moveable object of name " + objectPose.objectName @@ -646,7 +752,8 @@ bool placeStationary shouldFail = true; continue; } - if (isStaticNameToObject.ContainsKey(objectPose.objectName)) { + if (isStaticNameToObject.ContainsKey(objectPose.objectName)) + { errorMessage = objectPose.objectName + " is not a Moveable or Pickupable object. SetObjectPoses only works with Moveable and Pickupable sim objects."; @@ -657,7 +764,8 @@ bool placeStationary if ( !nameToObject.ContainsKey(objectPose.objectName) && !isStaticNameToObject.ContainsKey(objectPose.objectName) - ) { + ) + { errorMessage = objectPose.objectName + " does not exist in scene."; shouldFail = true; continue; @@ -666,13 +774,16 @@ bool placeStationary SimObjPhysics obj = nameToObject[objectPose.objectName]; SimObjPhysics existingSOP = obj.GetComponent(); SimObjPhysics copy; - if (placedOriginal.Contains(existingSOP)) { + if (placedOriginal.Contains(existingSOP)) + { copy = Instantiate(original: existingSOP); copy.transform.parent = GameObject.Find("Objects").transform; copy.name += "_copy_" + ii; copy.ObjectID = existingSOP.ObjectID + "_copy_" + ii; copy.objectID = copy.ObjectID; - } else { + } + else + { copy = existingSOP; placedOriginal.Add(existingSOP); } @@ -682,11 +793,14 @@ bool placeStationary copy.gameObject.SetActive(true); copy.gameObject.transform.parent = topObject.transform; - if (placeStationary) { + if (placeStationary) + { copy.GetComponent().collisionDetectionMode = CollisionDetectionMode.Discrete; copy.GetComponent().isKinematic = true; - } else { + } + else + { copy.GetComponent().isKinematic = false; } } @@ -698,27 +812,34 @@ bool placeStationary public System.Collections.Generic.IEnumerator GetValidReceptaclesForSimObj( SimObjPhysics simObj, List receptaclesInScene - ) { + ) + { SimObjType goObjType = simObj.ObjType; bool typeFoundInDictionary = ReceptacleRestrictions.PlacementRestrictions.ContainsKey( goObjType ); - if (typeFoundInDictionary) { + if (typeFoundInDictionary) + { 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 - foreach (SimObjPhysics receptacleSop in receptaclesInScene) { + foreach (SimObjPhysics receptacleSop in receptaclesInScene) + { // don't random spawn in objects that are pickupable to prevent Egg spawning in Plate with the plate spawned in Cabinet.... - if (receptacleSop.PrimaryProperty != SimObjPrimaryProperty.CanPickup) { - if (typesOfObjectsPrefabIsAllowedToSpawnIn.Contains(receptacleSop.ObjType)) { + if (receptacleSop.PrimaryProperty != SimObjPrimaryProperty.CanPickup) + { + if (typesOfObjectsPrefabIsAllowedToSpawnIn.Contains(receptacleSop.ObjType)) + { yield return receptacleSop; } } } - } else { + } + else + { // not found in dictionary! #if UNITY_EDITOR Debug.Log(simObj.ObjectID + "'s Type is not in the ReceptacleRestrictions dictionary!"); @@ -744,7 +865,8 @@ public bool RandomSpawnRequiredSceneObjects( String[] receptacleObjectIds, String[] objectIds, bool allowMoveable - ) { + ) + { #if UNITY_EDITOR var Masterwatch = System.Diagnostics.Stopwatch.StartNew(); #endif @@ -753,8 +875,10 @@ bool allowMoveable //sim objects in the scene at runtime to try and reposition SimObjPhysics[] simObjsInScene = GameObject.FindObjectsOfType(); List simObjsInSceneToGameObjectList = new List(); - foreach (SimObjPhysics sop in simObjsInScene) { - if (allowMoveable && sop.IsMoveable || sop.IsPickupable) { + foreach (SimObjPhysics sop in simObjsInScene) + { + if (allowMoveable && sop.IsMoveable || sop.IsPickupable) + { simObjsInSceneToGameObjectList.Add(sop.gameObject); } } @@ -763,7 +887,8 @@ bool allowMoveable RequiredObjects = simObjsInSceneToGameObjectList; SpawnedObjects = simObjsInSceneToGameObjectList; - if (RequiredObjects.Count == 0) { + if (RequiredObjects.Count == 0) + { #if UNITY_EDITOR Debug.Log("No objects in Required Objects array, please add them in editor"); #endif @@ -779,7 +904,8 @@ bool allowMoveable int HowManyCouldntSpawn = RequiredObjects.Count; // if we already spawned objects, lets just move them around - if (SpawnedObjects.Count > 0) { + if (SpawnedObjects.Count > 0) + { HowManyCouldntSpawn = SpawnedObjects.Count; Dictionary> typeToObjectList = @@ -790,23 +916,27 @@ bool allowMoveable // List listOfExcludedReceptacles = new List(); HashSet originalObjects = new HashSet(SpawnedObjects); - if (numDuplicatesOfType == null) { + if (numDuplicatesOfType == null) + { numDuplicatesOfType = new ObjectTypeCount[0]; } - foreach (ObjectTypeCount repeatCount in numDuplicatesOfType) { + foreach (ObjectTypeCount repeatCount in numDuplicatesOfType) + { SimObjType objType = (SimObjType) System.Enum.Parse(typeof(SimObjType), repeatCount.objectType); requestedNumDuplicatesOfType[objType] = repeatCount.count; } // Now lets go through all pickupable sim objects that are in the current scene - foreach (GameObject go in SpawnedObjects) { + foreach (GameObject go in SpawnedObjects) + { SimObjPhysics sop = null; sop = go.GetComponent(); // Add object types in the current scene to the typeToObjectList if not already on it - if (!typeToObjectList.ContainsKey(sop.ObjType)) { + if (!typeToObjectList.ContainsKey(sop.ObjType)) + { typeToObjectList[sop.ObjType] = new List(); } @@ -817,7 +947,8 @@ bool allowMoveable typeToObjectList[sop.ObjType].Count < requestedNumDuplicatesOfType[sop.ObjType] ) - ) { + ) + { typeToObjectList[sop.ObjType].Add(sop); } } @@ -829,14 +960,17 @@ bool allowMoveable List unduplicatedSimObjects = new List(); // Ok now lets go through each object type in the dictionary - foreach (SimObjType sopType in typeToObjectList.Keys) { + 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 - ) { - foreach (SimObjPhysics sop in typeToObjectList[sopType]) { + ) + { + foreach (SimObjPhysics sop in typeToObjectList[sopType]) + { gameObjsToPlaceInReceptacles.Add(sop.gameObject); } @@ -844,7 +978,8 @@ bool allowMoveable requestedNumDuplicatesOfType[sopType] - typeToObjectList[sopType].Count; // let's instantiate the duplicates now - for (int j = 0; j < numExtra; j++) { + 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) @@ -856,9 +991,12 @@ bool allowMoveable copy.objectID = copy.ObjectID; gameObjsToPlaceInReceptacles.Add(copy.gameObject); } - } else { + } + else + { // this object is not one that needs duplicates, so just add it to the unduplicatedSimObjects list - foreach (SimObjPhysics sop in typeToObjectList[sopType]) { + foreach (SimObjPhysics sop in typeToObjectList[sopType]) + { unduplicatedSimObjects.Add(sop.gameObject); } } @@ -872,7 +1010,8 @@ bool allowMoveable Dictionary> objTypeToReceptacles = new Dictionary>(); - foreach (SimObjPhysics receptacleSop in GatherAllReceptaclesInScene()) { + foreach (SimObjPhysics receptacleSop in GatherAllReceptaclesInScene()) + { SimObjType receptType = receptacleSop.ObjType; if ( ( @@ -886,8 +1025,10 @@ bool allowMoveable receptacleSop.ObjType ) ) - ) { - if (!objTypeToReceptacles.ContainsKey(receptacleSop.ObjType)) { + ) + { + if (!objTypeToReceptacles.ContainsKey(receptacleSop.ObjType)) + { objTypeToReceptacles[receptacleSop.ObjType] = new List(); } objTypeToReceptacles[receptacleSop.ObjType].Add(receptacleSop); @@ -895,11 +1036,13 @@ bool allowMoveable } InstantiatePrefabTest spawner = gameObject.GetComponent(); - foreach (GameObject gameObjToPlaceInReceptacle in gameObjsToPlaceInReceptacles) { + foreach (GameObject gameObjToPlaceInReceptacle in gameObjsToPlaceInReceptacles) + { SimObjPhysics sopToPlaceInReceptacle = gameObjToPlaceInReceptacle.GetComponent(); - if (staticPlacement) { + if (staticPlacement) + { sopToPlaceInReceptacle.GetComponent().isKinematic = true; } @@ -910,7 +1053,8 @@ bool allowMoveable if ( (objectIds != null && !objectIds.Contains(sopToPlaceInReceptacle.ObjectID)) || excludedSimObjects.Contains(sopToPlaceInReceptacle) - ) { + ) + { HowManyCouldntSpawn--; continue; } @@ -921,13 +1065,15 @@ SimObjPhysics receptacleSop in IterShuffleSimObjPhysicsDictList( objTypeToReceptacles, rng ) - ) { + ) + { List targetReceptacleSpawnPoints; 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; } @@ -939,15 +1085,18 @@ SimObjPhysics receptacleSop in IterShuffleSimObjPhysicsDictList( receptacleSop.DoesThisObjectHaveThisSecondaryProperty( SimObjSecondaryProperty.ObjectSpecificReceptacle ) - ) { + ) + { ObjectSpecificReceptacle osr = receptacleSop.GetComponent(); - if (osr.HasSpecificType(sopToPlaceInReceptacle.ObjType)) { + if (osr.HasSpecificType(sopToPlaceInReceptacle.ObjType)) + { // in the random spawn function, we need this additional check because there isn't a chance for // the physics update loop to fully update osr.isFull() correctly, which can cause multiple objects // to be placed on the same spot (ie: 2 pots on the same burner) - if (osr.attachPoint.transform.childCount > 0) { + if (osr.attachPoint.transform.childCount > 0) + { break; } @@ -955,7 +1104,8 @@ SimObjPhysics receptacleSop in IterShuffleSimObjPhysicsDictList( if ( receptacleSop.GetComponent().Type == SimObjType.StoveBurner - ) { + ) + { if ( StoveTopCheckSpawnArea( sopToPlaceInReceptacle, @@ -963,7 +1113,8 @@ SimObjPhysics receptacleSop in IterShuffleSimObjPhysicsDictList( osr.attachPoint.transform.rotation, false ) == true - ) { + ) + { // print("moving object now"); gameObjToPlaceInReceptacle.transform.position = osr.attachPoint.position; @@ -985,7 +1136,9 @@ SimObjPhysics receptacleSop in IterShuffleSimObjPhysicsDictList( break; } - } else { // for everything else (coffee maker, toilet paper holder, etc) just place it if there is nothing attached + } + 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( @@ -1018,31 +1171,37 @@ SimObjPhysics receptacleSop in IterShuffleSimObjPhysicsDictList( 90, true ) - ) { + ) + { HowManyCouldntSpawn--; spawned = true; break; } } - if (!spawned) { + if (!spawned) + { #if UNITY_EDITOR Debug.Log(gameObjToPlaceInReceptacle.name + " could not be spawned."); #endif // go.GetComponent().IsDisabled = true; - if (!originalObjects.Contains(gameObjToPlaceInReceptacle)) { + if (!originalObjects.Contains(gameObjToPlaceInReceptacle)) + { gameObjToPlaceInReceptacle.SetActive(false); Destroy(gameObjToPlaceInReceptacle); } } } - } else { + } + else + { /// XXX: add exception in at some point throw new NotImplementedException(); } #if UNITY_EDITOR - if (HowManyCouldntSpawn > 0) { + if (HowManyCouldntSpawn > 0) + { Debug.Log(HowManyCouldntSpawn + " object(s) could not be spawned into the scene!"); } @@ -1063,13 +1222,15 @@ public bool StoveTopCheckSpawnArea( 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) { + if (spawningInHand) + { layermask = LayerMask.GetMask( "SimObjVisible", "Procedural1", @@ -1077,7 +1238,9 @@ bool spawningInHand "Procedural3", "Procedural0" ); - } else { + } + 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( @@ -1094,8 +1257,10 @@ bool spawningInHand // laptops which have multiple sets of colliders, with one part moving... Collider[] objcols = simObj.transform.GetComponentsInChildren(); - foreach (Collider col in objcols) { - if (col.gameObject.name != "BoundingBox") { + foreach (Collider col in objcols) + { + if (col.gameObject.name != "BoundingBox") + { col.enabled = false; } } @@ -1133,21 +1298,27 @@ bool spawningInHand // now check if any of the hit colliders were any object EXCEPT other stove top objects i guess bool result = true; - if (hitColliders.Length > 0) { - foreach (Collider col in hitColliders) { + if (hitColliders.Length > 0) + { + foreach (Collider col in hitColliders) + { // if we hit some structure object like a stove top or countertop mesh, ignore it since we are snapping this to a specific position right here - if (!col.GetComponentInParent()) { + if (!col.GetComponentInParent()) + { break; } // if any sim object is hit that is not a stove burner, then ABORT - if (col.GetComponentInParent().Type != SimObjType.StoveBurner) { + if (col.GetComponentInParent().Type != SimObjType.StoveBurner) + { result = false; simObj.transform.position = originalPos; simObj.transform.rotation = originalRot; - foreach (Collider yes in objcols) { - if (yes.gameObject.name != "BoundingBox") { + foreach (Collider yes in objcols) + { + if (yes.gameObject.name != "BoundingBox") + { yes.enabled = true; } } @@ -1157,8 +1328,10 @@ bool spawningInHand } // nothing hit in colliders, so we are good to spawn. - foreach (Collider col in objcols) { - if (col.gameObject.name != "BoundingBox") { + foreach (Collider col in objcols) + { + if (col.gameObject.name != "BoundingBox") + { col.enabled = true; } } @@ -1171,26 +1344,32 @@ bool spawningInHand public List ShuffleSimObjPhysicsDictList( Dictionary> dict, int seed - ) { + ) + { List types = new List(); Dictionary indDict = new Dictionary(); - foreach (KeyValuePair> pair in dict) { + foreach (KeyValuePair> pair in dict) + { types.Add(pair.Key); indDict[pair.Key] = pair.Value.Count - 1; } types.Sort(); types.Shuffle_(seed); - foreach (SimObjType t in types) { + foreach (SimObjType t in types) + { dict[t].Shuffle_(seed); } bool changed = true; List shuffledSopList = new List(); - while (changed) { + while (changed) + { changed = false; - foreach (SimObjType type in types) { + foreach (SimObjType type in types) + { int i = indDict[type]; - if (i >= 0) { + if (i >= 0) + { changed = true; shuffledSopList.Add(dict[type][i]); indDict[type]--; @@ -1203,26 +1382,32 @@ int seed public IEnumerable IterShuffleSimObjPhysicsDictList( Dictionary> dict, System.Random rng - ) { + ) + { List types = new List(); Dictionary indDict = new Dictionary(); - foreach (KeyValuePair> pair in dict) { + foreach (KeyValuePair> pair in dict) + { types.Add(pair.Key); indDict[pair.Key] = pair.Value.Count - 1; } types.Sort(); types.Shuffle_(rng); - foreach (SimObjType t in types) { + foreach (SimObjType t in types) + { dict[t].Shuffle_(rng); } bool changed = true; List shuffledSopList = new List(); - while (changed) { + while (changed) + { changed = false; - foreach (SimObjType type in types) { + foreach (SimObjType type in types) + { int i = indDict[type]; - if (i >= 0) { + if (i >= 0) + { changed = true; yield return dict[type][i]; indDict[type]--; @@ -1231,11 +1416,16 @@ System.Random rng } } - protected static IEnumerator toStandardCoroutineIEnumerator(IEnumerator enumerator) { - while (enumerator.MoveNext()) { - if ((!enumerator.Current.HasValue) || (enumerator.Current <= 0f)) { + protected static IEnumerator toStandardCoroutineIEnumerator(IEnumerator enumerator) + { + while (enumerator.MoveNext()) + { + if ((!enumerator.Current.HasValue) || (enumerator.Current <= 0f)) + { yield return null; - } else { + } + else + { yield return new WaitForFixedUpdate(); } } @@ -1245,24 +1435,31 @@ public static void StartPhysicsCoroutine( MonoBehaviour startCoroutineUsing, IEnumerator enumerator, bool? autoSimulation = null - ) { + ) + { autoSimulation = autoSimulation.GetValueOrDefault(Physics.autoSimulation); - if (autoSimulation.Value) { + if (autoSimulation.Value) + { startCoroutineUsing.StartCoroutine(toStandardCoroutineIEnumerator(enumerator)); return; } var previousAutoSimulate = Physics.autoSimulation; Physics.autoSimulation = false; - while (enumerator.MoveNext()) { + while (enumerator.MoveNext()) + { float? fixedDeltaTime = enumerator.Current; - if (!fixedDeltaTime.HasValue) { + if (!fixedDeltaTime.HasValue) + { fixedDeltaTime = Time.fixedDeltaTime; } - if (fixedDeltaTime == 0f) { + if (fixedDeltaTime == 0f) + { Physics.SyncTransforms(); - } else { + } + else + { PhysicsSimulateTHOR(fixedDeltaTime.Value); } } @@ -1270,7 +1467,8 @@ public static void StartPhysicsCoroutine( } // Immediately disable physics autosimulation - public void PausePhysicsAutoSim() { + public void PausePhysicsAutoSim() + { Physics.autoSimulation = false; Physics.autoSyncTransforms = false; physicsSimulationPaused = true; @@ -1281,21 +1479,27 @@ public void AdvancePhysicsStep( float timeStep = 0.02f, float? simSeconds = null, bool allowAutoSimulation = false - ) { - if (timeStep <= 0f && simSeconds.GetValueOrDefault(0f) > 0f) { + ) + { + if (timeStep <= 0f && simSeconds.GetValueOrDefault(0f) > 0f) + { throw new InvalidOperationException($"timestep must be > 0"); } bool oldPhysicsAutoSim = Physics.autoSimulation; Physics.autoSimulation = false; - while (simSeconds.Value > 0.0f) { + while (simSeconds.Value > 0.0f) + { simSeconds = simSeconds.Value - timeStep; - if (simSeconds.Value <= 0) { + if (simSeconds.Value <= 0) + { // This is necessary to keep lastVelocity up-to-date for all sim objects and is // called just before the last physics simulation step. Rigidbody[] rbs = FindObjectsOfType(typeof(Rigidbody)) as Rigidbody[]; - foreach (Rigidbody rb in rbs) { - if (rb.GetComponentInParent()) { + foreach (Rigidbody rb in rbs) + { + if (rb.GetComponentInParent()) + { SimObjPhysics sop = rb.GetComponentInParent(); sop.lastVelocity = Math.Abs( rb.angularVelocity.sqrMagnitude + rb.velocity.sqrMagnitude @@ -1313,16 +1517,19 @@ public void AdvancePhysicsStep( } // Immediately enable physics autosimulation - public void UnpausePhysicsAutoSim() { + public void UnpausePhysicsAutoSim() + { Physics.autoSimulation = true; Physics.autoSyncTransforms = true; physicsSimulationPaused = false; } #if UNITY_EDITOR - void OnDrawGizmos() { + void OnDrawGizmos() + { Gizmos.color = Color.magenta; - if (m_Started) { + if (m_Started) + { Matrix4x4 cubeTransform = Matrix4x4.TRS(gizmopos, gizmoquaternion, gizmoscale); Matrix4x4 oldGizmosMatrix = Gizmos.matrix; diff --git a/unity/Assets/Scripts/PlacementManager.cs b/unity/Assets/Scripts/PlacementManager.cs index b885249e50..1c80eb8046 100644 --- a/unity/Assets/Scripts/PlacementManager.cs +++ b/unity/Assets/Scripts/PlacementManager.cs @@ -2,10 +2,14 @@ using System.Collections; using UnityEngine; -public class PlacementManager : MonoBehaviour { - public static PlacementManager Current { - get { - if (current == null) { +public class PlacementManager : MonoBehaviour +{ + public static PlacementManager Current + { + get + { + if (current == null) + { current = GameObject.FindObjectOfType(); } return current; @@ -26,7 +30,8 @@ public static bool GetPlacementPoint( float reach, float maxDistance, ref Vector3 point - ) { + ) + { UnityEngine.AI.NavMeshHit hit; if ( UnityEngine.AI.NavMesh.SamplePosition( @@ -35,7 +40,8 @@ ref Vector3 point maxDistance: maxDistance, areaMask: 1 << NavmeshShelfArea ) - ) { + ) + { // check whether we can see this point Vector3 viewPoint = agentCamera.WorldToViewportPoint(hit.position); Vector3 pointDirection = Vector3.zero; @@ -46,7 +52,8 @@ ref Vector3 point && viewPoint.x > SimUtil.ViewPointRangeLow // within x bounds && viewPoint.y < SimUtil.ViewPointRangeHigh && viewPoint.y > SimUtil.ViewPointRangeLow - ) { // within y bounds + ) + { // within y bounds // do a raycast in the direction of the item pointDirection = (hit.position - agentCameraPos).normalized; RaycastHit pointHit; @@ -59,7 +66,8 @@ ref Vector3 point SimUtil.RaycastVisibleLayerMask, QueryTriggerInteraction.Ignore ) && (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; return true; @@ -69,13 +77,15 @@ ref Vector3 point return false; } - public static void PlaceObjectAtPoint(SimObj simObj, Vector3 point) { + public static void PlaceObjectAtPoint(SimObj simObj, Vector3 point) + { simObj.transform.position = point + Vector3.up * DefaultDropDistance; simObj.gameObject.SetActive(true); Current.StartCoroutine(current.EnableSimObjPhysics(simObj)); } - public IEnumerator EnableSimObjPhysics(SimObj simObj) { + public IEnumerator EnableSimObjPhysics(SimObj simObj) + { // always wait for 1 frame to allow sim object to wake itself up yield return null; // move the simObj to the object root to ensure it's not parented under another rigidbody diff --git a/unity/Assets/Scripts/PlaneGizmo.cs b/unity/Assets/Scripts/PlaneGizmo.cs index f48e95c9c4..a8c61a2f2c 100644 --- a/unity/Assets/Scripts/PlaneGizmo.cs +++ b/unity/Assets/Scripts/PlaneGizmo.cs @@ -2,11 +2,13 @@ using System.Collections.Generic; using UnityEngine; -public class PlaneGizmo : MonoBehaviour { +public class PlaneGizmo : MonoBehaviour +{ // Start is called before the first frame update void Start() { } - void OnDrawGizmos() { + void OnDrawGizmos() + { // Gizmos.color = Color.yellow; Gizmos.color = new Color(1, 0.92f, 0.016f, 1f); diff --git a/unity/Assets/Scripts/PlayerControllers.cs b/unity/Assets/Scripts/PlayerControllers.cs index a5b88da038..f167feb0ac 100644 --- a/unity/Assets/Scripts/PlayerControllers.cs +++ b/unity/Assets/Scripts/PlayerControllers.cs @@ -5,8 +5,10 @@ // using PlayerControllers; // using UnityStandardAssets.Characters.FirstPerson; -namespace UnityStandardAssets.Characters.FirstPerson { - public enum ControlMode { +namespace UnityStandardAssets.Characters.FirstPerson +{ + public enum ControlMode + { DEBUG_TEXT_INPUT, FPS, DISCRETE_POINT_CLICK, @@ -14,7 +16,8 @@ public enum ControlMode { MINIMAL_FPS } - class PlayerControllers { + class PlayerControllers + { public static Dictionary controlModeToComponent = new Dictionary< ControlMode, Type diff --git a/unity/Assets/Scripts/PrefabNameRevert.cs b/unity/Assets/Scripts/PrefabNameRevert.cs index 0f704b0429..3fd29a0f98 100644 --- a/unity/Assets/Scripts/PrefabNameRevert.cs +++ b/unity/Assets/Scripts/PrefabNameRevert.cs @@ -3,45 +3,58 @@ using UnityEditor; using System.Collections.Generic; -public class PrefabNameRevert { +public class PrefabNameRevert +{ [MenuItem("Prefab/RevertName")] - static void RevertPrefabNames() { + static void RevertPrefabNames() + { RevertAllNames(Selection.GetFiltered(typeof(GameObject), SelectionMode.Editable)); } - public static string GetPrefabAssetName(GameObject prefab, string name = "") { + public static string GetPrefabAssetName(GameObject prefab, string name = "") + { // Debug.Log("Object " + name + " object: " + prefab.name); var original = PrefabUtility.GetCorrespondingObjectFromOriginalSource(prefab); - if (original != null) { + if (original != null) + { return original.name; - } else { + } + else + { Debug.LogError($"No prefab could be found for object '{prefab.name}'"); return null; } } - public static void RemoveNameModification(UnityEngine.Object aObj) { + public static void RemoveNameModification(UnityEngine.Object aObj) + { var mods = new List(PrefabUtility.GetPropertyModifications(aObj)); - for (int i = 0; i < mods.Count; i++) { - if (mods[i].propertyPath == "m_Name") { + for (int i = 0; i < mods.Count; i++) + { + if (mods[i].propertyPath == "m_Name") + { mods.RemoveAt(i); } } PrefabUtility.SetPropertyModifications(aObj, mods.ToArray()); } - public static void RevertAllNames(Object[] aObjects) { + public static void RevertAllNames(Object[] aObjects) + { var items = new List(); - foreach (var item in aObjects) { + foreach (var item in aObjects) + { var prefab = PrefabUtility.GetCorrespondingObjectFromOriginalSource(item); - if (prefab != null) { + if (prefab != null) + { Undo.RecordObject(item, "Revert perfab name"); item.name = prefab.name; items.Add(item); } } Undo.FlushUndoRecordObjects(); - foreach (var item in items) { + foreach (var item in items) + { RemoveNameModification(item); } } diff --git a/unity/Assets/Scripts/ProceduralAssetDatabase.cs b/unity/Assets/Scripts/ProceduralAssetDatabase.cs index 2d9d84bf83..6c89713353 100644 --- a/unity/Assets/Scripts/ProceduralAssetDatabase.cs +++ b/unity/Assets/Scripts/ProceduralAssetDatabase.cs @@ -4,8 +4,10 @@ using Priority_Queue; using UnityEngine; -namespace Thor.Procedural { - public class ProceduralAssetDatabase : MonoBehaviour { +namespace Thor.Procedural +{ + public class ProceduralAssetDatabase : MonoBehaviour + { public static ProceduralAssetDatabase Instance { get; private set; } [SerializeField] @@ -23,8 +25,10 @@ public class ProceduralAssetDatabase : MonoBehaviour { public bool dontDestroyOnLoad = true; - public void Awake() { - if (Instance != null) { + public void Awake() + { + if (Instance != null) + { Destroy(gameObject); return; } @@ -33,43 +37,54 @@ public void Awake() { this.assetMap = new ProceduralLRUCacheAssetMap( prefabs.GroupBy(p => p.name).ToDictionary(p => p.Key, p => p.First()) ); - if (dontDestroyOnLoad) { + if (dontDestroyOnLoad) + { DontDestroyOnLoad(gameObject); - } else { + } + else + { // Reset it back to enable caching for next time object is created dontDestroyOnLoad = true; } } - public void addAsset(GameObject asset, bool procedural = false) { + public void addAsset(GameObject asset, bool procedural = false) + { // prefabs.Add(asset); assetMap.addAsset(asset.name, asset, procedural); } - public void addAssets(IEnumerable assets, bool procedural = false) { - foreach (var asset in assets) { + public void addAssets(IEnumerable assets, bool procedural = false) + { + foreach (var asset in assets) + { assetMap.addAsset(asset.name, asset, procedural); } } - public bool ContainsAssetKey(string key) { + public bool ContainsAssetKey(string key) + { return assetMap.ContainsKey(key); } - public void touchProceduralLRUCache(IEnumerable ids) { + public void touchProceduralLRUCache(IEnumerable ids) + { this.assetMap.touch(ids); } - public void removeLRUItems(int limit) { + public void removeLRUItems(int limit) + { this.assetMap.removeLRU(limit: limit); } - public IEnumerable GetPrefabs() { + public IEnumerable GetPrefabs() + { return this.assetMap.Values(); } } - public class ProceduralLRUCacheAssetMap : AssetMap { + public class ProceduralLRUCacheAssetMap : AssetMap + { public SimplePriorityQueue proceduralAssetQueue { get; private set; } public int priorityMinValue { get; private set; } public int priorityMaxValue { get; private set; } @@ -84,7 +99,8 @@ public ProceduralLRUCacheAssetMap( int rankingMinValue = 0, int rankingMaxValue = 1 ) - : base(assetMap) { + : base(assetMap) + { this.priorityMinValue = this.originalPriorityMinValue = rankingMinValue; this.priorityMaxValue = this.originalPriorityMaxValue = rankingMaxValue; proceduralAssetQueue = new SimplePriorityQueue(); @@ -95,30 +111,37 @@ public ProceduralLRUCacheAssetMap( // so there can be times if we internally drive the LRU cache that we may delete // assets and not have the hook to create them - public override T getAsset(string name) { + public override T getAsset(string name) + { return assetMap[name]; } - public void addAsset(string id, T asset, bool procedural = true) { - if (procedural) { + public void addAsset(string id, T asset, bool procedural = true) + { + if (procedural) + { proceduralAssetQueue.Enqueue(id, this.priorityMaxValue); } this.assetMap.Add(id, asset); } - public void touch(IEnumerable ids) { + public void touch(IEnumerable ids) + { this.advanceExpiration(); this.use(ids); } - public void touch(string id) { + public void touch(string id) + { this.advanceExpiration(); this.use(id); } - public AsyncOperation removeLRU(int limit, bool deleteWithHighestPriority = true) { + public AsyncOperation removeLRU(int limit, bool deleteWithHighestPriority = true) + { // Debug.Log($"Running removeLRU with {limit}, {deleteWithHighestPriority}"); - if (proceduralAssetQueue.Count == 0) { + if (proceduralAssetQueue.Count == 0) + { // Debug.Log($"Queue empty, returning"); return null; } @@ -131,19 +154,24 @@ public AsyncOperation removeLRU(int limit, bool deleteWithHighestPriority = true while ( proceduralAssetQueue.Count > limit && (deleteWithHighestPriority || toDequeuePrio < this.priorityMaxValue) - ) { + ) + { var removed = proceduralAssetQueue.Dequeue(); - if (this.getAsset(removed) is GameObject go) { + if (this.getAsset(removed) is GameObject go) + { go.transform.parent = null; go.SetActive(false); this.assetMap.Remove(removed); GameObject.Destroy(go); - } else { + } + else + { this.assetMap.Remove(removed); } // Debug.Log($"Removing {removed}"); dequeueCount++; - if (proceduralAssetQueue.Count == 0) { + if (proceduralAssetQueue.Count == 0) + { break; } current = proceduralAssetQueue.First; @@ -151,12 +179,14 @@ public AsyncOperation removeLRU(int limit, bool deleteWithHighestPriority = true } // 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) => { + asyncOp.completed += (op) => + { Debug.Log("Asyncop callback called calling GC"); GC.Collect(); }; @@ -164,7 +194,8 @@ public AsyncOperation removeLRU(int limit, bool deleteWithHighestPriority = true // #if !UNITY_EDITOR && !UNITY_WEBGL float timeout = 2.0f; float startTime = Time.realtimeSinceStartup; - while (!asyncOp.isDone && Time.realtimeSinceStartup - startTime < timeout) { + while (!asyncOp.isDone && Time.realtimeSinceStartup - startTime < timeout) + { // waiting continue; } @@ -174,28 +205,38 @@ public AsyncOperation removeLRU(int limit, bool deleteWithHighestPriority = true return asyncOp; } - protected void use(IEnumerable ids) { - foreach (var id in ids) { + protected void use(IEnumerable ids) + { + foreach (var id in ids) + { this.use(id); } } - protected void use(string name) { - if (proceduralAssetQueue.Contains(name)) { + protected void use(string name) + { + if (proceduralAssetQueue.Contains(name)) + { var currentPriority = proceduralAssetQueue.GetPriority(name); - if (currentPriority < priorityMaxValue) { + if (currentPriority < priorityMaxValue) + { proceduralAssetQueue.UpdatePriority(name, priorityMaxValue); } } } // 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( diff --git a/unity/Assets/Scripts/ProceduralAssetEditor.cs b/unity/Assets/Scripts/ProceduralAssetEditor.cs index b59d826750..fe27efd145 100644 --- a/unity/Assets/Scripts/ProceduralAssetEditor.cs +++ b/unity/Assets/Scripts/ProceduralAssetEditor.cs @@ -21,9 +21,11 @@ using UnityEditor.SceneManagement; #endif -namespace Thor.Procedural { +namespace Thor.Procedural +{ [System.Serializable] - public class AssetEditorPaths { + public class AssetEditorPaths + { public string serializeBasePath; public string materialsRelativePath; public string texturesRelativePath; @@ -34,14 +36,17 @@ public class AssetEditorPaths { } [System.Serializable] - public class ObjaversePipelinseSettings { + public class ObjaversePipelinseSettings + { public string pythonExecutablePath; public string vidaRepo; public int timeoutSeconds; } - public class ProceduralAssetEditor : MonoBehaviour { - public AssetEditorPaths paths = new AssetEditorPaths() { + public class ProceduralAssetEditor : MonoBehaviour + { + public AssetEditorPaths paths = new AssetEditorPaths() + { serializeBasePath = "Assets/Resources/ai2thor-objaverse/NoveltyTHOR_Assets", materialsRelativePath = "Materials/objaverse", texturesRelativePath = "Textures", @@ -51,7 +56,8 @@ public class ProceduralAssetEditor : MonoBehaviour { 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 @@ -65,11 +71,15 @@ public class ProceduralAssetEditor : MonoBehaviour { public string objectId; #if UNITY_EDITOR - private string copyTexture(string original, string destinationDir) { + private string copyTexture(string original, string destinationDir) + { var outName = $"{destinationDir}/{Path.GetFileName(original)}"; - if (!File.Exists(outName)) { + if (!File.Exists(outName)) + { File.Copy(original, outName); - } else { + } + else + { Debug.LogWarning( $"Failed to save texture {outName}, as it already extists. To overwite delete them first and load object again." ); @@ -77,11 +87,13 @@ private string copyTexture(string original, string destinationDir) { return outName; } - private string getAssetRelativePath(string absPath) { + private string getAssetRelativePath(string absPath) + { return string.Join("/", absPath.Split('/').SkipWhile(x => x != "Assets")); } - private Texture2D loadTexture(string textureAbsPath) { + private Texture2D loadTexture(string textureAbsPath) + { return (Texture2D) AssetDatabase.LoadAssetAtPath( getAssetRelativePath(textureAbsPath), @@ -98,13 +110,15 @@ private Texture2D loadTexture(string textureAbsPath) { // } - private void SaveTextures(GameObject go, bool savePrefab) { + private void SaveTextures(GameObject go, bool savePrefab) + { var assetId = go.GetComponentInChildren().assetID; var matOutPath = $"{paths.serializeBasePath}/{paths.materialsRelativePath}/{assetId}.mat"; - if (File.Exists(matOutPath)) { + if (File.Exists(matOutPath)) + { Debug.LogWarning( $"Failed to save material {matOutPath}, as it already extists. To overwite delete it first and load object again." ); @@ -115,7 +129,9 @@ private void SaveTextures(GameObject go, bool savePrefab) { typeof(Material) ); go.GetComponentInChildren().sharedMaterial = savedMat; - } else { + } + else + { UnityEditor.AssetDatabase.CreateAsset( go.GetComponentInChildren().sharedMaterial, matOutPath @@ -128,7 +144,8 @@ private void SaveTextures(GameObject go, bool savePrefab) { var outTextureBasePath = $"{Application.dataPath}/{dir}/{paths.texturesRelativePath}/{assetId}"; - if (!Directory.Exists(outTextureBasePath)) { + if (!Directory.Exists(outTextureBasePath)) + { Directory.CreateDirectory(outTextureBasePath); } @@ -196,7 +213,8 @@ private void SaveTextures(GameObject go, bool savePrefab) { // mf.sharedMesh = mesh; - if (savePrefab) { + if (savePrefab) + { PrefabUtility.SaveAsPrefabAssetAndConnect( go, $"{paths.serializeBasePath}/{paths.prefabsRelativePath}/{assetId}.prefab", @@ -206,7 +224,8 @@ private void SaveTextures(GameObject go, bool savePrefab) { } // NOT WORKIGN drag prefab manually - private void SavePrefab(GameObject go) { + 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}"); @@ -221,7 +240,8 @@ out prefabSuccess Debug.Log($"---- prefab save {prefabSuccess}"); } - private GameObject importAsset(string objectPath, bool addAnotationComponent = false) { + private GameObject importAsset(string objectPath, bool addAnotationComponent = false) + { var jsonStr = System.IO.File.ReadAllText(objectPath); JObject obj = JObject.Parse(jsonStr); @@ -263,15 +283,20 @@ private GameObject importAsset(string objectPath, bool addAnotationComponent = f // var intermediate = result["intermediateGameObject"] as GameObject; // DestroyImmediate(intermediate); - if (go.transform.parent != null && !go.transform.parent.gameObject.activeSelf) { + if (go.transform.parent != null && !go.transform.parent.gameObject.activeSelf) + { go.transform.parent.gameObject.SetActive(true); } - if (savePrefabsOnLoad) { + if (savePrefabsOnLoad) + { SaveTextures(go, savePrefab); - } else { + } + else + { var runtimeP = go.GetComponent(); - if (runtimeP != null) { + if (runtimeP != null) + { runtimeP.RealoadTextures(); } } @@ -282,9 +307,11 @@ private GameObject importAsset(string objectPath, bool addAnotationComponent = f // TODO: put in ifdef block [Button(Expanded = true)] - public void LoadObject() { + public void LoadObject() + { var file = objectId.Trim(); - if (!file.EndsWith(".json")) { + if (!file.EndsWith(".json")) + { file += ".json"; } @@ -300,7 +327,8 @@ public void LoadObject() { Debug.Log(objectPath); // this.loadedHouse = readHouseFromJson(objectPath); - if (!File.Exists(objectPath)) { + if (!File.Exists(objectPath)) + { cancellAll = false; Debug.Log("Starting objaverse pipeline background process..."); coroutines.Add( @@ -308,15 +336,19 @@ public void LoadObject() { runAssetPipelineAsync( objectId, objaverseRoot, - () => { - if (!cancellAll) { + () => + { + if (!cancellAll) + { importAsset(objectPath, addAnotationComponent: true); } } ) ) ); - } else { + } + else + { importAsset(objectPath, forceCreateAnnotationComponent); } @@ -330,18 +362,21 @@ public void LoadObject() { } [Button(Expanded = true)] - public void CancelAll() { + public void CancelAll() + { EditorUtility.ClearProgressBar(); cancellAll = true; - foreach (var ap in this.processingIds.Values) { + foreach (var ap in this.processingIds.Values) + { Debug.Log($"Cancelled conversion process for '{ap.id}'"); ap.process.Kill(); ap.process.CancelOutputRead(); ap.process.CancelErrorRead(); } - foreach (var coroutine in coroutines) { + foreach (var coroutine in coroutines) + { StopCoroutine(coroutine); } @@ -351,7 +386,8 @@ public void CancelAll() { // [UnityEditor.MenuItem("Procedural/Fix Prefabs")] [Button(Expanded = false)] - public void FixPrefabs() { + public void FixPrefabs() + { 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); @@ -400,9 +436,11 @@ public void FixPrefabs() { // }); - foreach (var (assetId, go) in gos) { + foreach (var (assetId, go) in gos) + { var dir = string.Join("/", paths.serializeBasePath.Split('/').Skip(1)); - if (PrefabUtility.IsPartOfPrefabInstance(go)) { + if (PrefabUtility.IsPartOfPrefabInstance(go)) + { SerializeMesh.SaveMeshesAsObjAndReplaceReferences( go, assetId, @@ -418,7 +456,8 @@ public void FixPrefabs() { // meshGo.transform.localEulerAngles = negRot; // } Debug.Log($"Ran for {go.name}"); - if (go.GetComponentInChildren() != null) { + if (go.GetComponentInChildren() != null) + { DestroyImmediate(go.GetComponentInChildren()); } @@ -433,11 +472,14 @@ public void FixPrefabs() { } [MenuItem("Procedural/Revert Prefabs")] - public void RevertPrefabs() { + public void RevertPrefabs() + { var simObjs = GameObject.FindObjectsOfType(typeof(SimObjPhysics)) as SimObjPhysics[]; - foreach (var so in simObjs) { - if (PrefabUtility.IsPartOfPrefabInstance(so.gameObject)) { + foreach (var so in simObjs) + { + if (PrefabUtility.IsPartOfPrefabInstance(so.gameObject)) + { Debug.Log($"Reverting {so.gameObject}"); //PrefabUtility.RevertPropertyOverride() PrefabUtility.RevertPrefabInstance(so.gameObject, InteractionMode.UserAction); @@ -446,43 +488,56 @@ public void RevertPrefabs() { } [Button(Expanded = true)] - public void SaveObjectPrefabAndTextures() { + public void SaveObjectPrefabAndTextures() + { var transformRoot = GameObject.Find(objectId); var transform = gameObject.transform.root.FirstChildOrDefault(g => g.name == objectId); - if (transform == null) { + if (transform == null) + { transform = transformRoot.transform; } // Debug.Log($"Root: {gameObject.transform.root.name}"); - if (transform != null) { + if (transform != null) + { SaveTextures(transform.gameObject, savePrefab); - } else { + } + else + { Debug.LogError($"Invalid object {objectId} not present in scene."); } } [Button(Expanded = true)] - public void SaveAllPrefabsAndTextures() { + 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) { + 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")] - public static void ReloadTextures() { + public static void ReloadTextures() + { var procAssets = GameObject.FindObjectsOfType(typeof(RuntimePrefab)) as RuntimePrefab[]; - foreach (var asset in procAssets) { + foreach (var asset in procAssets) + { asset.RealoadTextures(); } } - class AsyncProcess { + class AsyncProcess + { public float progress; public diagnostics.Process process; public string id; @@ -501,13 +556,15 @@ private IEnumerator waitForProcess( 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) { + while (!p.HasExited) + { // var currentCount = processingIds.Count; // p.StandardOutput.ReadAsync() yield return new WaitForSeconds(sleepSeconds); @@ -517,14 +574,16 @@ int timeoutSeconds var deltaSeconds = Time.realtimeSinceStartup - start; int roundedSeconds = (int)Mathf.Round(deltaSeconds); - if (roundedSeconds % debugIntervalSeconds == 0) { + 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) { + if (currentCount < prevCount) + { // prevCount = currentCount; EditorUtility.DisplayProgressBar( "Objaverse import", @@ -539,7 +598,8 @@ int timeoutSeconds // } - if (deltaSeconds >= timeoutSeconds) { + if (deltaSeconds >= timeoutSeconds) + { Debug.Log( $"Timeout reached, possible issue with object '{id}', or increase components 'objaversePipelineConfig.timeoutSeconds'." ); @@ -549,7 +609,8 @@ int timeoutSeconds } } - private diagnostics.Process runPythonCommand(string id, string saveDir) { + 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"; @@ -559,7 +620,8 @@ private diagnostics.Process runPythonCommand(string id, string saveDir) { p.StartInfo = new diagnostics.ProcessStartInfo( objaversePipelineConfig.pythonExecutablePath, $"{pythonFilename} {objectId} {saveDir}" - ) { + ) + { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, @@ -573,7 +635,8 @@ private diagnostics.Process runPythonCommand(string id, string saveDir) { processingIds.GetOrAdd( id, - new AsyncProcess() { + new AsyncProcess() + { id = id, process = p, progress = 0.0f @@ -593,7 +656,8 @@ private diagnostics.Process runPythonCommand(string id, string saveDir) { // return processingIds.Values.Sum() / processingIds.Count; // } - private IEnumerator runAssetPipelineAsync(string id, string saveDir, Action callback = null) { + private IEnumerator runAssetPipelineAsync(string id, string saveDir, Action callback = null) + { // processingIds.TryUpdate(id) EditorUtility.DisplayProgressBar( "Objaverse import", @@ -639,7 +703,8 @@ private IEnumerator runAssetPipelineAsync(string id, string saveDir, Action call EditorUtility.DisplayProgressBar("Objaverse import", $"'{id}' Finished!", 1f); processingIds.TryRemove(id, out AsyncProcess val); - if (processingIds.IsEmpty) { + if (processingIds.IsEmpty) + { EditorUtility.ClearProgressBar(); } } diff --git a/unity/Assets/Scripts/ProceduralData.cs b/unity/Assets/Scripts/ProceduralData.cs index 8aa95b16b3..7358aa07d3 100644 --- a/unity/Assets/Scripts/ProceduralData.cs +++ b/unity/Assets/Scripts/ProceduralData.cs @@ -12,10 +12,12 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -namespace Thor.Procedural.Data { +namespace Thor.Procedural.Data +{ [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class AssetMetadata { + public class AssetMetadata + { public string id; public string type; public string primaryProperty; @@ -25,7 +27,8 @@ public class AssetMetadata { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class ProbeParameters { + public class ProbeParameters + { public string id; public Vector3 position; public float intensity; @@ -37,7 +40,8 @@ public class ProbeParameters { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class LightParameters { + public class LightParameters + { public string id { get; set; } public string type { get; set; } public Vector3 position { get; set; } @@ -65,7 +69,8 @@ this is a light that is a child of some sim object (ie: lamp) and it is controll [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class ShadowParameters { + public class ShadowParameters + { public string type { get; set; } = "Soft"; public float strength { get; set; } = 1.0f; @@ -77,18 +82,22 @@ public class ShadowParameters { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class SerializableColor { + public class SerializableColor + { public float r { get; set; } public float g { get; set; } public float b { get; set; } public float a { get; set; } = 1.0f; - public Color toUnityColor() { + public Color toUnityColor() + { return new Color(r, g, b, a); } - public static SerializableColor fromUnityColor(Color color) { - return new SerializableColor() { + public static SerializableColor fromUnityColor(Color color) + { + return new SerializableColor() + { r = color.r, g = color.g, b = color.b, @@ -99,7 +108,8 @@ public static SerializableColor fromUnityColor(Color color) { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class Margin { + public class Margin + { public float bottom { get; set; } public float top { get; set; } public float left { get; set; } @@ -108,7 +118,8 @@ public class Margin { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class Door : WallRectangularHole { + public class Door : WallRectangularHole + { public string id { get; set; } public string room0 { get; set; } public string room1 { get; set; } @@ -128,7 +139,8 @@ public class Door : WallRectangularHole { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class ProceduralParameters { + public class ProceduralParameters + { public float floorColliderThickness { get; set; } public float minWallColliderThickness { get; set; } public float receptacleHeight { get; set; } @@ -139,7 +151,8 @@ public class ProceduralParameters { public List reflections; - public MaterialProperties? ceilingMaterial = new MaterialProperties() { + public MaterialProperties? ceilingMaterial = new MaterialProperties() + { tilingDivisorX = 1.0f, tilingDivisorY = 1.0f }; @@ -156,14 +169,16 @@ public class ProceduralParameters { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class SerializableCollider { + public class SerializableCollider + { public Vector3[] vertices; public int[] triangles; } [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class PhysicalProperties { + public class PhysicalProperties + { public float mass = 1; public float drag = 0; public float angularDrag = 0.05f; @@ -173,7 +188,8 @@ public class PhysicalProperties { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class ObjectAnnotations { + public class ObjectAnnotations + { public string objectType = "Undefined"; public string primaryProperty = "Undefined"; public string[]? secondaryProperties = null; @@ -181,10 +197,12 @@ public class ObjectAnnotations { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class Ceiling { + public class Ceiling + { public string id { get; set; } public List polygon { get; set; } - public MaterialProperties material = new MaterialProperties() { + public MaterialProperties material = new MaterialProperties() + { tilingDivisorX = null, tilingDivisorY = null }; @@ -192,10 +210,12 @@ public class Ceiling { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class RoomHierarchy { + public class RoomHierarchy + { public string id { get; set; } public string roomType { get; set; } - public MaterialProperties floorMaterial = new MaterialProperties() { + public MaterialProperties floorMaterial = new MaterialProperties() + { tilingDivisorX = 1.0f, tilingDivisorY = 1.0f }; @@ -210,7 +230,8 @@ public class RoomHierarchy { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class PolygonWall { + public class PolygonWall + { public string id { get; set; } public List polygon { get; set; } public string roomId { get; set; } @@ -223,22 +244,26 @@ public class PolygonWall { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class BoundingBox { + public class BoundingBox + { public Vector3 min { get; set; } public Vector3 max { get; set; } - public Vector3 center() { + public Vector3 center() + { return this.min + (this.max - this.min) / 2.0f; } - public Vector3 size() { + public Vector3 size() + { return (this.max - this.min); } } [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class BoundingBoxWithOffset { + public class BoundingBoxWithOffset + { public Vector3 min { get; set; } public Vector3 max { get; set; } public Vector3 offset { get; set; } @@ -246,14 +271,16 @@ public class BoundingBoxWithOffset { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class VectorXZ { + public class VectorXZ + { public int x; public int z; } [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class Window : WallRectangularHole { + public class Window : WallRectangularHole + { public string id { get; set; } public string room0 { get; set; } public string room1 { get; set; } @@ -273,7 +300,8 @@ public class Window : WallRectangularHole { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class FlexibleRotation { + public class FlexibleRotation + { // Support Angle-Axis rotation (axis, degrees) public Vector3 axis; public float degrees; @@ -282,30 +310,38 @@ public class FlexibleRotation { private float? _x; private float? _y; private float? _z; - public float? x { + public float? x + { get { return _x; } - set { + set + { _x = value; setAngleAxis(); } } - public float? y { + public float? y + { get { return _y; } - set { + set + { _y = value; setAngleAxis(); } } - public float? z { + public float? z + { get { return _z; } - set { + set + { _z = value; setAngleAxis(); } } - private void setAngleAxis() { - if (x == null || y == null || z == null) { + private void setAngleAxis() + { + if (x == null || y == null || z == null) + { return; } Vector3 rot = new Vector3(x: x.Value, y: y.Value, z: z.Value); @@ -314,41 +350,48 @@ private void setAngleAxis() { (axis.x == Mathf.Infinity || axis.x == -Mathf.Infinity || float.IsNaN(axis.x)) && (axis.y == Mathf.Infinity || axis.y == -Mathf.Infinity || float.IsNaN(axis.y)) && (axis.z == Mathf.Infinity || axis.z == -Mathf.Infinity || float.IsNaN(axis.z)) - ) { + ) + { axis = Vector3.up; } - if (degrees == Mathf.Infinity || degrees == -Mathf.Infinity || float.IsNaN(degrees)) { + if (degrees == Mathf.Infinity || degrees == -Mathf.Infinity || float.IsNaN(degrees)) + { degrees = 0; } } - public static FlexibleRotation fromQuaternion(Quaternion quat) { + public static FlexibleRotation fromQuaternion(Quaternion quat) + { var r = new FlexibleRotation(); quat.ToAngleAxis(out r.degrees, out r.axis); return r; } - public Quaternion toQuaternion() { + public Quaternion toQuaternion() + { return Quaternion.AngleAxis(degrees, axis); } } [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class Child { + public class Child + { public string type { get; set; } } [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class Taxonomy { + public class Taxonomy + { public string name; public List children = null; } [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class HouseObject { + public class HouseObject + { public string id { get; set; } //set to SimObjPhysics.objectId public Vector3 position { get; set; } public FlexibleRotation rotation { get; set; } @@ -374,14 +417,16 @@ public class HouseObject { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class Roof { + public class Roof + { public MaterialProperties material { get; set; } public string assetId { get; set; } } [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class ProceduralHouse { + public class ProceduralHouse + { public ProceduralParameters proceduralParameters { get; set; } public string id { get; set; } public List rooms { get; set; } = new List(); @@ -395,7 +440,8 @@ public class ProceduralHouse { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class NavMeshConfig { + public class NavMeshConfig + { public int id; public float agentRadius; public int? tileSize; @@ -408,7 +454,8 @@ public class NavMeshConfig { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class HouseMetadata { + public class HouseMetadata + { public Dictionary agentPoses { get; set; } public string schema { get; set; } = null; @@ -417,7 +464,8 @@ public class HouseMetadata { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class AgentPose { + public class AgentPose + { public float horizon; public Vector3 position; public Vector3 rotation; @@ -426,7 +474,8 @@ public class AgentPose { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class MaterialProperties { + public class MaterialProperties + { // TODO: move material id, color (as albedo) and tiling divisors public string name { get; set; } public SerializableColor color { get; set; } @@ -438,7 +487,8 @@ public class MaterialProperties { public float? smoothness; } - public interface WallRectangularHole { + public interface WallRectangularHole + { string id { get; set; } string assetId { get; set; } string room0 { get; set; } @@ -456,7 +506,8 @@ public interface WallRectangularHole { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class Wall { + public class Wall + { public string id; public float height; public Vector3 p0; @@ -476,7 +527,8 @@ public class Wall { [Serializable] [MessagePackObject(keyAsPropertyName: true)] - public class ProceduralAsset { + public class ProceduralAsset + { public Vector3[] vertices; public Vector3[] normals; public string name; @@ -496,10 +548,13 @@ public class ProceduralAsset { public string parentTexturesDir = null; } - public static class ExtensionMethods { - public static T DeepClone(this T obj) { + public static class ExtensionMethods + { + public static T DeepClone(this T obj) + { // Don't serialize a null object, simply return the default for that object - if (ReferenceEquals(obj, null)) { + if (ReferenceEquals(obj, null)) + { return default; } @@ -511,7 +566,8 @@ public static T DeepClone(this T obj) { var str = Newtonsoft.Json.JsonConvert.SerializeObject( obj, Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { + new Newtonsoft.Json.JsonSerializerSettings() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver } @@ -526,7 +582,8 @@ public static TValue GetValueOrDefault( this Dictionary dictionary, TKey key, TValue defaultValue = default(TValue) - ) { + ) + { TValue value; return dictionary.TryGetValue(key, out value) ? value : defaultValue; } @@ -535,12 +592,16 @@ public static int AddCount( this Dictionary dictionary, TKey key, int count = 1 - ) { + ) + { int value; dictionary.TryGetValue(key, out value); - if (dictionary.ContainsKey(key)) { + if (dictionary.ContainsKey(key)) + { dictionary[key] = dictionary[key] + count; - } else { + } + else + { dictionary[key] = count; } return dictionary[key]; diff --git a/unity/Assets/Scripts/ProceduralRoomEditor.cs b/unity/Assets/Scripts/ProceduralRoomEditor.cs index f30d4734ed..ac8318f3e5 100644 --- a/unity/Assets/Scripts/ProceduralRoomEditor.cs +++ b/unity/Assets/Scripts/ProceduralRoomEditor.cs @@ -17,11 +17,13 @@ #endif [ExecuteInEditMode] -public class ProceduralRoomEditor : MonoBehaviour { +public class ProceduralRoomEditor : MonoBehaviour +{ private List<(Vector3, Color)> spheres = new List<(Vector3, Color)>(); public ProceduralHouse loadedHouse; - protected class NamedSimObj { + protected class NamedSimObj + { public string assetId; public string id; public SimObjPhysics simObj; @@ -33,7 +35,8 @@ protected class NamedSimObj { #if UNITY_EDITOR - private ProceduralHouse readHouseFromJson(string fileName) { + private ProceduralHouse readHouseFromJson(string fileName) + { var path = BuildLayoutPath(fileName); Debug.Log($"Loading: '{path}'"); var jsonStr = System.IO.File.ReadAllText(path); @@ -44,10 +47,12 @@ private ProceduralHouse readHouseFromJson(string fileName) { return obj.ToObject(); } - private List assignObjectIds() { + private List assignObjectIds() + { var root = GameObject.Find(ProceduralTools.DefaultObjectsRootName); //var counter = new Dictionary(); - if (root != null) { + if (root != null) + { var simobjs = root.transform.GetComponentsInChildren(); var namedObjects = simobjs @@ -56,7 +61,8 @@ private List assignObjectIds() { .SelectMany(objsOfType => objsOfType.Select( (simObj, index) => - new NamedSimObj { + new NamedSimObj + { assetId = !string.IsNullOrEmpty(simObj.assetID) ? simObj.assetID : PrefabNameRevert.GetPrefabAssetName(simObj.gameObject), @@ -66,7 +72,8 @@ private List assignObjectIds() { ) ) .ToList(); - foreach (var namedObj in namedObjects) { + foreach (var namedObj in namedObjects) + { Debug.Log( $" Renaming obj: {namedObj.simObj.gameObject.name} to {namedObj.id}, assetId: {namedObj.assetId}" ); @@ -78,14 +85,17 @@ private List assignObjectIds() { // foreach (var namedObj in this.namedSimObjects) { // Debug.Log($" Renamed obj: {namedObj.simObj.gameObject.name} to {namedObj.id}, assetId: {namedObj.assetId}" ); // } - } else { + } + else + { Debug.LogError($"No root object '{ProceduralTools.DefaultObjectsRootName}'"); return null; } } [Button(Expanded = true)] - public void LoadLayout() { + public void LoadLayout() + { this.loadedHouse = readHouseFromJson(this.layoutJSONFilename); var houseObj = ProceduralTools.CreateHouse( @@ -94,7 +104,8 @@ public void LoadLayout() { ); } - private List getPolygonFromWallPoints(Vector3 p0, Vector3 p1, float height) { + private List getPolygonFromWallPoints(Vector3 p0, Vector3 p1, float height) + { return new List() { p0, p1, p1 + Vector3.up * height, p0 + Vector3.up * height }; } @@ -103,12 +114,14 @@ 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) { + if (debug) + { Debug.Log( " wall " + $"name: '{wall.gameObject.name}' " @@ -137,14 +150,18 @@ private List getPolygonFromWallObject( wall.transform.TransformPoint(box.center + new Vector3(-offset.x, offset.y, 0.0f)), }; - if (!reverse) { + if (!reverse) + { return r; - } else { + } + else + { return new List() { r[1], r[0], r[3], r[2] }; } } - public class ConnectionAndWalls { + public class ConnectionAndWalls + { public WallRectangularHole connection; public List<(PolygonWall wall, string afterWallId)> walls; @@ -157,12 +174,14 @@ private IEnumerable serializeConnections( string prefix, Dictionary wallMap, Dictionary connectionMap = null - ) { + ) + { var flippedForward = filterType == SimObjType.Window; var connectionsWithWalls = connections .Where(s => s.Type == filterType) .Select( - (d, i) => { + (d, i) => + { var id = d.gameObject.name; // Debug.Log($"----- {prefix} " + d.gameObject.name); @@ -229,7 +248,8 @@ private IEnumerable serializeConnections( var normal = Vector3.Cross((p1World - p0World).normalized, p0UpWorld); - var colliderDistances = wallColliders.Select(collider => { + 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)); @@ -252,7 +272,8 @@ private IEnumerable serializeConnections( var upVec = (topP0 - cP0).normalized; - return new { + return new + { collider = collider, p0SqrDistance = (p1World - cP0).sqrMagnitude, p1SqrDistance = (p0World - cP1).sqrMagnitude, @@ -286,7 +307,8 @@ bool wallPointOnConnectionLine( 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); @@ -326,7 +348,8 @@ string name 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}" ); @@ -392,7 +415,8 @@ bool pointOnWallLine( Vector3 origin, string name, string side = "" - ) { + ) + { var originRef = new Vector3(origin.x, p.y, origin.z); var originToP = (p - originRef); @@ -413,7 +437,8 @@ bool pointOnWallLine( 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)))} " ); @@ -448,7 +473,8 @@ bool pointOnWallLine( // }; var wallRight = colliderDistances.Aggregate( - new { + new + { collider = box, p0SqrDistance = float.MaxValue, p1SqrDistance = float.MaxValue, @@ -474,7 +500,8 @@ bool pointOnWallLine( // && Vector3.Dot(next.normal, normal) > 0 var wallLeft = colliderDistances.Aggregate( - new { + new + { collider = box, p0SqrDistance = float.MaxValue, p1SqrDistance = float.MaxValue, @@ -483,10 +510,12 @@ bool pointOnWallLine( height = 0.0f, normal = new Vector3() }, - (min, next) => { + (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") { + 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)}" ); @@ -512,7 +541,8 @@ bool pointOnWallLine( Debug.Log($"^^^^^^^^^^^^ Wall left p0: {wallLeft.p0} p1: {wallLeft.p1}"); var backWallClosestLeft = colliderDistances.Aggregate( - new { + new + { collider = box, p0SqrDistance = float.MaxValue, p1SqrDistance = float.MaxValue, @@ -537,7 +567,8 @@ bool pointOnWallLine( ); var backWallClosestRight = colliderDistances.Aggregate( - new { + new + { collider = box, p0SqrDistance = float.MaxValue, p1SqrDistance = float.MaxValue, @@ -679,7 +710,8 @@ bool pointOnWallLine( .sharedMaterial; var lenn = (wall.polygon[1] - wall.polygon[0]).magnitude; // var height = - var wallRev = new PolygonWall { + var wallRev = new PolygonWall + { id = $"wall_{id}_back", roomId = connectionProps?.OpenToRoomId, polygon = new List() @@ -692,7 +724,8 @@ bool pointOnWallLine( // polygon = getPolygonFromWallPoints(p0, p1, backWallClosestRight.height), // TODO get material somehow // material = connectionProps?.openFromWallMaterial?.name - material = new MaterialProperties() { + material = new MaterialProperties() + { name = material.name, tilingDivisorX = lenn / material.mainTextureScale.x, tilingDivisorY = @@ -728,8 +761,10 @@ bool pointOnWallLine( // assetId = assetId == null ? d.assetID : assetId; - if (filterType == SimObjType.Doorway) { - connection = new Thor.Procedural.Data.Door { + if (filterType == SimObjType.Doorway) + { + connection = new Thor.Procedural.Data.Door + { id = id, room0 = connectionProps?.OpenFromRoomId, @@ -753,9 +788,12 @@ bool pointOnWallLine( openness = (connectionProps?.IsOpen).GetValueOrDefault() ? 1.0f : 0.0f, assetId = assetId }; - } else if (filterType == SimObjType.Window) { + } + else if (filterType == SimObjType.Window) + { var yMin = p0World.y - wallLeft.p1.y; - connection = new Thor.Procedural.Data.Window { + connection = new Thor.Procedural.Data.Window + { id = id, room0 = connectionProps?.OpenFromRoomId, @@ -860,7 +898,8 @@ bool pointOnWallLine( $"~~~~~~~~~~ Walls to delete {string.Join(", ", toDelete.Select(o => o.collider.name))}" ); - return new ConnectionAndWalls() { + return new ConnectionAndWalls() + { connection = connection, walls = wallsToCreate, wallIdsToDelete = toDelete.Select(o => o.collider.name).ToList() @@ -924,8 +963,10 @@ bool pointOnWallLine( // return doorWalls; // } - void OnDrawGizmosSelected() { - foreach (var (c, color) in spheres) { + void OnDrawGizmosSelected() + { + foreach (var (c, color) in spheres) + { Gizmos.color = color; Gizmos.DrawSphere(c, 0.2f); } @@ -938,15 +979,18 @@ private PolygonWall createNewWall( Vector3 p1, float height, Material material - ) { + ) + { var len = (p1 - p0).magnitude; - return new PolygonWall { + return new PolygonWall + { id = id, roomId = connectionProps?.OpenFromRoomId, 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 @@ -954,7 +998,8 @@ Material material }; } - private ProceduralHouse regenerateWallsData(ProceduralHouse house) { + private ProceduralHouse regenerateWallsData(ProceduralHouse house) + { // if (this.loadedHouse == null) { // this.loadedHouse = readHouseFromJson(this.layoutJSONFilename); // } @@ -967,16 +1012,19 @@ private ProceduralHouse regenerateWallsData(ProceduralHouse house) { var wallsJson = wallsGOs .Select( - (w, i) => { + (w, i) => + { var material = w.GetComponent().sharedMaterial; var poly = getPolygonFromWallObject(w.gameObject); var box = w.GetComponent(); - return new PolygonWall { + return new PolygonWall + { id = w.gameObject.name, roomId = w.GetComponentInChildren().RoomId, polygon = poly, - material = new MaterialProperties() { + material = new MaterialProperties() + { name = material.name, tilingDivisorX = box.size.x / material.mainTextureScale.x, tilingDivisorY = box.size.y / material.mainTextureScale.y @@ -1022,7 +1070,8 @@ private ProceduralHouse regenerateWallsData(ProceduralHouse house) { var wallWithInsertLocation = allNewConnections .SelectMany(s => s.walls) - .Select(wallIdPair => { + .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 ( @@ -1035,7 +1084,8 @@ private ProceduralHouse regenerateWallsData(ProceduralHouse house) { }); var toDeleteSet = new HashSet(allNewConnections.SelectMany(w => w.wallIdsToDelete)); //wallsJson = wallsJson.Where(w => !toDeleteSet.Contains(w.id)).ToList(); - foreach (var pair in wallWithInsertLocation) { + foreach (var pair in wallWithInsertLocation) + { wallsJson.Insert(pair.index + 1, pair.wall); } @@ -1051,7 +1101,8 @@ private ProceduralHouse regenerateWallsData(ProceduralHouse house) { ); // house.doors = doors.ToList(); // house.windows = windows.ToList(); - return new ProceduralHouse { + return new ProceduralHouse + { proceduralParameters = house.proceduralParameters, id = house.id, rooms = house.rooms, @@ -1072,26 +1123,30 @@ private ProceduralHouse regenerateWallsData(ProceduralHouse house) { // } [Button] - public void AssigObjectIds() { + public void AssigObjectIds() + { this.assignObjectIds(); } [Button] - public void ReloadScene() { + public void ReloadScene() + { var scene = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene(); UnityEditor.SceneManagement.EditorSceneManager.OpenScene(scene.path); } [Button(Expanded = true)] - public void SerializeSceneFromGameObjects(string outFilename) { + public void SerializeSceneFromGameObjects(string outFilename) + { // var path = BuildLayoutPath(layoutJSONFilename); // var jsonStr = System.IO.File.ReadAllText(path); // JObject jsonObj = JObject.Parse(jsonStr); // this.loadedHouse = jsonObj.ToObject(); // if (this.loadedHouse != null) { - if (String.IsNullOrWhiteSpace(this.layoutJSONFilename)) { + if (String.IsNullOrWhiteSpace(this.layoutJSONFilename)) + { Debug.LogError( "No base layout filename provided, need this to get procedural params. Add a 'layoutJSONFilename'" ); @@ -1121,7 +1176,8 @@ public void SerializeSceneFromGameObjects(string outFilename) { var skipObjects = new HashSet() { SimObjType.Doorway, SimObjType.Window }; house.objects = simObjects .Where(obj => !skipObjects.Contains(obj.simObj.Type)) - .Select(obj => { + .Select(obj => + { Vector3 axis; float degrees; obj.simObj.transform.rotation.ToAngleAxis(out degrees, out axis); @@ -1143,25 +1199,29 @@ public void SerializeSceneFromGameObjects(string outFilename) { LayerMask.GetMask("NonInteractive") ); string room = ""; - if (didHit) { + if (didHit) + { room = hit.collider.transform.GetComponentInParent()?.ObjectID; } Debug.Log("Processing " + obj.assetId + " ..."); - if (!assetDb.ContainsKey(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() { + 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() { + boundingBox = new BoundingBox() + { min = bb.center - (bb.size / 2.0f), max = bb.center + (bb.size / 2.0f) }, @@ -1182,7 +1242,8 @@ public void SerializeSceneFromGameObjects(string outFilename) { GameObject floorRoot; floorRoot = GameObject.Find(house.id); - if (floorRoot == null) { + if (floorRoot == null) + { floorRoot = GameObject.Find(ProceduralTools.DefaultHouseRootObjectName); } @@ -1194,7 +1255,8 @@ public void SerializeSceneFromGameObjects(string outFilename) { ); house.rooms = house - .rooms.Select(r => { + .rooms.Select(r => + { r.roomType = roomIdToProps[r.id].roomProps.RoomType; // TODO add more room annotations here return r; @@ -1214,7 +1276,8 @@ public void SerializeSceneFromGameObjects(string outFilename) { var gatheredLights = new List(); house.proceduralParameters.lights = sceneLights - .Select(l => { + .Select(l => + { RaycastHit hit; var didHit = Physics.Raycast( l.transform.position, @@ -1224,22 +1287,26 @@ public void SerializeSceneFromGameObjects(string outFilename) { LayerMask.GetMask("NonInteractive") ); string room = ""; - if (didHit) { + if (didHit) + { room = hit.collider.transform.GetComponentInParent()?.ObjectID; } // didHit = Physics.Raycast(l.transform.position, -Vector3.up,out hit, 1.0f, LayerMask.GetMask("SimObjVisible", "Procedural1", "Procedural2", "Procedural3", "Procedural0")); string objectLink = ""; var parentSim = l.GetComponentInParent(); //SimObjType.Lamp - if (parentSim != null) { //( parentSim?.ObjType).GetValueOrDefault() == SimObjType.FloorLamp ) + if (parentSim != null) + { //( parentSim?.ObjType).GetValueOrDefault() == SimObjType.FloorLamp ) objectLink = parentSim.ObjectID; } // if (didHit) { // objectLink = hit.transform.GetComponentInParent()?.objectID; // } ShadowParameters sp = null; - if (l.shadows != LightShadows.None) { - sp = new ShadowParameters() { + if (l.shadows != LightShadows.None) + { + sp = new ShadowParameters() + { strength = l.shadowStrength, type = Enum.GetName(typeof(LightShadows), l.shadows), normalBias = l.shadowNormalBias, @@ -1251,7 +1318,8 @@ public void SerializeSceneFromGameObjects(string outFilename) { ) }; } - return new LightParameters() { + return new LightParameters() + { id = l.gameObject.name, type = LightType.GetName(typeof(LightType), l.type), position = l.transform.position, @@ -1260,7 +1328,8 @@ public void SerializeSceneFromGameObjects(string outFilename) { intensity = l.intensity, indirectMultiplier = l.bounceIntensity, range = l.range, - rgb = new SerializableColor() { + rgb = new SerializableColor() + { r = l.color.r, g = l.color.g, b = l.color.b, @@ -1280,8 +1349,10 @@ public void SerializeSceneFromGameObjects(string outFilename) { .GetComponentsInChildren() ); house.proceduralParameters.reflections = probes - .Select(probeComp => { - return new ProbeParameters() { + .Select(probeComp => + { + return new ProbeParameters() + { background = SerializableColor.fromUnityColor(probeComp.backgroundColor), intensity = probeComp.intensity, boxSize = probeComp.size, @@ -1293,7 +1364,8 @@ public void SerializeSceneFromGameObjects(string outFilename) { }) .ToList(); - foreach (var probe in house.proceduralParameters.reflections) { + foreach (var probe in house.proceduralParameters.reflections) + { var go = new GameObject(probe.id); go.transform.position = probe.position; @@ -1306,7 +1378,8 @@ public void SerializeSceneFromGameObjects(string outFilename) { probeComp.shadowDistance = probe.shadowDistance; } - house.proceduralParameters.ceilingMaterial = new MaterialProperties() { + house.proceduralParameters.ceilingMaterial = new MaterialProperties() + { name = GameObject .Find(ProceduralTools.DefaultCeilingRootObjectName) .GetComponentInChildren() @@ -1319,7 +1392,8 @@ public void SerializeSceneFromGameObjects(string outFilename) { var jsonResolver = new ShouldSerializeContractResolver(); var outJson = JObject.FromObject( house, - new Newtonsoft.Json.JsonSerializer() { + new Newtonsoft.Json.JsonSerializer() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver } @@ -1329,9 +1403,11 @@ public void SerializeSceneFromGameObjects(string outFilename) { System.IO.File.WriteAllText(outPath, outJson.ToString()); } - private string BuildLayoutPath(string layoutFilename) { + private string BuildLayoutPath(string layoutFilename) + { layoutFilename = layoutFilename.Trim(); - if (!layoutFilename.EndsWith(".json")) { + if (!layoutFilename.EndsWith(".json")) + { layoutFilename += ".json"; } var path = Application.dataPath + LoadBasePath + layoutFilename; @@ -1339,7 +1415,8 @@ private string BuildLayoutPath(string layoutFilename) { } [UnityEditor.MenuItem("Procedural/Build Asset Database")] - public static void BuildAssetDB() { + 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())); @@ -1354,7 +1431,8 @@ public static void BuildAssetDB() { } [UnityEditor.MenuItem("Procedural/Filter Asset Database")] - public static void ReduceAssetDb() { + public static void ReduceAssetDb() + { var proceduralADB = GameObject.FindObjectOfType(); var house = readHouseFromJsonStatic("test_0_out.json"); @@ -1373,14 +1451,16 @@ public static void ReduceAssetDb() { 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))); 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) { + public static IEnumerable getAllMaterials(ProceduralHouse house) + { return house .rooms.SelectMany(r => r.ceilings.Select(c => c.material.name) @@ -1390,14 +1470,16 @@ public static IEnumerable getAllMaterials(ProceduralHouse house) { .Concat(new List() { house.proceduralParameters.ceilingMaterial.name }); } - public static IEnumerable getAssetIds(ProceduralHouse house) { + public static IEnumerable getAssetIds(ProceduralHouse house) + { return house .objects.Select(o => o.assetId) .Concat(house.windows.Select(w => w.assetId)) .Concat(house.doors.Select(d => d.assetId)); } - public static ProceduralHouse readHouseFromJsonStatic(string fileName) { + public static ProceduralHouse readHouseFromJsonStatic(string fileName) + { var path = BuildLayoutPathStatic(fileName); Debug.Log($"Loading: '{path}'"); var jsonStr = System.IO.File.ReadAllText(path); @@ -1408,10 +1490,12 @@ public static ProceduralHouse readHouseFromJsonStatic(string fileName) { return obj.ToObject(); } - public static string BuildLayoutPathStatic(string layoutFilename) { + public static string BuildLayoutPathStatic(string layoutFilename) + { layoutFilename = layoutFilename.Trim(); string LoadBasePath = "/Resources/rooms/"; - if (!layoutFilename.EndsWith(".json")) { + if (!layoutFilename.EndsWith(".json")) + { layoutFilename += ".json"; } var path = Application.dataPath + LoadBasePath + layoutFilename; diff --git a/unity/Assets/Scripts/ProceduralTemplates.cs b/unity/Assets/Scripts/ProceduralTemplates.cs index 48c584a9e1..bda1bd3915 100644 --- a/unity/Assets/Scripts/ProceduralTemplates.cs +++ b/unity/Assets/Scripts/ProceduralTemplates.cs @@ -15,9 +15,11 @@ using UnityEditor; #endif -namespace Thor.Procedural { +namespace Thor.Procedural +{ [Serializable] - public class HouseTemplate { + public class HouseTemplate + { public string id; public string layout; public HouseMetadata metadata; @@ -30,7 +32,8 @@ public class HouseTemplate { } [Serializable] - public class RoomTemplate { + public class RoomTemplate + { public PolygonWall wallTemplate; public RoomHierarchy floorTemplate; @@ -38,11 +41,13 @@ public class RoomTemplate { public float wallHeight = 2.0f; } - public static class Templates { + public static class Templates + { public static ProceduralHouse createHouseFromTemplate( HouseTemplate houseTemplate, int outsideBoundaryId = 0 - ) { + ) + { var layout = houseTemplate.layout; var objects = houseTemplate.objectsLayouts; @@ -50,7 +55,8 @@ public static ProceduralHouse createHouseFromTemplate( l.Split('\n') .Select(x => x.Split(' ') - .Select(i => { + .Select(i => + { int res; var isInt = int.TryParse(i, out res); return (res, isInt); @@ -80,7 +86,8 @@ public static ProceduralHouse createHouseFromTemplate( IEnumerable> holePairs = new List>(); - if (houseTemplate.doors != null) { + if (houseTemplate.doors != null) + { holePairs = holePairs.Concat( houseTemplate.doors.Select(d => new KeyValuePair( d.Key, @@ -88,7 +95,8 @@ d.Value as WallRectangularHole )) ); } - if (houseTemplate.windows != null) { + if (houseTemplate.windows != null) + { holePairs = holePairs.Concat( houseTemplate.windows.Select(d => new KeyValuePair( d.Key, @@ -110,7 +118,8 @@ d.Value as WallRectangularHole (row, column + 1) }; - if (layoutIntArray.Select(r => r.Length).Distinct().Count() > 1) { + if (layoutIntArray.Select(r => r.Length).Distinct().Count() > 1) + { throw new ArgumentException("Invalid layout all rows must be the same size"); } @@ -126,10 +135,12 @@ d.Value as WallRectangularHole objectLayer.SelectMany( (objectRow, row) => objectRow.Select( - (id, column) => { + (id, column) => + { // ignore no door ones var isHole = holeTemplates.Keys.Contains(id); - if (isHole) { + if (isHole) + { var neighborIndices = new List<(int row, int column)>() { (row, column) @@ -154,7 +165,8 @@ d.Value as WallRectangularHole var neighborFunctions = neighborIndices .Take(2) .Select((index, i) => (index, i)) - .Where(v => { + .Where(v => + { return ProceduralTools.withinArrayBoundary( v.index, rows, @@ -168,7 +180,8 @@ d.Value as WallRectangularHole .Select(tup => nf[tup.i]); var twoHeaded = false; - if (neighborFunctions.Count() > 1) { + if (neighborFunctions.Count() > 1) + { var cornerLeftTopNeighbor = ( row: row - 1, column: column - 1 @@ -182,7 +195,8 @@ d.Value as WallRectangularHole && objectArray[layer][ cornerLeftTopNeighbor.row ][cornerLeftTopNeighbor.column] == id - ) { + ) + { neighborFunctions = new List< Func<(int, int), (int, int)> >() @@ -190,13 +204,16 @@ d.Value as WallRectangularHole ((int row, int col) c) => (c.row - 1, c.col - 1) }; - } else { + } + else + { twoHeaded = true; } } var doorStarts = neighborFunctions - .Select(f => { + .Select(f => + { var minIndex = (row, column); var prevMinIndex = minIndex; while ( @@ -208,7 +225,8 @@ d.Value as WallRectangularHole && objectArray[layer][minIndex.row][ minIndex.column ] == id - ) { + ) + { prevMinIndex = minIndex; minIndex = f(minIndex); } @@ -216,15 +234,18 @@ d.Value as WallRectangularHole }) .ToList(); - foreach (var doorStartIndex in doorStarts) { + foreach (var doorStartIndex in doorStarts) + { (string, int, (int, int)) key = ( id, layer, doorStartIndex ); - if (doorDict.ContainsKey(key)) { + if (doorDict.ContainsKey(key)) + { var connected = holeContinuation; - if (!twoHeaded) { + if (!twoHeaded) + { var k = holeContinuation.SelectMany(c => doorDict[(id, layer, c)] ); @@ -233,7 +254,9 @@ d.Value as WallRectangularHole doorDict[key] = new HashSet<(int, int)>( doorDict[key].Union(connected) ); - } else { + } + else + { doorDict[key] = new HashSet<(int, int)>( holeContinuation ); @@ -260,7 +283,8 @@ d.Value as WallRectangularHole new Dictionary<((double, double), (double, double)), string>(); var roomsWithWalls = roomIds .Where(id => id != outsideBoundaryId) - .Select(intId => { + .Select(intId => + { var id = intId.ToString(); RoomTemplate template; var inDict = houseTemplate.rooms.TryGetValue(id, out template); @@ -284,9 +308,12 @@ d.Value as WallRectangularHole 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 = @@ -301,7 +328,8 @@ d.Value as WallRectangularHole var walls = walls2D .Select( - (w, i) => { + (w, i) => + { var wallCopy = template.wallTemplate.DeepClone(); wallCopy.id = wallToId(i, room.id, template.wallTemplate.id); wallCopy.polygon = new List() @@ -350,7 +378,8 @@ d.Value as WallRectangularHole var holes = doorDict .SelectMany( - (d, i) => { + (d, i) => + { var holeTemplateId = d.Key.id; var holeStart = d.Key.index; // d.Value.Min(); var holeEnd = d.Value.Max(); @@ -359,17 +388,24 @@ d.Value as WallRectangularHole var isDoor = hole is Data.Door; var isWindow = hole is Data.Window; - if (inDict) { - if (isDoor) { + if (inDict) + { + if (isDoor) + { hole = (hole as Data.Door).DeepClone(); - } else if (isWindow) { + } + else if (isWindow) + { hole = (hole as Data.Window).DeepClone(); } - } else { + } + else + { hole = getDefaultHoleTemplate(); } - if (hole == null) { + if (hole == null) + { return new List() { }; } @@ -385,7 +421,8 @@ d.Value as WallRectangularHole !string.IsNullOrEmpty(hole.room0) && isInt && room0ArrayValue == room1Id - ) { + ) + { var tmp = room0Id; room0Id = room1Id; room1Id = tmp; @@ -400,7 +437,8 @@ d.Value as WallRectangularHole column: holeEnd.column - holeStart.column ); - if (doorDir.row > 1 || doorDir.column > 1) { + if (doorDir.row > 1 || doorDir.column > 1) + { throw new ArgumentException(" invalid door thickness with id " + d.Key); } @@ -435,7 +473,8 @@ d.Value as WallRectangularHole column: holeStart.column + holeAdjustOffset.column ); - var wall0 = room0Walls2D.Find(x => { + var wall0 = room0Walls2D.Find(x => + { var xDiff = Math.Abs(holeStartCoords.row - x.Item1.row); var zDiff = Math.Abs(holeStartCoords.column - x.Item1.column); @@ -459,7 +498,8 @@ d.Value as WallRectangularHole && Math.Abs(dot) < 1e-4; }); - var wall1 = room1Walls2D.Find(x => { + var wall1 = room1Walls2D.Find(x => + { var xDiff = Math.Abs(holeStartCoords.row - x.Item1.row); var zDiff = Math.Abs(holeStartCoords.column - x.Item1.column); @@ -492,7 +532,8 @@ d.Value as WallRectangularHole if ( string.IsNullOrEmpty(hole.assetId) || !assetMap.ContainsKey(hole.assetId) - ) { + ) + { return new List() { }; } @@ -500,7 +541,8 @@ d.Value as WallRectangularHole Debug.Log("---- Hole offset null? " + (hole == null)); - if (holeOffset == null) { + if (holeOffset == null) + { return new List() { }; } @@ -546,13 +588,15 @@ d.Value as WallRectangularHole var strRoomIds = new HashSet(roomIds.Select(x => x.ToString())); var houseObjects = objectCoordinates .Where(item => !doorIds.Contains(item.id) && !strRoomIds.Contains(item.id)) - .SelectMany(item => { + .SelectMany(item => + { var coord = item.Item3; var result = new List(); var template = houseTemplate.objects.GetValueOrDefault(item.id, null); - if (template != null) { + if (template != null) + { var obj = template.DeepClone(); var count = objectIdCounter.AddCount(item.id); @@ -561,7 +605,8 @@ d.Value as WallRectangularHole var floorTemplate = houseTemplate.rooms[roomId.ToString()]; obj.room = roomIntToId(roomId, floorTemplate.floorTemplate); - if (string.IsNullOrEmpty(obj.assetId) || !assetMap.ContainsKey(obj.assetId)) { + if (string.IsNullOrEmpty(obj.assetId) || !assetMap.ContainsKey(obj.assetId)) + { return result; } @@ -580,12 +625,14 @@ d.Value as WallRectangularHole ) + centerOffset; // - new Vector3(centerOffset.x, -centerOffset.y, centerOffset.z); obj.rotation = obj.rotation == null - ? new FlexibleRotation() { + ? new FlexibleRotation() + { axis = new Vector3(0.0f, 1.0f, 0.0f), degrees = 0 } : obj.rotation; - if (asset != null) { + if (asset != null) + { result.Add(obj); } } @@ -593,11 +640,13 @@ d.Value as WallRectangularHole return result; }); - HouseMetadata metadata = new HouseMetadata { + HouseMetadata metadata = new HouseMetadata + { schema = ProceduralTools.CURRENT_HOUSE_SCHEMA }; - return new ProceduralHouse() { + return new ProceduralHouse() + { metadata = new HouseMetadata() { schema = houseTemplate.metadata.schema }, proceduralParameters = houseTemplate.proceduralParameters.DeepClone(), id = !string.IsNullOrEmpty(houseTemplate.id) ? houseTemplate.id : houseId(), @@ -609,34 +658,43 @@ d.Value as WallRectangularHole }; } - public static RoomTemplate getDefaultRoomTemplate() { - return new RoomTemplate() { - wallTemplate = new PolygonWall() { + public static RoomTemplate getDefaultRoomTemplate() + { + return new RoomTemplate() + { + wallTemplate = new PolygonWall() + { polygon = new List() { new Vector3(0.0f, 3.0f, 0.0f) } }, floorTemplate = new RoomHierarchy() { } }; } - public static WallRectangularHole getDefaultHoleTemplate() { + 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) { + > 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++) { + 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) { + if (a != b) + { walls[(Math.Min(a, b), Math.Max(a, b))].Add(((row - 1, col), (row, col))); } b = floorplan[row + 1][col]; - if (a != b) { + if (a != b) + { walls[(Math.Min(a, b), Math.Max(a, b))].Add(((row, col - 1), (row, col))); } } @@ -650,33 +708,43 @@ public static Dictionary< 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) { + foreach (var item in walls) + { var wallGroupId = item.Key; var wallPairs = item.Value; var wallMap = new Dictionary<(int, int), HashSet<(int, int)>>(); - foreach (var wall in wallPairs) { - if (!wallMap.ContainsKey(wall.Item1)) { + foreach (var wall in wallPairs) + { + if (!wallMap.ContainsKey(wall.Item1)) + { wallMap[wall.Item1] = new HashSet<(int, int)>(); } wallMap[wall.Item1].Add(wall.Item2); } var didUpdate = true; - while (didUpdate) { + while (didUpdate) + { didUpdate = false; var wallMapCopy = wallMap.Keys.ToDictionary(_ => _, _ => wallMap[_]); - foreach (var w1_1 in wallMapCopy.Keys) { - if (!wallMap.ContainsKey(w1_1)) { + foreach (var w1_1 in wallMapCopy.Keys) + { + if (!wallMap.ContainsKey(w1_1)) + { continue; } var breakLoop = false; - foreach (var w1_2 in wallMap[w1_1]) { - if (wallMap.ContainsKey(w1_2)) { + foreach (var w1_2 in wallMap[w1_1]) + { + if (wallMap.ContainsKey(w1_2)) + { var w2_1 = w1_2; - foreach (var w2_2 in wallMap[w2_1]) { + foreach (var w2_2 in wallMap[w2_1]) + { if ( ( w1_1.Item1 == w1_2.Item1 @@ -688,12 +756,14 @@ public static Dictionary< && 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) - ) { + ) + { wallMap.Remove(w2_1); } wallMap[w1_1].Remove(w2_1); @@ -703,19 +773,23 @@ public static Dictionary< break; } } - if (breakLoop) { + if (breakLoop) + { break; } } - if (breakLoop) { + if (breakLoop) + { break; } } } } output[wallGroupId] = new HashSet<((int row, int col), (int row, int col))>(); - foreach (var w1 in wallMap.Keys) { - foreach (var w2 in wallMap[w1]) { + foreach (var w1 in wallMap.Keys) + { + foreach (var w2 in wallMap[w1]) + { output[wallGroupId].Add((w1, w2)); } } @@ -734,7 +808,8 @@ public static Dictionary< > boundaryGroups, float scale, int precision - ) { + ) + { return boundaryGroups.ToDictionary( bg => bg.Key, bg => new HashSet<((double, double), (double, double))>( @@ -756,7 +831,8 @@ int 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 ); @@ -765,22 +841,28 @@ int precision walls[0] }; remainingWalls.Remove(walls[0]); - while (remainingWalls.Count > 0) { + while (remainingWalls.Count > 0) + { var didBreak = false; - foreach (var wall in remainingWalls) { - if (output.Last().Item2 == wall.Item1) { + 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) { + if (!didBreak) + { throw new ArgumentException($"No connecting wall for {output.Last()}!"); } } @@ -796,21 +878,26 @@ public static Dictionary< HashSet<((double row, double col), (double row, double col))> > boundaryGroups, IEnumerable roomIds - ) { + ) + { var output = new Dictionary>(); - foreach (var roomId in roomIds) { + 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))) { + foreach (var k in boundaryGroups.Keys.Where(k => TupleContains(k, roomId))) + { roomWals.AddRange(boundaryGroups[k]); } 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) { + if (edgeSum > 0) + { wallLoop = wallLoop .Reverse<((double row, double col), (double row, double col))>() .Select(p => (p.Item2, p.Item1)) @@ -821,11 +908,13 @@ IEnumerable roomIds return output; } - public static string roomIntToId(int id, RoomHierarchy room) { + public static string roomIntToId(int id, RoomHierarchy room) + { return $"{room.id}{id}"; } - public static string houseId() { + public static string houseId() + { return "house"; } @@ -833,28 +922,35 @@ 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}"; } - public static string wallToId(int wallIndexInRoom, string roomId, string wallIdPrefix = "") { + public static string wallToId(int wallIndexInRoom, string roomId, string wallIdPrefix = "") + { 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 { + 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); } @@ -864,20 +960,26 @@ public class DefaultDictionary : Dictionary } } - 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) { + if (set != null) + { + foreach (T t in set) + { hashCode = hashCode ^ (set.Comparer.GetHashCode(t) & 0x7FFFFFFF); } } @@ -885,7 +987,8 @@ public int GetHashCode(HashSet set) { } } - private static bool TupleContains((int, int) t, int id) { + private static bool TupleContains((int, int) t, int id) + { return t.Item1 == id || t.Item2 == id; } } diff --git a/unity/Assets/Scripts/ProceduralTools.cs b/unity/Assets/Scripts/ProceduralTools.cs index dfd541f496..aafc957872 100644 --- a/unity/Assets/Scripts/ProceduralTools.cs +++ b/unity/Assets/Scripts/ProceduralTools.cs @@ -18,37 +18,46 @@ using UnityEditor; #endif -namespace Thor.Procedural { +namespace Thor.Procedural +{ [ExecuteInEditMode] [Serializable] - public class AssetMap { + public class AssetMap + { protected Dictionary assetMap; - public AssetMap(Dictionary assetMap) { + public AssetMap(Dictionary assetMap) + { this.assetMap = assetMap; } - public virtual T getAsset(string name) { + public virtual T getAsset(string name) + { return assetMap[name]; } - public virtual bool ContainsKey(string key) { + public virtual bool ContainsKey(string key) + { return assetMap.ContainsKey(key); } - public virtual int Count() { + public virtual int Count() + { return assetMap.Count; } - public virtual IEnumerable Keys() { + public virtual IEnumerable Keys() + { return assetMap.Keys; } - public virtual IEnumerable Values() { + public virtual IEnumerable Values() + { return assetMap.Values; } - public virtual void Clear() { + public virtual void Clear() + { assetMap.Clear(); } } @@ -56,18 +65,22 @@ public virtual void Clear() { // TODO: Turn caller of procedural tools into an instance that has certain // creation attributes like the material database [ExecuteInEditMode] - public class RoomCreatorFactory { + public class RoomCreatorFactory + { public RoomCreatorFactory(AssetMap materials, AssetMap prefabs) { } - public static GameObject CreateProceduralRoomFromArray() { + public static GameObject CreateProceduralRoomFromArray() + { return null; } } - public static class ProceduralTools { + public static class ProceduralTools + { public const string CURRENT_HOUSE_SCHEMA = "1.0.0"; - public class Rectangle { + public class Rectangle + { public Vector3 center; public float width; public float depth; @@ -80,7 +93,8 @@ private static IEnumerable GenerateTriangleVisibilityPoints( Vector3 p1, Vector3 p2, float interval = 1 / 3.0f - ) { + ) + { // Create Vector2 array from Vector3s, since y-axis is redundant Vector2[] tPoints = new Vector2[] { @@ -97,57 +111,73 @@ private static IEnumerable GenerateTriangleVisibilityPoints( float largestAngle = Vector2.Angle(tPoints[0] - tPoints[2], tPoints[1] - tPoints[0]); // Check tPoints[1] - if ((tPoints[0] - tPoints[2]).sqrMagnitude >= longestSideSquare) { + if ((tPoints[0] - tPoints[2]).sqrMagnitude >= longestSideSquare) + { widestAngledPoint = tPoints[1]; largestAngle = Vector2.Angle(tPoints[1] - tPoints[0], tPoints[2] - tPoints[1]); } // Check tPoints[2] - if ((tPoints[1] - tPoints[0]).sqrMagnitude >= longestSideSquare) { + if ((tPoints[1] - tPoints[0]).sqrMagnitude >= longestSideSquare) + { widestAngledPoint = tPoints[2]; largestAngle = Vector2.Angle(tPoints[2] - tPoints[1], tPoints[0] - tPoints[2]); } // Check if triangle is already right-angled, and if so, use it as the v-point origin - if (Mathf.Approximately(largestAngle, 90)) { + if (Mathf.Approximately(largestAngle, 90)) + { Vector2[] rightTriangle1 = new Vector2[3]; vPointLocalOrigin = widestAngledPoint; - if (Vector2.Equals(widestAngledPoint, tPoints[0])) { + if (Vector2.Equals(widestAngledPoint, tPoints[0])) + { rightTriangle1 = new Vector2[] { tPoints[2], tPoints[0], tPoints[1] }; ; - } else if (Vector2.Equals(widestAngledPoint, 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])) { + } + else if (Vector2.Equals(widestAngledPoint, tPoints[2])) + { rightTriangle1 = new Vector2[] { tPoints[1], tPoints[2], tPoints[0] }; } trianglevPoints2D = FindVPointsOnTriangle(rightTriangle1, false); } // If triangle is not right-angled, find v-point origin with trigonometry - else { + else + { Vector2[] rightTriangle2 = new Vector2[3]; // float t; // Enters here!!! - if (Vector2.Equals(widestAngledPoint, tPoints[0])) { + if (Vector2.Equals(widestAngledPoint, tPoints[0])) + { trianglevPoints2D = FindVPointLocalOrigin(tPoints[0], tPoints[1], tPoints[2]); - } else if (Vector2.Equals(widestAngledPoint, tPoints[1])) { + } + else if (Vector2.Equals(widestAngledPoint, tPoints[1])) + { trianglevPoints2D = FindVPointLocalOrigin(tPoints[1], tPoints[2], tPoints[0]); - } else if (Vector2.Equals(widestAngledPoint, tPoints[2])) { + } + else if (Vector2.Equals(widestAngledPoint, tPoints[2])) + { trianglevPoints2D = FindVPointLocalOrigin(tPoints[2], tPoints[0], tPoints[1]); } } // Convert Vector2 vPoints to Vector3 vPoints List trianglevPoints = new List(); - foreach (Vector2 vPoint2D in trianglevPoints2D) { + foreach (Vector2 vPoint2D in trianglevPoints2D) + { trianglevPoints.Add(new Vector3(vPoint2D.x, p0.y, vPoint2D.y)); } return trianglevPoints; - List FindVPointLocalOrigin(Vector2 a, Vector2 b, Vector2 c) { + List FindVPointLocalOrigin(Vector2 a, Vector2 b, Vector2 c) + { List rightTriangleVPoints = new List(); float sideLength = (a - c).magnitude @@ -161,7 +191,8 @@ List FindVPointLocalOrigin(Vector2 a, Vector2 b, Vector2 c) { } // Find all valid v-points along local grid - List FindVPointsOnTriangle(Vector2[] rightTriangle, bool triangle2) { + List FindVPointsOnTriangle(Vector2[] rightTriangle, bool triangle2) + { int startingX = triangle2 ? 1 : 0; float xMax = (rightTriangle[0] - rightTriangle[1]).magnitude; float yMax = (rightTriangle[2] - rightTriangle[1]).magnitude; @@ -171,8 +202,10 @@ List FindVPointsOnTriangle(Vector2[] rightTriangle, bool triangle2) { Vector2 currentPoint; // Check if each v-point is inside right triangle - for (int i = startingX; i * interval < xMax; i++) { - for (int j = 0; j * interval < yMax; j++) { + 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 @@ -190,7 +223,8 @@ List FindVPointsOnTriangle(Vector2[] rightTriangle, bool triangle2) { rightTriangle[2] - currentPoint, rightTriangle[0] - currentPoint ) - ) { + ) + { rightTriangleVPoints.Add(currentPoint); } } @@ -204,7 +238,8 @@ 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(); @@ -224,48 +259,61 @@ private static Mesh GenerateFloorMesh( floor.uv = GenerateUVs(); return floor; - int[] TriangulateVertices() { + int[] TriangulateVertices() + { List indices = new List(); int n = m_points.Length; - if (n < 3) { + if (n < 3) + { return indices.ToArray(); } int[] V = new int[n]; - if (Area() > 0) { - for (int v = 0; v < n; v++) { + if (Area() > 0) + { + for (int v = 0; v < n; v++) + { V[v] = v; } - } else { - for (int v = 0; v < n; v++) { + } + else + { + for (int v = 0; v < n; v++) + { V[v] = (n - 1) - v; } } int nv = n; int count = 2 * nv; - for (int v = nv - 1; nv > 2;) { - if ((count--) <= 0) { + for (int v = nv - 1; nv > 2; ) + { + if ((count--) <= 0) + { return indices.ToArray(); } int u = v; - if (nv <= u) { + if (nv <= u) + { u = 0; } v = u + 1; - if (nv <= v) { + if (nv <= v) + { v = 0; } int w = v + 1; - if (nv <= w) { + if (nv <= w) + { w = 0; } - if (Snip(u, v, w, nv, V)) { + if (Snip(u, v, w, nv, V)) + { int a, b, c, @@ -275,16 +323,20 @@ int[] TriangulateVertices() { b = V[v]; c = V[w]; - if (!clockWise) { + if (!clockWise) + { indices.Add(a); indices.Add(b); indices.Add(c); - } else { + } + else + { indices.Add(c); indices.Add(b); indices.Add(a); } - for (s = v, t = v + 1; t < nv; s++, t++) { + for (s = v, t = v + 1; t < nv; s++, t++) + { V[s] = V[t]; } @@ -297,10 +349,12 @@ int[] TriangulateVertices() { return indices.ToArray(); } - float Area() { + float Area() + { int n = m_points.Length; float A = 0.0f; - for (int p = n - 1, q = 0; q < n; p = q++) { + for (int p = n - 1, q = 0; q < n; p = q++) + { Vector2 pval = m_points[p]; Vector2 qval = m_points[q]; A += pval.x * qval.y - qval.x * pval.y; @@ -308,22 +362,27 @@ float Area() { return (A * 0.5f); } - bool Snip(int u, int v, int w, int n, int[] V) { + bool Snip(int u, int v, int w, int n, int[] V) + { int p; Vector2 A = m_points[V[u]]; Vector2 B = m_points[V[v]]; Vector2 C = m_points[V[w]]; - if (Mathf.Epsilon > (((B.x - A.x) * (C.y - A.y)) - ((B.y - A.y) * (C.x - A.x)))) { + if (Mathf.Epsilon > (((B.x - A.x) * (C.y - A.y)) - ((B.y - A.y) * (C.x - A.x)))) + { return false; } - for (p = 0; p < n; p++) { - if ((p == u) || (p == v) || (p == w)) { + for (p = 0; p < n; p++) + { + if ((p == u) || (p == v) || (p == w)) + { continue; } Vector2 P = m_points[V[p]]; - if (InsideTriangle(A, B, C, P)) { + if (InsideTriangle(A, B, C, P)) + { return false; } } @@ -331,7 +390,8 @@ bool Snip(int u, int v, int w, int n, int[] V) { return true; } - bool InsideTriangle(Vector2 A, Vector2 B, Vector2 C, Vector2 P) { + bool InsideTriangle(Vector2 A, Vector2 B, Vector2 C, Vector2 P) + { float ax, ay, bx, @@ -368,11 +428,13 @@ bool InsideTriangle(Vector2 A, Vector2 B, Vector2 C, Vector2 P) { return ((aCROSSbp >= 0.0f) && (bCROSScp >= 0.0f) && (cCROSSap >= 0.0f)); } - Vector2[] GenerateUVs() { + Vector2[] GenerateUVs() + { Vector2[] uvArray = new Vector2[m_points.Length]; float texelDensity = 5f; - for (int i = 0; i < m_points.Length; i++) { + for (int i = 0; i < m_points.Length; i++) + { uvArray[i] = (m_points[i] - m_points[0]) / texelDensity; } @@ -385,7 +447,8 @@ public static UnityEngine.Mesh GetPolygonMesh( RoomHierarchy room, float yOffset = 0.0f, bool generateBackFaces = false - ) { + ) + { return new Mesh(); } @@ -397,7 +460,8 @@ public static GameObject CreateVisibilityPointsOnPlane( Transform transform = null, WallRectangularHole hole = null, string postfixName = "" - ) { + ) + { var visibilityPoints = new GameObject($"VisibilityPoints{postfixName}"); var width = right.magnitude; var height = top.magnitude; @@ -415,7 +479,8 @@ public static GameObject CreateVisibilityPointsOnPlane( var rightNorm = right.normalized; var topNorm = top.normalized; - if (hole != null && transform != null) { + if (hole != null && transform != null) + { // var wallTransform = new Matrix4x4(rightNorm, topNorm, Vector3.Cross(rightNorm, topNorm), start); // var holeMaxWorld = wallTransform.MultiplyPoint(hole.boundingBox.max); // var holeMinWorld = wallTransform.MultiplyPoint(hole.boundingBox.min); @@ -479,15 +544,18 @@ public static GameObject CreateVisibilityPointsOnPlane( 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)) { + if (hole != null && bounds.Contains(pos)) + { continue; } @@ -502,10 +570,12 @@ public static GameObject CreateVisibilityPointsOnPlane( public static GameObject CreateVisibilityPointsGameObject( IEnumerable visibilityPoints - ) { + ) + { var visibilityPointsGO = new GameObject("VisibilityPoints"); var count = 0; - foreach (var point in visibilityPoints) { + foreach (var point in visibilityPoints) + { var vp = new GameObject($"VisibilityPoint ({count})"); vp.transform.position = point; vp.transform.parent = visibilityPointsGO.transform; @@ -519,7 +589,8 @@ public static GameObject createWalls( AssetMap materialDb, ProceduralParameters proceduralParameters, string gameObjectId = "Structure" - ) { + ) + { var structure = new GameObject(gameObjectId); var wallsPerRoom = walls.GroupBy(w => w.roomId).Select(m => m.ToList()).ToList(); @@ -543,9 +614,12 @@ public static GameObject createWalls( // zip3 = zip3.Reverse().ToArray(); var index = 0; - foreach (var wallTuples in zip3) { - foreach ((Wall w0, Wall w1, Wall w2) in wallTuples) { - if (!w0.empty) { + foreach (var wallTuples in zip3) + { + foreach ((Wall w0, Wall w1, Wall w2) in wallTuples) + { + if (!w0.empty) + { var wallGO = createAndJoinWall( index, materialDb, @@ -570,7 +644,8 @@ public static GameObject createWalls( return structure; } - private static float getWallDegreesRotation(Wall wall) { + private static float getWallDegreesRotation(Wall wall) + { var p0p1 = wall.p1 - wall.p0; var p0p1_norm = p0p1.normalized; @@ -585,7 +660,8 @@ private static float TriangleArea( int index0, int index1, int index2 - ) { + ) + { Vector3 a = vertices[index0]; Vector3 b = vertices[index1]; Vector3 c = vertices[index2]; @@ -594,7 +670,8 @@ int index2 return area; } - private static float GetBBXYArea(BoundingBox bb) { + private static float GetBBXYArea(BoundingBox bb) + { var diff = bb.max - bb.min; return diff.x * diff.y; } @@ -611,7 +688,8 @@ public static GameObject createAndJoinWall( int layer = 8, bool squareTiling = false, bool backFaces = false - ) { + ) + { var wallGO = new GameObject(toCreate.id); SetLayer(wallGO, layer); @@ -648,12 +726,15 @@ public static GameObject createAndJoinWall( var theta = -Mathf.Sign(p0p1_norm.z) * Mathf.Acos(Vector3.Dot(p0p1_norm, Vector3.right)); - if (globalVertexPositions) { + if (globalVertexPositions) + { p0 = toCreate.p0; p1 = toCreate.p1; boxCenter = center; - } else { + } + else + { p0 = -(width / 2.0f) * Vector3.right - new Vector3(0.0f, toCreate.height / 2.0f, toCreate.thickness / 2.0f); @@ -688,12 +769,15 @@ public static GameObject createAndJoinWall( IEnumerable colliderBoundingBoxes = new List(); - if (toCreate.hole != null) { - if (toCreate.hole.holePolygon != null && toCreate.hole.holePolygon.Count != 2) { + 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." ); - if (toCreate.hole.holePolygon.Count < 2) { + 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}." ); @@ -705,7 +789,8 @@ public static GameObject createAndJoinWall( var dims = holeBB.max - holeBB.min; var offset = new Vector2(holeBB.min.x, holeBB.min.y); - if (toCreate.hole.wall1 == toCreate.id) { + if (toCreate.hole.wall1 == toCreate.id) + { offset = new Vector2(width - holeBB.max.x, holeBB.min.y); } @@ -784,23 +869,28 @@ public static GameObject createAndJoinWall( var toRemove = new List(); // const float areaEps = 1e-4f; - for (int i = 0; i < triangles.Count / 3; i++) { + 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) { + if (area <= areaEps) + { toRemove.AddRange(new List() { i * 3, i * 3 + 1, i * 3 + 2 }); } } var toRemoveSet = new HashSet(toRemove); triangles = triangles.Where((t, i) => !toRemoveSet.Contains(i)).ToList(); - if (generateBackFaces) { + if (generateBackFaces) + { triangles.AddRange(triangles.AsEnumerable().Reverse().ToList()); } - } else { + } + else + { vertices = new List() { p0, @@ -813,7 +903,8 @@ public static GameObject createAndJoinWall( // Counter clockwise wall definition left hand rule // triangles = new List() { 0, 3, 2, 0, 2, 1 }; - if (generateBackFaces) { + if (generateBackFaces) + { triangles.AddRange(triangles.AsEnumerable().Reverse().ToList()); } } @@ -835,7 +926,8 @@ public static GameObject createAndJoinWall( meshF.sharedMesh = mesh; var meshRenderer = wallGO.AddComponent(); - if (toCreate.hole != null) { + if (toCreate.hole != null) + { // var meshCollider = wallGO.AddComponent(); // meshCollider.sharedMesh = mesh; @@ -846,7 +938,8 @@ public static GameObject createAndJoinWall( holeColliders.transform.localRotation = Quaternion.identity; var i = 0; - foreach (var boundingBox in colliderBoundingBoxes) { + foreach (var boundingBox in colliderBoundingBoxes) + { var colliderObj = new GameObject($"Collider_{i}"); colliderObj.transform.parent = holeColliders.transform; colliderObj.transform.localPosition = Vector3.zero; @@ -857,7 +950,9 @@ public static GameObject createAndJoinWall( boxCollider.center = boundingBox.center(); boxCollider.size = boundingBox.size() + Vector3.forward * colliderThickness; } - } else { + } + else + { var boxC = wallGO.AddComponent(); boxC.center = boxCenter; boxC.size = boxSize; @@ -923,7 +1018,8 @@ public static GameObject createFloorCollider( GameObject floorGameObject, Rectangle rectangle, float thickness - ) { + ) + { var colliders = new GameObject("Colliders"); var collider = new GameObject("Col"); @@ -971,7 +1067,8 @@ public static GameObject createFloorReceptacle( Rectangle rectangle, float height, string namePostfix = "" - ) { + ) + { var receptacleTriggerBox = new GameObject($"ReceptacleTriggerBox{namePostfix}"); // SimObjInvisible receptacleTriggerBox.layer = 9; @@ -995,7 +1092,8 @@ public static SimObjPhysics setWallSimObjPhysics( GameObject visibilityPoints, Vector3 boxCenter, Vector3 boxSize - ) { + ) + { var wallrb = wallGameObject.AddComponent(); wallrb.isKinematic = true; @@ -1025,8 +1123,10 @@ Vector3 boxSize var PotentialColliders = wallGameObject.GetComponentsInChildren(false); List actuallyMyColliders = new List(); - foreach (Collider c in PotentialColliders) { - if (c.enabled) { + foreach (Collider c in PotentialColliders) + { + if (c.enabled) + { actuallyMyColliders.Add(c); } } @@ -1045,7 +1145,8 @@ public static SimObjPhysics setRoomSimObjectPhysics( GameObject visibilityPoints, GameObject receptacleTriggerBox, Collider collider - ) { + ) + { return setRoomSimObjectPhysics( floorGameObject, simObjId, @@ -1055,13 +1156,15 @@ Collider collider ); } - public static RoomProperties setRoomProperties(GameObject gameObject, RoomHierarchy room) { + public static RoomProperties setRoomProperties(GameObject gameObject, RoomHierarchy room) + { var roomProps = gameObject.AddComponent(); roomProps.RoomType = room.roomType; return roomProps; } - public static WallProperties setFloorProperties(GameObject gameObject, Wall wall) { + public static WallProperties setFloorProperties(GameObject gameObject, Wall wall) + { var wallProps = gameObject.AddComponent(); wallProps.RoomId = wall.roomId; return wallProps; @@ -1070,7 +1173,8 @@ public static WallProperties setFloorProperties(GameObject gameObject, Wall wall public static ConnectionProperties setConnectionProperties( GameObject gameObject, WallRectangularHole hole - ) { + ) + { var holeProps = gameObject.AddComponent(); holeProps.OpenFromRoomId = hole.room0; holeProps.OpenToRoomId = hole.room1; @@ -1083,7 +1187,8 @@ public static SimObjPhysics setRoomSimObjectPhysics( GameObject visibilityPoints, GameObject[] receptacleTriggerBoxes = null, Collider[] colliders = null - ) { + ) + { var boundingBox = new GameObject("BoundingBox"); var bbCollider = boundingBox.AddComponent(); bbCollider.enabled = false; @@ -1106,12 +1211,14 @@ public static SimObjPhysics setRoomSimObjectPhysics( simObjPhysics.transform.parent = floorGameObject.transform; - if (receptacleTriggerBoxes != null) { + if (receptacleTriggerBoxes != null) + { secondaryProperties = new SimObjSecondaryProperty[] { SimObjSecondaryProperty.Receptacle }; - foreach (var receptacleTriggerBox in receptacleTriggerBoxes) { + foreach (var receptacleTriggerBox in receptacleTriggerBoxes) + { receptacleTriggerBox.AddComponent(); } } @@ -1126,14 +1233,16 @@ public static GameObject createSimObjPhysicsGameObject( string tag = "SimObjPhysics", int layer = 8, bool withRigidBody = true - ) { + ) + { var floorGameObject = new GameObject(name); floorGameObject.transform.position = position.GetValueOrDefault(); floorGameObject.tag = tag; floorGameObject.layer = layer; - if (withRigidBody) { + if (withRigidBody) + { var rb = floorGameObject.AddComponent(); rb.mass = 1.0f; rb.angularDrag = 0.05f; @@ -1148,13 +1257,15 @@ public static GameObject createSimObjPhysicsGameObject( return floorGameObject; } - private static void setUpFloorMesh(GameObject floorGameObject, Mesh mesh, Material material) { + private static void setUpFloorMesh(GameObject floorGameObject, Mesh mesh, Material material) + { floorGameObject.GetComponent().mesh = mesh; var meshRenderer = floorGameObject.GetComponent(); meshRenderer.material = material; } - private static BoundingBox getRoomRectangle(IEnumerable polygonPoints) { + 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, @@ -1172,14 +1283,16 @@ private static BoundingBox getRoomRectangle(IEnumerable polygonPoints) 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); WallRectangularHole val; var hole = holes.TryGetValue(wall.id, out val) ? val : null; var p0 = polygons.ElementAt(0); - return new Wall() { + return new Wall() + { id = wall.id, p0 = polygons.ElementAt(0), p1 = polygons.ElementAt(1), @@ -1193,10 +1306,12 @@ Dictionary holes }; } - private static Vector2 getAxisAlignedWidthDepth(IEnumerable polygon) { + private static Vector2 getAxisAlignedWidthDepth(IEnumerable polygon) + { // TODO: include rotation in json for floor and ceiling to compute the real scale not axis aligned scale - if (polygon.Count() > 1) { + if (polygon.Count() > 1) + { var maxX = polygon.Max(p => p.x); var maxZ = polygon.Max(p => p.z); @@ -1210,20 +1325,25 @@ private static Vector2 getAxisAlignedWidthDepth(IEnumerable polygon) { return Vector2.zero; } - private static Vector2? getWallMaterialOffset(string wallId) { + private static Vector2? getWallMaterialOffset(string wallId) + { var wallGO = GameObject.Find(wallId); - if (wallGO == null) { + if (wallGO == null) + { return null; } var renderer = wallGO.GetComponent(); - if (renderer == null) { + if (renderer == null) + { return null; } return renderer.material.mainTextureOffset; } - private static BoundingBox getHoleBoundingBox(WallRectangularHole hole) { - if (hole.holePolygon == null || hole.holePolygon.Count < 2) { + 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." ); @@ -1238,7 +1358,8 @@ private static Material generatePolygonMaterial( 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 ( @@ -1249,20 +1370,23 @@ private static Material generatePolygonMaterial( && offsetX == 0.0f && offsetY == 0.0f && !materialProperties.unlit - ) { + ) + { return sharedMaterial; } var materialCopy = new Material(sharedMaterial); - if (materialProperties.color != null) { + if (materialProperties.color != null) + { materialCopy.color = materialProperties.color.toUnityColor(); } var tilingX = dimensions.x / materialProperties.tilingDivisorX.GetValueOrDefault(1.0f); var tilingY = dimensions.y / materialProperties.tilingDivisorY.GetValueOrDefault(1.0f); - if (squareTiling) { + if (squareTiling) + { tilingX = Math.Max(tilingX, tilingY); tilingY = tilingX; } @@ -1270,19 +1394,22 @@ private static Material generatePolygonMaterial( materialCopy.mainTextureScale = new Vector2(tilingX, tilingY); materialCopy.mainTextureOffset = new Vector2(offsetX, offsetY); - if (materialProperties.unlit) { + if (materialProperties.unlit) + { var shader = Shader.Find("Unlit/Color"); materialCopy.shader = shader; } - if (materialProperties.metallic != null) { + if (materialProperties.metallic != null) + { materialCopy.SetFloat( "_Metallic", materialProperties.metallic.GetValueOrDefault(0.0f) ); } - if (materialProperties.metallic != null) { + if (materialProperties.metallic != null) + { materialCopy.SetFloat( "_Glossiness", materialProperties.smoothness.GetValueOrDefault(0.0f) @@ -1303,27 +1430,36 @@ private static Material generatePolygonMaterial( public static string DefaultObjectsRootName => "Objects"; public static void SetLayer(GameObject go, int layer) - where T : Component { - if (go.GetComponent() != null) { + where T : Component + { + if (go.GetComponent() != null) + { go.layer = layer; } - foreach (Transform child in go.transform) { + foreach (Transform child in go.transform) + { SetLayer(child.gameObject, layer); } } - public static (int, int, int) parseHouseVersion(string version) { - if (string.IsNullOrEmpty(version)) { + 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 Debug.Log($"HouseVersion: {string.Join(", ", versionSplit)}"); #endif var versionResult = new int[] { 0, 0, 0 } .Select( - (x, i) => { - if (versionSplit.Length > i) { + (x, i) => + { + if (versionSplit.Length > i) + { int outVersion; bool canParse = int.TryParse(versionSplit[i], out outVersion); return canParse ? outVersion : x; @@ -1336,13 +1472,16 @@ public static (int, int, int) parseHouseVersion(string version) { } } - public static int compareVersion((int, int, int) v0, (int, int, int) v1) { + 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 ); - foreach (var diff in diffs) { - if (diff != 0) { + foreach (var diff in diffs) + { + if (diff != 0) + { return diff; } } @@ -1353,14 +1492,20 @@ private static bool validateHouseObjects( AssetMap assetDb, IEnumerable hos, List missingIds - ) { - if (hos == null) { + ) + { + if (hos == null) + { return true; - } else { + } + else + { var result = true; - foreach (var ho in hos) { + foreach (var ho in hos) + { var inDb = assetDb.ContainsKey(ho.assetId); - if (!inDb) { + if (!inDb) + { missingIds.Add(ho.assetId); } result = inDb && validateHouseObjects(assetDb, ho.children, missingIds); @@ -1374,16 +1519,19 @@ public static GameObject CreateHouse( ProceduralHouse house, AssetMap materialDb, Vector3? position = null - ) { + ) + { // raise exception if metadata contains schema - if (house.metadata == null || house.metadata.schema == null) { + 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}'" ); } 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'" @@ -1394,7 +1542,8 @@ public static GameObject CreateHouse( var latestSchema = parseHouseVersion(CURRENT_HOUSE_SCHEMA); var versionCompare = compareVersion(schema, latestSchema); - if (versionCompare != 0) { + 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'." @@ -1440,7 +1589,8 @@ public static GameObject CreateHouse( withRigidBody: false ); - for (int i = 0; i < house.rooms.Count(); i++) { + for (int i = 0; i < house.rooms.Count(); i++) + { var room = house.rooms.ElementAt(i); var subFloorGO = createSimObjPhysicsGameObject(room.id); var mesh = ProceduralTools.GenerateFloorMesh(room.floorPolygon); @@ -1487,7 +1637,8 @@ public static GameObject CreateHouse( // allow layer to be overwritten // will break support for spawnObjectInReceptacle - if (!String.IsNullOrEmpty(room.layer)) { + if (!String.IsNullOrEmpty(room.layer)) + { SetLayer(subFloorGO, LayerMask.NameToLayer(room.layer)); } @@ -1503,7 +1654,8 @@ public static GameObject CreateHouse( var boundingBox = getRoomRectangle(house.rooms.SelectMany(r => r.floorPolygon)); var dimension = boundingBox.max - boundingBox.min; - var rectangle = new Rectangle() { + var rectangle = new Rectangle() + { center = boundingBox.min + dimension / 2.0f, width = dimension.x, depth = dimension.z, @@ -1547,7 +1699,8 @@ public static GameObject CreateHouse( wallsGO.transform.parent = structureGO.transform; // generate ceiling - if (ceilingMaterialId != "") { + if (ceilingMaterialId != "") + { var ceilingParent = new GameObject(DefaultCeilingRootObjectName); // OLD rectangular ceiling, may be usefull to have as a feature, much faster @@ -1565,7 +1718,8 @@ public static GameObject CreateHouse( ) .ToArray(); - for (int i = 0; i < house.rooms.Count(); i++) { + for (int i = 0; i < house.rooms.Count(); i++) + { var ceilingMesh = ceilingMeshes[i]; var room = house.rooms[i]; var floorName = house.rooms[i].id; @@ -1586,9 +1740,11 @@ public static GameObject CreateHouse( string roomCeilingMaterialId = ceilingMaterialId; MaterialProperties ceilingMaterialProperties = null; - if (room.ceilings.Count > 0) { + if (room.ceilings.Count > 0) + { ceilingMaterialProperties = room.ceilings[0].material; - if (!string.IsNullOrEmpty(room.ceilings[0].material.name)) { + if (!string.IsNullOrEmpty(room.ceilings[0].material.name)) + { roomCeilingMaterialId = room.ceilings[0].material.name; } } @@ -1614,11 +1770,13 @@ public static GameObject CreateHouse( } CollisionDetectionMode collDet = CollisionDetectionMode.ContinuousSpeculative; - if (!string.IsNullOrEmpty(house.proceduralParameters.collisionDetectionMode)) { + if (!string.IsNullOrEmpty(house.proceduralParameters.collisionDetectionMode)) + { Enum.TryParse(house.proceduralParameters.collisionDetectionMode, true, out collDet); } - foreach (var obj in house.objects) { + foreach (var obj in house.objects) + { spawnObjectHierarchy(obj, collDet); } @@ -1633,12 +1791,14 @@ public static GameObject CreateHouse( ) .ToDictionary(d => d.door.id, d => (d.wall0, d.wall1)); var count = 0; - foreach (WallRectangularHole holeCover in windowsAndDoors) { + foreach (WallRectangularHole holeCover in windowsAndDoors) + { var coverPrefab = assetMap.getAsset(holeCover.assetId); (Wall wall0, Wall wall1) wall; var wallExists = doorsToWalls.TryGetValue(holeCover.id, out wall); - if (wallExists) { + if (wallExists) + { var p0p1 = wall.wall0.p1 - wall.wall0.p0; var p0p1_norm = p0p1.normalized; @@ -1675,7 +1835,8 @@ public static GameObject CreateHouse( setConnectionProperties(go, holeCover); var canOpen = go.GetComponentInChildren(); - if (canOpen != null) { + if (canOpen != null) + { canOpen.SetOpennessImmediate(holeCover.openness); } @@ -1685,11 +1846,14 @@ public static GameObject CreateHouse( } var lightingRoot = new GameObject(DefaultLightingRootName); - if (house.proceduralParameters.lights != null) { - foreach (var lightParams in house.proceduralParameters.lights) { + if (house.proceduralParameters.lights != null) + { + foreach (var lightParams in house.proceduralParameters.lights) + { var go = new GameObject(lightParams.id); go.transform.position = lightParams.position; - if (lightParams.rotation != null) { + if (lightParams.rotation != null) + { go.transform.rotation = lightParams.rotation.toQuaternion(); } var light = go.AddComponent(); @@ -1705,13 +1869,16 @@ public static GameObject CreateHouse( light.intensity = lightParams.intensity; light.bounceIntensity = lightParams.indirectMultiplier; light.range = lightParams.range; - if (lightParams.cullingMaskOff != null) { - foreach (var layer in lightParams.cullingMaskOff) { + if (lightParams.cullingMaskOff != null) + { + foreach (var layer in lightParams.cullingMaskOff) + { light.cullingMask &= ~(1 << LayerMask.NameToLayer(layer)); } } - if (lightParams.shadow != null) { + if (lightParams.shadow != null) + { light.shadowStrength = lightParams.shadow.strength; light.shadows = (LightShadows) Enum.Parse( @@ -1733,8 +1900,10 @@ public static GameObject CreateHouse( } } - if (house.proceduralParameters.reflections != null) { - foreach (var probe in house.proceduralParameters.reflections) { + if (house.proceduralParameters.reflections != null) + { + foreach (var probe in house.proceduralParameters.reflections) + { var go = new GameObject(probe.id); go.transform.position = probe.position; @@ -1759,7 +1928,8 @@ public static GameObject CreateHouse( 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; @@ -1770,7 +1940,9 @@ public static GameObject CreateHouse( cam.backgroundColor = mat.color; // RenderSettings.ambientSkyColor = - } else { + } + else + { RenderSettings.skybox = materialDb.getAsset(house.proceduralParameters.skyboxId); } DynamicGI.UpdateEnvironment(); @@ -1795,13 +1967,15 @@ public static GameObject CreateHouse( return floorGameObject; } - private static void setAgentPose(ProceduralHouse house, AgentManager agentManager) { + private static void setAgentPose(ProceduralHouse house, AgentManager agentManager) + { // teleport the agent into the scene if ( house.metadata != null && house.metadata.agentPoses != null && house.metadata.agentPoses.ContainsKey(agentManager.agentMode) - ) { + ) + { BaseFPSAgentController bfps = agentManager.primaryAgent; Vector3 newPosition = house.metadata.agentPoses[agentManager.agentMode].position; Vector3 newRotation = house.metadata.agentPoses[agentManager.agentMode].rotation; @@ -1812,7 +1986,8 @@ private static void setAgentPose(ProceduralHouse house, AgentManager agentManage bool savedAutoSyncTransforms = Physics.autoSyncTransforms; Physics.autoSyncTransforms = true; - if (newPosition != null) { + if (newPosition != null) + { bfps.transform.position = newPosition; Vector3 target = new Vector3( @@ -1822,16 +1997,19 @@ private static void setAgentPose(ProceduralHouse house, AgentManager agentManage ); Vector3 dir = target - bfps.transform.position; Vector3 movement = dir.normalized * 100.0f; - if (movement.magnitude > dir.magnitude) { + if (movement.magnitude > dir.magnitude) + { movement = dir; } movement.y = Physics.gravity.y * bfps.m_GravityMultiplier; bfps.GetComponent().Move(movement); } - if (newRotation != null) { + if (newRotation != null) + { bfps.transform.rotation = Quaternion.Euler(newRotation); } - if (newHorizon.HasValue) { + if (newHorizon.HasValue) + { bfps.m_Camera.transform.localEulerAngles = new Vector3( newHorizon.Value, bfps.m_Camera.transform.localEulerAngles.y, @@ -1842,11 +2020,15 @@ private static void setAgentPose(ProceduralHouse house, AgentManager agentManage agentManager.agentMode != "locobot" && agentManager.agentMode != "stretch" && newStanding != null - ) { + ) + { PhysicsRemoteFPSAgentController pfps = bfps as PhysicsRemoteFPSAgentController; - if (newStanding == true) { + if (newStanding == true) + { pfps.stand(); - } else { + } + else + { pfps.crouch(); } } @@ -1857,13 +2039,16 @@ private static void setAgentPose(ProceduralHouse house, AgentManager agentManage public static void spawnObjectHierarchy( HouseObject houseObject, CollisionDetectionMode proceduralParamsCollisionDetMode - ) { - if (houseObject == null) { + ) + { + if (houseObject == null) + { return; } CollisionDetectionMode collDet = proceduralParamsCollisionDetMode; - if (!string.IsNullOrEmpty(houseObject.collisionDetectionMode)) { + if (!string.IsNullOrEmpty(houseObject.collisionDetectionMode)) + { Enum.TryParse(houseObject.collisionDetectionMode, true, out collDet); } // Debug.Log($"----- obj {houseObject.id} , {houseObject.collisionDetectionMode} procPar {proceduralParamsCollisionDetMode} final: {collDet}"); @@ -1873,12 +2058,15 @@ CollisionDetectionMode proceduralParamsCollisionDetMode houseObject, collDet ); - if (go != null) { + if (go != null) + { tagObjectNavmesh(go, "Not Walkable"); } - if (houseObject.children != null) { - foreach (var child in houseObject.children) { + if (houseObject.children != null) + { + foreach (var child in houseObject.children) + { spawnObjectHierarchy(child, proceduralParamsCollisionDetMode); } } @@ -1888,9 +2076,11 @@ public static void tagObjectNavmesh( GameObject gameObject, string navMeshAreaName = "Walkable", bool ignore = false - ) { + ) + { var modifier = gameObject.GetComponent(); - if (modifier == null) { + if (modifier == null) + { modifier = gameObject.AddComponent(); } modifier.ignoreFromBuild = ignore; @@ -1898,11 +2088,13 @@ public static void tagObjectNavmesh( modifier.area = NavMesh.GetAreaFromName(navMeshAreaName); } - public static string NavMeshSurfaceName(int index) { + public static string NavMeshSurfaceName(int index) + { return $"NavMeshSurface_{index}"; } - public static GameObject buildNavMeshSurface(NavMeshBuildSettings buildSettings, int index) { + public static GameObject buildNavMeshSurface(NavMeshBuildSettings buildSettings, int index) + { var go = new GameObject(NavMeshSurfaceName(index)); var navMeshSurface = go.AddComponent(); navMeshSurface.agentTypeID = buildSettings.agentTypeID; @@ -1912,7 +2104,8 @@ public static GameObject buildNavMeshSurface(NavMeshBuildSettings buildSettings, return go; } - public static GameObject buildNavMeshSurface(NavMeshConfig navMeshConfig, int index) { + public static GameObject buildNavMeshSurface(NavMeshConfig navMeshConfig, int index) + { var go = new GameObject(NavMeshSurfaceName(index)); var navMeshSurface = go.AddComponent(); @@ -1929,8 +2122,10 @@ public static GameObject buildNavMeshSurface(NavMeshConfig navMeshConfig, int in public static void activateAllNavmeshSurfaces( IEnumerable navmeshSurfaces - ) { - foreach (var nvms in navmeshSurfaces) { + ) + { + foreach (var nvms in navmeshSurfaces) + { nvms.enabled = true; } } @@ -1938,7 +2133,8 @@ IEnumerable navmeshSurfaces 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}" @@ -1958,8 +2154,10 @@ public static NavMeshSurfaceExtended activateOnlyNavmeshSurface( // targetHit.position, path // ); - foreach (var nvms in navmeshSurfaces) { - if (nvms != navMesh) { + foreach (var nvms in navmeshSurfaces) + { + if (nvms != navMesh) + { nvms.enabled = false; } } @@ -1972,19 +2170,24 @@ public static NavMeshSurfaceExtended activateOnlyNavmeshSurface( return navMesh; } - public static int getNavMeshAgentId(int? navMeshId = null) { + public static int getNavMeshAgentId(int? navMeshId = null) + { var idSet = new HashSet( NavMeshSurfaceExtended.activeSurfaces.Select(n => n.agentTypeID) ); - if (!navMeshId.HasValue) { - if (NavMeshSurfaceExtended.activeSurfaces.Count > 0) { + if (!navMeshId.HasValue) + { + if (NavMeshSurfaceExtended.activeSurfaces.Count > 0) + { return NavMeshSurfaceExtended.activeSurfaces[0].agentTypeID; } // TODO consider IthorScenes, not sure we use NavMeshSurface // 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( @@ -1994,7 +2197,8 @@ public static int getNavMeshAgentId(int? navMeshId = null) { return navMeshId.GetValueOrDefault(); } - public static NavMeshSurfaceExtended getNavMeshSurfaceForAgentId(int agentId) { + public static NavMeshSurfaceExtended getNavMeshSurfaceForAgentId(int agentId) + { return NavMeshSurface.activeSurfaces.Find(s => s.agentTypeID == agentId) as NavMeshSurfaceExtended; } @@ -2002,7 +2206,8 @@ public static NavMeshSurfaceExtended getNavMeshSurfaceForAgentId(int agentId) { public static NavMeshBuildSettings navMeshConfigToBuildSettings( NavMeshConfig config, NavMeshBuildSettings defaultBuildSettings - ) { + ) + { defaultBuildSettings.agentTypeID = config.id; defaultBuildSettings.agentRadius = config.agentRadius; defaultBuildSettings.tileSize = config.tileSize.GetValueOrDefault( @@ -2028,7 +2233,8 @@ NavMeshBuildSettings defaultBuildSettings public static NavMeshConfig navMeshBuildSettingsToConfig( NavMeshBuildSettings navMeshBuildSettings - ) { + ) + { var navMeshConfig = new NavMeshConfig(); navMeshConfig.id = navMeshBuildSettings.agentTypeID; navMeshConfig.agentRadius = navMeshBuildSettings.agentRadius; @@ -2041,17 +2247,21 @@ NavMeshBuildSettings navMeshBuildSettings return navMeshConfig; } - public static NavMeshBuildSettings navMeshConfigToBuildSettings(NavMeshConfig config) { + public static NavMeshBuildSettings navMeshConfigToBuildSettings(NavMeshConfig config) + { return navMeshConfigToBuildSettings(config, NavMesh.GetSettingsByIndex(0)); } - public static string NavMeshSurfaceParent() { + public static string NavMeshSurfaceParent() + { return "NavMeshSurfaces"; } - public static void buildNavMeshes(GameObject floorGameObject, List navMeshes) { + public static void buildNavMeshes(GameObject floorGameObject, List navMeshes) + { var defaultSettings = NavMesh.GetSettingsByIndex(0); - if (navMeshes == null || navMeshes.Count == 0) { + if (navMeshes == null || navMeshes.Count == 0) + { navMeshes = new List() { navMeshBuildSettingsToConfig(defaultSettings) @@ -2068,7 +2278,8 @@ public static void buildNavMeshes(GameObject floorGameObject, List defaultSettings) .Select( - (c, i) => { + (c, i) => + { return navMeshConfigToBuildSettings(navMeshes[i], c); } ); @@ -2078,7 +2289,8 @@ public static void buildNavMeshes(GameObject floorGameObject, List(); tagObjectNavmesh(navMeshAgent.gameObject, ignore: true); @@ -2151,26 +2364,31 @@ public static void buildNavMesh(GameObject floorGameObject, float? voxelSize = n #if UNITY_EDITOR public static List FindAssetsByType() - where T : UnityEngine.Object { + where T : UnityEngine.Object + { List assets = new List(); string[] guids = AssetDatabase.FindAssets( string.Format("t:{0}", typeof(T).ToString().Replace("UnityEngine.", "")) ); - for (int i = 0; i < guids.Length; i++) { + for (int i = 0; i < guids.Length; i++) + { string assetPath = AssetDatabase.GUIDToAssetPath(guids[i]); T asset = AssetDatabase.LoadAssetAtPath(assetPath); - if (asset != null) { + if (asset != null) + { assets.Add(asset); } } return assets; } - public static List FindPrefabsInAssets() { + public static List FindPrefabsInAssets() + { var assets = 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, @@ -2183,12 +2401,14 @@ public static List FindPrefabsInAssets() { || assetPath.Contains("Entryway Objects") || assetPath.Contains("Custom Project Objects") || assetPath.Contains("Assets/Resources") - ) { + ) + { continue; } GameObject asset = AssetDatabase.LoadAssetAtPath(assetPath); - if (asset != null && asset.GetComponent()) { + if (asset != null && asset.GetComponent()) + { assets.Add(asset); } } @@ -2197,7 +2417,8 @@ public static List FindPrefabsInAssets() { #endif //not sure if this is needed, a helper function like this might exist somewhere already? - public static AssetMap getAssetMap() { + public static AssetMap getAssetMap() + { var assetDB = GameObject.FindObjectOfType(); return assetDB.assetMap; // return new AssetMap(assetDB.prefabs.GroupBy(p => p.name).ToDictionary(p => p.Key, p => p.First())); @@ -2208,8 +2429,10 @@ public static GameObject spawnHouseObject( AssetMap goDb, HouseObject ho, CollisionDetectionMode collisionDetectionMode - ) { - if (goDb.ContainsKey(ho.assetId)) { + ) + { + if (goDb.ContainsKey(ho.assetId)) + { var go = goDb.getAsset(ho.assetId); return spawnSimObjPrefab( @@ -2229,7 +2452,9 @@ CollisionDetectionMode collisionDetectionMode layer: ho.layer, collisionDetectionMode: collisionDetectionMode ); - } else { + } + else + { Debug.LogError($"Asset not in Database: `{ho.assetId}`"); return null; } @@ -2253,35 +2478,45 @@ public static GameObject spawnSimObjPrefab( Vector3? scale = null, CollisionDetectionMode collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative - ) { + ) + { var go = prefab; var spawned = GameObject.Instantiate(original: go); //, position, Quaternion.identity); //, position, rotation); - if (!String.IsNullOrEmpty(layer)) { + if (!String.IsNullOrEmpty(layer)) + { SetLayer(spawned, LayerMask.NameToLayer(layer)); } - if (openness.HasValue) { + if (openness.HasValue) + { var canOpen = spawned.GetComponentInChildren(); - if (canOpen != null) { + if (canOpen != null) + { canOpen.SetOpennessImmediate(openness.Value); } } - if (isOn.HasValue) { + if (isOn.HasValue) + { var canToggle = spawned.GetComponentInChildren(); - if (canToggle != null) { - if (isOn.Value != canToggle.isOn) { + if (canToggle != null) + { + if (isOn.Value != canToggle.isOn) + { canToggle.Toggle(); } } } - if (isDirty.HasValue) { + if (isDirty.HasValue) + { var dirt = spawned.GetComponentInChildren(); - if (dirt != null) { - if (isDirty.Value != dirt.IsDirty()) { + if (dirt != null) + { + if (isDirty.Value != dirt.IsDirty()) + { dirt.ToggleCleanOrDirty(); } } @@ -2292,17 +2527,20 @@ public static GameObject spawnSimObjPrefab( .transform; // scale the object - if (scale.HasValue) { + if (scale.HasValue) + { spawned.transform.localScale = scale.Value; Transform[] children = new Transform[spawned.transform.childCount]; - for (int i = 0; i < spawned.transform.childCount; i++) { + for (int i = 0; i < spawned.transform.childCount; i++) + { children[i] = spawned.transform.GetChild(i); } // detach all children spawned.transform.DetachChildren(); spawned.transform.localScale = Vector3.one; - foreach (Transform t in children) { + foreach (Transform t in children) + { t.SetParent(spawned.transform); } spawned @@ -2311,7 +2549,8 @@ public static GameObject spawnSimObjPrefab( } // var rotaiton = Quaternion.AngleAxis(rotation.degrees, rotation.axis); - if (positionBoundingBoxCenter) { + if (positionBoundingBoxCenter) + { var simObj = spawned.GetComponent(); var box = simObj.AxisAlignedBoundingBox; // box.enabled = true; @@ -2320,7 +2559,9 @@ public static GameObject spawnSimObjPrefab( spawned.transform.position = rotation * (spawned.transform.localPosition - box.center) + position; spawned.transform.rotation = rotation; - } else { + } + else + { spawned.transform.position = position; spawned.transform.rotation = rotation; } @@ -2328,7 +2569,8 @@ public static GameObject spawnSimObjPrefab( var toSpawn = spawned.GetComponent(); Rigidbody rb = spawned.GetComponent(); rb.isKinematic = kinematic; - if (!kinematic) { + if (!kinematic) + { rb.collisionDetectionMode = collisionDetectionMode; } toSpawn.objectID = id; @@ -2339,16 +2581,20 @@ public static GameObject spawnSimObjPrefab( Shader unlitShader = null; - if (unlit) { + if (unlit) + { unlitShader = Shader.Find("Unlit/Color"); } - if (materialProperties != null) { + if (materialProperties != null) + { var materials = toSpawn .GetComponentsInChildren() .Select(mr => mr.material); - foreach (var mat in materials) { - if (materialProperties.color != null) { + foreach (var mat in materials) + { + if (materialProperties.color != null) + { mat.color = new Color( materialProperties.color.r, materialProperties.color.g, @@ -2356,16 +2602,19 @@ public static GameObject spawnSimObjPrefab( materialProperties.color.a ); } - if (unlit) { + if (unlit) + { mat.shader = unlitShader; } - if (materialProperties?.metallic != null) { + if (materialProperties?.metallic != null) + { mat.SetFloat( "_Metallic", materialProperties.metallic.GetValueOrDefault(0.0f) ); } - if (materialProperties?.smoothness != null) { + if (materialProperties?.smoothness != null) + { mat.SetFloat( "_Glossiness", materialProperties.smoothness.GetValueOrDefault(0.0f) @@ -2382,8 +2631,10 @@ public static GameObject spawnSimObjPrefab( SimObjPhysics[] childSimObjects = toSpawn.transform.gameObject.GetComponentsInChildren(); int childNumber = 0; - for (int i = 0; i < childSimObjects.Length; i++) { - if (childSimObjects[i].objectID == id) { + for (int i = 0; i < childSimObjects.Length; i++) + { + if (childSimObjects[i].objectID == id) + { // skip the parent object that's ID has already been assigned continue; } @@ -2401,7 +2652,8 @@ public static GameObject spawnObjectInReceptacle( SimObjPhysics receptacleSimObj, Vector3 position, FlexibleRotation rotation = null - ) { + ) + { 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(); @@ -2418,7 +2670,8 @@ public static GameObject spawnObjectInReceptacle( rotation: Quaternion.identity ); spawned.transform.parent = GameObject.Find(DefaultObjectsRootName).transform; - if (rotation != null) { + if (rotation != null) + { Vector3 toRot = rotation.axis * rotation.degrees; spawned.transform.Rotate(toRot.x, toRot.y, toRot.z); } @@ -2432,14 +2685,17 @@ public static GameObject spawnObjectInReceptacle( var success = false; - if (agent.placeNewObjectAtPoint(toSpawn, position)) { + if (agent.placeNewObjectAtPoint(toSpawn, position)) + { 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(); bool cornerCheck = true; - foreach (Vector3 p in corners) { - if (!con.CheckIfPointIsAboveReceptacleTriggerBox(p)) { + foreach (Vector3 p in corners) + { + if (!con.CheckIfPointIsAboveReceptacleTriggerBox(p)) + { cornerCheck = false; //this position would cause object to fall off table //double back and reset object to try again with another point @@ -2457,18 +2713,21 @@ public static GameObject spawnObjectInReceptacle( Mathf.Infinity, LayerMask.GetMask("NonInteractive") ) - ) { + ) + { // Debug.Log("FloorCheck"); floorCheck = false; } - if (!cornerCheck || !floorCheck) { + if (!cornerCheck || !floorCheck) + { // Debug.Log("corner || floor"); success = false; } //if all corners were succesful, break out of this loop, don't keep trying - if (success) { + if (success) + { rb.isKinematic = false; toSpawn.objectID = objectId; toSpawn.name = objectId; @@ -2478,7 +2737,8 @@ public static GameObject spawnObjectInReceptacle( } //if after trying all spawn points, it failed to position, delete object from scene and return null - if (!success) { + if (!success) + { UnityEngine.Object.Destroy(toSpawn.transform.gameObject); return null; } @@ -2493,7 +2753,8 @@ public static GameObject spawnObjectInReceptacleRandomly( string objectId, SimObjPhysics receptacleSimObj, FlexibleRotation rotation = null - ) { + ) + { var spawnCoordinates = receptacleSimObj.FindMySpawnPointsFromTriggerBox(); var go = goDb.getAsset(prefabName); var pos = spawnCoordinates.Shuffle_().First(); @@ -2512,7 +2773,8 @@ public static GameObject spawnObjectInReceptacleRandomly( rotation: Quaternion.identity ); spawned.transform.parent = GameObject.Find(DefaultObjectsRootName).transform; - if (rotation != null) { + if (rotation != null) + { Vector3 toRot = rotation.axis * rotation.degrees; spawned.transform.Rotate(toRot.x, toRot.y, toRot.z); } @@ -2526,11 +2788,13 @@ public static GameObject spawnObjectInReceptacleRandomly( var success = false; - for (int i = 0; i < spawnCoordinates.Count; i++) { + for (int i = 0; i < spawnCoordinates.Count; i++) + { //place object at the given point, this also checks the spawn area to see if its clear //if not clear, it will return false var canPlace = agent.placeNewObjectAtPoint(toSpawn, spawnCoordinates[i]); - if (canPlace) { + if (canPlace) + { success = true; List corners = GetCorners(toSpawn); //this only attempts to check the first ReceptacleTriggerBox of the receptacle, does not handle multiple receptacle boxes @@ -2538,8 +2802,10 @@ public static GameObject spawnObjectInReceptacleRandomly( .ReceptacleTriggerBoxes[0] .GetComponent(); bool cornerCheck = true; - foreach (Vector3 p in corners) { - if (!con.CheckIfPointIsAboveReceptacleTriggerBox(p)) { + foreach (Vector3 p in corners) + { + if (!con.CheckIfPointIsAboveReceptacleTriggerBox(p)) + { cornerCheck = false; //this position would cause object to fall off table //double back and reset object to try again with another point @@ -2557,18 +2823,21 @@ public static GameObject spawnObjectInReceptacleRandomly( Mathf.Infinity, LayerMask.GetMask("NonInteractive") ) - ) { + ) + { floorCheck = false; } - if (!cornerCheck || !floorCheck) { + if (!cornerCheck || !floorCheck) + { success = false; continue; } } //if all corners were succesful, break out of this loop, don't keep trying - if (success) { + if (success) + { rb.isKinematic = false; toSpawn.objectID = objectId; toSpawn.name = objectId; @@ -2579,14 +2848,16 @@ public static GameObject spawnObjectInReceptacleRandomly( } //if after trying all spawn points, it failed to position, delete object from scene and return null - if (!success) { + if (!success) + { UnityEngine.Object.Destroy(toSpawn.transform.gameObject); return null; } return toSpawn.transform.gameObject; } - private static List GetCorners(SimObjPhysics sop) { + private static List GetCorners(SimObjPhysics sop) + { //get corners of the bounding box of the object spawned in GameObject bb = sop.BoundingBox.transform.gameObject; BoxCollider bbcol = bb.GetComponent(); @@ -2646,33 +2917,40 @@ private static List GetCorners(SimObjPhysics sop) { return corners; } - public static bool withinArrayBoundary((int row, int col) current, int rows, int columns) { + 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; } - public static BoundingBoxWithOffset getHoleAssetBoundingBox(string holeAssetId) { + public static BoundingBoxWithOffset getHoleAssetBoundingBox(string holeAssetId) + { var assetMap = ProceduralTools.getAssetMap(); - if (!assetMap.ContainsKey(holeAssetId)) { + if (!assetMap.ContainsKey(holeAssetId)) + { return null; } GameObject asset = assetMap.getAsset(holeAssetId); var holeMetadata = asset.GetComponentInChildren(); - if (holeMetadata == null) { + 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; // 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() { + return new BoundingBoxWithOffset() + { min = Vector3.zero, max = diff, offset = min @@ -2680,9 +2958,11 @@ public static BoundingBoxWithOffset getHoleAssetBoundingBox(string holeAssetId) } } - public static AssetMap GetMaterials() { + public static AssetMap GetMaterials() + { var assetDB = GameObject.FindObjectOfType(); - if (assetDB != null) { + if (assetDB != null) + { return new AssetMap( assetDB.materials.GroupBy(m => m.name).ToDictionary(m => m.Key, m => m.First()) ); @@ -2690,9 +2970,11 @@ public static AssetMap GetMaterials() { return null; } - public static AssetMap GetPrefabs() { + public static AssetMap GetPrefabs() + { var assetDB = GameObject.FindObjectOfType(); - if (assetDB != null) { + if (assetDB != null) + { return new AssetMap( assetDB .GetPrefabs() @@ -2703,31 +2985,37 @@ public static AssetMap GetPrefabs() { return null; } - public static Dictionary getAssetMetadata(GameObject asset) { - if (asset.GetComponent() == null) { + public static Dictionary getAssetMetadata(GameObject asset) + { + if (asset.GetComponent() == null) + { return null; } var simObj = asset.GetComponent(); var bb = simObj.AxisAlignedBoundingBox; - return new Dictionary() { + return new Dictionary() + { ["name"] = simObj.gameObject.name, ["objectType"] = simObj.Type.ToString(), ["primaryProperty"] = simObj.PrimaryProperty.ToString(), ["secondaryProperties"] = simObj .SecondaryProperties.Select(s => s.ToString()) .ToList(), - ["boundingBox"] = new BoundingBox() { + ["boundingBox"] = new BoundingBox() + { min = bb.center - bb.size / 2.0f, max = bb.center + bb.size / 2.0f } }; } - public static Texture2D SwapChannelsRGBAtoRRRB(Texture2D originalTexture) { + public static Texture2D SwapChannelsRGBAtoRRRB(Texture2D originalTexture) + { Color[] pixels = originalTexture.GetPixels(); - for (int i = 0; i < pixels.Length; i++) { + for (int i = 0; i < pixels.Length; i++) + { Color temp = pixels[i]; pixels[i] = new Color(temp.r, temp.r, temp.r, temp.b); } @@ -2760,7 +3048,8 @@ public static Dictionary CreateAsset( Transform parent = null, bool addAnotationComponent = false, string parentTexturesDir = "" - ) { + ) + { // create a new game object GameObject go = new GameObject(); @@ -2768,13 +3057,15 @@ public static Dictionary CreateAsset( GameObject meshObj = new GameObject("mesh"); meshObj.transform.parent = go.transform; Mesh mesh = new Mesh(); - if (vertices.Length >= 65535) { + if (vertices.Length >= 65535) + { mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32; } mesh.vertices = vertices; mesh.triangles = triangles; mesh.normals = normals; - if (uvs != null) { + if (uvs != null) + { mesh.uv = uvs; } mesh.RecalculateTangents(); @@ -2793,9 +3084,11 @@ public static Dictionary CreateAsset( meshCollidersObj.layer = LayerMask.NameToLayer("SimObjVisible"); meshCollidersObj.transform.parent = go.transform; List meshColliders = new List(); - if (colliders != null && colliders.Length > 0) { + if (colliders != null && colliders.Length > 0) + { int i = 0; - foreach (var collider in colliders) { + foreach (var collider in colliders) + { // create a mesh of the collider Mesh colliderMesh = new Mesh(); colliderMesh.vertices = collider.vertices; @@ -2827,7 +3120,8 @@ public static Dictionary CreateAsset( GameObject visPoints = new GameObject("VisibilityPoints"); visPoints.transform.parent = go.transform; Transform[] visPointTransforms = new Transform[visibilityPoints.Length]; - for (int i = 0; i < visibilityPoints.Length; i++) { + for (int i = 0; i < visibilityPoints.Length; i++) + { GameObject visPoint = new GameObject($"visPoint_{i}"); visPoint.transform.parent = visPoints.transform; visPoint.transform.localPosition = visibilityPoints[i]; @@ -2839,8 +3133,10 @@ public static Dictionary CreateAsset( go.transform.Rotate(Vector3.up, yRotOffset); GameObject newGo = new GameObject(); - foreach (Transform t in go.GetComponentsInChildren()) { - if (t.parent == go.transform) { + foreach (Transform t in go.GetComponentsInChildren()) + { + if (t.parent == go.transform) + { t.parent = newGo.transform; } } @@ -2852,7 +3148,8 @@ public static Dictionary CreateAsset( go.layer = LayerMask.NameToLayer("SimObjVisible"); go.tag = "SimObjPhysics"; - if (addAnotationComponent) { + if (addAnotationComponent) + { go.AddComponent(); } @@ -2860,7 +3157,8 @@ public static Dictionary CreateAsset( RuntimePrefab runtimePrefab = null; // load image from disk - if (albedoTexturePath != null) { + if (albedoTexturePath != null) + { albedoTexturePath = !Path.IsPathRooted(albedoTexturePath) ? Path.Combine(parentTexturesDir, albedoTexturePath) : albedoTexturePath; @@ -2880,39 +3178,48 @@ public static Dictionary CreateAsset( // assign the material to the game object meshObj.GetComponent().material = mat; runtimePrefab.sharedMaterial = mat; - } else { + } + else + { // create a new material mat = new Material(Shader.Find("Standard")); meshObj.GetComponent().material = mat; } - if (metallicSmoothnessTexturePath != null) { + if (metallicSmoothnessTexturePath != null) + { metallicSmoothnessTexturePath = !Path.IsPathRooted(metallicSmoothnessTexturePath) ? Path.Combine(parentTexturesDir, metallicSmoothnessTexturePath) : metallicSmoothnessTexturePath; - if (runtimePrefab == null) { + if (runtimePrefab == null) + { runtimePrefab = go.AddComponent(); } runtimePrefab.metallicSmoothnessTexturePath = metallicSmoothnessTexturePath; mat.EnableKeyword("_METALLICGLOSSMAP"); byte[] imageBytes = File.ReadAllBytes(metallicSmoothnessTexturePath); Texture2D tex = new Texture2D(2, 2); - if (metallicSmoothnessTexturePath.ToLower().EndsWith(".jpg")) { + if (metallicSmoothnessTexturePath.ToLower().EndsWith(".jpg")) + { tex = SwapChannelsRGBAtoRRRB(tex); } tex.LoadImage(imageBytes); mat.SetTexture("_MetallicGlossMap", tex); - } else { + } + else + { mat.SetFloat("_Metallic", 0f); mat.SetFloat("_Glossiness", 0f); } - if (normalTexturePath != null) { + if (normalTexturePath != null) + { normalTexturePath = !Path.IsPathRooted(normalTexturePath) ? Path.Combine(parentTexturesDir, normalTexturePath) : normalTexturePath; - if (runtimePrefab == null) { + if (runtimePrefab == null) + { runtimePrefab = go.AddComponent(); } runtimePrefab.normalTexturePath = normalTexturePath; @@ -2924,11 +3231,13 @@ public static Dictionary CreateAsset( mat.SetTexture("_BumpMap", tex); } - if (emissionTexturePath != null) { + if (emissionTexturePath != null) + { emissionTexturePath = !Path.IsPathRooted(emissionTexturePath) ? Path.Combine(parentTexturesDir, emissionTexturePath) : emissionTexturePath; - if (runtimePrefab == null) { + if (runtimePrefab == null) + { runtimePrefab = go.AddComponent(); } runtimePrefab.emissionTexturePath = emissionTexturePath; @@ -2946,7 +3255,8 @@ public static Dictionary CreateAsset( // add the rigidbody Rigidbody rb = go.AddComponent(); - if (physicalProperties != null) { + if (physicalProperties != null) + { rb.mass = physicalProperties.mass; rb.drag = physicalProperties.drag; rb.angularDrag = physicalProperties.angularDrag; @@ -2962,13 +3272,15 @@ public static Dictionary CreateAsset( sop.objectID = name; // add the annotations of the object - if (annotations == null) { + if (annotations == null) + { annotations = new ObjectAnnotations(); } sop.PrimaryProperty = (SimObjPrimaryProperty) Enum.Parse(typeof(SimObjPrimaryProperty), annotations.primaryProperty); sop.Type = (SimObjType)Enum.Parse(typeof(SimObjType), annotations.objectType); - if (annotations.secondaryProperties == null) { + if (annotations.secondaryProperties == null) + { annotations.secondaryProperties = new string[0]; } sop.SecondaryProperties = annotations @@ -2981,12 +3293,14 @@ public static Dictionary CreateAsset( forceCreateObjectOrientedBoundingBox: true ); - if (receptacleCandidate) { + if (receptacleCandidate) + { BaseFPSAgentController.TryToAddReceptacleTriggerBox(sop: sop); GameObject receptacleTriggerBoxes = go .transform.Find("ReceptacleTriggerBoxes") .gameObject; - if (receptacleTriggerBoxes.transform.childCount > 0) { + if (receptacleTriggerBoxes.transform.childCount > 0) + { sop.SecondaryProperties = new SimObjSecondaryProperty[] { SimObjSecondaryProperty.Receptacle @@ -2997,12 +3311,14 @@ public static Dictionary CreateAsset( // Add the asset to the procedural asset database var assetDb = GameObject.FindObjectOfType(); Transform prefabParentTransform = parent; - if (assetDb != null && assetDb.assetMap != null) { + if (assetDb != null && assetDb.assetMap != null) + { assetDb.addAsset(go, procedural: true); // get child object on assetDb's game object that's called "Prefabs" // and add the prefab to that prefabParentTransform = assetDb.transform.Find("Prefabs"); - if (prefabParentTransform == null) { + if (prefabParentTransform == null) + { var prefabParent = new GameObject("Prefabs"); prefabParent.transform.parent = assetDb.transform; prefabParent.SetActive(false); @@ -3028,8 +3344,10 @@ public static Dictionary CreateAsset( MonoBehaviour.Destroy(oldGo); - if (serializable) { - if (returnObject) { + if (serializable) + { + if (returnObject) + { result["gameObject"] = go; } } diff --git a/unity/Assets/Scripts/RandomExtensions.cs b/unity/Assets/Scripts/RandomExtensions.cs index f840127aaf..2f57b21748 100644 --- a/unity/Assets/Scripts/RandomExtensions.cs +++ b/unity/Assets/Scripts/RandomExtensions.cs @@ -3,8 +3,10 @@ using System.Collections; using System.Collections.Generic; -namespace RandomExtensions { - public static class RandomExtensions { +namespace RandomExtensions +{ + public static class RandomExtensions + { /** * Generates normally distributed numbers. Each operation makes two Gaussians for the price of one, * and apparently they can be cached or something for better performance, but who cares. @@ -12,7 +14,8 @@ public static class RandomExtensions { * @param mu Mean of the distribution * @param sigma Standard deviation */ - public static double NextGaussian(this Random r, double mu = 0, double sigma = 1) { + public static double NextGaussian(this Random r, double mu = 0, double sigma = 1) + { var u1 = r.NextDouble(); var u2 = r.NextDouble(); var rand_std_normal = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2); @@ -24,7 +27,8 @@ public static double NextGaussian(this Random r, double mu = 0, double sigma = 1 Double.IsNaN(rand_normal) || Double.IsInfinity(rand_normal) || Double.IsNegativeInfinity(rand_normal) - ) { + ) + { return mu; } diff --git a/unity/Assets/Scripts/Rearrangeable.cs b/unity/Assets/Scripts/Rearrangeable.cs index 3ff48e94b2..34883b4dae 100644 --- a/unity/Assets/Scripts/Rearrangeable.cs +++ b/unity/Assets/Scripts/Rearrangeable.cs @@ -2,19 +2,23 @@ using System.Collections; using UnityEngine; -public enum FurniturePosition { +public enum FurniturePosition +{ Undesirable, Desireable, } [ExecuteInEditMode] -public class Rearrangeable : MonoBehaviour { +public class Rearrangeable : MonoBehaviour +{ public bool EditorPos = false; public Transform StartPosition; public Transform EndPosition; public SimObj ParentSimObj; - public FurniturePosition Position { - get { + public FurniturePosition Position + { + get + { return ParentSimObj.Animator.GetBool("AnimState1") ? FurniturePosition.Undesirable : FurniturePosition.Desireable; @@ -23,29 +27,37 @@ public FurniturePosition Position { bool reportedError = false; - public void MoveTo(FurniturePosition state) { + public void MoveTo(FurniturePosition state) + { ParentSimObj.Animator.SetBool("AnimState1", state == FurniturePosition.Undesirable); } - void OnEnable() { - if (!Application.isPlaying) { - if (StartPosition == null) { + void OnEnable() + { + if (!Application.isPlaying) + { + if (StartPosition == null) + { StartPosition = new GameObject(name + "_StartPosition").transform; StartPosition.parent = transform.parent; StartPosition.localPosition = transform.localPosition; StartPosition.localRotation = transform.localRotation; } - if (EndPosition == null) { + if (EndPosition == null) + { EndPosition = new GameObject(name + "_EndPosition").transform; EndPosition.parent = transform.parent; EndPosition.localPosition = transform.localPosition; EndPosition.localRotation = transform.localRotation; } - if (ParentSimObj == null) { + if (ParentSimObj == null) + { ParentSimObj = gameObject.GetComponent(); } - if (ParentSimObj != null) { - if (!ParentSimObj.IsAnimated) { + if (ParentSimObj != null) + { + if (!ParentSimObj.IsAnimated) + { Animator a = ParentSimObj.gameObject.AddComponent(); a.runtimeAnimatorController = Resources.Load("ToggleableAnimController") as RuntimeAnimatorController; @@ -53,30 +65,39 @@ void OnEnable() { gameObject.SetActive(true); } } - } else { + } + else + { MoveTo(FurniturePosition.Undesirable); } } - void Update() { - if (ParentSimObj == null) { - if (!reportedError) { + void Update() + { + if (ParentSimObj == null) + { + if (!reportedError) + { reportedError = true; Debug.LogError("Parent sim obj null in rearrangeable " + name); } return; } - if (!ParentSimObj.IsAnimated) { - if (!reportedError) { + if (!ParentSimObj.IsAnimated) + { + if (!reportedError) + { reportedError = true; Debug.LogError("Parent sim obj is not animated in rearrangeable " + name); } return; } - if (StartPosition == null || EndPosition == null) { - if (!reportedError) { + if (StartPosition == null || EndPosition == null) + { + if (!reportedError) + { reportedError = true; Debug.LogError("Start or end positions is null in rearrangeable " + name); } @@ -84,26 +105,33 @@ void Update() { } bool startPos = false; - if (Application.isPlaying) { + if (Application.isPlaying) + { startPos = ParentSimObj.Animator.GetBool("AnimState1"); - } else { + } + else + { startPos = EditorPos; } ParentSimObj.transform.position = startPos ? StartPosition.position : EndPosition.position; ParentSimObj.transform.rotation = startPos ? StartPosition.rotation : EndPosition.rotation; } - void OnDrawGizmos() { - if (Application.isPlaying) { + void OnDrawGizmos() + { + if (Application.isPlaying) + { return; } - if (ParentSimObj == null || StartPosition == null || EndPosition == null) { + if (ParentSimObj == null || StartPosition == null || EndPosition == null) + { return; } MeshFilter mf = ParentSimObj.GetComponentInChildren(); - if (mf != null) { + if (mf != null) + { Gizmos.color = EditorPos ? Color.Lerp(Color.red, Color.clear, 0.5f) : Color.Lerp(Color.green, Color.clear, 0.5f); diff --git a/unity/Assets/Scripts/Receptacle.cs b/unity/Assets/Scripts/Receptacle.cs index a37ba48b0f..0155f5d815 100644 --- a/unity/Assets/Scripts/Receptacle.cs +++ b/unity/Assets/Scripts/Receptacle.cs @@ -4,19 +4,25 @@ [RequireComponent(typeof(SimObj))] [ExecuteInEditMode] -public class Receptacle : MonoBehaviour { +public class Receptacle : MonoBehaviour +{ public Collider VisibilityCollider; public Transform[] Pivots; public GameObject MessItem; - public bool IsClean { - get { - if (MessItem != null) { + public bool IsClean + { + get + { + if (MessItem != null) + { return !MessItem.activeSelf; } return true; } - set { - if (MessItem != null) { + set + { + if (MessItem != null) + { MessItem.SetActive(!value); } } @@ -25,8 +31,10 @@ public bool IsClean { private SimObj[] startupItems; private Vector3 lastPosition; - protected virtual void OnEnable() { - if (VisibilityCollider == null) { + protected virtual void OnEnable() + { + if (VisibilityCollider == null) + { Debug.LogError( "Visibility collider is not set on receptacle " + name + " - this should not happen" ); @@ -37,20 +45,26 @@ protected virtual void OnEnable() { // leave other colliders alone VisibilityCollider.tag = SimUtil.ReceptacleTag; - if (Application.isPlaying) { + if (Application.isPlaying) + { // un-parent all parented sim objs temporarily // this way any sim objs we're holding can grab their colliders startupItems = new SimObj[Pivots.Length]; - for (int i = 0; i < Pivots.Length; i++) { - if (Pivots[i].childCount > 0) { + for (int i = 0; i < Pivots.Length; i++) + { + if (Pivots[i].childCount > 0) + { startupItems[i] = Pivots[i].GetChild(0).GetComponent(); - if (startupItems[i] == null) { + if (startupItems[i] == null) + { Debug.LogError( "Found a non-SimObj child in a receptacle " + name + " pivot - this should not happen" ); - } else { + } + else + { startupItems[i].transform.parent = null; } } @@ -58,26 +72,32 @@ protected virtual void OnEnable() { // see if we have more than 1 collider - if we do, make the visibility collider a trigger Collider[] colliders = gameObject.GetComponentsInChildren(); - if (colliders.Length > 1) { + if (colliders.Length > 1) + { VisibilityCollider.isTrigger = true; } } } - protected void Start() { - if (Application.isPlaying) { + protected void Start() + { + if (Application.isPlaying) + { // now that all sim objs have updated themselves // re-parent all children of pivots // and set any sim objs to invisible - for (int i = 0; i < Pivots.Length; i++) { - if (startupItems[i] != null) { + for (int i = 0; i < Pivots.Length; i++) + { + if (startupItems[i] != null) + { startupItems[i].transform.parent = Pivots[i]; startupItems[i].transform.localPosition = Vector3.zero; startupItems[i].transform.localRotation = Quaternion.identity; startupItems[i].VisibleToRaycasts = false; // if the item starts in a receptacle, it has no 'startup position' // so destroy its startup transform - if (startupItems[i].StartupTransform != null) { + if (startupItems[i].StartupTransform != null) + { GameObject.Destroy(startupItems[i].StartupTransform.gameObject); } } @@ -85,9 +105,12 @@ protected void Start() { } } - void OnDrawGizmos() { - if (Pivots != null && Pivots.Length > 0) { - foreach (Transform pivot in Pivots) { + void OnDrawGizmos() + { + if (Pivots != null && Pivots.Length > 0) + { + foreach (Transform pivot in Pivots) + { Gizmos.color = Color.Lerp(Color.cyan, Color.clear, 0.5f); Gizmos.DrawCube(pivot.position, Vector3.one * 0.05f); Gizmos.color = Color.green; diff --git a/unity/Assets/Scripts/ResourceAssetManager.cs b/unity/Assets/Scripts/ResourceAssetManager.cs index 9541854540..ab272b7a29 100644 --- a/unity/Assets/Scripts/ResourceAssetManager.cs +++ b/unity/Assets/Scripts/ResourceAssetManager.cs @@ -6,31 +6,38 @@ using UnityEngine; public class ResourceAssetReference - where T : UnityEngine.Object { + where T : UnityEngine.Object +{ public readonly string Name; public readonly string ResourcePath; private T _asset; - public ResourceAssetReference(string resourcePath, string name) { + public ResourceAssetReference(string resourcePath, string name) + { this.Name = name; this.ResourcePath = resourcePath; } - public T Load() { - if (this._asset == null) { + public T Load() + { + if (this._asset == null) + { this._asset = Resources.Load(ResourcePath); } return this._asset; } } -public class ResourceAssetManager { - private class ResourceAsset { +public class ResourceAssetManager +{ + private class ResourceAsset + { // must have empty constructor for JSON deserialization public ResourceAsset() { } #if UNITY_EDITOR - public ResourceAsset(string assetPath) { + public ResourceAsset(string assetPath) + { var asset = AssetDatabase.LoadMainAssetAtPath(assetPath); this.path = assetPath; this.labels = AssetDatabase.GetLabels(asset); @@ -45,8 +52,10 @@ public ResourceAsset(string assetPath) { public string name; } - private class ResourceAssetCatalog { - public ResourceAssetCatalog() { + private class ResourceAssetCatalog + { + public ResourceAssetCatalog() + { this.assets = new List(); this.timestamp = DateTimeOffset.Now.ToUnixTimeSeconds(); } @@ -62,7 +71,8 @@ public ResourceAssetCatalog() { private Dictionary> labelIndex = new Dictionary>(); - public ResourceAssetManager() { + public ResourceAssetManager() + { #if UNITY_EDITOR this.RefreshCatalog(); #else @@ -77,20 +87,24 @@ public ResourceAssetManager() { #if UNITY_EDITOR - private string[] findResourceGuids() { + private string[] findResourceGuids() + { return AssetDatabase.FindAssets("t:material", new[] { "Assets/Resources" }); } - public void RefreshCatalog() { + public void RefreshCatalog() + { this.catalog = new ResourceAssetCatalog(); - foreach (string guid in this.findResourceGuids()) { + 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 - ) { + ) + { continue; } @@ -100,16 +114,21 @@ public void RefreshCatalog() { this.generateLabelIndex(); } - public void BuildCatalog() { + public void BuildCatalog() + { this.RefreshCatalog(); this.writeCatalog(); } #endif - private void generateLabelIndex() { - foreach (var labeledAsset in this.catalog.assets) { - foreach (var label in labeledAsset.labels) { - if (!this.labelIndex.ContainsKey(label)) { + private void generateLabelIndex() + { + foreach (var labeledAsset in this.catalog.assets) + { + foreach (var label in labeledAsset.labels) + { + if (!this.labelIndex.ContainsKey(label)) + { this.labelIndex[label] = new List(); } this.labelIndex[label].Add(labeledAsset); @@ -117,9 +136,11 @@ private void generateLabelIndex() { } } - private ResourceAssetCatalog readCatalog() { + private ResourceAssetCatalog readCatalog() + { string catalogResourcePath = relativePath(ResourcesPath, CatalogPath); - if (Path.HasExtension(catalogResourcePath)) { + if (Path.HasExtension(catalogResourcePath)) + { string ext = Path.GetExtension(catalogResourcePath); catalogResourcePath = catalogResourcePath.Remove( catalogResourcePath.Length - ext.Length, @@ -128,7 +149,8 @@ private ResourceAssetCatalog readCatalog() { } var jsonResource = Resources.Load(catalogResourcePath); - if (jsonResource == null) { + if (jsonResource == null) + { return null; } @@ -136,21 +158,25 @@ private ResourceAssetCatalog readCatalog() { } // just handles case where relativeTo is the prefix of fullPath - private string relativePath(string relativeTo, string fullPath) { + private string relativePath(string relativeTo, string fullPath) + { return fullPath.Remove(0, relativeTo.Length); } - private void writeCatalog() { + private void writeCatalog() + { string json = serialize(this.catalog); // .tmp files are ignored by Unity under Assets/ string tmpCatalogPath = CatalogPath + ".tmp"; - if (File.Exists(tmpCatalogPath)) { + if (File.Exists(tmpCatalogPath)) + { File.Delete(tmpCatalogPath); } File.WriteAllText(tmpCatalogPath, json); - if (File.Exists(CatalogPath)) { + if (File.Exists(CatalogPath)) + { File.Delete(CatalogPath); } // Doing a delete + move to make the write atomic and avoid writing a possibly invalid JSON @@ -159,12 +185,16 @@ private void writeCatalog() { } public List> FindResourceAssetReferences(string label) - where T : UnityEngine.Object { + 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) { + 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), @@ -179,17 +209,21 @@ public List> FindResourceAssetReferences(string lab } return assetRefs; - } else { + } + else + { return assetRefs; } } - private string serialize(ResourceAssetCatalog catalog) { + private string serialize(ResourceAssetCatalog catalog) + { var jsonResolver = new ShouldSerializeContractResolver(); return Newtonsoft.Json.JsonConvert.SerializeObject( catalog, Newtonsoft.Json.Formatting.None, - new Newtonsoft.Json.JsonSerializerSettings() { + new Newtonsoft.Json.JsonSerializerSettings() + { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore, ContractResolver = jsonResolver } diff --git a/unity/Assets/Scripts/RobotArmTest/Adjust_Slider.cs b/unity/Assets/Scripts/RobotArmTest/Adjust_Slider.cs index e5ef9cef0d..686eb0d014 100644 --- a/unity/Assets/Scripts/RobotArmTest/Adjust_Slider.cs +++ b/unity/Assets/Scripts/RobotArmTest/Adjust_Slider.cs @@ -2,24 +2,30 @@ using System.Collections.Generic; using UnityEngine; -public class Adjust_Slider : MonoBehaviour { +public class Adjust_Slider : MonoBehaviour +{ public Transform robotArmRoot; Vector3 localStartingPoint; float minThreshold = -0.32f; float maxThreshold = 0.15f; - void Start() { + void Start() + { localStartingPoint = this.transform.localPosition; } - void Update() { - if (robotArmRoot.localPosition.y < minThreshold) { + 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 ); - } else if (robotArmRoot.localPosition.y > maxThreshold) { + } + else if (robotArmRoot.localPosition.y > maxThreshold) + { this.transform.localPosition = new Vector3( this.transform.localPosition.x, localStartingPoint.y + Mathf.Abs(robotArmRoot.localPosition.y - maxThreshold), diff --git a/unity/Assets/Scripts/RobotArmTest/Align_to_Joint_Normal.cs b/unity/Assets/Scripts/RobotArmTest/Align_to_Joint_Normal.cs index 1581969b15..91817bc88f 100644 --- a/unity/Assets/Scripts/RobotArmTest/Align_to_Joint_Normal.cs +++ b/unity/Assets/Scripts/RobotArmTest/Align_to_Joint_Normal.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class Align_to_Joint_Normal : MonoBehaviour { +public class Align_to_Joint_Normal : MonoBehaviour +{ public Transform root; public Transform mid; public Transform tip; @@ -13,15 +14,19 @@ public class Align_to_Joint_Normal : MonoBehaviour { jointTangent; Transform positionAlignedJoint; - void Update() { + void Update() + { joint1 = mid.position - root.position; joint2 = tip.position - mid.position; jointNormal = Vector3.Cross(joint1, joint2); - if (isMidJointAngler == true) { + if (isMidJointAngler == true) + { positionAlignedJoint = tip; jointTangent = Vector3.Cross(joint2, jointNormal); - } else { + } + else + { positionAlignedJoint = mid; jointTangent = Vector3.Cross(joint1, jointNormal); } diff --git a/unity/Assets/Scripts/RobotArmTest/FK_IK_Solver.cs b/unity/Assets/Scripts/RobotArmTest/FK_IK_Solver.cs index 4a7cf5950c..d91b6f1f9f 100644 --- a/unity/Assets/Scripts/RobotArmTest/FK_IK_Solver.cs +++ b/unity/Assets/Scripts/RobotArmTest/FK_IK_Solver.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class FK_IK_Solver : MonoBehaviour { +public class FK_IK_Solver : MonoBehaviour +{ public bool isIKDriven; public Transform armRoot, armShoulder, @@ -42,7 +43,8 @@ public class FK_IK_Solver : MonoBehaviour { elbowPosition; // this must be Awake vs Start since when the Arm is activated, Start() will not have been called - void Awake() { + void Awake() + { bone1Length = (armShoulder.position - armRoot.position).magnitude; bone2Length = (armElbow.position - armShoulder.position).magnitude; bone3Length = (armWrist.position - armElbow.position).magnitude; @@ -51,14 +53,17 @@ void Awake() { #if UNITY_EDITOR // Uncomment this when testing in Unity - void Update() { + void Update() + { ManipulateArm(); } #endif - public void ManipulateArm() { + public void ManipulateArm() + { // Check if arm is driven by IK or FK - if (isIKDriven == true) { + if (isIKDriven == true) + { // Adjust pole position IKPole.parent.position = IKTarget.position; IKPole.parent.forward = IKTarget.position - armShoulder.position; @@ -67,7 +72,8 @@ public void ManipulateArm() { 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; @@ -136,13 +142,17 @@ public void ManipulateArm() { armElbow.position = elbowPosition; armWrist.position = IKTarget.position; armWrist.rotation = IKTarget.rotation; - } else { + } + else + { Vector3 armDirectionVector = (IKTarget.position - armShoulder.position).normalized; armElbow.position = armShoulder.position + armDirectionVector * bone1Length; armWrist.position = armElbow.position + armDirectionVector * bone2Length; armWrist.rotation = IKTarget.rotation; } - } else { + } + else + { armRoot.position = FKRootTarget.position; armRoot.rotation = FKRootTarget.rotation; armShoulder.position = FKShoulderTarget.position; @@ -162,7 +172,8 @@ public void ManipulateArm() { AlignToJointNormal(armWrist.GetChild(0), armElbow, armWrist, armHand, true); } - float FindParameter(float p0x, float p0y, float p0z, float a, float b, float c, float d) { + 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)); @@ -175,7 +186,8 @@ void AlignToJointNormal( Transform mid, Transform tip, bool isMidJointAngled - ) { + ) + { Vector3 bone1 = mid.position - root.position; Vector3 bone2 = tip.position - mid.position; Vector3 jointNormal = Vector3.Cross(bone1, bone2); @@ -183,10 +195,13 @@ bool isMidJointAngled Transform positionAlignedJoint; - if (isMidJointAngled == true) { + if (isMidJointAngled == true) + { positionAlignedJoint = tip; jointTangent = Vector3.Cross(bone2, jointNormal); - } else { + } + else + { positionAlignedJoint = mid; jointTangent = Vector3.Cross(bone1, jointNormal); } diff --git a/unity/Assets/Scripts/RobotArmTest/Manipulator_Clamp.cs b/unity/Assets/Scripts/RobotArmTest/Manipulator_Clamp.cs index daa07e3475..0a49e46de1 100644 --- a/unity/Assets/Scripts/RobotArmTest/Manipulator_Clamp.cs +++ b/unity/Assets/Scripts/RobotArmTest/Manipulator_Clamp.cs @@ -3,7 +3,8 @@ using System.Collections.Generic; using UnityEngine; -public class Manipulator_Clamp : MonoBehaviour { +public class Manipulator_Clamp : MonoBehaviour +{ Vector3[] currentCoordinates = new Vector3[2]; Vector3[] prevCoordinates = new Vector3[2]; Transform rootJoint; @@ -12,34 +13,42 @@ public class Manipulator_Clamp : MonoBehaviour { Vector3 rootToShoulder; Vector3 shoulderToWrist; - void Start() { + void Start() + { currentCoordinates[0] = transform.position; currentCoordinates[1] = transform.eulerAngles; prevCoordinates = currentCoordinates; - foreach (Transform transform in transform.parent.parent.parent) { - if (transform.name == "robot_arm_1_jnt") { + foreach (Transform transform in transform.parent.parent.parent) + { + if (transform.name == "robot_arm_1_jnt") + { rootJoint = transform; } } - foreach (Transform transform in rootJoint) { - if (transform.name == "robot_arm_2_jnt") { + foreach (Transform transform in rootJoint) + { + if (transform.name == "robot_arm_2_jnt") + { shoulderJoint = transform; } } } - void Update() { + void Update() + { // Debug.Log("Checking for hemisphere change!"); - if (transform.position != prevCoordinates[0]) { + if (transform.position != prevCoordinates[0]) + { // Clamp to front hemisphere rootToWrist = rootJoint.InverseTransformPoint(transform.position); // Debug.Log("Z from " + rootJoint.gameObject.name + " to " + transform.gameObject.name + ": " + rootToWrist); rootToShoulder = shoulderJoint.localPosition; // Debug.Log("Z from " + rootJoint.gameObject.name + " to shoulder: " + shoulderJoint.gameObject.name + ": " + rootToShoulder); - if (rootToWrist.z - 0.01f <= rootToShoulder.z) { + 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) @@ -51,7 +60,8 @@ void Update() { // Maximum shoulder-to-wrist length is ~0.6335!!! shoulderToWrist = rootToWrist - rootToShoulder; // Debug.Log(shoulderToWrist.magnitude + " vs " + shoulderJoint.InverseTransformPoint(transform.position).magnitude); - if (shoulderToWrist.sqrMagnitude >= Mathf.Pow(0.6335f, 2) && shoulderToWrist.z > 0) { + 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 diff --git a/unity/Assets/Scripts/RobotArmTest/Stretch_Arm_Solver.cs b/unity/Assets/Scripts/RobotArmTest/Stretch_Arm_Solver.cs index 415f5a35ee..5479a2f062 100644 --- a/unity/Assets/Scripts/RobotArmTest/Stretch_Arm_Solver.cs +++ b/unity/Assets/Scripts/RobotArmTest/Stretch_Arm_Solver.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class Stretch_Arm_Solver : MonoBehaviour { +public class Stretch_Arm_Solver : MonoBehaviour +{ public Transform armRoot, armTarget; Transform arm1, @@ -20,12 +21,14 @@ public class Stretch_Arm_Solver : MonoBehaviour { frontArmExtensionLimit = 0.516f; #if UNITY_EDITOR - void Update() { + void Update() + { ManipulateStretchArm(); } #endif - public void ManipulateStretchArm() { + public void ManipulateStretchArm() + { arm1 = armRoot.GetChild(0); arm2 = arm1.GetChild(0); arm3 = arm2.GetChild(0); diff --git a/unity/Assets/Scripts/RoomProperties.cs b/unity/Assets/Scripts/RoomProperties.cs index fb7e0d5843..b3914a86ad 100644 --- a/unity/Assets/Scripts/RoomProperties.cs +++ b/unity/Assets/Scripts/RoomProperties.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class RoomProperties : MonoBehaviour { +public class RoomProperties : MonoBehaviour +{ // TODO make an enum once we have a final set of room types //public enum RoomType {} public string RoomType; diff --git a/unity/Assets/Scripts/RuntimePrefab.cs b/unity/Assets/Scripts/RuntimePrefab.cs index 5155bd59e5..8c93dbdf2e 100644 --- a/unity/Assets/Scripts/RuntimePrefab.cs +++ b/unity/Assets/Scripts/RuntimePrefab.cs @@ -11,7 +11,8 @@ #endif [ExecuteInEditMode] -public class RuntimePrefab : MonoBehaviour { +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, @@ -29,9 +30,11 @@ public class RuntimePrefab : MonoBehaviour { // the texture again, since they can share it. public Material sharedMaterial; - Texture2D SwapChannelsRGBAtoRRRB(Texture2D originalTexture) { + Texture2D SwapChannelsRGBAtoRRRB(Texture2D originalTexture) + { Color[] pixels = originalTexture.GetPixels(); - for (int i = 0; i < pixels.Length; i++) { + for (int i = 0; i < pixels.Length; i++) + { Color temp = pixels[i]; pixels[i] = new Color(temp.r, temp.r, temp.r, temp.b); // Swap R and B } @@ -42,11 +45,14 @@ Texture2D SwapChannelsRGBAtoRRRB(Texture2D originalTexture) { return newTexture; } - private void reloadtextures() { + private void reloadtextures() + { GameObject mesh = transform.Find("mesh").gameObject; // load the texture from disk - if (!string.IsNullOrEmpty(albedoTexturePath)) { - if (sharedMaterial.mainTexture == null) { + if (!string.IsNullOrEmpty(albedoTexturePath)) + { + if (sharedMaterial.mainTexture == null) + { byte[] imageBytes = File.ReadAllBytes(albedoTexturePath); Texture2D tex = new Texture2D(2, 2); tex.LoadImage(imageBytes); @@ -54,18 +60,21 @@ private void reloadtextures() { } } - if (!string.IsNullOrEmpty(metallicSmoothnessTexturePath)) { + if (!string.IsNullOrEmpty(metallicSmoothnessTexturePath)) + { sharedMaterial.EnableKeyword("_METALLICGLOSSMAP"); byte[] imageBytes = File.ReadAllBytes(metallicSmoothnessTexturePath); Texture2D tex = new Texture2D(2, 2); tex.LoadImage(imageBytes); - if (metallicSmoothnessTexturePath.ToLower().EndsWith(".jpg")) { + if (metallicSmoothnessTexturePath.ToLower().EndsWith(".jpg")) + { tex = SwapChannelsRGBAtoRRRB(tex); } sharedMaterial.SetTexture("_MetallicGlossMap", tex); } - if (!string.IsNullOrEmpty(normalTexturePath)) { + if (!string.IsNullOrEmpty(normalTexturePath)) + { sharedMaterial.EnableKeyword("_NORMALMAP"); byte[] imageBytes = File.ReadAllBytes(normalTexturePath); Texture2D tex = new Texture2D(2, 2); @@ -73,7 +82,8 @@ private void reloadtextures() { sharedMaterial.SetTexture("_BumpMap", tex); } - if (!string.IsNullOrEmpty(emissionTexturePath)) { + if (!string.IsNullOrEmpty(emissionTexturePath)) + { sharedMaterial.globalIlluminationFlags = MaterialGlobalIlluminationFlags.RealtimeEmissive; sharedMaterial.EnableKeyword("_EMISSION"); @@ -85,13 +95,15 @@ private void reloadtextures() { } } - public void Awake() { + public void Awake() + { reloadtextures(); } #if UNITY_EDITOR [Button(Expanded = true)] - public void RealoadTextures() { + public void RealoadTextures() + { reloadtextures(); } diff --git a/unity/Assets/Scripts/SceneManager.cs b/unity/Assets/Scripts/SceneManager.cs index ea4ccab543..a83492bf02 100644 --- a/unity/Assets/Scripts/SceneManager.cs +++ b/unity/Assets/Scripts/SceneManager.cs @@ -9,10 +9,14 @@ #endif [ExecuteInEditMode] -public class SceneManager : MonoBehaviour { - public static SceneManager Current { - get { - if (current == null) { +public class SceneManager : MonoBehaviour +{ + public static SceneManager Current + { + get + { + if (current == null) + { current = GameObject.FindObjectOfType(); } return current; @@ -50,11 +54,13 @@ public static SceneManager Current { public List ObjectsInScene = new List(); - void OnEnable() { + void OnEnable() + { GatherSimObjsInScene(); #if UNITY_EDITOR - if (!Application.isPlaying) { + if (!Application.isPlaying) + { SetUpParents(); SetUpFPSController(); SetUpNavigation(); @@ -66,7 +72,8 @@ void OnEnable() { } // generates a object ID for a sim object - public void AssignObjectID(SimObj obj) { + public void AssignObjectID(SimObj obj) + { // object ID is a string consisting of: //[SimObjType]_[X0.00]:[Y0.00]:[Z0.00] Vector3 pos = obj.transform.position; @@ -76,20 +83,24 @@ public void AssignObjectID(SimObj obj) { obj.ObjectID = obj.Type.ToString() + "|" + xPos + "|" + yPos + "|" + zPos; } - public void GatherSimObjsInScene() { + public void GatherSimObjsInScene() + { ObjectsInScene = new List(); ObjectsInScene.AddRange(GameObject.FindObjectsOfType()); ObjectsInScene.Sort((x, y) => (x.Type.ToString().CompareTo(y.Type.ToString()))); - foreach (SimObj o in ObjectsInScene) { + foreach (SimObj o in ObjectsInScene) + { AssignObjectID(o); } } #if UNITY_EDITOR // returns an array of required types NOT found in scene - public SimObjType[] CheckSceneForRequiredTypes() { + public SimObjType[] CheckSceneForRequiredTypes() + { List typesToCheck = null; - switch (LocalSceneType) { + switch (LocalSceneType) + { case SceneType.Kitchen: default: typesToCheck = new List(RequiredObjectTypes); @@ -107,13 +118,15 @@ public SimObjType[] CheckSceneForRequiredTypes() { typesToCheck = new List(RequiredTypesBathroom); break; } - foreach (SimObj obj in ObjectsInScene) { + foreach (SimObj obj in ObjectsInScene) + { typesToCheck.Remove(obj.Type); } return typesToCheck.ToArray(); } - public void SetUpParents() { + public void SetUpParents() + { FindOrCreateParent(ref ObjectsParent, ObjectsParentName); FindOrCreateParent(ref ControlsParent, ControlsParentName); FindOrCreateParent(ref LightingParent, LightingParentName); @@ -121,22 +134,30 @@ public void SetUpParents() { FindOrCreateParent(ref TargetsParent, TargetsParentName); } - public void AutoStructureNavigation() { + public void AutoStructureNavigation() + { Transform[] transforms = StructureParent.GetComponentsInChildren(); // take a wild guess that floor will be floor and ceiling will be ceiling - foreach (Transform t in transforms) { - if (t.name.Contains("Ceiling")) { + foreach (Transform t in transforms) + { + if (t.name.Contains("Ceiling")) + { // set it to not walkable GameObjectUtility.SetNavMeshArea(t.gameObject, PlacementManager.NavemeshNoneArea); - } else if (t.name.Contains("Floor")) { + } + else if (t.name.Contains("Floor")) + { // set it to floor GameObjectUtility.SetNavMeshArea(t.gameObject, PlacementManager.NavmeshFloorArea); - } else { + } + 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 @@ -150,15 +171,18 @@ public void AutoStructureNavigation() { } } - public void GatherObjectsUnderParents() { + public void GatherObjectsUnderParents() + { SetUpParents(); // move everything under structure by default // then move things to other folders based on their tags or type SimObj[] simObjs = GameObject.FindObjectsOfType(); - foreach (SimObj o in simObjs) { + foreach (SimObj o in simObjs) + { Receptacle r = o.transform.GetComponentInParent(); - if (r == null || r.gameObject == o.gameObject) { + if (r == null || r.gameObject == o.gameObject) + { o.transform.parent = ObjectsParent; } } @@ -166,7 +190,8 @@ public void GatherObjectsUnderParents() { GameObject[] rootObjects = UnityEngine .SceneManagement.SceneManager.GetActiveScene() .GetRootGameObjects(); - foreach (GameObject rootObject in rootObjects) { + foreach (GameObject rootObject in rootObjects) + { // make sure it's not a parent if ( rootObject != gameObject @@ -176,49 +201,60 @@ public void GatherObjectsUnderParents() { && rootObject.transform != TargetsParent && rootObject.transform != ControlsParent && rootObject.name != FPSControllerPrefab.name - ) { + ) + { rootObject.transform.parent = StructureParent; EditorUtility.SetDirty(rootObject); } } ReflectionProbe[] probes = GameObject.FindObjectsOfType(); - foreach (ReflectionProbe p in probes) { + foreach (ReflectionProbe p in probes) + { p.transform.parent = LightingParent; } Light[] lights = GameObject.FindObjectsOfType(); - foreach (Light l in lights) { + foreach (Light l in lights) + { // TODO specify whether to gather prefab lights // if it's NOT in a prefab, move it - if (PrefabUtility.GetCorrespondingObjectFromSource(l.gameObject) == null) { + if (PrefabUtility.GetCorrespondingObjectFromSource(l.gameObject) == null) + { l.transform.parent = LightingParent; } } // tag all the structure colliders Collider[] cols = StructureParent.GetComponentsInChildren(); - foreach (Collider c in cols) { + foreach (Collider c in cols) + { c.tag = "Structure"; c.gameObject.layer = SimUtil.RaycastVisibleLayer; } // set all structure transforms to static Transform[] transforms = StructureParent.GetComponentsInChildren(); - foreach (Transform tr in transforms) { + foreach (Transform tr in transforms) + { tr.gameObject.isStatic = true; GameObjectUtility.SetStaticEditorFlags(tr.gameObject, StaticEditorFlags.BatchingStatic); } } - public void ReplaceGenerics() { + public void ReplaceGenerics() + { SimObj[] simObjs = GameObject.FindObjectsOfType(); - foreach (SimObj generic in simObjs) { - foreach (SimObj platonic in PlatonicPrefabs) { - if (generic.Type == platonic.Type) { + foreach (SimObj generic in simObjs) + { + 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; - if (prefab == null || prefab != platonic.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 = @@ -236,7 +272,8 @@ public void ReplaceGenerics() { } } - public void SetUpLighting() { + public void SetUpLighting() + { // thanks for not exposing these props, Unity :P // this may break in later versions var getLightmapSettingsMethod = typeof(LightmapEditorSettings).GetMethod( @@ -260,7 +297,8 @@ public void SetUpLighting() { settingsObject.ApplyModifiedProperties(); } - public void SetUpNavigation() { + public void SetUpNavigation() + { // thanks for not exposing these props, Unity :P // this may break in later versions SerializedObject settingsObject = new SerializedObject( @@ -286,26 +324,34 @@ public void SetUpNavigation() { settingsObject.ApplyModifiedProperties(); } - public void SetUpFPSController() { - if (FPSControllerPrefab == null) { + public void SetUpFPSController() + { + if (FPSControllerPrefab == null) + { Debug.LogError("FPS controller prefab is not set in Scene Manager."); return; } GameObject fpsObj = GameObject.Find(FPSControllerPrefab.name); - if (fpsObj == null) { + if (fpsObj == null) + { fpsObj = PrefabUtility.InstantiatePrefab(FPSControllerPrefab) as GameObject; fpsObj.name = FPSControllerPrefab.name; - } else { + } + else + { // re-attach to prefab GameObject prefabParent = PrefabUtility.GetCorrespondingObjectFromSource(fpsObj) as GameObject; - if (prefabParent == null) { + if (prefabParent == null) + { // if it's not attached to a prefab, delete and start over Vector3 pos = fpsObj.transform.position; GameObject.DestroyImmediate(fpsObj); fpsObj = PrefabUtility.InstantiatePrefab(FPSControllerPrefab) as GameObject; fpsObj.transform.position = pos; - } else { + } + else + { PrefabUtility.RevertPrefabInstance(fpsObj, InteractionMode.AutomatedAction); } } @@ -348,9 +394,11 @@ public void SetUpFPSController() { //} } - void FindOrCreateParent(ref Transform parentTransform, string parentName) { + void FindOrCreateParent(ref Transform parentTransform, string parentName) + { GameObject parentGo = GameObject.Find(parentName); - if (parentGo == null) { + if (parentGo == null) + { parentGo = new GameObject(parentName); } // set to root just in case @@ -361,17 +409,20 @@ void FindOrCreateParent(ref Transform parentTransform, string parentName) { #endif } -public enum SceneAnimationMode { +public enum SceneAnimationMode +{ Instant, Smooth, } -public enum ScenePhysicsMode { +public enum ScenePhysicsMode +{ Static, Dynamic, } -public enum SceneType { +public enum SceneType +{ Kitchen, LivingRoom, Bathroom, diff --git a/unity/Assets/Scripts/ScreenShotFromCamera.cs b/unity/Assets/Scripts/ScreenShotFromCamera.cs index 99f009cf7f..81e9f0bbe5 100644 --- a/unity/Assets/Scripts/ScreenShotFromCamera.cs +++ b/unity/Assets/Scripts/ScreenShotFromCamera.cs @@ -1,13 +1,15 @@ using System.Collections; using UnityEngine; -public class ScreenShotFromCamera : MonoBehaviour { +public class ScreenShotFromCamera : MonoBehaviour +{ public int resWidth = 3840; public int resHeight = 2160; private bool takeHiResShot = false; - public static string ScreenShotName(int width, int height) { + public static string ScreenShotName(int width, int height) + { return string.Format( "{0}/screenshots/screen_{1}x{2}_{3}.png", Application.dataPath, @@ -17,13 +19,16 @@ public static string ScreenShotName(int width, int height) { ); } - public void TakeHiResShot() { + public void TakeHiResShot() + { takeHiResShot = true; } - void LateUpdate() { + void LateUpdate() + { takeHiResShot |= Input.GetKeyDown("k"); - if (takeHiResShot) { + if (takeHiResShot) + { RenderTexture rt = new RenderTexture(resWidth, resHeight, 24); GetComponent().targetTexture = rt; Texture2D screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGB24, false); diff --git a/unity/Assets/Scripts/Screenshot360.cs b/unity/Assets/Scripts/Screenshot360.cs index 8090785b7e..5360116c55 100644 --- a/unity/Assets/Scripts/Screenshot360.cs +++ b/unity/Assets/Scripts/Screenshot360.cs @@ -6,11 +6,13 @@ using UnityEditor; #endif -public class Screenshot360 : MonoBehaviour { +public class Screenshot360 : MonoBehaviour +{ #if UNITY_EDITOR [MenuItem("GameObject/Take 360 Screenshot")] #endif - private static void Generate360Screenshot() { + private static void Generate360Screenshot() + { int imageWidth = 4096; bool saveAsJPEG = true; bool newFileName = false; @@ -19,8 +21,10 @@ private static void Generate360Screenshot() { byte[] bytes = I360Render.Capture(imageWidth, saveAsJPEG); - if (bytes != null) { - while (!newFileName) { + if (bytes != null) + { + while (!newFileName) + { if ( File.Exists( "Assets/360Photos/360Render_" @@ -29,9 +33,12 @@ private static void Generate360Screenshot() { + currentCount + (saveAsJPEG ? ".jpeg" : ".png") ) - ) { + ) + { currentCount++; - } else { + } + else + { path = Path.Combine( "Assets/360Photos", "360Render_" diff --git a/unity/Assets/Scripts/SerializeMesh.cs b/unity/Assets/Scripts/SerializeMesh.cs index 8f0e53c8ad..6925bf7567 100644 --- a/unity/Assets/Scripts/SerializeMesh.cs +++ b/unity/Assets/Scripts/SerializeMesh.cs @@ -7,9 +7,11 @@ using UnityEditor; #endif -namespace Thor.Utils { +namespace Thor.Utils +{ [System.Serializable] - public class SerializableMesh { + public class SerializableMesh + { // [SerializeField] public Vector2[] uv; // [SerializeField] public Vector3[] verticies; // [SerializeField] public Vector3[] normals; @@ -24,7 +26,8 @@ public class SerializableMesh { [ExecuteInEditMode] [RequireComponent(typeof(MeshFilter))] - public class SerializeMesh : MonoBehaviour { + public class SerializeMesh : MonoBehaviour + { // [HideInInspector] [SerializeField] Vector2[] uv; // [HideInInspector] [SerializeField] Vector3[] verticies; // [HideInInspector] [SerializeField] Vector3[] normals; @@ -42,11 +45,13 @@ public class SerializeMesh : MonoBehaviour { private static int materialCount = 0; - private static string getAssetRelativePath(string absPath) { + private static string getAssetRelativePath(string absPath) + { return string.Join("/", absPath.Split('/').SkipWhile(x => x != "Assets")); } - public static string MeshToObj(string name, Mesh mesh) { + public static string MeshToObj(string name, Mesh mesh) + { var objString = $"o {name}"; var verts = string.Join( "\n", @@ -83,10 +88,12 @@ private static string SaveAsObj( string outPath, string prefix = "", bool overwite = true - ) { + ) + { var obj = MeshToObj(assetId, mesh); - if (!Directory.Exists(outPath)) { + if (!Directory.Exists(outPath)) + { Directory.CreateDirectory(outPath); } @@ -94,11 +101,14 @@ private static string SaveAsObj( var sep = prefix == "" ? "" : "_"; var fileObj = $"{outPath}/{prefix}_{assetId}.obj"; - if (!File.Exists(fileObj) || overwite) { + if (!File.Exists(fileObj) || overwite) + { Debug.Log($"Writing obj to `{fileObj}`"); File.WriteAllText(fileObj, obj); - } else { + } + else + { Debug.Log($"File `{fileObj}` exists, skipping"); } @@ -113,7 +123,8 @@ public static void SaveMeshesAsObjAndReplaceReferences( string collidersOutPath, bool overwrite = true, GameObject sourceGo = null - ) { + ) + { var meshGo = go.transform.Find("mesh"); var useOriginalAssetGeo = sourceGo != null; @@ -123,7 +134,8 @@ public static void SaveMeshesAsObjAndReplaceReferences( var collidersSourceMeshes = colliders.Select(c => c.sharedMesh); - if (useOriginalAssetGeo) { + if (useOriginalAssetGeo) + { mainMesh = sourceGo .transform.Find("mesh") .GetComponentInChildren() @@ -152,7 +164,8 @@ public static void SaveMeshesAsObjAndReplaceReferences( AssetDatabase.Refresh(); // is this necessary? - if (mainMesh.indexFormat == UnityEngine.Rendering.IndexFormat.UInt32) { + if (mainMesh.indexFormat == UnityEngine.Rendering.IndexFormat.UInt32) + { var mi = AssetImporter.GetAtPath(getAssetRelativePath(objPath)) as ModelImporter; mi.indexFormat = ModelImporterIndexFormat.UInt32; } @@ -167,9 +180,11 @@ public static void SaveMeshesAsObjAndReplaceReferences( (Mesh)AssetDatabase.LoadAssetAtPath(getAssetRelativePath(path), typeof(Mesh)) ) .ToArray(); - for (var i = 0; i < colliders.Length; i++) { + for (var i = 0; i < colliders.Length; i++) + { // is this necessary? - if (colliders[i].sharedMesh.indexFormat == UnityEngine.Rendering.IndexFormat.UInt32) { + if (colliders[i].sharedMesh.indexFormat == UnityEngine.Rendering.IndexFormat.UInt32) + { var mi = AssetImporter.GetAtPath(getAssetRelativePath(colliderObjPaths[i])) as ModelImporter; @@ -181,15 +196,18 @@ public static void SaveMeshesAsObjAndReplaceReferences( colliders = go .transform.Find("TriggerColliders") .GetComponentsInChildren(); - for (var i = 0; i < colliders.Length; i++) { + for (var i = 0; i < colliders.Length; 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 { @@ -197,15 +215,18 @@ void Awake() { // } } - void Start() { - if (serialized) { + void Start() + { + if (serialized) + { return; } Serialize(); } - private SerializableMesh serializeMesh(Mesh mesh) { + private SerializableMesh serializeMesh(Mesh mesh) + { var outMesh = new SerializableMesh(); outMesh.uv = mesh.uv; outMesh.verticies = mesh.vertices; @@ -214,7 +235,8 @@ private SerializableMesh serializeMesh(Mesh mesh) { return outMesh; } - private Mesh deSerializeMesh(SerializableMesh serializedMesh) { + private Mesh deSerializeMesh(SerializableMesh serializedMesh) + { Mesh mesh = new Mesh(); mesh.vertices = serializedMesh.verticies; mesh.triangles = serializedMesh.triangles; @@ -223,7 +245,8 @@ private Mesh deSerializeMesh(SerializableMesh serializedMesh) { return mesh; } - public void Serialize() { + public void Serialize() + { Debug.Log("--- Serialize called " + transform.parent.gameObject.name); var mesh = GetComponent().mesh; @@ -242,7 +265,8 @@ public void Serialize() { // } Debug.Log($"----- Serializing collider meshes {colliders.Length}"); - for (var i = 0; i < colliders.Length; i++) { + for (var i = 0; i < colliders.Length; i++) + { var collisionMesh = colliders[i].sharedMesh; this.collisionMeshes[i] = this.serializeMesh(collisionMesh); } @@ -272,7 +296,8 @@ public void Serialize() { // } } - public Mesh Rebuild() { + public Mesh Rebuild() + { Mesh mesh = this.deSerializeMesh(model); // Mesh mesh = new Mesh(); @@ -290,7 +315,8 @@ public Mesh Rebuild() { .parent.Find("Colliders") .GetComponentsInChildren(); - for (var i = 0; i < colliders.Length; i++) { + for (var i = 0; i < colliders.Length; i++) + { colliders[i].sharedMesh = deSerializeMesh(this.collisionMeshes[i]); } @@ -298,7 +324,8 @@ public Mesh Rebuild() { .parent.Find("TriggerColliders") .GetComponentsInChildren(); - for (var i = 0; i < colliders.Length; i++) { + for (var i = 0; i < colliders.Length; i++) + { colliders[i].sharedMesh = deSerializeMesh(this.collisionMeshes[i]); } @@ -308,24 +335,31 @@ public Mesh Rebuild() { #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) { + if (GUILayout.Button("Serialize")) + { + if (obj) + { obj.Serialize(); } } diff --git a/unity/Assets/Scripts/SimObj.cs b/unity/Assets/Scripts/SimObj.cs index 06b2440068..99877e69f8 100644 --- a/unity/Assets/Scripts/SimObj.cs +++ b/unity/Assets/Scripts/SimObj.cs @@ -6,16 +6,20 @@ [ExecuteInEditMode] [RequireComponent(typeof(Rigidbody))] -public class SimObj : MonoBehaviour, SimpleSimObj { - public string ObjectID { +public class SimObj : MonoBehaviour, SimpleSimObj +{ + public string ObjectID + { get { return objectID; } - set { + set + { // TODO add an ID lock objectID = value; } } - public bool IsVisible { + public bool IsVisible + { get { return isVisible; } set { isVisible = value; } } @@ -72,42 +76,54 @@ public bool IsVisible { // stores the location of the simObj on startup - public SimObjType ObjType { + public SimObjType ObjType + { get { return Type; } } - public List ReceptacleObjectIds { - get { + public List ReceptacleObjectIds + { + get + { List objectIds = new List(); - foreach (SimObj o in SimUtil.GetItemsFromReceptacle(this.Receptacle)) { + foreach (SimObj o in SimUtil.GetItemsFromReceptacle(this.Receptacle)) + { objectIds.Add(o.objectID); } return objectIds; } } - public Transform StartupTransform { + public Transform StartupTransform + { get { return startupTransform; } } - public Animator Animator { + public Animator Animator + { get { return animator; } } - public Receptacle Receptacle { + public Receptacle Receptacle + { get { return receptacle; } } - public Rearrangeable Rearrangeable { + public Rearrangeable Rearrangeable + { get { return rearrangeable; } } - public bool IsReceptacle { + public bool IsReceptacle + { get { return receptacle != null; } } - public bool IsAnimated { + public bool IsAnimated + { get { return animator != null; } } - public bool IsAnimating { + public bool IsAnimating + { get { return isAnimating; } - set { + set + { #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(this); #endif @@ -115,54 +131,73 @@ public bool IsAnimating { } } - private bool updateAnimState(Animator anim, int value) { + private bool updateAnimState(Animator anim, int value) + { AnimatorControllerParameter param = anim.parameters[0]; - if (anim.GetInteger(param.name) == value) { + if (anim.GetInteger(param.name) == value) + { return false; - } else { + } + else + { anim.SetInteger(param.name, value); return true; } } - private bool updateAnimState(Animator anim, bool value) { + private bool updateAnimState(Animator anim, bool value) + { AnimatorControllerParameter param = anim.parameters[0]; - if (anim.GetBool(param.name) == value) { + if (anim.GetBool(param.name) == value) + { return false; - } else { + } + else + { anim.SetBool(param.name, value); return true; } } - public bool Open() { + public bool Open() + { bool res = false; - if (OPEN_CLOSE_STATES.ContainsKey(this.Type)) { + if (OPEN_CLOSE_STATES.ContainsKey(this.Type)) + { res = updateAnimState(this.Animator, OPEN_CLOSE_STATES[this.Type]["open"]); - } else if (this.IsAnimated) { + } + else if (this.IsAnimated) + { res = updateAnimState(this.Animator, true); } return res; } - public bool Close() { + public bool Close() + { bool res = false; - if (OPEN_CLOSE_STATES.ContainsKey(this.Type)) { + if (OPEN_CLOSE_STATES.ContainsKey(this.Type)) + { res = updateAnimState(this.Animator, OPEN_CLOSE_STATES[this.Type]["close"]); - } else if (this.IsAnimated) { + } + else if (this.IsAnimated) + { res = updateAnimState(this.Animator, false); } return res; } - public bool VisibleToRaycasts { + public bool VisibleToRaycasts + { get { return visibleToRaycasts; } - set { - if (colliders == null) { + set + { + if (colliders == null) + { #if UNITY_EDITOR Debug.LogWarning( "Warning: Tried to set colliders enabled before item was initialized in " + name @@ -172,12 +207,14 @@ public bool VisibleToRaycasts { return; } - if (visibleToRaycasts != value) { + if (visibleToRaycasts != value) + { visibleToRaycasts = value; gameObject.layer = ( visibleToRaycasts ? SimUtil.RaycastVisibleLayer : SimUtil.RaycastHiddenLayer ); - for (int i = 0; i < colliders.Length; i++) { + for (int i = 0; i < colliders.Length; i++) + { colliders[i].gameObject.layer = ( visibleToRaycasts ? SimUtil.RaycastVisibleLayer : SimUtil.RaycastHiddenLayer ); @@ -185,19 +222,23 @@ public bool VisibleToRaycasts { } } } - public Vector3 CenterPoint { + public Vector3 CenterPoint + { get { return centerPoint; } } - public Vector3 TopPoint { + public Vector3 TopPoint + { get { return topPoint; } } - public Vector3 BottomPoint { + public Vector3 BottomPoint + { get { return bottomPoint; } } - public Bounds Bounds { + public Bounds Bounds + { get { return bounds; } } @@ -205,7 +246,8 @@ public Bounds Bounds { #if UNITY_EDITOR // used for debugging object visibility - public string Error { + public string Error + { get { return error; } } string error = string.Empty; @@ -228,47 +270,60 @@ public string Error { private Bounds bounds; // this guy right here caused the giant groceries... should only be an issue with pivots - public void ResetScale() { + public void ResetScale() + { Transform tempParent = transform.parent; transform.parent = null; transform.localScale = startupScale; transform.parent = tempParent; } - public bool IsPickupable { - get { + public bool IsPickupable + { + get + { return !this.IsOpenable && !this.IsReceptacle && !(Array.IndexOf(ImmobileTypes, this.Type) >= 0); } } - public bool IsOpen { - get { + public bool IsOpen + { + get + { Animator anim = this.Animator; AnimatorControllerParameter param = anim.parameters[0]; - if (OPEN_CLOSE_STATES.ContainsKey(this.Type)) { + if (OPEN_CLOSE_STATES.ContainsKey(this.Type)) + { return anim.GetInteger(param.name) == OPEN_CLOSE_STATES[this.Type]["open"]; - } else { + } + else + { return anim.GetBool(param.name); } } } - public bool IsOpenable { + public bool IsOpenable + { get { return Array.IndexOf(OpenableTypes, this.Type) >= 0 && this.IsAnimated; } } - public void RecalculatePoints() { + public void RecalculatePoints() + { // get first renderer in object, use that object's bounds to get center point Renderer r = null; - if (!IsReceptacle) { + if (!IsReceptacle) + { r = gameObject.GetComponentInChildren(); } - if (r != null) { + if (r != null) + { centerPoint = r.bounds.center; - if (UseWidthSearch) { + if (UseWidthSearch) + { topPoint = centerPoint + (Vector3.left * r.bounds.extents.x) @@ -277,23 +332,32 @@ public void RecalculatePoints() { centerPoint + (Vector3.right * r.bounds.extents.x) + (Vector3.back * r.bounds.extents.z); - } else { + } + else + { topPoint = centerPoint + (Vector3.up * r.bounds.extents.y); bottomPoint = centerPoint + (Vector3.down * r.bounds.extents.y); } bounds = r.bounds; - } else { + } + else + { // get the first collider Collider c = null; - if (IsReceptacle) { + if (IsReceptacle) + { c = receptacle.VisibilityCollider; - } else { + } + else + { c = gameObject.GetComponentInChildren(); } - if (c != null) { + if (c != null) + { centerPoint = c.bounds.center; - if (UseWidthSearch) { + if (UseWidthSearch) + { topPoint = centerPoint + (Vector3.left * c.bounds.extents.x) @@ -302,29 +366,37 @@ public void RecalculatePoints() { centerPoint + (Vector3.right * c.bounds.extents.x) + (Vector3.back * c.bounds.extents.z); - } else { + } + else + { topPoint = centerPoint + (Vector3.up * c.bounds.extents.y); bottomPoint = centerPoint + (Vector3.down * c.bounds.extents.y); } bounds = c.bounds; - } else { + } + else + { Debug.Log("Couldn't calculate center point in " + gameObject.name); } } } - void OnCollisionEnter(Collision col) { + 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) { + void OnCollisionExit(Collision col) + { this.hasCollision = true; } - protected virtual void OnEnable() { - if (SceneManager.Current == null) { + protected virtual void OnEnable() + { + if (SceneManager.Current == null) + { return; } @@ -344,7 +416,8 @@ protected virtual void OnEnable() { colliders = gameObject.GetComponentsInChildren(); // if the manip type isn't inventory, use the presence of the rearrangeable component to determine type - switch (Manipulation) { + switch (Manipulation) + { case SimObjManipType.Inventory: break; @@ -356,28 +429,35 @@ protected virtual void OnEnable() { } #if UNITY_EDITOR - if (Type == SimObjType.Undefined) { + if (Type == SimObjType.Undefined) + { // check our prefab just in case the enum has gotten disconnected GameObject prefabParent = UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(gameObject) as GameObject; - if (prefabParent != null) { + if (prefabParent != null) + { SimObj ps = prefabParent.GetComponent(); - if (ps != null) { + if (ps != null) + { Type = ps.Type; } } } - if (!Application.isPlaying) { - foreach (Collider c in colliders) { + if (!Application.isPlaying) + { + foreach (Collider c in colliders) + { c.gameObject.layer = SimUtil.RaycastVisibleLayer; } // if we're type static, set our renderers to static so navmeshes generate correctly MeshRenderer[] renderers = gameObject.GetComponentsInChildren(); - foreach (MeshRenderer mr in renderers) { - switch (Manipulation) { + foreach (MeshRenderer mr in renderers) + { + switch (Manipulation) + { case SimObjManipType.Static: mr.gameObject.isStatic = true; UnityEditor.GameObjectUtility.SetNavMeshArea( @@ -418,12 +498,15 @@ protected virtual void OnEnable() { #endif Rigidbody rb = GetComponent(); - if (rb == null) { + if (rb == null) + { rb = gameObject.AddComponent(); } - if (SceneManager.Current.LocalPhysicsMode == ScenePhysicsMode.Dynamic) { - switch (Manipulation) { + if (SceneManager.Current.LocalPhysicsMode == ScenePhysicsMode.Dynamic) + { + switch (Manipulation) + { case SimObjManipType.Static: case SimObjManipType.StaticNoPlacement: rb.isKinematic = true; @@ -433,15 +516,20 @@ protected virtual void OnEnable() { rb.isKinematic = false; break; } - } else { + } + else + { rb.isKinematic = true; } RecalculatePoints(); - if (Application.isPlaying) { - if (startupTransform == null) { - switch (Manipulation) { + if (Application.isPlaying) + { + if (startupTransform == null) + { + switch (Manipulation) + { case SimObjManipType.Inventory: // if we can enter inventory // create a transform that stores our startup position @@ -469,62 +557,79 @@ protected virtual void OnEnable() { } #if UNITY_EDITOR - public void RefreshColliders() { + public void RefreshColliders() + { colliders = gameObject.GetComponentsInChildren(); } - void CheckForErrors() { + void CheckForErrors() + { error = string.Empty; colliders = gameObject.GetComponentsInChildren(); // make sure all raycast targets are tagged correctly - if (colliders.Length == 0) { + if (colliders.Length == 0) + { error = "No colliders attached!"; return; } - if (!gameObject.CompareTag(SimUtil.ReceptacleTag)) { + if (!gameObject.CompareTag(SimUtil.ReceptacleTag)) + { gameObject.tag = SimUtil.SimObjTag; } - foreach (Collider c in colliders) { + foreach (Collider c in colliders) + { // don't re-tag something that's tagged as a receptacle - if (!c.CompareTag(SimUtil.ReceptacleTag)) { + if (!c.CompareTag(SimUtil.ReceptacleTag)) + { c.gameObject.tag = SimUtil.SimObjTag; } } - if (Type == SimObjType.Undefined) { + if (Type == SimObjType.Undefined) + { error = "Type is undefined!"; return; } - if (UseCustomBounds && BoundsTransform == null) { + if (UseCustomBounds && BoundsTransform == null) + { error = "Using custom bounds but no BoundsTransform supplied!"; } } - void Update() { + void Update() + { // TEMPORARY - we'll move this into receptacl - if (transform.position != lastPosition) { + if (transform.position != lastPosition) + { lastPosition = transform.position; RecalculatePoints(); } } - void OnDrawGizmos() { + void OnDrawGizmos() + { Gizmos.color = Color.white; - if (!SimUtil.ShowObjectVisibility) { + if (!SimUtil.ShowObjectVisibility) + { VisibleNow = false; } - if (!string.IsNullOrEmpty(error)) { + if (!string.IsNullOrEmpty(error)) + { Gizmos.color = Color.Lerp(Color.red, Color.clear, 0.5f); Gizmos.DrawSphere(transform.position, 0.25f); CheckForErrors(); - } else { - if (UseCustomBounds && SimUtil.ShowCustomBounds) { - if (BoundsTransform != null) { + } + else + { + if (UseCustomBounds && SimUtil.ShowCustomBounds) + { + if (BoundsTransform != null) + { // draw aligned bounding box Gizmos.matrix = transform.localToWorldMatrix; Gizmos.color = VisibleNow ? Color.yellow : Color.cyan; @@ -540,7 +645,8 @@ void OnDrawGizmos() { } } - if (UnityEditor.Selection.activeGameObject == gameObject) { + if (UnityEditor.Selection.activeGameObject == gameObject) + { Gizmos.color = Color.white; Gizmos.DrawWireSphere(CenterPoint, 0.02f); Gizmos.color = Color.Lerp(Color.cyan, Color.clear, 0.5f); @@ -548,10 +654,12 @@ void OnDrawGizmos() { Gizmos.DrawWireSphere(BottomPoint, 0.02f); } - if (VisibleNow) { + if (VisibleNow) + { // draw an outline around our biggest renderer MeshFilter mf = gameObject.GetComponentInChildren(false); - if (mf != null) { + if (mf != null) + { Gizmos.color = Color.yellow; Gizmos.DrawWireMesh( mf.sharedMesh, @@ -560,9 +668,12 @@ void OnDrawGizmos() { mf.transform.rotation, mf.transform.lossyScale ); - } else { + } + else + { // probably a visibility collider only sim obj - if (IsReceptacle) { + if (IsReceptacle) + { Gizmos.color = Color.yellow; // Gizmos.matrix = receptacle.VisibilityCollider.transform.worldToLocalMatrix; Gizmos.DrawSphere(centerPoint, 0.25f); @@ -575,7 +686,8 @@ void OnDrawGizmos() { #endif } -public interface SimpleSimObj { +public interface SimpleSimObj +{ SimObjType ObjType { get; } string ObjectID { get; set; } List ReceptacleObjectIds { get; } diff --git a/unity/Assets/Scripts/SimObjPhysics.cs b/unity/Assets/Scripts/SimObjPhysics.cs index 9a5eacc116..136e699e1a 100644 --- a/unity/Assets/Scripts/SimObjPhysics.cs +++ b/unity/Assets/Scripts/SimObjPhysics.cs @@ -10,7 +10,8 @@ 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; @@ -125,30 +126,36 @@ public class SimObjPhysics : MonoBehaviour, SimpleSimObj { private bool forceCreateObjectOrientedBoundingBox = false; - private bool shouldCreateObjectOrientedBoundingBox { - get { + private bool shouldCreateObjectOrientedBoundingBox + { + get + { return this.forceCreateObjectOrientedBoundingBox || this.IsPickupable || this.IsMoveable; } } - public GameObject GetSceneManager() { + public GameObject GetSceneManager() + { return sceneManager.gameObject; } - public float GetTimerResetValue() { + public float GetTimerResetValue() + { return TimerResetValue; } - public void SetHowManySecondsUntilRoomTemp(float f) { + public void SetHowManySecondsUntilRoomTemp(float f) + { TimerResetValue = f; HowManySecondsUntilRoomTemp = f; } private bool StartRoomTempTimer = false; - public void SetStartRoomTempTimer(bool b) { + public void SetStartRoomTempTimer(bool b) + { StartRoomTempTimer = b; } @@ -161,31 +168,37 @@ public void SetStartRoomTempTimer(bool b) { public List CurrentlyContains; #endif - public class PhysicsMaterialValues { + public class PhysicsMaterialValues + { public float DynamicFriction; public float StaticFriction; public float Bounciness; - public PhysicsMaterialValues(float dFriction, float sFriction, float b) { + public PhysicsMaterialValues(float dFriction, float sFriction, float b) + { DynamicFriction = dFriction; StaticFriction = sFriction; Bounciness = b; } } - public void AddToContainedObjectReferences(SimObjPhysics t) { + public void AddToContainedObjectReferences(SimObjPhysics t) + { ContainedObjectReferences.Add(t); } - public void RemoveFromContainedObjectReferences(SimObjPhysics t) { + public void RemoveFromContainedObjectReferences(SimObjPhysics t) + { ContainedObjectReferences.Remove(t); } public void syncBoundingBoxes( bool forceCacheReset = false, bool forceCreateObjectOrientedBoundingBox = false - ) { - if (forceCreateObjectOrientedBoundingBox) { + ) + { + if (forceCreateObjectOrientedBoundingBox) + { bool shouldCreateBefore = this.shouldCreateObjectOrientedBoundingBox; this.forceCreateObjectOrientedBoundingBox = forceCreateObjectOrientedBoundingBox; @@ -213,7 +226,8 @@ public void syncBoundingBoxes( && (!this.IsBreakable || this.IsBroken == this.boundingBoxCacheKey.IsBroken) && Quaternion.Angle(rotation, this.boundingBoxCacheKey.rotation) < 0.0001f && Vector3.Distance(position, this.boundingBoxCacheKey.position) < 0.0001f - ) { + ) + { return; } this.cachedAxisAlignedBoundingBox = this.axisAlignedBoundingBox(); @@ -221,25 +235,31 @@ public void syncBoundingBoxes( this.boundingBoxCacheKey = new BoundingBoxCacheKey(); this.boundingBoxCacheKey.position = position; this.boundingBoxCacheKey.rotation = rotation; - if (this.IsOpenable) { + if (this.IsOpenable) + { this.boundingBoxCacheKey.IsOpen = this.IsOpen; this.boundingBoxCacheKey.openness = this.openness; } - if (this.IsBreakable) { + if (this.IsBreakable) + { this.boundingBoxCacheKey.IsBroken = this.IsBroken; } - if (this.IsSliced) { + if (this.IsSliced) + { this.boundingBoxCacheKey.IsSliced = this.IsSliced; } } - private AxisAlignedBoundingBox axisAlignedBoundingBox() { + private AxisAlignedBoundingBox axisAlignedBoundingBox() + { AxisAlignedBoundingBox b = new AxisAlignedBoundingBox(); // unparent child simobjects during bounding box generation List childSimObjects = new List(); - foreach (SimObjPhysics simObject in this.transform.GetComponentsInChildren()) { - if (simObject != this) { + foreach (SimObjPhysics simObject in this.transform.GetComponentsInChildren()) + { + if (simObject != this) + { childSimObjects.Add(simObject.transform); // TODO: fix, This line makes accessing the axisAligned bounding box of some composed object during edior fail @@ -260,9 +280,11 @@ private AxisAlignedBoundingBox axisAlignedBoundingBox() { Collider[] cols = this.GetComponentsInChildren(); // 0 colliders mean the object is despawned, so this will cause objects broken into pieces to not generate an axis aligned box - if (cols.Length == 0) { + if (cols.Length == 0) + { SimObjPhysics sopc = this.GetComponent(); - if (sopc.IsBroken || sopc.IsSliced) { + if (sopc.IsBroken || sopc.IsSliced) + { #if UNITY_EDITOR Debug.Log( "Object is broken or sliced in pieces, no AxisAligned box generated: " @@ -270,7 +292,9 @@ private AxisAlignedBoundingBox axisAlignedBoundingBox() { ); #endif return b; - } else { + } + else + { #if UNITY_EDITOR Debug.Log("Something went wrong, no Colliders were found on" + this.name); #endif @@ -279,17 +303,21 @@ private AxisAlignedBoundingBox axisAlignedBoundingBox() { } Bounds bounding = UtilityFunctions.CreateEmptyBounds(); - foreach (Collider c in cols) { - if (c.enabled && !c.isTrigger) { + foreach (Collider c in cols) + { + if (c.enabled && !c.isTrigger) + { bounding.Encapsulate(c.bounds); } } - foreach (Transform visPoint in this.VisibilityPoints) { + foreach (Transform visPoint in this.VisibilityPoints) + { bounding.Encapsulate(visPoint.position); } // reparent child simobjects - foreach (Transform childSimObject in childSimObjects) { + foreach (Transform childSimObject in childSimObjects) + { childSimObject.SetParent(this.transform); } @@ -310,9 +338,12 @@ private AxisAlignedBoundingBox axisAlignedBoundingBox() { bounding.center.z + bounding.size.z / 2f, bounding.center.z - bounding.size.z / 2f }; - foreach (float x in xs) { - foreach (float y in ys) { - foreach (float z in zs) { + foreach (float x in xs) + { + foreach (float y in ys) + { + foreach (float z in zs) + { cornerPoints.Add(new float[] { x, y, z }); } } @@ -325,18 +356,24 @@ private AxisAlignedBoundingBox axisAlignedBoundingBox() { return b; } - private ObjectOrientedBoundingBox objectOrientedBoundingBox() { - if (this.shouldCreateObjectOrientedBoundingBox) { + private ObjectOrientedBoundingBox objectOrientedBoundingBox() + { + if (this.shouldCreateObjectOrientedBoundingBox) + { ObjectOrientedBoundingBox b = new ObjectOrientedBoundingBox(); bool shouldSetupBBox = false; - try { + try + { shouldSetupBBox = this.BoundingBox == null; - } catch (UnassignedReferenceException e) { + } + catch (UnassignedReferenceException e) + { shouldSetupBBox = true; } - if (shouldSetupBBox) { + if (shouldSetupBBox) + { GameObject bb = new GameObject("BoundingBox"); bb.transform.position = gameObject.transform.position; bb.transform.SetParent(gameObject.transform); @@ -352,8 +389,10 @@ private ObjectOrientedBoundingBox objectOrientedBoundingBox() { List childSimObjects = new List(); foreach ( SimObjPhysics simObject in this.transform.GetComponentsInChildren() - ) { - if (simObject != this) { + ) + { + if (simObject != this) + { childSimObjects.Add(simObject.transform); simObject.transform.parent = null; } @@ -367,8 +406,10 @@ SimObjPhysics simObject in this.transform.GetComponentsInChildren // 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"); - foreach (Collider c in clone.transform.GetComponentsInChildren()) { - if (c.enabled) { + foreach (Collider c in clone.transform.GetComponentsInChildren()) + { + if (c.enabled) + { // save the state of all the layers prior to modifying cols.Add((c, c.transform.gameObject.layer)); @@ -381,14 +422,17 @@ SimObjPhysics simObject in this.transform.GetComponentsInChildren Bounds newBB = UtilityFunctions.CreateEmptyBounds(); // Encapsulate all active colliders in SimObject's array - foreach ((Collider, LayerMask) colAndLayerMask in cols) { + foreach ((Collider, LayerMask) colAndLayerMask in cols) + { Collider c = colAndLayerMask.Item1; - if (!c.isTrigger && c.gameObject != clone.GetComponent().BoundingBox) { + if (!c.isTrigger && c.gameObject != clone.GetComponent().BoundingBox) + { newBB.Encapsulate(c.bounds); } } // Encapsulate all visilibity points of the SimObject array - foreach (Transform visPoint in clone.GetComponent().VisibilityPoints) { + foreach (Transform visPoint in clone.GetComponent().VisibilityPoints) + { newBB.Encapsulate(visPoint.position); } @@ -399,12 +443,14 @@ SimObjPhysics simObject in this.transform.GetComponentsInChildren this.BoundingBox.GetComponent().size = newBB.extents * 2.0f; // Re-enable colliders, moving them back to their original layer - foreach ((Collider, LayerMask) colAndLayerMask in cols) { + foreach ((Collider, LayerMask) colAndLayerMask in cols) + { colAndLayerMask.Item1.transform.gameObject.layer = colAndLayerMask.Item2; } // reparent child simobjects - foreach (Transform childSimObject in childSimObjects) { + foreach (Transform childSimObject in childSimObjects) + { childSimObject.SetParent(this.transform); } @@ -454,7 +500,8 @@ SimObjPhysics simObject in this.transform.GetComponentsInChildren ); List cornerPoints = new List(); - foreach (Vector3 p in points) { + foreach (Vector3 p in points) + { cornerPoints.Add(new float[] { p.x, p.y, p.z }); } @@ -466,22 +513,28 @@ SimObjPhysics simObject in this.transform.GetComponentsInChildren return null; } - public void DropContainedObjectsStationary() { + public void DropContainedObjectsStationary() + { this.DropContainedObjects(reparentContainedObjects: false, forceKinematic: true); } - public void DropContainedObjects(bool reparentContainedObjects, bool forceKinematic) { - if (this.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { + public void DropContainedObjects(bool reparentContainedObjects, bool forceKinematic) + { + if (this.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) + { GameObject topObject = null; - foreach (SimObjPhysics sop in this.ContainedObjectReferences) { + foreach (SimObjPhysics sop in this.ContainedObjectReferences) + { // for every object that is contained by this object turn off // the colliders, leaving Trigger Colliders active (this is important to maintain visibility!) sop.transform.Find("Colliders").gameObject.SetActive(true); sop.isInAgentHand = false; // Agent hand flag - if (reparentContainedObjects) { - if (topObject == null) { + if (reparentContainedObjects) + { + if (topObject == null) + { topObject = GameObject.Find("Objects"); } sop.transform.SetParent(topObject.transform); @@ -489,7 +542,8 @@ public void DropContainedObjects(bool reparentContainedObjects, bool forceKinema Rigidbody rb = sop.GetComponent(); rb.isKinematic = forceKinematic; - if (!forceKinematic) { + if (!forceKinematic) + { rb.useGravity = true; rb.constraints = RigidbodyConstraints.None; rb.collisionDetectionMode = CollisionDetectionMode.ContinuousSpeculative; @@ -499,159 +553,212 @@ public void DropContainedObjects(bool reparentContainedObjects, bool forceKinema } } - public AxisAlignedBoundingBox AxisAlignedBoundingBox { - get { + public AxisAlignedBoundingBox AxisAlignedBoundingBox + { + get + { this.syncBoundingBoxes(); return this.cachedAxisAlignedBoundingBox; } } - public ObjectOrientedBoundingBox ObjectOrientedBoundingBox { - get { + public ObjectOrientedBoundingBox ObjectOrientedBoundingBox + { + get + { this.syncBoundingBoxes(); return this.cachedObjectOrientedBoundingBox; } } - public void ClearContainedObjectReferences() { + public void ClearContainedObjectReferences() + { ContainedObjectReferences.Clear(); } - public string ObjectID { + public string ObjectID + { get { return objectID; } set { objectID = value; } } - public SimObjType ObjType { + public SimObjType ObjType + { get { return Type; } set { Type = value; } } - public int ReceptacleCount { + public int ReceptacleCount + { get { return 0; } } - public List ReceptacleObjectIds { + public List ReceptacleObjectIds + { get { return this.GetAllSimObjectsInReceptacleTriggersByObjectID(); } } // get all objects contained by this receptacle object as a list of SimObjPhysics - public List SimObjectsContainedByReceptacle { + public List SimObjectsContainedByReceptacle + { get { return this.GetAllSimObjectsInReceptacleTriggers(); } } // return mass of object - public float Mass { - get { + public float Mass + { + get + { var rb = this.GetComponent(); return rb != null ? rb.mass : 0.0f; } } // if this pickupable object is being held by the agent right - public bool isPickedUp { + public bool isPickedUp + { 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 { - get { - if (this.GetComponent()) { + private bool isToggleable + { + get + { + if (this.GetComponent()) + { // if this object is self controlled, it is toggleable - if (this.GetComponent().ReturnSelfControlled()) { + 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 { + else + { return false; } - } else { + } + else + { return false; } // return this.GetComponent(); } } - public bool IsToggled { - get { + public bool IsToggled + { + get + { // note: this can return "toggled on or off" info about objects that are controlled by other sim objects // for example, a stove burner will return if it is on/off even though the burner itself cannot be interacted with // to toggle the on/off state. Stove burners and objects like it can only have their state toggled by a sim object // that controls it (in this case stove knob -controls-> stove burner) CanToggleOnOff ctoo = this.GetComponent(); - if (ctoo != null) { + if (ctoo != null) + { return ctoo.isOn; - } else { + } + else + { return false; } } } - public float openness { + public float openness + { get { return this.GetComponent().currentOpenness; } } - public bool IsOpen { - get { + public bool IsOpen + { + get + { CanOpen_Object coo = this.GetComponent(); - if (coo != null) { + if (coo != null) + { return coo.isOpen; - } else { + } + else + { return false; } } } - public bool IsBroken { - get { + public bool IsBroken + { + get + { Break b = this.GetComponentInChildren(); - if (b != null) { + if (b != null) + { return b.isBroken(); - } else { + } + else + { return false; } } } - public bool IsFilled { - get { + public bool IsFilled + { + get + { Fill f = this.GetComponent(); - if (f != null) { + if (f != null) + { return f.IsFilled(); - } else { + } + else + { return false; } } } - public string FillLiquid { - get { + public string FillLiquid + { + get + { Fill f = this.GetComponent(); return f == null ? null : f.FilledLiquid(); } } - public bool IsDirty { - get { + public bool IsDirty + { + get + { Dirty deedsdonedirtcheap = this.GetComponent(); - if (deedsdonedirtcheap != null) { + if (deedsdonedirtcheap != null) + { return deedsdonedirtcheap.IsDirty(); - } else { + } + else + { return false; } } } - public bool IsCooked { - get { + public bool IsCooked + { + get + { CookObject tasty = this.GetComponent(); - if (tasty != null) { + if (tasty != null) + { return tasty.IsCooked(); - } else { + } + else + { return false; } } @@ -659,42 +766,54 @@ public bool IsCooked { // if the object has been sliced, the rest of it has been disabled so it can't be seen or interacted with, but the metadata // will still reflect it's last position at time of being sliced. This is similar to break - public bool IsSliced { - get { + public bool IsSliced + { + get + { SliceObject kars = this.GetComponent(); - if (kars != null) { + if (kars != null) + { return kars.IsSliced(); - } else { + } + else + { return false; } } } /// these aren't in yet, just placeholder - public bool CanBeUsedUp { + public bool CanBeUsedUp + { get { return false; } } - public bool IsUsedUp { + public bool IsUsedUp + { get { return false; } } /// end placeholder stuff // return temperature enum here - public Temperature CurrentObjTemp { + public Temperature CurrentObjTemp + { get { return CurrentTemperature; } } - private void FindMySpawnPoints(BaseFPSAgentController agent = null) { + private void FindMySpawnPoints(BaseFPSAgentController agent = null) + { List temp = new List(); - foreach (GameObject rtb in ReceptacleTriggerBoxes) { + foreach (GameObject rtb in ReceptacleTriggerBoxes) + { Contains containsScript = rtb.GetComponent(); temp.AddRange(containsScript.GetValidSpawnPoints(agent)); } - if (agent != null) { + if (agent != null) + { temp.Sort( - delegate (ReceptacleSpawnPoint one, ReceptacleSpawnPoint two) { + delegate(ReceptacleSpawnPoint one, ReceptacleSpawnPoint two) + { return Vector3 .Distance(agent.transform.position, one.Point) .CompareTo(Vector3.Distance(agent.transform.position, two.Point)); @@ -709,9 +828,11 @@ private void FindMySpawnPoints(BaseFPSAgentController agent = null) { public List FindMySpawnPointsFromTriggerBox( bool forceVisible = false, bool top = false - ) { + ) + { List points = new List(); - foreach (GameObject rtb in ReceptacleTriggerBoxes) { + foreach (GameObject rtb in ReceptacleTriggerBoxes) + { points.AddRange( rtb.GetComponent().GetValidSpawnPointsFromTriggerBox(top: top) ); @@ -724,9 +845,11 @@ public List FindMySpawnPointsFromTriggerBox( public List FindMySpawnPointsFromTriggerBoxInLocalSpace( bool forceVisible = false, bool top = false - ) { + ) + { List points = new List(); - foreach (GameObject rtb in ReceptacleTriggerBoxes) { + foreach (GameObject rtb in ReceptacleTriggerBoxes) + { points.AddRange( rtb.GetComponent().GetValidSpawnPointsFromTriggerBoxLocalSpace(top: top) ); @@ -737,33 +860,42 @@ public List FindMySpawnPointsFromTriggerBoxInLocalSpace( // set ReturnPointsCloseToAgent to true if only points near the agent are wanted // set to false if all potential points on the object are wanted - public List ReturnMySpawnPoints(BaseFPSAgentController agent = null) { + public List ReturnMySpawnPoints(BaseFPSAgentController agent = null) + { FindMySpawnPoints(agent); return MySpawnPoints; } - public void ResetContactPointsDictionary() { + public void ResetContactPointsDictionary() + { contactPointsDictionary.Clear(); } - void OnCollisionEnter(Collision col) { + void OnCollisionEnter(Collision col) + { // this is to enable kinematics if this object hits another object that isKinematic but needs to activate // physics uppon being touched/collided - if (droneFPSAgent == null) { + if (droneFPSAgent == null) + { return; } // GameObject agent = GameObject.Find("FPSController"); - if (col.transform.GetComponentInParent()) { + if (col.transform.GetComponentInParent()) + { // add a check for if it's for initialization - if (droneFPSAgent.HasLaunch(this)) { + if (droneFPSAgent.HasLaunch(this)) + { // add a check for if this is the object caought by the drone - if (!droneFPSAgent.isObjectCaught(this)) { + if (!droneFPSAgent.isObjectCaught(this)) + { // emperically find the relative velocity > 1 means a "real" hit. - if (col.relativeVelocity.magnitude > 1) { + if (col.relativeVelocity.magnitude > 1) + { // make sure we only count hit once per time, not for all collision contact points of an object. - if (!contactPointsDictionary.ContainsKey(col.collider)) { + if (!contactPointsDictionary.ContainsKey(col.collider)) + { numSimObjHit++; } } @@ -771,21 +903,27 @@ void OnCollisionEnter(Collision col) { } } // add a check for if the hitting one is a structure object - else if (col.transform.GetComponentInParent()) { + else if (col.transform.GetComponentInParent()) + { // add a check for if it's for initialization - if (droneFPSAgent.HasLaunch(this)) { + if (droneFPSAgent.HasLaunch(this)) + { // add a check for if this is the object caought by the drone - if (!droneFPSAgent.isObjectCaught(this)) { + if (!droneFPSAgent.isObjectCaught(this)) + { // emperically find the relative velocity > 1 means a "real" hit. - if (col.relativeVelocity.magnitude > 1) { + if (col.relativeVelocity.magnitude > 1) + { // make sure we only count hit once per time, not for all collision contact points of an object. - if (!contactPointsDictionary.ContainsKey(col.collider)) { + if (!contactPointsDictionary.ContainsKey(col.collider)) + { numStructureHit++; // check if structure hit is a floor if ( col.transform.GetComponentInParent().WhatIsMyStructureObjectTag == StructureObjectTag.Floor - ) { + ) + { numFloorHit++; } } @@ -797,14 +935,16 @@ void OnCollisionEnter(Collision col) { contactPointsDictionary[col.collider] = col.contacts; } - void OnCollisionExit(Collision col) { + void OnCollisionExit(Collision col) + { contactPointsDictionary.Remove(col.collider); } #if UNITY_EDITOR [UnityEditor.MenuItem("SimObjectPhysics/Create RB Collider")] - public static void CreateRBCollider() { + public static void CreateRBCollider() + { GameObject prefabRoot = Selection.activeGameObject; // print(prefabRoot.name); @@ -826,15 +966,18 @@ public static void CreateRBCollider() { } [UnityEditor.MenuItem("SimObjectPhysics/Change All Lights to Soft")] - public static void AllOfTheLights() { + public static void AllOfTheLights() + { Light[] lights = FindObjectsOfType(typeof(Light)) as Light[]; - foreach (Light l in lights) { + foreach (Light l in lights) + { l.shadows = LightShadows.Soft; } } [UnityEditor.MenuItem("SimObjectPhysics/Create Sim Obj from Mesh &r")] - public static void CreateFromMesh() { + public static void CreateFromMesh() + { GameObject prefabRoot = Selection.activeGameObject; GameObject top = new GameObject(prefabRoot.name); top.transform.position = prefabRoot.transform.position; @@ -849,41 +992,48 @@ public static void CreateFromMesh() { } [UnityEditor.MenuItem("SimObjectPhysics/Set Transform Scale to 1 &e")] - public static void ResetTransformScale() { + public static void ResetTransformScale() + { GameObject selected = Selection.activeGameObject; List selectedchildren = new List(); - foreach (Transform t in selected.transform) { + foreach (Transform t in selected.transform) + { // print(t.name); selectedchildren.Add(t); // t.SetParent(null); } - foreach (Transform yes in selectedchildren) { + foreach (Transform yes in selectedchildren) + { yes.SetParent(null); } selected.transform.localScale = new Vector3(1, 1, 1); - foreach (Transform t in selectedchildren) { + foreach (Transform t in selectedchildren) + { t.SetParent(selected.transform); } } [UnityEditor.MenuItem("SimObjectPhysics/Set All Transforms to Defaults &d")] - public static void ResetTransform() { + public static void ResetTransform() + { GameObject selected = Selection.activeGameObject; List selectedchildren = new List(); - foreach (Transform t in selected.transform) { + foreach (Transform t in selected.transform) + { // print(t.name); selectedchildren.Add(t); // t.SetParent(null); } - foreach (Transform yes in selectedchildren) { + foreach (Transform yes in selectedchildren) + { yes.SetParent(null); } @@ -891,24 +1041,28 @@ public static void ResetTransform() { selected.transform.localRotation = new Quaternion(0, 0, 0, 0); selected.transform.localScale = new Vector3(1, 1, 1); - foreach (Transform t in selectedchildren) { + foreach (Transform t in selectedchildren) + { t.SetParent(selected.transform); } } [UnityEditor.MenuItem("SimObjectPhysics/Rotate Box Flap 90 on Y &s")] - public static void RotateTheBoxFlap() { + public static void RotateTheBoxFlap() + { GameObject selected = Selection.activeGameObject; List selectedchildren = new List(); - foreach (Transform t in selected.transform) { + foreach (Transform t in selected.transform) + { // print(t.name); selectedchildren.Add(t); // t.SetParent(null); } - foreach (Transform yes in selectedchildren) { + foreach (Transform yes in selectedchildren) + { yes.SetParent(null); } @@ -919,13 +1073,15 @@ public static void RotateTheBoxFlap() { selected.transform.localRotation = Quaternion.Euler(setrot + new Vector3(-180, 180, 180)); // This is weird and we don't know why selected.transform.localScale = new Vector3(1, 1, 1); - foreach (Transform t in selectedchildren) { + foreach (Transform t in selectedchildren) + { t.SetParent(selected.transform); } } #endif - private void initializeProperties() { + private void initializeProperties() + { this.IsReceptacle = Array.IndexOf(SecondaryProperties, SimObjSecondaryProperty.Receptacle) > -1 && ReceptacleTriggerBoxes != null; @@ -948,35 +1104,44 @@ private void initializeProperties() { } // Use this for initialization - void Start() { + void Start() + { // For debug in editor only #if UNITY_EDITOR List temp = new List(SecondaryProperties); - if (temp.Contains(SimObjSecondaryProperty.Receptacle)) { - if (ReceptacleTriggerBoxes.Length == 0) { + if (temp.Contains(SimObjSecondaryProperty.Receptacle)) + { + if (ReceptacleTriggerBoxes.Length == 0) + { Debug.LogError( this.name + " is missing ReceptacleTriggerBoxes please hook them up" ); } } - if (temp.Contains(SimObjSecondaryProperty.ObjectSpecificReceptacle)) { - if (!gameObject.GetComponent()) { + if (temp.Contains(SimObjSecondaryProperty.ObjectSpecificReceptacle)) + { + if (!gameObject.GetComponent()) + { Debug.LogError(this.name + " is missing the ObjectSpecificReceptacle component!"); } } - if (this.tag != "SimObjPhysics") { + if (this.tag != "SimObjPhysics") + { Debug.LogError(this.name + " is missing SimObjPhysics tag!"); } - if (IsPickupable || IsMoveable) { - if (salientMaterials.Length == 0) { + if (IsPickupable || IsMoveable) + { + if (salientMaterials.Length == 0) + { Debug.LogError(this.name + " is missing Salient Materials array!"); } } - if (this.transform.localScale != new Vector3(1, 1, 1)) { + if (this.transform.localScale != new Vector3(1, 1, 1)) + { Debug.LogError(this.name + " is not at uniform scale! Set scale to (1, 1, 1)!!!"); } #endif @@ -986,7 +1151,8 @@ void Start() { MyColliders.Length ]; - for (int i = 0; i < MyColliders.Length; i++) { + for (int i = 0; i < MyColliders.Length; i++) + { OriginalPhysicsMaterialValuesForAllMyColliders[i] = new PhysicsMaterialValues( MyColliders[i].material.dynamicFriction, MyColliders[i].material.staticFriction, @@ -996,17 +1162,20 @@ void Start() { myRigidbody = gameObject.GetComponent(); myRigidbody = gameObject.GetComponent(); - if (myRigidbody != null) { + if (myRigidbody != null) + { Rigidbody rb = myRigidbody; RBoriginalAngularDrag = rb.angularDrag; RBoriginalDrag = rb.drag; //default all rigidbodies so that if their drag/angular drag is zero, it's at least nonzero - if (myRigidbody.drag == 0) { + if (myRigidbody.drag == 0) + { myRigidbody.drag = 0.01f; } - if (myRigidbody.angularDrag == 0) { + if (myRigidbody.angularDrag == 0) + { myRigidbody.angularDrag = 0.01f; } } @@ -1020,9 +1189,12 @@ void Start() { // Spawn Dirt Decal Surface if this object is setup for cleaning bool onlyForThisObject = this.gameObject.GetComponent(); - if (onlyForThisObject) { - if (sceneManager.placeDecalSurfaceOnReceptacles && this.IsReceptacle) { - foreach (GameObject go in ReceptacleTriggerBoxes) { + 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; @@ -1047,21 +1219,25 @@ public void SpawnDirtOnReceptacle( int howManyDirt, int randomSeed, DirtSpawnPosition[] spawnPoints = null - ) { + ) + { DecalSpawner decalSpawner = this.gameObject.GetComponentInChildren(); decalSpawner.SpawnDirt(howManyDirt, randomSeed, spawnPoints); } - public DirtCoordinateBounds GetDirtCoordinateBounds() { + public DirtCoordinateBounds GetDirtCoordinateBounds() + { DecalSpawner decalSpawner = this.gameObject.GetComponentInChildren(); return decalSpawner.GetDirtCoordinateBounds(); } - public bool DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty prop) { + public bool DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty prop) + { bool result = false; List temp = new List(SecondaryProperties); - if (temp.Contains(prop)) { + if (temp.Contains(prop)) + { result = true; } @@ -1069,13 +1245,16 @@ public bool DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty prop } // Update is called once per frame - void Update() { + void Update() + { 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) { + if (CurrentTemperature != Temperature.RoomTemp && StartRoomTempTimer == true) + { HowManySecondsUntilRoomTemp -= Time.deltaTime; - if (HowManySecondsUntilRoomTemp < 0) { + if (HowManySecondsUntilRoomTemp < 0) + { CurrentTemperature = Temperature.RoomTemp; HowManySecondsUntilRoomTemp = TimerResetValue; } @@ -1085,7 +1264,8 @@ void Update() { } } - void LateUpdate() { + void LateUpdate() + { // only update lastVelocity if physicsAutosimulation = true, otherwise let the Advance Physics function take care of it; if (sceneManager.physicsSimulationPaused == false && myRigidbody != null) // record this object's current velocity @@ -1097,11 +1277,13 @@ void LateUpdate() { } // used for throwing the sim object, or anything that requires adding force for some reason - public void ApplyForce(ServerAction action) { + public void ApplyForce(ServerAction action) + { Vector3 dir = new Vector3(action.x, action.y, action.z); Rigidbody myrb = gameObject.GetComponent(); - if (myrb.IsSleeping()) { + if (myrb.IsSleeping()) + { myrb.WakeUp(); } @@ -1111,10 +1293,12 @@ public void ApplyForce(ServerAction action) { } // overload that doesn't use a server action - public void ApplyForce(Vector3 dir, float magnitude) { + public void ApplyForce(Vector3 dir, float magnitude) + { Rigidbody myrb = gameObject.GetComponent(); - if (myrb.IsSleeping()) { + if (myrb.IsSleeping()) + { myrb.WakeUp(); } @@ -1124,16 +1308,22 @@ public void ApplyForce(Vector3 dir, float magnitude) { } // return all sim objects contained by this object if it is a receptacle - public List GetAllSimObjectsInReceptacleTriggers() { + public List GetAllSimObjectsInReceptacleTriggers() + { List objs = new List(); - if (DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { - if (ReceptacleTriggerBoxes != null) { - foreach (GameObject go in ReceptacleTriggerBoxes) { + if (DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) + { + if (ReceptacleTriggerBoxes != null) + { + foreach (GameObject go in ReceptacleTriggerBoxes) + { foreach ( SimObjPhysics sop in go.GetComponent().CurrentlyContainedObjects() - ) { - if (!objs.Contains(sop)) { + ) + { + if (!objs.Contains(sop)) + { // print(sop.transform.name); objs.Add(sop); } @@ -1146,14 +1336,20 @@ SimObjPhysics sop in go.GetComponent().CurrentlyContainedObjects() } // return all sim objects by object ID contained by this object if it is a receptacle - public List GetAllSimObjectsInReceptacleTriggersByObjectID() { + public List GetAllSimObjectsInReceptacleTriggersByObjectID() + { List objs = new List(); - if (DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) { - if (ReceptacleTriggerBoxes != null) { - foreach (GameObject go in ReceptacleTriggerBoxes) { - foreach (string s in go.GetComponent().CurrentlyContainedObjectIDs()) { - if (!objs.Contains(s)) { + if (DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle)) + { + if (ReceptacleTriggerBoxes != null) + { + foreach (GameObject go in ReceptacleTriggerBoxes) + { + foreach (string s in go.GetComponent().CurrentlyContainedObjectIDs()) + { + if (!objs.Contains(s)) + { // print(sop.transform.name); objs.Add(s); } @@ -1165,16 +1361,21 @@ public List GetAllSimObjectsInReceptacleTriggersByObjectID() { return objs; } - public List ContainedGameObjects() { + public List ContainedGameObjects() + { List objs = new List(); // get box collider dimensions of ReceptacleTriggerBox if this is a receptacle - if (IsReceptacle) { - foreach (GameObject rtb in ReceptacleTriggerBoxes) { + if (IsReceptacle) + { + foreach (GameObject rtb in ReceptacleTriggerBoxes) + { foreach ( GameObject g in rtb.GetComponent().CurrentlyContainedGameObjects() - ) { - if (!objs.Contains(g)) { + ) + { + if (!objs.Contains(g)) + { objs.Add(g); } } @@ -1188,14 +1389,16 @@ GameObject g in rtb.GetComponent().CurrentlyContainedGameObjects() return objs; } - public void OnTriggerEnter(Collider other) { + 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 (other.CompareTag("HighFriction")) //&& (PrimaryProperty == SimObjPrimaryProperty.CanPickup || PrimaryProperty == SimObjPrimaryProperty.Moveable)) { Rigidbody rb = gameObject.GetComponent(); @@ -1204,7 +1407,8 @@ public void OnTriggerEnter(Collider other) { rb.drag = HFrbdrag; rb.angularDrag = HFrbangulardrag; - foreach (Collider col in MyColliders) { + foreach (Collider col in MyColliders) + { col.material.dynamicFriction = HFdynamicfriction; col.material.staticFriction = HFstaticfriction; col.material.bounciness = HFbounciness; @@ -1213,14 +1417,16 @@ public void OnTriggerEnter(Collider other) { } } - public void OnTriggerExit(Collider other) { + public void OnTriggerExit(Collider other) + { if ( other.CompareTag("HighFriction") && ( PrimaryProperty == SimObjPrimaryProperty.CanPickup || PrimaryProperty == SimObjPrimaryProperty.Moveable ) - ) { + ) + { // print( "resetting to default trigger exit"); Rigidbody rb = gameObject.GetComponent(); @@ -1228,7 +1434,8 @@ public void OnTriggerExit(Collider other) { rb.drag = RBoriginalDrag; rb.angularDrag = RBoriginalAngularDrag; - for (int i = 0; i < MyColliders.Length; i++) { + for (int i = 0; i < MyColliders.Length; i++) + { MyColliders[i].material.dynamicFriction = OriginalPhysicsMaterialValuesForAllMyColliders[i].DynamicFriction; MyColliders[i].material.staticFriction = @@ -1245,7 +1452,8 @@ public void BeingPickedUpByArticulatedAgent( ArticulatedArmController arm, float breakForce = 20.0f, float breakTorque = 20.0f - ) { + ) + { articulatedArmHoldingMe = arm; myRigidbody.isKinematic = false; @@ -1260,7 +1468,8 @@ public void BeingPickedUpByArticulatedAgent( } //callback for when joint breaks due to force - public void OnJointBreak(float breakForce) { + public void OnJointBreak(float breakForce) + { Debug.Log("A joint has just been broken!, force: " + breakForce); BeingDropped(); //remove just this from held objects in case like, we picked up multiple things @@ -1268,11 +1477,15 @@ public void OnJointBreak(float breakForce) { articulatedArmHoldingMe.heldObjects.Remove(this); } - public void BeingDropped() { + public void BeingDropped() + { GameObject topObject = GameObject.Find("Objects"); - if (topObject != null) { + if (topObject != null) + { this.transform.parent = topObject.transform; - } else { + } + else + { this.transform.parent = null; } @@ -1284,12 +1497,14 @@ public void BeingDropped() { } #if UNITY_EDITOR - void OnDrawGizmos() { + void OnDrawGizmos() + { Gizmos.color = Color.white; // if this object is in visibile range and not blocked by any other object, it is visible // visible drawn in yellow - if (debugIsVisible == true && gameObject.GetComponentInChildren()) { + if (debugIsVisible == true && gameObject.GetComponentInChildren()) + { MeshFilter mf = gameObject.GetComponentInChildren(false); Gizmos.color = Color.yellow; Gizmos.DrawWireMesh( @@ -1302,7 +1517,8 @@ void OnDrawGizmos() { } // interactable drawn in magenta - if (debugIsInteractable && gameObject.GetComponentInChildren()) { + if (debugIsInteractable && gameObject.GetComponentInChildren()) + { MeshFilter mf = gameObject.GetComponentInChildren(false); Gizmos.color = Color.magenta; Gizmos.DrawWireMesh( @@ -1316,8 +1532,10 @@ void OnDrawGizmos() { // draw visibility points for editor Gizmos.color = Color.yellow; - if (VisibilityPoints != null && VisibilityPoints.Length > 0) { - foreach (Transform t in VisibilityPoints) { + if (VisibilityPoints != null && VisibilityPoints.Length > 0) + { + foreach (Transform t in VisibilityPoints) + { // if (t != null) //{ Gizmos.DrawSphere(t.position, 0.01f); @@ -1335,7 +1553,8 @@ void OnDrawGizmos() { // RIGHT CLICK this script in the inspector to reveal these options //[ContextMenu("Cabinet")] - void SetUpCabinet() { + void SetUpCabinet() + { Type = SimObjType.Cabinet; PrimaryProperty = SimObjPrimaryProperty.Static; @@ -1346,13 +1565,15 @@ void SetUpCabinet() { gameObject.transform.tag = "SimObjPhysics"; gameObject.layer = 8; - if (!gameObject.GetComponent()) { + if (!gameObject.GetComponent()) + { gameObject.AddComponent(); } this.GetComponent().isKinematic = true; - if (!gameObject.GetComponent()) { + if (!gameObject.GetComponent()) + { gameObject.AddComponent(); gameObject.GetComponent().SetMovementToRotate(); } @@ -1371,7 +1592,8 @@ void SetUpCabinet() { Transform door = transform.Find("CabinetDoor"); - if (!gameObject.transform.Find("StaticVisPoints")) { + if (!gameObject.transform.Find("StaticVisPoints")) + { GameObject svp = new GameObject("StaticVisPoints"); svp.transform.position = gameObject.transform.position; svp.transform.SetParent(gameObject.transform); @@ -1381,7 +1603,8 @@ void SetUpCabinet() { vp.transform.SetParent(svp.transform); } - if (!door.Find("Colliders")) { + if (!door.Find("Colliders")) + { GameObject col = new GameObject("Colliders"); col.transform.position = door.position; col.transform.SetParent(door); @@ -1394,7 +1617,8 @@ void SetUpCabinet() { coll.transform.SetParent(col.transform); } - if (!door.Find("VisibilityPoints")) { + if (!door.Find("VisibilityPoints")) + { GameObject VisPoints = new GameObject("VisibilityPoints"); VisPoints.transform.position = door.position; VisPoints.transform.SetParent(door); @@ -1402,9 +1626,12 @@ void SetUpCabinet() { GameObject vp = new GameObject("VisPoint"); vp.transform.position = VisPoints.transform.position; vp.transform.SetParent(VisPoints.transform); - } else { + } + else + { Transform VisPoints = door.Find("VisibilityPoints"); - foreach (Transform child in VisPoints) { + foreach (Transform child in VisPoints) + { vpoints.Add(child); child.gameObject.tag = "Untagged"; child.gameObject.layer = 8; @@ -1412,44 +1639,59 @@ void SetUpCabinet() { } //////////////////////// - foreach (Transform child in gameObject.transform) { - if (child.name == "StaticVisPoints") { - foreach (Transform svp in child) { - if (!vpoints.Contains(svp)) { + foreach (Transform child in gameObject.transform) + { + if (child.name == "StaticVisPoints") + { + foreach (Transform svp in child) + { + if (!vpoints.Contains(svp)) + { vpoints.Add(svp); } } } - if (child.name == "ReceptacleTriggerBox") { + if (child.name == "ReceptacleTriggerBox") + { // print("check"); - if (!recepboxes.Contains(child.gameObject)) { + if (!recepboxes.Contains(child.gameObject)) + { recepboxes.Add(child.gameObject); } } // found the cabinet door, go into it and populate triggerboxes, colliders, t colliders, and vis points - if (child.name == "CabinetDoor") { - if (child.GetComponent()) { + if (child.name == "CabinetDoor") + { + if (child.GetComponent()) + { DestroyImmediate(child.GetComponent(), true); } - if (child.GetComponent()) { + if (child.GetComponent()) + { DestroyImmediate(child.GetComponent(), true); } - if (!movparts.Contains(child.gameObject)) { + if (!movparts.Contains(child.gameObject)) + { movparts.Add(child.gameObject); } - foreach (Transform c in child) { - if (c.name == "Colliders") { - foreach (Transform col in c) { - if (!cols.Contains(col.gameObject)) { + foreach (Transform c in child) + { + if (c.name == "Colliders") + { + foreach (Transform col in c) + { + if (!cols.Contains(col.gameObject)) + { cols.Add(col.gameObject); } - if (col.childCount == 0) { + if (col.childCount == 0) + { GameObject prefabRoot = col.gameObject; GameObject inst = Instantiate( @@ -1481,9 +1723,12 @@ void SetUpCabinet() { // } // } - if (c.name == "VisibilityPoints") { - foreach (Transform col in c) { - if (!vpoints.Contains(col.transform)) { + if (c.name == "VisibilityPoints") + { + foreach (Transform col in c) + { + if (!vpoints.Contains(col.transform)) + { vpoints.Add(col.transform); } } @@ -1501,7 +1746,8 @@ void SetUpCabinet() { gameObject.GetComponent().openPositions = new Vector3[movparts.Count]; gameObject.GetComponent().closedPositions = new Vector3[movparts.Count]; - if (openPositions.Count != 0) { + if (openPositions.Count != 0) + { gameObject.GetComponent().openPositions = openPositions.ToArray(); } @@ -1509,7 +1755,8 @@ void SetUpCabinet() { } //[ContextMenu("Table")] - void SetUpTable() { + void SetUpTable() + { this.Type = SimObjType.DiningTable; this.PrimaryProperty = SimObjPrimaryProperty.Static; this.SecondaryProperties = new SimObjSecondaryProperty[] @@ -1521,7 +1768,8 @@ void SetUpTable() { // GameObject inst = Instantiate(new GameObject(), gameObject.transform, true); // inst.AddComponent(); - if (!gameObject.transform.Find("BoundingBox")) { + if (!gameObject.transform.Find("BoundingBox")) + { GameObject bb = new GameObject("BoundingBox"); bb.transform.position = gameObject.transform.position; bb.transform.SetParent(gameObject.transform); @@ -1535,8 +1783,10 @@ void SetUpTable() { List recepboxes = new List(); - foreach (Transform t in gameObject.transform) { - if (t.GetComponent()) { + foreach (Transform t in gameObject.transform) + { + if (t.GetComponent()) + { recepboxes.Add(t.gameObject); } } @@ -1545,7 +1795,8 @@ void SetUpTable() { } [ContextMenu("Setup Floor")] - void FloorSetupContext() { + void FloorSetupContext() + { this.Type = SimObjType.Floor; this.PrimaryProperty = SimObjPrimaryProperty.Static; @@ -1554,7 +1805,8 @@ void FloorSetupContext() { SimObjSecondaryProperty.Receptacle }; - if (!gameObject.GetComponent()) { + if (!gameObject.GetComponent()) + { gameObject.AddComponent(); } @@ -1576,7 +1828,8 @@ void FloorSetupContext() { } //[ContextMenu("Drawer")] - void SetUpDrawer() { + void SetUpDrawer() + { this.Type = SimObjType.Drawer; this.PrimaryProperty = SimObjPrimaryProperty.Static; this.SecondaryProperties = new SimObjSecondaryProperty[] @@ -1590,7 +1843,8 @@ void SetUpDrawer() { // delete the trigger colliders and bounding box here // also probably edit ContextSetupSimObjPhysics to not create trigger colliders anymore - if (!gameObject.GetComponent()) { + if (!gameObject.GetComponent()) + { gameObject.AddComponent(); } CanOpen_Object coo = gameObject.GetComponent(); @@ -1605,14 +1859,18 @@ void SetUpDrawer() { List recepboxes = new List(); - foreach (Transform t in gameObject.transform) { - if (t.name == "BoundingBox") { + foreach (Transform t in gameObject.transform) + { + if (t.name == "BoundingBox") + { DestroyImmediate(t.gameObject, true); break; } - if (t.name == "ReceptacleTriggerBox") { - if (!recepboxes.Contains(t.gameObject)) { + if (t.name == "ReceptacleTriggerBox") + { + if (!recepboxes.Contains(t.gameObject)) + { recepboxes.Add(t.gameObject); } } @@ -1650,12 +1908,14 @@ void SetUpDrawer() { } //[ContextMenu("Find BoundingBox")] - void ContextFindBoundingBox() { + void ContextFindBoundingBox() + { BoundingBox = gameObject.transform.Find("BoundingBox").gameObject; } //[ContextMenu("Set Up Microwave")] - void ContextSetUpMicrowave() { + void ContextSetUpMicrowave() + { this.Type = SimObjType.Microwave; this.PrimaryProperty = SimObjPrimaryProperty.Static; @@ -1663,7 +1923,8 @@ void ContextSetUpMicrowave() { this.SecondaryProperties[0] = SimObjSecondaryProperty.Receptacle; this.SecondaryProperties[1] = SimObjSecondaryProperty.CanOpen; - if (!gameObject.transform.Find("BoundingBox")) { + if (!gameObject.transform.Find("BoundingBox")) + { GameObject bb = new GameObject("BoundingBox"); bb.transform.position = gameObject.transform.position; bb.transform.SetParent(gameObject.transform); @@ -1673,17 +1934,21 @@ void ContextSetUpMicrowave() { bb.layer = 0; BoundingBox = bb; - } else { + } + else + { BoundingBox = gameObject.transform.Find("BoundingBox").gameObject; } - if (!gameObject.GetComponent()) { + if (!gameObject.GetComponent()) + { gameObject.AddComponent(); } List vplist = new List(); - if (!gameObject.transform.Find("StaticVisPoints")) { + if (!gameObject.transform.Find("StaticVisPoints")) + { GameObject svp = new GameObject("StaticVisPoints"); svp.transform.position = gameObject.transform.position; svp.transform.SetParent(gameObject.transform); @@ -1691,9 +1956,12 @@ void ContextSetUpMicrowave() { GameObject vp = new GameObject("vPoint"); vp.transform.position = svp.transform.position; vp.transform.SetParent(svp.transform); - } else { + } + else + { Transform vp = gameObject.transform.Find("StaticVisPoints"); - foreach (Transform child in vp) { + foreach (Transform child in vp) + { vplist.Add(child); // set correct tag and layer for each object @@ -1703,7 +1971,8 @@ void ContextSetUpMicrowave() { } Transform door = gameObject.transform.Find("Door"); - if (!door.Find("Col")) { + if (!door.Find("Col")) + { GameObject col = new GameObject("Col"); col.transform.position = door.transform.position; col.transform.SetParent(door.transform); @@ -1714,7 +1983,8 @@ void ContextSetUpMicrowave() { col.layer = 8; } - if (!door.Find("VisPoints")) { + if (!door.Find("VisPoints")) + { // empty to hold all visibility points GameObject vp = new GameObject("VisPoints"); vp.transform.position = door.transform.position; @@ -1724,9 +1994,12 @@ void ContextSetUpMicrowave() { GameObject vpc = new GameObject("vPoint"); vpc.transform.position = vp.transform.position; vpc.transform.SetParent(vp.transform); - } else { + } + else + { Transform vp = door.Find("VisPoints"); - foreach (Transform child in vp) { + foreach (Transform child in vp) + { vplist.Add(child); // set correct tag and layer for each object @@ -1743,7 +2016,8 @@ void ContextSetUpMicrowave() { coo.closedPositions = new Vector3[] { Vector3.zero }; coo.SetMovementToRotate(); - if (gameObject.transform.Find("ReceptacleTriggerBox")) { + if (gameObject.transform.Find("ReceptacleTriggerBox")) + { GameObject[] rtb = new GameObject[] { gameObject.transform.Find("ReceptacleTriggerBox").transform.gameObject @@ -1753,11 +2027,13 @@ void ContextSetUpMicrowave() { } //[ContextMenu("Static Mesh Collider with Receptacle")] - void SetUpSimObjWithStaticMeshCollider() { + void SetUpSimObjWithStaticMeshCollider() + { if ( this.Type == SimObjType.Undefined || this.PrimaryProperty == SimObjPrimaryProperty.Undefined - ) { + ) + { Debug.Log("Type / Primary Property is missing"); return; } @@ -1765,12 +2041,14 @@ void SetUpSimObjWithStaticMeshCollider() { gameObject.tag = "SimObjPhysics"; gameObject.layer = 8; - if (!gameObject.GetComponent()) { + if (!gameObject.GetComponent()) + { gameObject.AddComponent(); } gameObject.GetComponent().isKinematic = true; - if (!gameObject.transform.Find("VisibilityPoints")) { + if (!gameObject.transform.Find("VisibilityPoints")) + { // empty to hold all visibility points GameObject vp = new GameObject("VisibilityPoints"); vp.transform.position = gameObject.transform.position; @@ -1782,7 +2060,8 @@ void SetUpSimObjWithStaticMeshCollider() { vpc.transform.SetParent(vp.transform); } - if (!gameObject.transform.Find("BoundingBox")) { + if (!gameObject.transform.Find("BoundingBox")) + { GameObject rac = new GameObject("BoundingBox"); rac.transform.position = gameObject.transform.position; rac.transform.SetParent(gameObject.transform); @@ -1792,21 +2071,26 @@ void SetUpSimObjWithStaticMeshCollider() { List rtbList = new List(); - foreach (Transform t in gameObject.transform) { - if (t.GetComponent()) { + foreach (Transform t in gameObject.transform) + { + if (t.GetComponent()) + { t.gameObject.tag = "SimObjPhysics"; t.gameObject.layer = 8; // now check if it has pillows or something? - foreach (Transform yes in t) { - if (yes.GetComponent()) { + foreach (Transform yes in t) + { + if (yes.GetComponent()) + { yes.gameObject.tag = "SimObjPhysics"; yes.gameObject.layer = 8; } } } - if (t.GetComponent()) { + if (t.GetComponent()) + { rtbList.Add(t.gameObject); } } @@ -1818,7 +2102,8 @@ void SetUpSimObjWithStaticMeshCollider() { } //[UnityEditor.MenuItem("SimObjectPhysics/AppleSlice")] - public static void ContextSetupAppleSlice() { + public static void ContextSetupAppleSlice() + { GameObject prefabRoot = Selection.activeGameObject; GameObject c = new GameObject("AppleSlice"); c.transform.position = prefabRoot.transform.position; @@ -1826,11 +2111,13 @@ public static void ContextSetupAppleSlice() { prefabRoot.transform.SetParent(c.transform); prefabRoot.name = "Mesh"; - if (!c.GetComponent()) { + if (!c.GetComponent()) + { c.AddComponent(); } - if (c.GetComponent()) { + if (c.GetComponent()) + { SimObjPhysics sop = c.GetComponent(); sop.PrimaryProperty = SimObjPrimaryProperty.CanPickup; sop.Type = SimObjType.AppleSliced; @@ -1839,11 +2126,13 @@ public static void ContextSetupAppleSlice() { c.tag = "SimObjPhysics"; c.layer = 8; - if (!c.GetComponent()) { + if (!c.GetComponent()) + { c.AddComponent(); } - if (!c.transform.Find("Colliders")) { + if (!c.transform.Find("Colliders")) + { GameObject col = new GameObject("Colliders"); col.transform.position = c.transform.position; col.transform.SetParent(c.transform); @@ -1856,7 +2145,8 @@ public static void ContextSetupAppleSlice() { cc.layer = 8; } - if (!c.transform.Find("VisibilityPoints")) { + if (!c.transform.Find("VisibilityPoints")) + { // empty to hold all visibility points GameObject vp = new GameObject("VisibilityPoints"); vp.transform.position = c.transform.position; @@ -1868,7 +2158,8 @@ public static void ContextSetupAppleSlice() { vpc.transform.SetParent(vp.transform); } - if (!c.transform.Find("BoundingBox")) { + if (!c.transform.Find("BoundingBox")) + { GameObject rac = new GameObject("BoundingBox"); rac.transform.position = c.transform.position; rac.transform.SetParent(c.transform); @@ -1880,18 +2171,21 @@ public static void ContextSetupAppleSlice() { } //[UnityEditor.MenuItem("SimObjectPhysics/LightSwitch")] - public static void ContextSetupLightSwitch() { + public static void ContextSetupLightSwitch() + { GameObject prefabRoot = Selection.activeGameObject; GameObject c = new GameObject("LightSwitch"); c.transform.position = prefabRoot.transform.position; prefabRoot.transform.SetParent(c.transform); prefabRoot.name = "Mesh"; - if (!c.GetComponent()) { + if (!c.GetComponent()) + { c.AddComponent(); } - if (c.GetComponent()) { + if (c.GetComponent()) + { SimObjPhysics sop = c.GetComponent(); sop.PrimaryProperty = SimObjPrimaryProperty.Static; sop.Type = SimObjType.LightSwitch; @@ -1905,12 +2199,14 @@ public static void ContextSetupLightSwitch() { c.layer = 8; c.isStatic = true; - if (!c.GetComponent()) { + if (!c.GetComponent()) + { Rigidbody rb = c.AddComponent(); rb.isKinematic = true; } - if (!c.transform.Find("Colliders")) { + if (!c.transform.Find("Colliders")) + { GameObject col = new GameObject("Colliders"); col.transform.position = c.transform.position; col.transform.SetParent(c.transform); @@ -1923,7 +2219,8 @@ public static void ContextSetupLightSwitch() { cc.layer = 8; } - if (!c.transform.Find("VisibilityPoints")) { + if (!c.transform.Find("VisibilityPoints")) + { // empty to hold all visibility points GameObject vp = new GameObject("VisibilityPoints"); vp.transform.position = c.transform.position; @@ -1938,15 +2235,19 @@ public static void ContextSetupLightSwitch() { c.GetComponent().SetupCollidersVisPoints(); // add the CanToggleOnOff component and set it up with correct values - if (!c.GetComponent()) { + if (!c.GetComponent()) + { CanToggleOnOff ctoo = c.AddComponent(); List childmeshes = new List(); List childRotations = new List(); - foreach (Transform t in c.transform) { - if (t.name == "Mesh") { - foreach (Transform tt in t) { + foreach (Transform t in c.transform) + { + if (t.name == "Mesh") + { + foreach (Transform tt in t) + { childmeshes.Add(tt.gameObject); childRotations.Add(tt.transform.localEulerAngles); } @@ -1961,14 +2262,16 @@ public static void ContextSetupLightSwitch() { } [ContextMenu("Setup Colliders, VisPoints, and Bounding Box")] - public void SetupCollidersVisPoints() { + public void SetupCollidersVisPoints() + { ContextSetUpColliders(); ContextSetUpVisibilityPoints(); ContextSetUpBoundingBox(); } //[UnityEditor.MenuItem("SimObjectPhysics/Toaster")] - public static void ContextSetupToaster() { + public static void ContextSetupToaster() + { GameObject prefabRoot = Selection.activeGameObject; GameObject c = new GameObject("Toaster_"); c.transform.position = prefabRoot.transform.position; @@ -1976,11 +2279,13 @@ public static void ContextSetupToaster() { prefabRoot.transform.SetParent(c.transform); prefabRoot.name = "Mesh"; - if (!c.GetComponent()) { + if (!c.GetComponent()) + { c.AddComponent(); } - if (c.GetComponent()) { + if (c.GetComponent()) + { SimObjPhysics sop = c.GetComponent(); sop.PrimaryProperty = SimObjPrimaryProperty.Static; sop.Type = SimObjType.Toaster; @@ -1990,11 +2295,13 @@ public static void ContextSetupToaster() { c.tag = "SimObjPhysics"; c.layer = 8; - if (!c.GetComponent()) { + if (!c.GetComponent()) + { c.AddComponent(); } - if (!c.transform.Find("Colliders")) { + if (!c.transform.Find("Colliders")) + { GameObject col = new GameObject("Colliders"); col.transform.position = c.transform.position; col.transform.SetParent(c.transform); @@ -2007,7 +2314,8 @@ public static void ContextSetupToaster() { cc.layer = 8; } - if (!c.transform.Find("VisibilityPoints")) { + if (!c.transform.Find("VisibilityPoints")) + { // empty to hold all visibility points GameObject vp = new GameObject("VisibilityPoints"); vp.transform.position = c.transform.position; @@ -2019,7 +2327,8 @@ public static void ContextSetupToaster() { vpc.transform.SetParent(vp.transform); } - if (!c.transform.Find("BoundingBox")) { + if (!c.transform.Find("BoundingBox")) + { GameObject rac = new GameObject("BoundingBox"); rac.transform.position = c.transform.position; rac.transform.SetParent(c.transform); @@ -2031,24 +2340,32 @@ public static void ContextSetupToaster() { } //[ContextMenu("Toaster Setup References")] - void ToasterSetupReferences() { + void ToasterSetupReferences() + { ContextSetUpColliders(); ContextSetUpVisibilityPoints(); ContextSetUpBoundingBox(); - foreach (Transform t in gameObject.transform) { - if (t.name == "Colliders") { - if (!gameObject.transform.Find("TriggerColliders")) { + foreach (Transform t in gameObject.transform) + { + if (t.name == "Colliders") + { + if (!gameObject.transform.Find("TriggerColliders")) + { GameObject inst = Instantiate(t.gameObject, gameObject.transform, true); inst.name = "TriggerColliders"; - foreach (Transform yes in inst.transform) { + foreach (Transform yes in inst.transform) + { yes.GetComponent().isTrigger = true; } - } else { + } + else + { DestroyImmediate(gameObject.transform.Find("TriggerColliders").gameObject); GameObject inst = Instantiate(t.gameObject, gameObject.transform, true); inst.name = "TriggerColliders"; - foreach (Transform yes in inst.transform) { + foreach (Transform yes in inst.transform) + { yes.GetComponent().isTrigger = true; } } @@ -2057,11 +2374,13 @@ void ToasterSetupReferences() { } [ContextMenu("Setup")] - public void ContextSetUpSimObjPhysics() { + public void ContextSetUpSimObjPhysics() + { if ( this.Type == SimObjType.Undefined || this.PrimaryProperty == SimObjPrimaryProperty.Undefined - ) { + ) + { Debug.Log("Type / Primary Property is missing"); return; } @@ -2069,13 +2388,15 @@ public void ContextSetUpSimObjPhysics() { gameObject.tag = "SimObjPhysics"; gameObject.layer = 8; - if (!gameObject.GetComponent()) { + if (!gameObject.GetComponent()) + { gameObject.AddComponent(); } gameObject.GetComponent().isKinematic = true; - if (!gameObject.transform.Find("Colliders")) { + if (!gameObject.transform.Find("Colliders")) + { GameObject c = new GameObject("Colliders"); c.transform.position = gameObject.transform.position; c.transform.SetParent(gameObject.transform); @@ -2091,7 +2412,8 @@ public void ContextSetUpSimObjPhysics() { cc.layer = 8; } - if (!gameObject.transform.Find("VisibilityPoints")) { + if (!gameObject.transform.Find("VisibilityPoints")) + { // empty to hold all visibility points GameObject vp = new GameObject("VisibilityPoints"); vp.transform.position = gameObject.transform.position; @@ -2105,7 +2427,8 @@ public void ContextSetUpSimObjPhysics() { vpc.transform.localEulerAngles = Vector3.zero; } - if (!gameObject.transform.Find("BoundingBox")) { + if (!gameObject.transform.Find("BoundingBox")) + { GameObject rac = new GameObject("BoundingBox"); rac.transform.position = gameObject.transform.position; rac.transform.SetParent(gameObject.transform); @@ -2117,40 +2440,52 @@ public void ContextSetUpSimObjPhysics() { List recepboxes = new List(); - foreach (Transform t in gameObject.transform) { + foreach (Transform t in gameObject.transform) + { // add any receptacle trigger boxes - if (t.GetComponent()) { - if (!recepboxes.Contains(t.gameObject)) { + if (t.GetComponent()) + { + if (!recepboxes.Contains(t.gameObject)) + { recepboxes.Add(t.gameObject); } } - if (t.name == "Colliders") { - if (!gameObject.transform.Find("TriggerColliders")) { + if (t.name == "Colliders") + { + if (!gameObject.transform.Find("TriggerColliders")) + { GameObject inst = Instantiate(t.gameObject, gameObject.transform, true); inst.name = "TriggerColliders"; - foreach (Transform yes in inst.transform) { + foreach (Transform yes in inst.transform) + { yes.GetComponent().isTrigger = true; } - } else { + } + else + { DestroyImmediate(gameObject.transform.Find("TriggerColliders").gameObject); GameObject inst = Instantiate(t.gameObject, gameObject.transform, true); inst.name = "TriggerColliders"; - foreach (Transform yes in inst.transform) { + foreach (Transform yes in inst.transform) + { yes.GetComponent().isTrigger = true; } } } // check if child object "t" has any objects under it called "Colliders" - if (t.Find("Colliders")) { + if (t.Find("Colliders")) + { Transform childColliderObject = t.Find("Colliders"); // if TriggerColliders dont already exist as a child under this child object t, create it by copying childColliderObject - if (!t.Find("TriggerColliders")) { + if (!t.Find("TriggerColliders")) + { GameObject inst = Instantiate(childColliderObject.gameObject, t, true); inst.name = "TriggerColliders"; - foreach (Transform thing in inst.transform) { + foreach (Transform thing in inst.transform) + { thing.GetComponent().isTrigger = true; } } @@ -2167,13 +2502,16 @@ public void ContextSetUpSimObjPhysics() { } //[ContextMenu("Set Up Colliders")] - public void ContextSetUpColliders() { + public void ContextSetUpColliders() + { List listColliders = new List(); - if (transform.Find("Colliders")) { + if (transform.Find("Colliders")) + { Transform Colliders = transform.Find("Colliders"); - foreach (Transform child in Colliders) { + foreach (Transform child in Colliders) + { // list.toarray listColliders.Add(child.GetComponent()); @@ -2182,7 +2520,8 @@ public void ContextSetUpColliders() { child.gameObject.tag = "SimObjPhysics"; child.gameObject.layer = 8; - if (child.GetComponent()) { + if (child.GetComponent()) + { child.GetComponent().enabled = true; child.GetComponent().isTrigger = false; } @@ -2190,11 +2529,14 @@ public void ContextSetUpColliders() { } // loop through all child objects. For each object, check if the child itself has a child called Colliders.... - foreach (Transform child in transform) { - if (child.Find("Colliders") && !child.GetComponent()) { + foreach (Transform child in transform) + { + if (child.Find("Colliders") && !child.GetComponent()) + { Transform Colliders = child.Find("Colliders"); - foreach (Transform childschild in Colliders) { + foreach (Transform childschild in Colliders) + { // list.toarray listColliders.Add(childschild.GetComponent()); @@ -2203,7 +2545,8 @@ public void ContextSetUpColliders() { childschild.gameObject.tag = "SimObjPhysics"; childschild.gameObject.layer = 8; - if (childschild.GetComponent()) { + if (childschild.GetComponent()) + { childschild.GetComponent().enabled = true; childschild.GetComponent().isTrigger = false; } @@ -2215,13 +2558,16 @@ public void ContextSetUpColliders() { } //[ContextMenu("Set Up TriggerColliders")] - void ContextSetUpTriggerColliders() { - if (transform.Find("TriggerColliders")) { + void ContextSetUpTriggerColliders() + { + if (transform.Find("TriggerColliders")) + { Transform tc = transform.Find("TriggerColliders"); List listtc = new List(); - foreach (Transform child in tc) { + foreach (Transform child in tc) + { // list.toarray listtc.Add(child.gameObject); @@ -2230,7 +2576,8 @@ void ContextSetUpTriggerColliders() { child.gameObject.tag = "SimObjPhysics"; child.gameObject.layer = 8; - if (child.GetComponent()) { + if (child.GetComponent()) + { child.GetComponent().enabled = true; child.GetComponent().isTrigger = true; } @@ -2241,13 +2588,16 @@ void ContextSetUpTriggerColliders() { } // [ContextMenu("Set Up VisibilityPoints")] - public void ContextSetUpVisibilityPoints() { + public void ContextSetUpVisibilityPoints() + { List vplist = new List(); - if (transform.Find("VisibilityPoints")) { + if (transform.Find("VisibilityPoints")) + { Transform vp = transform.Find("VisibilityPoints"); - foreach (Transform child in vp) { + foreach (Transform child in vp) + { vplist.Add(child); // set correct tag and layer for each object @@ -2256,11 +2606,14 @@ public void ContextSetUpVisibilityPoints() { } } - foreach (Transform child in transform) { - if (child.Find("VisibilityPoints") && !child.GetComponent()) { + foreach (Transform child in transform) + { + if (child.Find("VisibilityPoints") && !child.GetComponent()) + { Transform vp = child.Find("VisibilityPoints"); - foreach (Transform childschild in vp) { + foreach (Transform childschild in vp) + { vplist.Add(childschild); childschild.gameObject.tag = "Untagged"; childschild.gameObject.layer = 8; @@ -2273,13 +2626,15 @@ public void ContextSetUpVisibilityPoints() { #endif //[ContextMenu("Set Up Bounding Box")] - public void ContextSetUpBoundingBox(bool forceCacheReset = false) { + public void ContextSetUpBoundingBox(bool forceCacheReset = false) + { Vector3[] transformSaver = new Vector3[] { transform.position, transform.eulerAngles }; transform.position = Vector3.zero; transform.eulerAngles = Vector3.zero; - if (BoundingBox == null) { + if (BoundingBox == null) + { GameObject BoundingBox = new GameObject("BoundingBox"); BoundingBox.transform.parent = gameObject.transform; BoundingBox.transform.localPosition = Vector3.zero; @@ -2296,7 +2651,8 @@ public void ContextSetUpBoundingBox(bool forceCacheReset = false) { BoundingBox.tag = "Untagged"; BoundingBox.layer = 9; // layer 9 - SimObjInvisible - if (!Physics.autoSyncTransforms) { + if (!Physics.autoSyncTransforms) + { Physics.SyncTransforms(); } @@ -2311,7 +2667,8 @@ public void ContextSetUpBoundingBox(bool forceCacheReset = false) { // Transform rootBoneSurrogateParent = new GameObject().transform; // Reset existing Bounding Box - if (BoundingBox.GetComponent()) { + if (BoundingBox.GetComponent()) + { BoundingBox.GetComponent().enabled = true; BoundingBox.GetComponent().center = colliders[0].bounds.center; BoundingBox.GetComponent().size = Vector3.zero; @@ -2322,34 +2679,42 @@ public void ContextSetUpBoundingBox(bool forceCacheReset = false) { Vector3 maxMeshXYZ = colliders[0].bounds.center; // Encapsulate all colliders - foreach (Collider collider in colliders) { + foreach (Collider collider in colliders) + { newBoundingBox.Encapsulate(collider.gameObject.GetComponent().bounds); } // Encapsulate all mesh filters (used instead of mesh renderers because you can sample individual vertex ids with the filters) // Excluded min-y because my material ID triangles are all located way below their respective main-meshes // newBoundingBox.Encapsulate(meshGroup.GetComponent().mesh.bounds.min); - foreach (MeshFilter meshFilter in meshes) { + foreach (MeshFilter meshFilter in meshes) + { // if (meshFilter.gameObject.name != "screen_1" && meshFilter.gameObject.name != "screen_2") //{ - foreach (Vector3 vertex in meshFilter.sharedMesh.vertices) { - if (minMeshXZ.x > meshFilter.gameObject.transform.TransformPoint(vertex).x) { + foreach (Vector3 vertex in meshFilter.sharedMesh.vertices) + { + if (minMeshXZ.x > meshFilter.gameObject.transform.TransformPoint(vertex).x) + { minMeshXZ.x = meshFilter.gameObject.transform.TransformPoint(vertex).x; } - if (minMeshXZ.z > meshFilter.gameObject.transform.TransformPoint(vertex).z) { + if (minMeshXZ.z > meshFilter.gameObject.transform.TransformPoint(vertex).z) + { minMeshXZ.z = meshFilter.gameObject.transform.TransformPoint(vertex).z; } - if (maxMeshXYZ.x < meshFilter.gameObject.transform.TransformPoint(vertex).x) { + if (maxMeshXYZ.x < meshFilter.gameObject.transform.TransformPoint(vertex).x) + { maxMeshXYZ.x = meshFilter.gameObject.transform.TransformPoint(vertex).x; } - if (maxMeshXYZ.y < meshFilter.gameObject.transform.TransformPoint(vertex).y) { + if (maxMeshXYZ.y < meshFilter.gameObject.transform.TransformPoint(vertex).y) + { maxMeshXYZ.y = meshFilter.gameObject.transform.TransformPoint(vertex).y; } - if (maxMeshXYZ.z < meshFilter.gameObject.transform.TransformPoint(vertex).z) { + if (maxMeshXYZ.z < meshFilter.gameObject.transform.TransformPoint(vertex).z) + { maxMeshXYZ.z = meshFilter.gameObject.transform.TransformPoint(vertex).z; } @@ -2398,7 +2763,8 @@ public void ContextSetUpBoundingBox(bool forceCacheReset = false) { transform.position = transformSaver[0]; transform.eulerAngles = transformSaver[1]; - if (forceCacheReset) { + if (forceCacheReset) + { this.syncBoundingBoxes(forceCacheReset: true); } } @@ -2408,7 +2774,8 @@ public static ObjectMetadata ObjectMetadataFromSimObjPhysics( SimObjPhysics simObj, bool isVisible, bool isInteractable - ) { + ) + { ObjectMetadata objMeta = new ObjectMetadata(); GameObject o = simObj.gameObject; objMeta.name = o.name; @@ -2418,7 +2785,8 @@ bool isInteractable objMeta.receptacle = simObj.IsReceptacle; objMeta.openable = simObj.IsOpenable; - if (objMeta.openable) { + if (objMeta.openable) + { objMeta.isOpen = simObj.IsOpen; objMeta.openness = simObj.openness; } @@ -2427,28 +2795,33 @@ bool isInteractable //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)) { + if (simObj.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanToggleOnOff)) + { objMeta.isToggled = simObj.IsToggled; } objMeta.breakable = simObj.IsBreakable; - if (objMeta.breakable) { + if (objMeta.breakable) + { objMeta.isBroken = simObj.IsBroken; } objMeta.canFillWithLiquid = simObj.IsFillable; - if (objMeta.canFillWithLiquid) { + if (objMeta.canFillWithLiquid) + { objMeta.isFilledWithLiquid = simObj.IsFilled; objMeta.fillLiquid = simObj.FillLiquid; } objMeta.dirtyable = simObj.IsDirtyable; - if (objMeta.dirtyable) { + if (objMeta.dirtyable) + { objMeta.isDirty = simObj.IsDirty; } objMeta.cookable = simObj.IsCookable; - if (objMeta.cookable) { + if (objMeta.cookable) + { objMeta.isCooked = simObj.IsCooked; } @@ -2457,12 +2830,14 @@ bool isInteractable 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]; - for (int i = 0; i < simObj.salientMaterials.Length; i++) { + for (int i = 0; i < simObj.salientMaterials.Length; i++) + { salientMaterialsToString[i] = simObj.salientMaterials[i].ToString(); } @@ -2485,12 +2860,14 @@ bool isInteractable // } objMeta.sliceable = simObj.IsSliceable; - if (objMeta.sliceable) { + if (objMeta.sliceable) + { objMeta.isSliced = simObj.IsSliced; } objMeta.canBeUsedUp = simObj.CanBeUsedUp; - if (objMeta.canBeUsedUp) { + if (objMeta.canBeUsedUp) + { objMeta.isUsedUp = simObj.IsUsedUp; } @@ -2523,7 +2900,8 @@ bool isInteractable return objMeta; } - class BoundingBoxCacheKey { + class BoundingBoxCacheKey + { public Vector3 position; public Quaternion rotation; public bool IsOpen; diff --git a/unity/Assets/Scripts/SimObjType.cs b/unity/Assets/Scripts/SimObjType.cs index 339fb07c27..7307b426d6 100644 --- a/unity/Assets/Scripts/SimObjType.cs +++ b/unity/Assets/Scripts/SimObjType.cs @@ -5,7 +5,8 @@ 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 +public enum SimObjManipType : int +{ // We aren't using these manip types for the Physics Implementation, they are being replaced with the SimObjPrimaryProperty below Inventory = 0, Static = 1, Rearrangeable = 2, @@ -103,7 +104,8 @@ public enum SimObjSecondaryProperty : int // EACH SimObjPhysics can have any num } [Serializable] -public enum SimObjType : int { +public enum SimObjType : int +{ // undefined is always the first value Undefined = 0, @@ -280,7 +282,8 @@ public enum SimObjType : int { Objaverse = 167 } -public static class ReceptacleRestrictions { +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) diff --git a/unity/Assets/Scripts/SimTesting.cs b/unity/Assets/Scripts/SimTesting.cs index 2f3f109eb2..b9180d1062 100644 --- a/unity/Assets/Scripts/SimTesting.cs +++ b/unity/Assets/Scripts/SimTesting.cs @@ -4,8 +4,10 @@ using UnityEngine; // class for testing SimUtil functions -public class SimTesting : MonoBehaviour { - public enum TestMethod { +public class SimTesting : MonoBehaviour +{ + public enum TestMethod + { SpherecastAll, CheckVisibility, Raycast, @@ -30,22 +32,29 @@ public enum TestMethod { public bool foundPlacementPoint; public SimObj inventoryObject; - void Start() { - if (inventoryObject != null) { + void Start() + { + if (inventoryObject != null) + { inventoryObject.gameObject.SetActive(false); } } #if UNITY_EDITOR // used to show what's currently visible - void OnGUI() { - if (SimObjsInView != null) { - if (SimObjsInView.Length > 10) { + void OnGUI() + { + if (SimObjsInView != null) + { + if (SimObjsInView.Length > 10) + { int horzIndex = -1; GUILayout.BeginHorizontal(); - foreach (SimObj o in SimObjsInView) { + foreach (SimObj o in SimObjsInView) + { horzIndex++; - if (horzIndex >= 3) { + if (horzIndex >= 3) + { GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); horzIndex = 0; @@ -57,8 +66,11 @@ void OnGUI() { ); } GUILayout.EndHorizontal(); - } else { - foreach (SimObj o in SimObjsInView) { + } + else + { + foreach (SimObj o in SimObjsInView) + { GUILayout.Button( o.ObjectID, UnityEditor.EditorStyles.miniButton, @@ -71,16 +83,19 @@ void OnGUI() { #endif #if UNITY_EDITOR - void OnDisable() { + void OnDisable() + { // make all sim objs invisible SimObj[] simObjs = GameObject.FindObjectsOfType(); - foreach (SimObj o in simObjs) { + foreach (SimObj o in simObjs) + { o.VisibleNow = false; } } #endif - void Update() { + void Update() + { // check for a navmesh hit foundPlacementPoint = PlacementManager.GetPlacementPoint( transform.position, @@ -91,15 +106,20 @@ void Update() { ref placementPoint ); - if (inventoryObject != null && Input.GetKeyDown(KeyCode.P)) { - if (inventoryObject.gameObject.activeSelf) { + if (inventoryObject != null && Input.GetKeyDown(KeyCode.P)) + { + if (inventoryObject.gameObject.activeSelf) + { SimUtil.TakeItem(inventoryObject); - } else if (foundPlacementPoint) { + } + else if (foundPlacementPoint) + { PlacementManager.PlaceObjectAtPoint(inventoryObject, placementPoint); } } - switch (Method) { + switch (Method) + { case TestMethod.CheckVisibility: default: SimObjsInView = SimUtil.GetAllVisibleSimObjs(Cam, MaxDistance); @@ -109,12 +129,14 @@ ref placementPoint } // resize the array to avoid confusion in the test - if (SimObjsInView.Length != NumItems) { + if (SimObjsInView.Length != NumItems) + { Array.Resize(ref SimObjsInView, NumItems); } } - void OnDrawGizmos() { + void OnDrawGizmos() + { Gizmos.color = Color.cyan; Gizmos.DrawSphere(Cam.transform.position, 0.1f); Gizmos.color = Color.grey; @@ -130,7 +152,8 @@ void OnDrawGizmos() { Gizmos.color = foundPlacementPoint ? Color.green : Color.gray; Gizmos.DrawSphere(transform.position + (Cam.transform.forward * ReachDistance), 0.05f); - if (foundPlacementPoint) { + if (foundPlacementPoint) + { Gizmos.DrawLine( transform.position + (Cam.transform.forward * ReachDistance), placementPoint diff --git a/unity/Assets/Scripts/SimUtil.cs b/unity/Assets/Scripts/SimUtil.cs index f0d4d3bdb5..0d21435a06 100644 --- a/unity/Assets/Scripts/SimUtil.cs +++ b/unity/Assets/Scripts/SimUtil.cs @@ -7,7 +7,8 @@ using UnityEngine; using UnityEngine.SceneManagement; -public static class SimUtil { +public static class SimUtil +{ // how fast smooth-animated s / cabinets / etc animate public const float SmoothAnimationSpeed = 0.5f; @@ -36,13 +37,18 @@ public static class SimUtil { #region SimObj utility functions - public static SimObj[] GetAllVisibleSimObjs(Camera agentCamera, float maxDistance) { + public static SimObj[] GetAllVisibleSimObjs(Camera agentCamera, float maxDistance) + { #if UNITY_EDITOR - if (ShowObjectVisibility) { + if (ShowObjectVisibility) + { // set all objects to invisible before starting - THIS IS EXPENSIVE - if (SceneManager.Current != null) { - foreach (SimObj obj in SceneManager.Current.ObjectsInScene) { - if (obj != null) { + if (SceneManager.Current != null) + { + foreach (SimObj obj in SceneManager.Current.ObjectsInScene) + { + if (obj != null) + { obj.VisibleNow = false; } } @@ -66,13 +72,16 @@ public static SimObj[] GetAllVisibleSimObjs(Camera agentCamera, float maxDistanc QueryTriggerInteraction.Collide ); // go through them one by one and determine if they're actually simObjs - for (int i = 0; i < colliders.Length; i++) { + for (int i = 0; i < colliders.Length; i++) + { if ( colliders[i].CompareTag(SimUtil.SimObjTag) || colliders[i].CompareTag(SimUtil.ReceptacleTag) - ) { + ) + { SimObj o = null; - if (GetSimObjFromCollider(colliders[i], out o)) { + if (GetSimObjFromCollider(colliders[i], out o)) + { // this may result in duplicates because of 'open' receptacles // but using a hashset cancels that out // don't worry about items contained in receptacles until visibility @@ -82,8 +91,10 @@ 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)) { + foreach (SimObj item in uniqueItems) + { + if (!CheckItemBounds(item, agentCameraPos)) + { // if the camera isn't in bounds, skip this item continue; } @@ -92,8 +103,10 @@ public static SimObj[] GetAllVisibleSimObjs(Camera agentCamera, float maxDistanc // if it's a receptacle // raycast against every pivot in the receptacle just to make sure we don't miss anything - if (item.IsReceptacle) { - foreach (Transform pivot in item.Receptacle.Pivots) { + if (item.IsReceptacle) + { + foreach (Transform pivot in item.Receptacle.Pivots) + { canSeeItem = CheckPointVisibility( item, pivot.position, @@ -105,14 +118,17 @@ public static SimObj[] GetAllVisibleSimObjs(Camera agentCamera, float maxDistanc out hit ); // if we can see it no need for more checks! - if (canSeeItem) { + if (canSeeItem) + { break; } } } - if (!canSeeItem) { - for (int i = 0; i < VisibilityCheckSteps; i++) { + if (!canSeeItem) + { + for (int i = 0; i < VisibilityCheckSteps; i++) + { canSeeItem = CheckPointVisibility( item, Vector3.Lerp( @@ -129,20 +145,23 @@ out hit ); // if we can see it no need for more checks! - if (canSeeItem) { + if (canSeeItem) + { break; } } } - if (canSeeItem) { + if (canSeeItem) + { // if it's the same object, add it to the list #if UNITY_EDITOR item.VisibleNow = ShowObjectVisibility & true; #endif items.Add(item); // now check to see if it's a receptacle interior - if (item.IsReceptacle && hit.collider.CompareTag(SimUtil.ReceptacleTag)) { + if (item.IsReceptacle && hit.collider.CompareTag(SimUtil.ReceptacleTag)) + { // if it is, add the items in the receptacle as well items.AddRange( GetVisibleItemsFromReceptacle( @@ -167,7 +186,8 @@ out hit } // checks whether a point is in view of the camera - public static bool CheckPointVisibility(Vector3 itemTargetPoint, Camera agentCamera) { + public static bool CheckPointVisibility(Vector3 itemTargetPoint, Camera agentCamera) + { Vector3 viewPoint = agentCamera.WorldToViewportPoint(itemTargetPoint); if ( viewPoint.z > 0 // in front of camera @@ -175,7 +195,8 @@ public static bool CheckPointVisibility(Vector3 itemTargetPoint, Camera agentCam && viewPoint.x > ViewPointRangeLow // within x bounds && viewPoint.y < ViewPointRangeHigh && viewPoint.y > ViewPointRangeLow - ) { // within y bounds + ) + { // within y bounds return true; } return false; @@ -192,7 +213,8 @@ static bool CheckPointVisibility( bool checkTrigger, float maxDistance, out RaycastHit hit - ) { + ) + { hit = new RaycastHit(); Vector3 viewPoint = agentCamera.WorldToViewportPoint(itemTargetPoint); @@ -202,7 +224,8 @@ out RaycastHit hit && viewPoint.x > ViewPointRangeLow // within x bounds && viewPoint.y < ViewPointRangeHigh && viewPoint.y > ViewPointRangeLow - ) { // within y bounds + ) + { // within y bounds Vector3 itemDirection = Vector3.zero; // do a raycast in the direction of the item itemDirection = (itemTargetPoint - agentCameraPos).normalized; @@ -236,12 +259,14 @@ out RaycastHit hit : 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 UNITY_EDITOR Debug.DrawLine( agentCameraPos, @@ -264,23 +289,29 @@ out RaycastHit hit // if successful, object is placed into the world and activated // this only works on objects of SimObjManipulation type 'inventory' // if an object was spawned in a Receptacle, this function will also return false - public static bool PutItemBackInStartupPosition(SimObj item) { - if (item == null) { + public static bool PutItemBackInStartupPosition(SimObj item) + { + if (item == null) + { Debug.LogError("Item is null, not putting item back"); return false; } bool result = false; - switch (item.Manipulation) { + switch (item.Manipulation) + { case SimObjManipType.Inventory: - if (item.StartupTransform != null) { + if (item.StartupTransform != null) + { item.transform.position = item.StartupTransform.position; item.transform.rotation = item.StartupTransform.rotation; item.transform.localScale = item.StartupTransform.localScale; item.gameObject.SetActive(true); result = true; - } else { + } + else + { Debug.LogWarning( "Item had no startup transform. This probably means it was spawned in a receptacle." ); @@ -296,7 +327,8 @@ public static bool PutItemBackInStartupPosition(SimObj item) { // TAKES an item // removes it from any receptacles, then disables it entirely // this works whether the item is standalone or in a receptacle - public static void TakeItem(SimObj item) { + public static void TakeItem(SimObj item) + { // make item visible to raycasts // unparent in case it's in a receptacle item.VisibleToRaycasts = true; @@ -310,9 +342,11 @@ public static void TakeItem(SimObj item) { } // checks whether the item - public static bool CheckItemBounds(SimObj item, Vector3 agentPosition) { + public static bool CheckItemBounds(SimObj item, Vector3 agentPosition) + { // if the item doesn't use custom bounds this is an automatic pass - if (!item.UseCustomBounds) { + if (!item.UseCustomBounds) + { return true; } @@ -328,23 +362,29 @@ public static bool CheckItemBounds(SimObj item, Vector3 agentPosition) { // searches for a SimObj item under a receptacle by ID // this does not TAKE the item, it just searches for it - public static bool FindItemFromReceptacleByID(string itemID, Receptacle r, out SimObj item) { + public static bool FindItemFromReceptacleByID(string itemID, Receptacle r, out SimObj item) + { item = null; // make sure we're not doing something insane - if (r == null) { + if (r == null) + { Debug.LogError("Receptacle was null, not searching for item"); return false; } - if (!IsObjectIDValid(itemID)) { + if (!IsObjectIDValid(itemID)) + { Debug.LogError("itemID " + itemID.ToString() + " is NOT valid, not searching for item"); return false; } SimObj checkItem = null; - for (int i = 0; i < r.Pivots.Length; i++) { - if (r.Pivots[i].childCount > 0) { + for (int i = 0; i < r.Pivots.Length; i++) + { + if (r.Pivots[i].childCount > 0) + { checkItem = r.Pivots[i].GetChild(0).GetComponent(); - if (checkItem != null && checkItem.ObjectID == itemID) { + if (checkItem != null && checkItem.ObjectID == itemID) + { // if the item under the pivot is a SimObj with the right id // we've found what we're after item = checkItem; @@ -362,22 +402,28 @@ public static bool FindItemFromReceptacleByType( SimObjType itemType, Receptacle r, out SimObj item - ) { + ) + { item = null; // make sure we're not doing something insane - if (r == null) { + if (r == null) + { Debug.LogError("Receptacle was null, not searching for item"); return false; } - if (itemType == SimObjType.Undefined) { + if (itemType == SimObjType.Undefined) + { Debug.LogError("Can't search for type UNDEFINED, not searching for item"); return false; } SimObj checkItem = null; - for (int i = 0; i < r.Pivots.Length; i++) { - if (r.Pivots[i].childCount > 0) { + for (int i = 0; i < r.Pivots.Length; i++) + { + if (r.Pivots[i].childCount > 0) + { checkItem = r.Pivots[i].GetChild(0).GetComponent(); - if (checkItem != null && checkItem.Type == itemType) { + if (checkItem != null && checkItem.Type == itemType) + { // if the item under the pivot is a SimObj of the right type // we've found what we're after item = checkItem; @@ -392,23 +438,28 @@ out SimObj item // 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 - public static bool AddItemToVisibleReceptacle(SimObj item, Receptacle r, Camera camera) { + public static bool AddItemToVisibleReceptacle(SimObj item, Receptacle r, Camera camera) + { // make sure we're not doing something insane - if (item == null) { + if (item == null) + { Debug.LogError("Can't add null item to receptacle"); return false; } - if (r == null) { + if (r == null) + { Debug.LogError("Receptacle was null, not adding item"); return false; } - if (item.gameObject == r.gameObject) { + if (item.gameObject == r.gameObject) + { Debug.LogError("Receptacle and item were same object, can't add item to itself"); return false; } // make sure there's room in the recepticle Transform emptyPivot = null; - if (!GetFirstEmptyVisibleReceptaclePivot(r, camera, out emptyPivot)) { + if (!GetFirstEmptyVisibleReceptaclePivot(r, camera, out emptyPivot)) + { Debug.Log("No visible Pivots found"); return false; } @@ -418,23 +469,28 @@ public static bool AddItemToVisibleReceptacle(SimObj item, Receptacle r, Camera // 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 - public static bool AddItemToReceptacle(SimObj item, Receptacle r) { + public static bool AddItemToReceptacle(SimObj item, Receptacle r) + { // make sure we're not doing something insane - if (item == null) { + if (item == null) + { Debug.LogError("Can't add null item to receptacle"); return false; } - if (r == null) { + if (r == null) + { Debug.LogError("Receptacle was null, not adding item"); return false; } - if (item.gameObject == r.gameObject) { + if (item.gameObject == r.gameObject) + { Debug.LogError("Receptacle and item were same object, can't add item to itself"); return false; } // make sure there's room in the recepticle Transform emptyPivot = null; - if (!GetFirstEmptyReceptaclePivot(r, out emptyPivot)) { + if (!GetFirstEmptyReceptaclePivot(r, out emptyPivot)) + { // Debug.Log ("Receptacle is full"); return false; } @@ -444,13 +500,16 @@ public static bool AddItemToReceptacle(SimObj item, Receptacle r) { // 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 - public static bool AddItemToReceptaclePivot(SimObj item, Transform pivot) { - if (item == null) { + 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) { + if (pivot == null) + { Debug.LogError( "Pivot was null when attempting to add item " + item.name @@ -476,10 +535,13 @@ public static bool AddItemToReceptaclePivot(SimObj item, Transform pivot) { return true; } - public static bool GetFirstEmptyReceptaclePivot(Receptacle r, out Transform emptyPivot) { + public static bool GetFirstEmptyReceptaclePivot(Receptacle r, out Transform emptyPivot) + { emptyPivot = null; - for (int i = 0; i < r.Pivots.Length; i++) { - if (r.Pivots[i].childCount == 0) { + for (int i = 0; i < r.Pivots.Length; i++) + { + if (r.Pivots[i].childCount == 0) + { emptyPivot = r.Pivots[i]; break; } @@ -491,15 +553,18 @@ public static bool GetFirstEmptyVisibleReceptaclePivot( Receptacle r, Camera camera, out Transform emptyPivot - ) { + ) + { Plane[] planes = GeometryUtility.CalculateFrustumPlanes(camera); emptyPivot = null; - for (int i = 0; i < r.Pivots.Length; i++) { + for (int i = 0; i < r.Pivots.Length; i++) + { Transform t = r.Pivots[i]; Bounds bounds = new Bounds(t.position, new Vector3(0.05f, 0.05f, 0.05f)); - if (t.childCount == 0 && GeometryUtility.TestPlanesAABB(planes, bounds)) { + if (t.childCount == 0 && GeometryUtility.TestPlanesAABB(planes, bounds)) + { emptyPivot = r.Pivots[i]; break; } @@ -508,9 +573,11 @@ out Transform emptyPivot } // tries to get a SimObj from a collider, returns false if none found - public static bool GetSimObjFromCollider(Collider c, out SimObj o) { + public static bool GetSimObjFromCollider(Collider c, out SimObj o) + { o = null; - if (c.attachedRigidbody == null) { + if (c.attachedRigidbody == null) + { // all sim objs must have a kinematic rigidbody return false; } @@ -519,9 +586,11 @@ public static bool GetSimObjFromCollider(Collider c, out SimObj o) { } // tries to get a receptacle from a collider, returns false if none found - public static bool GetReceptacleFromCollider(Collider c, out Receptacle r) { + public static bool GetReceptacleFromCollider(Collider c, out Receptacle r) + { r = null; - if (c.attachedRigidbody == null) { + if (c.attachedRigidbody == null) + { // all sim objs must have a kinematic rigidbody return false; } @@ -531,10 +600,13 @@ public static bool GetReceptacleFromCollider(Collider c, out Receptacle r) { // gets all SimObjs contained in a receptacle // this does not TAKE any of these items - public static SimObj[] GetItemsFromReceptacle(Receptacle r) { + public static SimObj[] GetItemsFromReceptacle(Receptacle r) + { List items = new List(); - foreach (Transform t in r.Pivots) { - if (t.childCount > 0) { + foreach (Transform t in r.Pivots) + { + if (t.childCount > 0) + { items.Add(t.GetChild(0).GetComponent()); } } @@ -548,18 +620,24 @@ public static SimObj[] GetVisibleItemsFromReceptacle( Camera agentCamera, Vector3 agentCameraPos, float maxDistance - ) { + ) + { List items = new List(); // RaycastHit hit = new RaycastHit(); - foreach (Transform t in r.Pivots) { - if (t.childCount > 0) { + foreach (Transform t in r.Pivots) + { + if (t.childCount > 0) + { SimObj item = t.GetChild(0).GetComponent(); // check whether the item is visible (center point only) // since it's inside a receptacle, it will be on the invisible layer - if (CheckPointVisibility(item.CenterPoint, agentCamera)) { + if (CheckPointVisibility(item.CenterPoint, agentCamera)) + { item.VisibleNow = true; items.Add(item); - } else { + } + else + { item.VisibleNow = false; } } @@ -567,7 +645,8 @@ float maxDistance return items.ToArray(); } - public static bool IsObjectIDValid(string objectID) { + public static bool IsObjectIDValid(string objectID) + { return !string.IsNullOrEmpty(objectID); } @@ -577,9 +656,12 @@ public static bool IsObjectIDValid(string objectID) { #if UNITY_EDITOR [UnityEditor.MenuItem("AI2-THOR/Set Up Base Objects")] - public static void SetUpBaseObjects() { - foreach (GameObject go in UnityEditor.Selection.gameObjects) { - if (go.transform.childCount > 0 && go.transform.GetChild(0).name == "Base") { + public static void SetUpBaseObjects() + { + foreach (GameObject go in UnityEditor.Selection.gameObjects) + { + if (go.transform.childCount > 0 && go.transform.GetChild(0).name == "Base") + { continue; } GameObject newGo = new GameObject(go.name); @@ -589,7 +671,8 @@ public static void SetUpBaseObjects() { go.transform.parent = newGo.transform; go.name = "Base"; BoxCollider bc = go.GetComponent(); - if (bc == null) { + if (bc == null) + { go.AddComponent(); } } @@ -601,7 +684,8 @@ public static void BuildScene( 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"; @@ -629,8 +713,10 @@ bool launchOnBuild } [UnityEditor.MenuItem("AI2-THOR/RandomizeMaterials/Bin Materials")] - static void BinMaterials() { - HashSet getMaterialsInScene() { + static void BinMaterials() + { + HashSet getMaterialsInScene() + { HashSet sceneMeshRenderers = new HashSet(); HashSet sceneMaterials = new HashSet(); @@ -643,7 +729,8 @@ HashSet getMaterialsInScene() { ); // Get all shared Materials from MeshRenderers - foreach (MeshRenderer meshRenderer in sceneMeshRenderers) { + foreach (MeshRenderer meshRenderer in sceneMeshRenderers) + { sceneMaterials.UnionWith(meshRenderer.sharedMaterials); } @@ -653,7 +740,8 @@ HashSet getMaterialsInScene() { Dictionary> materialMetadata = new Dictionary< string, HashSet - >() { + >() + { ["RawTrainMaterials"] = new HashSet(), ["RawValMaterials"] = new HashSet(), ["RawTestMaterials"] = new HashSet(), @@ -665,14 +753,17 @@ HashSet getMaterialsInScene() { }; // iTHOR scenes - foreach (int sceneType in new int[] { 0, 200, 300, 400 }) { - for (int i = 1; i <= 30; i++) { + foreach (int sceneType in new int[] { 0, 200, 300, 400 }) + { + for (int i = 1; i <= 30; i++) + { string scenePath = $"Assets/Scenes/FloorPlan{sceneType + i}_physics.unity"; UnityEditor.SceneManagement.EditorSceneManager.OpenScene(scenePath); HashSet materials = getMaterialsInScene(); - switch (sceneType) { + switch (sceneType) + { case 0: materialMetadata["RawKitchenMaterials"].UnionWith(materials); break; @@ -687,13 +778,18 @@ HashSet getMaterialsInScene() { break; } - if (i <= 20) { + if (i <= 20) + { // train scene materialMetadata["RawTrainMaterials"].UnionWith(materials); - } else if (i <= 25) { + } + else if (i <= 25) + { // val scene materialMetadata["RawValMaterials"].UnionWith(materials); - } else { + } + else + { // test scene materialMetadata["RawTestMaterials"].UnionWith(materials); } @@ -701,8 +797,10 @@ HashSet getMaterialsInScene() { } // RoboTHOR train - for (int i = 1; i <= 12; i++) { - for (int j = 1; j <= 5; j++) { + for (int i = 1; i <= 12; i++) + { + for (int j = 1; j <= 5; j++) + { string scenePath = $"Assets/Scenes/FloorPlan_Train{i}_{j}.unity"; UnityEditor.SceneManagement.EditorSceneManager.OpenScene(scenePath); @@ -713,8 +811,10 @@ HashSet getMaterialsInScene() { } // RoboTHOR val - for (int i = 1; i <= 3; i++) { - for (int j = 1; j <= 5; j++) { + for (int i = 1; i <= 3; i++) + { + for (int j = 1; j <= 5; j++) + { string scenePath = $"Assets/Scenes/FloorPlan_Val{i}_{j}.unity"; UnityEditor.SceneManagement.EditorSceneManager.OpenScene(scenePath); @@ -729,9 +829,11 @@ HashSet getMaterialsInScene() { GameObject physicsSceneManager = UnityEditor.PrefabUtility.LoadPrefabContents(prefabPath); ColorChanger colorChangeComponent = physicsSceneManager.GetComponent(); - foreach (KeyValuePair> keyValuePair in materialMetadata) { + foreach (KeyValuePair> keyValuePair in materialMetadata) + { string label = keyValuePair.Key; - foreach (Material mat in keyValuePair.Value) { + foreach (Material mat in keyValuePair.Value) + { HashSet labels = new HashSet(AssetDatabase.GetLabels(mat)); labels.Add(label); AssetDatabase.SetLabels(mat, labels.ToArray()); @@ -746,9 +848,11 @@ HashSet getMaterialsInScene() { } [UnityEditor.MenuItem("AI2-THOR/Replace Generic Prefabs in All Scenes")] - static void ReplacePrefabsInAllScenes() { + static void ReplacePrefabsInAllScenes() + { UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes(); - for (int i = 1; i <= 30; i++) { + for (int i = 1; i <= 30; i++) + { string scenePath = "Assets/Scenes/FloorPlan" + i.ToString() + ".unity"; UnityEditor.EditorUtility.DisplayProgressBar( "Replacing generics...", @@ -756,9 +860,12 @@ static void ReplacePrefabsInAllScenes() { (1f / 30) * i ); UnityEngine.SceneManagement.Scene openScene = new UnityEngine.SceneManagement.Scene(); - try { + try + { openScene = UnityEditor.SceneManagement.EditorSceneManager.OpenScene(scenePath); - } catch (Exception e) { + } + catch (Exception e) + { Debug.LogException(e); continue; } @@ -767,7 +874,8 @@ static void ReplacePrefabsInAllScenes() { sm.ReplaceGenerics(); // save the scene and close it UnityEditor.SceneManagement.EditorSceneManager.SaveScene(openScene); - if (UnityEditor.SceneManagement.EditorSceneManager.loadedSceneCount > 1) { + if (UnityEditor.SceneManagement.EditorSceneManager.loadedSceneCount > 1) + { UnityEditor.SceneManagement.EditorSceneManager.CloseScene(openScene, true); } } @@ -775,9 +883,11 @@ static void ReplacePrefabsInAllScenes() { } [UnityEditor.MenuItem("AI2-THOR/Set SceneManager Scene Number")] - static void SetSceneManagerSceneNumber() { + static void SetSceneManagerSceneNumber() + { UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes(); - for (int i = 1; i <= 30; i++) { + for (int i = 1; i <= 30; i++) + { string scenePath = "Assets/Scenes/FloorPlan" + (i + 200).ToString() + ".unity"; UnityEditor.EditorUtility.DisplayProgressBar( "Setting scene numbers...", @@ -785,9 +895,12 @@ static void SetSceneManagerSceneNumber() { (1f / 30) * i ); UnityEngine.SceneManagement.Scene openScene = new UnityEngine.SceneManagement.Scene(); - try { + try + { openScene = UnityEditor.SceneManagement.EditorSceneManager.OpenScene(scenePath); - } catch (Exception e) { + } + catch (Exception e) + { Debug.LogException(e); continue; } @@ -796,7 +909,8 @@ static void SetSceneManagerSceneNumber() { sm.SceneNumber = i; // save the scene and close it UnityEditor.SceneManagement.EditorSceneManager.SaveScene(openScene); - if (UnityEditor.SceneManagement.EditorSceneManager.loadedSceneCount > 1) { + if (UnityEditor.SceneManagement.EditorSceneManager.loadedSceneCount > 1) + { UnityEditor.SceneManagement.EditorSceneManager.CloseScene(openScene, true); } } @@ -804,12 +918,16 @@ static void SetSceneManagerSceneNumber() { } [UnityEditor.MenuItem("AI2-THOR/Set Pivot Scales to 1")] - static void SetPivotScalesToOne() { + static void SetPivotScalesToOne() + { Transform[] transforms = GameObject.FindObjectsOfType(); - foreach (Transform t in transforms) { - if (t.name.Contains("Pivot")) { + foreach (Transform t in transforms) + { + if (t.name.Contains("Pivot")) + { GameObject prefabParent = null; - if (UnityEditor.EditorUtility.IsPersistent(t)) { + if (UnityEditor.EditorUtility.IsPersistent(t)) + { prefabParent = UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(t.gameObject) as GameObject; @@ -817,12 +935,14 @@ static void SetPivotScalesToOne() { Transform pivot = t; 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; - if (pivot.localScale != Vector3.one) { + if (pivot.localScale != Vector3.one) + { Debug.Log( "Found pivot with non-uniform scale (" + pivot.localScale.ToString() @@ -831,11 +951,13 @@ static void SetPivotScalesToOne() { ); } pivot.localScale = Vector3.one; - if (child != null) { + if (child != null) + { child.parent = pivot; } pivot.parent = tempParent; - if (prefabParent != null) { + if (prefabParent != null) + { Debug.Log("Reconnecting to " + prefabParent.name); UnityEditor.PrefabUtility.RevertPrefabInstance( t.gameObject, @@ -850,7 +972,8 @@ static void SetPivotScalesToOne() { } [UnityEditor.MenuItem("AI2-THOR/Add Pickupable Objects to Physics Scene Manager")] - static void AddPickupableObjectsToPhysicsSceneManager() { + static void AddPickupableObjectsToPhysicsSceneManager() + { PhysicsSceneManager physicsSceneManager = GameObject.FindObjectOfType(); @@ -859,13 +982,16 @@ static void AddPickupableObjectsToPhysicsSceneManager() { 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 7a80f9af98..593287d195 100644 --- a/unity/Assets/Scripts/SliceObject.cs +++ b/unity/Assets/Scripts/SliceObject.cs @@ -5,7 +5,8 @@ using UnityEngine.Rendering; using UnityStandardAssets.Characters.FirstPerson; -public class SliceObject : MonoBehaviour { +public class SliceObject : MonoBehaviour +{ // prefab that this object should change to when "sliced" [Header("Object To Change To")] [SerializeField] @@ -16,24 +17,28 @@ public class SliceObject : MonoBehaviour { [SerializeField] protected bool isSliced = false; - public bool IsSliced() { + public bool IsSliced() + { return isSliced; } - void OnEnable() { + 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 (ObjectToChangeTo == null) { + if (ObjectToChangeTo == null) + { Debug.LogError(gameObject.transform.name + " is missing Object To Change To!"); } @@ -55,9 +60,11 @@ void Start() { } void Update() { } // action to be called from PhysicsRemoteFPSAgentController - public void Slice() { + public void Slice() + { // if this is already sliced, we can't slice again so yeah stop that - if (isSliced == true) { + if (isSliced == true) + { return; } @@ -67,7 +74,8 @@ public void Slice() { rb.isKinematic = true; // turn off everything except the top object, so we can continue to report back isSliced meta info without the object being "active" - foreach (Transform t in gameObject.transform) { + foreach (Transform t in gameObject.transform) + { t.gameObject.SetActive(false); } @@ -77,7 +85,8 @@ public void Slice() { !gameObject .GetComponent() .DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.CanBeCooked) - ) { + ) + { // instantiate the normal object if this object is not cooked, otherwise.... resultObject = Instantiate( original: ObjectToChangeTo, @@ -88,7 +97,8 @@ public void Slice() { 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 { + else + { // instantiate the normal object if this object is not cooked, otherwise.... resultObject = Instantiate( original: ObjectToChangeTo, @@ -98,9 +108,11 @@ public void Slice() { resultObject.transform.parent = GameObject.Find("Objects").transform; isSliced = true; - if (gameObject.GetComponent().IsCooked()) { + if (gameObject.GetComponent().IsCooked()) + { // cook all objects under the resultObject - foreach (Transform t in resultObject.transform) { + foreach (Transform t in resultObject.transform) + { t.GetComponent().Cook(); } } @@ -109,13 +121,16 @@ public void Slice() { PhysicsSceneManager psm = GameObject .Find("PhysicsSceneManager") .GetComponent(); - if (psm != null) { + 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()) { + 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 // there is an association with the original source object int count = 0; - foreach (Transform t in resultObject.transform) { + foreach (Transform t in resultObject.transform) + { SimObjPhysics tsop = t.GetComponent(); psm.Generate_InheritedObjectID( gameObject.GetComponent(), @@ -134,9 +149,11 @@ public void Slice() { } } // the spawned object is a sim object itself, so make an ID for it - else { + 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 - if (resultObject.GetComponent().Type == SimObjType.EggCracked) { + if (resultObject.GetComponent().Type == SimObjType.EggCracked) + { resultObject.transform.rotation = Quaternion.Euler(Vector3.zero); } @@ -154,7 +171,9 @@ public void Slice() { // also add the spawned object's RB to the cache of all rigidbodies in scene psm.AddToRBSInScene(resultrb); } - } else { + } + else + { Debug.LogError("Physics Scene Manager object is missing from scene!"); } @@ -163,8 +182,10 @@ public void Slice() { .Find("PhysicsSceneManager") .GetComponent() .PrimaryAgent; - if (primaryAgent.imageSynthesis) { - if (primaryAgent.imageSynthesis.enabled) { + if (primaryAgent.imageSynthesis) + { + if (primaryAgent.imageSynthesis.enabled) + { primaryAgent.imageSynthesis.OnSceneChange(); } } diff --git a/unity/Assets/Scripts/SpongeClean.cs b/unity/Assets/Scripts/SpongeClean.cs index d173766440..b37394f9bf 100644 --- a/unity/Assets/Scripts/SpongeClean.cs +++ b/unity/Assets/Scripts/SpongeClean.cs @@ -2,15 +2,18 @@ using System.Collections.Generic; using UnityEngine; -public class SpongeClean : MonoBehaviour { +public class SpongeClean : MonoBehaviour +{ // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } - public void OnTriggerEnter(Collider other) { - if (other.CompareTag("Dirt") || other.CompareTag("Pen")) { + public void OnTriggerEnter(Collider other) + { + if (other.CompareTag("Dirt") || other.CompareTag("Pen")) + { //other.transform.position = other.transform.position + new Vector3(0, 1.0f, 0); Destroy(other.transform.gameObject); } diff --git a/unity/Assets/Scripts/StandardShaderUtils.cs b/unity/Assets/Scripts/StandardShaderUtils.cs index 3089a6267f..739cd7db4e 100644 --- a/unity/Assets/Scripts/StandardShaderUtils.cs +++ b/unity/Assets/Scripts/StandardShaderUtils.cs @@ -2,16 +2,20 @@ using UnityEngine; -public static class StandardShaderUtils { - public enum BlendMode { +public static class StandardShaderUtils +{ + public enum BlendMode + { Opaque, Cutout, Fade, Transparent } - public static void ChangeRenderMode(Material standardShaderMaterial, BlendMode blendMode) { - switch (blendMode) { + public static void ChangeRenderMode(Material standardShaderMaterial, BlendMode blendMode) + { + switch (blendMode) + { case BlendMode.Opaque: standardShaderMaterial.SetInt( "_SrcBlend", diff --git a/unity/Assets/Scripts/StoveKnob.cs b/unity/Assets/Scripts/StoveKnob.cs index b214722c35..dfdc88d38b 100644 --- a/unity/Assets/Scripts/StoveKnob.cs +++ b/unity/Assets/Scripts/StoveKnob.cs @@ -5,7 +5,8 @@ //[ExecuteInEditMode] [RequireComponent(typeof(SimObj))] -public class StoveKnob : MonoBehaviour { +public class StoveKnob : MonoBehaviour +{ public SimObj StoveRange; public bool On = false; @@ -16,24 +17,30 @@ public class StoveKnob : MonoBehaviour { SimObj simObj; bool displayedError = false; - void Awake() { + void Awake() + { simObj = gameObject.GetComponent(); } - void Update() { - if (KnobTransform == null || StoveRange == null) { - if (!displayedError) { + void Update() + { + if (KnobTransform == null || StoveRange == null) + { + if (!displayedError) + { displayedError = true; Debug.LogError("Knob transform or stove range null in Stove Knob " + name); } return; } - if (!Application.isPlaying) { + if (!Application.isPlaying) + { KnobTransform.localEulerAngles = On ? OnRotation : OffRotation; return; } - if (!simObj.IsAnimated) { + if (!simObj.IsAnimated) + { return; } diff --git a/unity/Assets/Scripts/StoveTopElectric.cs b/unity/Assets/Scripts/StoveTopElectric.cs index 564f0c9986..93e6e8e594 100644 --- a/unity/Assets/Scripts/StoveTopElectric.cs +++ b/unity/Assets/Scripts/StoveTopElectric.cs @@ -2,7 +2,8 @@ using System.Collections; using UnityEngine; -public class StoveTopElectric : MonoBehaviour { +public class StoveTopElectric : MonoBehaviour +{ public SimObj ParentObj; public Material BurnerOnMat; public int MatIndex; @@ -11,14 +12,16 @@ public class StoveTopElectric : MonoBehaviour { Material[] matArrayOn; Material[] matArrayOff; - void Awake() { + void Awake() + { ParentObj = gameObject.GetComponent(); matArrayOn = BurnerRenderer.sharedMaterials; matArrayOff = BurnerRenderer.sharedMaterials; matArrayOn[MatIndex] = BurnerOnMat; } - void Update() { + void Update() + { BurnerRenderer.sharedMaterials = ParentObj.Animator.GetBool("AnimState1") ? matArrayOn : matArrayOff; diff --git a/unity/Assets/Scripts/StretchAgentController.cs b/unity/Assets/Scripts/StretchAgentController.cs index e342445345..a67cd37ebf 100644 --- a/unity/Assets/Scripts/StretchAgentController.cs +++ b/unity/Assets/Scripts/StretchAgentController.cs @@ -8,8 +8,10 @@ using UnityEngine.Rendering.PostProcessing; using UnityEngine.UIElements; -namespace UnityStandardAssets.Characters.FirstPerson { - public partial class StretchAgentController : ArmAgentController { +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 @@ -36,7 +38,8 @@ AgentManager agentManager ) : base(baseAgentComponent, agentManager) { } - public override void updateImageSynthesis(bool status) { + public override void updateImageSynthesis(bool status) + { base.updateImageSynthesis(status); // updateImageSynthesis is run in BaseFPSController's Initialize method after the @@ -47,7 +50,8 @@ public override void updateImageSynthesis(bool status) { agentManager.updateThirdPartyCameraImageSynthesis(status); } - public override ActionFinished InitializeBody(ServerAction initializeAction) { + public override ActionFinished InitializeBody(ServerAction initializeAction) + { VisibilityCapsule = StretchVisCap; m_CharacterController.center = new Vector3(0, -0.1821353f, -0.1092373f); m_CharacterController.radius = 0.1854628f; @@ -75,7 +79,8 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { .GetComponent(); fp_camera_2.gameObject.SetActive(true); agentManager.registerAsThirdPartyCamera(fp_camera_2); - if (initializeAction.antiAliasing != null) { + if (initializeAction.antiAliasing != null) + { agentManager.updateAntiAliasing( postProcessLayer: fp_camera_2.gameObject.GetComponentInChildren(), antiAliasing: initializeAction.antiAliasing @@ -93,15 +98,21 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { fp_camera_2.fieldOfView = defaultSecondaryCameraFieldOfView; // limit camera from looking too far down/up - if (Mathf.Approximately(initializeAction.maxUpwardLookAngle, 0.0f)) { + if (Mathf.Approximately(initializeAction.maxUpwardLookAngle, 0.0f)) + { this.maxUpwardLookAngle = 25f; - } else { + } + else + { this.maxUpwardLookAngle = initializeAction.maxUpwardLookAngle; } - if (Mathf.Approximately(initializeAction.maxDownwardLookAngle, 0.0f)) { + if (Mathf.Approximately(initializeAction.maxDownwardLookAngle, 0.0f)) + { this.maxDownwardLookAngle = 90f; - } else { + } + else + { this.maxDownwardLookAngle = initializeAction.maxDownwardLookAngle; } @@ -111,7 +122,8 @@ public override ActionFinished InitializeBody(ServerAction initializeAction) { out secondaryCameraParams ); - if (setSecondaryParams.GetValueOrDefault()) { + if (setSecondaryParams.GetValueOrDefault()) + { CameraParameters.setCameraParameters(fp_camera_2, secondaryCameraParams); } @@ -133,10 +145,12 @@ out secondaryCameraParams return ActionFinished.Success; } - private ArmController getArmImplementation() { + private ArmController getArmImplementation() + { Stretch_Robot_Arm_Controller arm = GetComponentInChildren(); - if (arm == null) { + 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." @@ -145,7 +159,8 @@ private ArmController getArmImplementation() { return arm; } - protected override ArmController getArm() { + protected override ArmController getArm() + { return getArmImplementation(); } @@ -154,7 +169,8 @@ public bool teleportArm( float? rotation = null, bool worldRelative = false, bool forceAction = false - ) { + ) + { Stretch_Robot_Arm_Controller arm = getArmImplementation() as Stretch_Robot_Arm_Controller; GameObject posRotManip = arm.GetArmTarget(); @@ -164,31 +180,39 @@ public bool teleportArm( float oldLocalRotationAngle = posRotManip.transform.localEulerAngles.y; // establish defaults in the absence of inputs - if (position == null) { + if (position == null) + { position = new Vector3(0f, 0.1f, 0f); } - if (rotation == null) { + if (rotation == null) + { rotation = -180f; } // teleport arm! - if (!worldRelative) { + if (!worldRelative) + { posRotManip.transform.localPosition = (Vector3)position; posRotManip.transform.localEulerAngles = new Vector3(0, (float)rotation % 360, 0); - } else { + } + else + { posRotManip.transform.position = (Vector3)position; posRotManip.transform.eulerAngles = new Vector3(0, (float)rotation % 360, 0); } bool success = false; arm.ContinuousUpdate(0f); - if ((!forceAction) && SArm.IsArmColliding()) { + if ((!forceAction) && SArm.IsArmColliding()) + { errorMessage = "collision detected at desired transform, cannot teleport"; posRotManip.transform.localPosition = oldLocalPosition; posRotManip.transform.localEulerAngles = new Vector3(0, oldLocalRotationAngle, 0); arm.ContinuousUpdate(0f); - } else { + } + else + { success = true; } arm.resetPosRotManipulator(); @@ -200,7 +224,8 @@ public void TeleportArm( float? rotation = null, bool worldRelative = false, bool forceAction = false - ) { + ) + { actionFinished( teleportArm( position: position, @@ -231,8 +256,10 @@ public ActionFinished TryReachObject( string objectId, Vector3? position = null, bool returnToInitialPosition = false - ) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + ) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; return new ActionFinished() { success = false, toEmitState = true }; } @@ -249,7 +276,8 @@ public ActionFinished TryReachObject( Vector3 oldArmLocalEulerAngles = armTarget.transform.localEulerAngles; int oldGripperOpenState = gripperOpennessState; - if (position.HasValue) { + if (position.HasValue) + { transform.position = position.Value; Physics.SyncTransforms(); } @@ -277,7 +305,8 @@ public ActionFinished TryReachObject( bool success = false; Vector3 pointOnObject = Vector3.zero; - foreach (Vector3 point in closePoints) { + foreach (Vector3 point in closePoints) + { #if UNITY_EDITOR Debug.DrawLine(point, point + transform.up * 0.3f, Color.red, 20f); #endif @@ -323,7 +352,8 @@ public ActionFinished TryReachObject( rotation: armTarget.transform.eulerAngles.y, worldRelative: true ) - ) { + ) + { # if UNITY_EDITOR Debug.Log("Agent arm is colliding after teleporting arm"); # endif @@ -331,7 +361,8 @@ public ActionFinished TryReachObject( } Physics.SyncTransforms(); - if (isAgentCapsuleColliding(null)) { + if (isAgentCapsuleColliding(null)) + { # if UNITY_EDITOR Debug.Log("Agent capsule is colliding after teleporting arm"); # endif @@ -339,14 +370,17 @@ public ActionFinished TryReachObject( } bool touchingObject = false; - foreach (SimObjPhysics sop in arm.WhatObjectsAreInsideMagnetSphereAsSOP(false)) { - if (sop.ObjectID == objectId) { + foreach (SimObjPhysics sop in arm.WhatObjectsAreInsideMagnetSphereAsSOP(false)) + { + if (sop.ObjectID == objectId) + { touchingObject = true; break; } } - if (!touchingObject) { + if (!touchingObject) + { # if UNITY_EDITOR Debug.Log("Agent is not touching object after teleporting arm"); # endif @@ -362,7 +396,8 @@ public ActionFinished TryReachObject( } Dictionary actionReturn = null; - if (success) { + if (success) + { actionReturn = new Dictionary() { { "position", transform.position }, @@ -373,7 +408,8 @@ public ActionFinished TryReachObject( }; } - if (returnToInitialPosition) { + if (returnToInitialPosition) + { teleportArm( position: oldArmLocalPosition, rotation: oldArmLocalEulerAngles.y, @@ -386,7 +422,8 @@ public ActionFinished TryReachObject( Physics.SyncTransforms(); } - return new ActionFinished() { + return new ActionFinished() + { success = success, actionReturn = actionReturn, toEmitState = returnToInitialPosition @@ -416,12 +453,15 @@ public ActionFinished GetTouchingPoses( Vector3[] positions = null, float maxDistance = 1f, int maxPoses = int.MaxValue // works like infinity - ) { - if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) { + ) + { + if (!physicsSceneManager.ObjectIdToSimObjPhysics.ContainsKey(objectId)) + { errorMessage = $"Cannot find object with id {objectId}."; return new ActionFinished() { success = false, toEmitState = true }; } - if (maxPoses <= 0) { + if (maxPoses <= 0) + { throw new ArgumentOutOfRangeException("maxPoses must be > 0."); } @@ -430,7 +470,8 @@ public ActionFinished GetTouchingPoses( Vector3 bboxSize = sop.AxisAlignedBoundingBox.size; float fudgeFactor = Mathf.Sqrt(bboxSize.x * bboxSize.x + bboxSize.z * bboxSize.z) / 2f; - if (positions == null) { + if (positions == null) + { positions = getReachablePositions(); } @@ -444,14 +485,16 @@ public ActionFinished GetTouchingPoses( .ToList(); List poses = new List(); - foreach (Vector3 position in filteredPositions) { + foreach (Vector3 position in filteredPositions) + { ActionFinished af = TryReachObject( objectId: objectId, position: position, returnToInitialPosition: true ); - if (af.success) { + if (af.success) + { poses.Add(af.actionReturn); # if UNITY_EDITOR Debug.DrawLine( @@ -463,7 +506,8 @@ public ActionFinished GetTouchingPoses( # endif } - if (poses.Count >= maxPoses) { + if (poses.Count >= maxPoses) + { break; } } @@ -481,9 +525,11 @@ public override IEnumerator RotateWristRelative( float roll = 0f, float speed = 10f, bool returnToStart = true - ) { + ) + { // pitch and roll are not supported for the stretch and so we throw an error - if (pitch != 0f || roll != 0f) { + if (pitch != 0f || roll != 0f) + { throw new System.NotImplementedException( "Pitch and roll are not supported for the stretch agent." ); @@ -509,9 +555,11 @@ public IEnumerator RotateWrist( float roll = 0f, float speed = 10f, bool returnToStart = true - ) { + ) + { // pitch and roll are not supported for the stretch and so we throw an error - if (pitch != 0f || roll != 0f) { + if (pitch != 0f || roll != 0f) + { throw new System.NotImplementedException( "Pitch and roll are not supported for the stretch agent." ); @@ -524,14 +572,16 @@ public IEnumerator RotateWrist( // Normalize target yaw to be bounded by [0, 360) (startingRotation is defaults to this) yaw %= 360; - if (yaw < 0) { + if (yaw < 0) + { yaw += 360; } // Find shortest relativeRotation to feed into rotateWrist yaw -= startingRotation; - if (Mathf.Abs(yaw) > 180) { + if (Mathf.Abs(yaw) > 180) + { yaw = (Mathf.Abs(yaw) - 360) * Mathf.Sign(yaw); } @@ -545,45 +595,66 @@ public IEnumerator RotateWrist( ); } - protected int gripperOpenFloatToState(float openness) { - if (-100 <= openness && openness < 0) { + protected int gripperOpenFloatToState(float openness) + { + if (-100 <= openness && openness < 0) + { return 0; - } else if (0 <= openness && openness < 5) { + } + else if (0 <= openness && openness < 5) + { return 1; - } else if (5 <= openness && openness < 15) { + } + else if (5 <= openness && openness < 15) + { return 2; - } else if (15 <= openness && openness < 25) { + } + else if (15 <= openness && openness < 25) + { return 3; - } else if (25 <= openness && openness < 35) { + } + else if (25 <= openness && openness < 35) + { return 4; - } else if (35 <= openness && openness < 45) { + } + else if (35 <= openness && openness < 45) + { return 5; - } else if (45 <= openness && openness <= 50) { + } + else if (45 <= openness && openness <= 50) + { return 6; - } else { + } + else + { throw new InvalidOperationException( $"Invalid value for `openness`: '{openness}'. Value should be between -100 and 50" ); } } - public ActionFinished SetGripperOpenness(float? openness, int? openState = null) { + public ActionFinished SetGripperOpenness(float? openness, int? openState = null) + { setGripperOpenness(openness: openness, openState: openState); return ActionFinished.Success; } //moving this to a helper function so we can call it without sending back an ActionFinished call - public void setGripperOpenness(float? openness, int? openState = null) { - if (openness.HasValue == openState.HasValue) { + public void setGripperOpenness(float? openness, int? openState = null) + { + if (openness.HasValue == openState.HasValue) + { throw new InvalidOperationException( $"Only one of openness or openState should have a value" ); } - if (openness.HasValue) { + if (openness.HasValue) + { openState = gripperOpenFloatToState(openness.Value); } - foreach (GameObject opennessState in GripperOpennessStates) { + foreach (GameObject opennessState in GripperOpennessStates) + { opennessState.SetActive(false); } @@ -613,14 +684,19 @@ public void setGripperOpenness(float? openness, int? openState = null) { // actionFinished(true); // } - public void RotateCameraMount(float degrees, bool secondary = false) { + public void RotateCameraMount(float degrees, bool secondary = false) + { var minDegree = -80.00001f; var maxDegree = 80.00001f; - if (degrees >= minDegree && degrees <= maxDegree) { + if (degrees >= minDegree && degrees <= maxDegree) + { Camera cam; - if (secondary) { + if (secondary) + { cam = agentManager.thirdPartyCameras[0]; - } else { + } + else + { cam = m_Camera; } AgentManager.OptionalVector3 localEulerAngles = new AgentManager.OptionalVector3( @@ -630,29 +706,37 @@ public void RotateCameraMount(float degrees, bool secondary = false) { ); int agentId = -1; - for (int i = 0; i < agentManager.agents.Count; i++) { - if (agentManager.agents[i] == this) { + for (int i = 0; i < agentManager.agents.Count; i++) + { + if (agentManager.agents[i] == this) + { agentId = i; break; } } - if (agentId != 0) { + if (agentId != 0) + { errorMessage = "Only the primary agent can rotate the camera for now."; actionFinished(false); return; } - if (secondary) { + if (secondary) + { agentManager.UpdateThirdPartyCamera( thirdPartyCameraId: 0, rotation: localEulerAngles, agentPositionRelativeCoordinates: true, agentId: agentId ); - } else { + } + else + { agentManager.UpdateMainCamera(rotation: localEulerAngles); } - } else { + } + 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 453d593746..57b20468c0 100644 --- a/unity/Assets/Scripts/Stretch_Robot_Arm_Controller.cs +++ b/unity/Assets/Scripts/Stretch_Robot_Arm_Controller.cs @@ -5,7 +5,8 @@ using UnityEngine; using UnityStandardAssets.Characters.FirstPerson; -public partial class Stretch_Robot_Arm_Controller : ArmController { +public partial class Stretch_Robot_Arm_Controller : ArmController +{ [SerializeField] private Transform armBase, handCameraTransform, @@ -24,65 +25,84 @@ public partial class Stretch_Robot_Arm_Controller : ArmController { private bool deadZoneCheck; - public override Transform pickupParent() { + public override Transform pickupParent() + { return magnetSphere.transform; } - public override Vector3 wristSpaceOffsetToWorldPos(Vector3 offset) { + public override Vector3 wristSpaceOffsetToWorldPos(Vector3 offset) + { return handCameraTransform.TransformPoint(offset) - handCameraTransform.position + WristToManipulator; } - public override Vector3 armBaseSpaceOffsetToWorldPos(Vector3 offset) { + public override Vector3 armBaseSpaceOffsetToWorldPos(Vector3 offset) + { return this.transform.TransformPoint(offset) - this.transform.position; } - public override Vector3 pointToWristSpace(Vector3 point) { + public override Vector3 pointToWristSpace(Vector3 point) + { return handCameraTransform.TransformPoint(point) + WristToManipulator; } - public override Vector3 pointToArmBaseSpace(Vector3 point) { + public override Vector3 pointToArmBaseSpace(Vector3 point) + { return armBase.transform.TransformPoint(point); } - public override void ContinuousUpdate(float fixedDeltaTime) { + public override void ContinuousUpdate(float fixedDeltaTime) + { solver.ManipulateStretchArm(); } - private bool DeadZoneCheck() { - if (deadZoneCheck) { + private bool DeadZoneCheck() + { + if (deadZoneCheck) + { 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) { + if (cLimit < ccLimit) + { cLimit += 360; - if (currentYaw < ccLimit) { + if (currentYaw < ccLimit) + { currentYaw += 360; } } - if (currentYaw < ccLimit || currentYaw > cLimit) { + if (currentYaw < ccLimit || currentYaw > cLimit) + { return true; - } else { + } + else + { return false; } - } else { + } + else + { return false; } } - public override bool ShouldHalt() { + public override bool ShouldHalt() + { return base.ShouldHalt() || DeadZoneCheck(); } - public override string GetHaltMessage() { + public override string GetHaltMessage() + { var errorMessage = base.GetHaltMessage(); - if (errorMessage == "") { - if (DeadZoneCheck()) { + if (errorMessage == "") + { + if (DeadZoneCheck()) + { errorMessage = "Rotated up against Stretch arm wrist's dead-zone, could not reach target: '" + armTarget.rotation @@ -92,7 +112,8 @@ public override string GetHaltMessage() { return errorMessage; } - public override GameObject GetArmTarget() { + public override GameObject GetArmTarget() + { return armTarget.gameObject; } @@ -101,7 +122,8 @@ public override GameObject GetArmTarget() { // return ActionFinished.Success; // } - void Start() { + void Start() + { this.collisionListener = this.GetComponentInParent(); this.collisionListener.registerAllChildColliders(); @@ -115,8 +137,10 @@ void Start() { // clean up arm colliders, removing triggers List cleanedCaps = new List(); - foreach (CapsuleCollider c in armCaps) { - if (!c.isTrigger) { + foreach (CapsuleCollider c in armCaps) + { + if (!c.isTrigger) + { cleanedCaps.Add(c); } } @@ -124,8 +148,10 @@ void Start() { ArmCapsuleColliders = cleanedCaps.ToArray(); List cleanedBoxes = new List(); - foreach (BoxCollider b in armBoxes) { - if (!b.isTrigger) { + foreach (BoxCollider b in armBoxes) + { + if (!b.isTrigger) + { cleanedBoxes.Add(b); } } @@ -136,8 +162,10 @@ void Start() { // TODO: Currently explicitly ignoring all arm self collisions (for efficiency)! var colliders = this.GetComponentsInChildren(); - foreach (Collider c0 in colliders) { - foreach (Collider c1 in colliders) { + foreach (Collider c0 in colliders) + { + foreach (Collider c1 in colliders) + { Physics.IgnoreCollision(c0, c1); } } @@ -145,21 +173,27 @@ void Start() { solver = this.gameObject.GetComponentInChildren(); //call SetGripperOpenness logic in StretchAgentController here - ((StretchAgentController)PhysicsController).setGripperOpenness(openness: null, openState: 1); + ((StretchAgentController)PhysicsController).setGripperOpenness( + openness: null, + openState: 1 + ); } - public void resetPosRotManipulator() { + public void resetPosRotManipulator() + { Physics.SyncTransforms(); armTarget.position = handCameraTransform.transform.position + WristToManipulator; ; } - protected override void lastStepCallback() { + protected override void lastStepCallback() + { resetPosRotManipulator(); setDeadZoneCheck(false); } - public void setDeadZoneCheck(bool enabled) { + public void setDeadZoneCheck(bool enabled) + { deadZoneCheck = enabled; } @@ -170,7 +204,8 @@ public IEnumerator rotateWrist( float fixedDeltaTime, bool returnToStartPositionIfFailed = false, bool isRelativeRotation = true - ) { + ) + { // float clockwiseLocalRotationLimit = 77.5f; // float counterClockwiseLocalRotationLimit = 102.5f; float currentContinuousRotation, @@ -188,24 +223,32 @@ public IEnumerator rotateWrist( // targetContinuousRotation is the end-rotation state on the bounds number-range // (which allows acute and obtuse rotation end-states to be distinct) // targetRelativeRotation is simply the final relative-rotation - if (isRelativeRotation) { - if (Mathf.Abs(rotation) <= 180) { + if (isRelativeRotation) + { + if (Mathf.Abs(rotation) <= 180) + { targetRotation = armTarget.transform.rotation * Quaternion.Euler(0, rotation, 0); - } else { + } + else + { // Calculate target and secTargetRotation targetRelativeRotation = rotation / 2; targetRotation = armTarget.transform.rotation * Quaternion.Euler(0, targetRelativeRotation, 0); secTargetRotation = targetRotation * Quaternion.Euler(0, targetRelativeRotation, 0); } - } else { + } + 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 - ) { + ) + { continuousClockwiseLocalRotationLimit += 360; - if (currentContinuousRotation < continuousCounterClockwiseLocalRotationLimit) { + if (currentContinuousRotation < continuousCounterClockwiseLocalRotationLimit) + { currentContinuousRotation += 360; } } @@ -216,19 +259,25 @@ public IEnumerator rotateWrist( 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 { + } + else + { float nonReflexAngularDistance, reflexAngularDistance; // Calculate proximity of non-reflex angle extreme to target - if (targetContinuousRotation < continuousCounterClockwiseLocalRotationLimit) { + if (targetContinuousRotation < continuousCounterClockwiseLocalRotationLimit) + { nonReflexAngularDistance = continuousCounterClockwiseLocalRotationLimit - targetContinuousRotation; - } else { + } + else + { nonReflexAngularDistance = targetContinuousRotation - continuousClockwiseLocalRotationLimit; } @@ -242,28 +291,37 @@ public IEnumerator rotateWrist( if ( secTargetContinuousRotation > continuousCounterClockwiseLocalRotationLimit && secTargetContinuousRotation < continuousClockwiseLocalRotationLimit - ) { + ) + { targetRotation = armTarget.transform.rotation * Quaternion.Euler(0, targetRelativeRotation, 0); secTargetRotation = targetRotation * Quaternion.Euler(0, targetRelativeRotation, 0); - } else { + } + else + { // Calculate proximity of reflex angle extreme to target - if (secTargetContinuousRotation < continuousCounterClockwiseLocalRotationLimit) { + if (secTargetContinuousRotation < continuousCounterClockwiseLocalRotationLimit) + { reflexAngularDistance = continuousCounterClockwiseLocalRotationLimit - secTargetContinuousRotation; - } else { // if (secTargetContinuousRotation > continuousClockwiseLocalRotationLimit) { + } + else + { // if (secTargetContinuousRotation > continuousClockwiseLocalRotationLimit) { reflexAngularDistance = secTargetContinuousRotation - continuousClockwiseLocalRotationLimit; } // Calculate which distance gets wrist closer to target - if (nonReflexAngularDistance <= reflexAngularDistance) { + if (nonReflexAngularDistance <= reflexAngularDistance) + { targetRotation = armTarget.transform.rotation * Quaternion.Euler(0, rotation, 0); - } else { + } + else + { targetRotation = armTarget.transform.rotation * Quaternion.Euler(0, targetRelativeRotation, 0); @@ -305,7 +363,8 @@ public IEnumerator rotateWrist( ); } - public override ArmMetadata GenerateMetadata() { + public override ArmMetadata GenerateMetadata() + { ArmMetadata meta = new ArmMetadata(); // meta.handTarget = armTarget.position; Transform joint = transform; @@ -318,12 +377,18 @@ public override ArmMetadata GenerateMetadata() { Quaternion currentRotation; // Assign joint metadata to remaining joints, which all have identical hierarchies - for (int i = 1; i <= 8; i++) { - if (i == 1) { + for (int i = 1; i <= 8; i++) + { + if (i == 1) + { joint = joint.Find("stretch_robot_lift_jnt"); - } else if (i <= 6) { + } + else if (i <= 6) + { joint = joint.Find("stretch_robot_arm_" + (i - 1) + "_jnt"); - } else { + } + else + { joint = joint.Find("stretch_robot_wrist_" + (i - 6) + "_jnt"); } @@ -347,7 +412,8 @@ public override ArmMetadata GenerateMetadata() { currentRotation = joint.rotation; // Check that world-relative rotation is angle-axis-notation-compatible - if (currentRotation != new Quaternion(0, 0, 0, -1)) { + if (currentRotation != new Quaternion(0, 0, 0, -1)) + { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); jointMeta.rotation = new Vector4( vectorRot.x, @@ -355,7 +421,9 @@ public override ArmMetadata GenerateMetadata() { vectorRot.z, ConvertAngleToZeroCentricRange(angleRot * Mathf.Sign(vectorRot.y)) ); - } else { + } + else + { jointMeta.rotation = new Vector4(1, 0, 0, 0); } @@ -368,7 +436,8 @@ public override ArmMetadata GenerateMetadata() { currentRotation = Quaternion.Inverse(armBase.rotation) * joint.rotation; // Check that root-relative rotation is angle-axis-notation-compatible - if (currentRotation != new Quaternion(0, 0, 0, -1)) { + if (currentRotation != new Quaternion(0, 0, 0, -1)) + { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); jointMeta.rootRelativeRotation = new Vector4( vectorRot.x, @@ -376,7 +445,9 @@ public override ArmMetadata GenerateMetadata() { vectorRot.z, ConvertAngleToZeroCentricRange(angleRot * Mathf.Sign(vectorRot.y)) ); - } else { + } + else + { jointMeta.rootRelativeRotation = new Vector4(1, 0, 0, 0); } @@ -385,14 +456,16 @@ public override ArmMetadata GenerateMetadata() { // } // PARENT-JOINT RELATIVE ROTATION - if (i != 1) { + if (i != 1) + { parentJoint = joint.parent; // Grab rotation of current joint's angler relative to parent joint's angler currentRotation = Quaternion.Inverse(parentJoint.rotation) * joint.rotation; // Check that parent-relative rotation is angle-axis-notation-compatible - if (currentRotation != new Quaternion(0, 0, 0, -1)) { + if (currentRotation != new Quaternion(0, 0, 0, -1)) + { currentRotation.ToAngleAxis(angle: out angleRot, axis: out vectorRot); jointMeta.localRotation = new Vector4( vectorRot.x, @@ -400,10 +473,14 @@ public override ArmMetadata GenerateMetadata() { vectorRot.z, ConvertAngleToZeroCentricRange(angleRot * Mathf.Sign(vectorRot.y)) ); - } else { + } + else + { jointMeta.localRotation = new Vector4(1, 0, 0, 0); } - } else { + } + else + { // Special case for stretch_robot_lift_jnt because it has no parent-joint jointMeta.localRotation = jointMeta.rootRelativeRotation; } @@ -417,8 +494,10 @@ public override ArmMetadata GenerateMetadata() { // note this is different from objects intersecting the hand's sphere, // there could be a case where an object is inside the sphere but not picked up by the hand List heldObjectIDs = new List(); - if (heldObjects != null) { - foreach (SimObjPhysics sop in heldObjects.Keys) { + if (heldObjects != null) + { + foreach (SimObjPhysics sop in heldObjects.Keys) + { heldObjectIDs.Add(sop.objectID); } } @@ -442,18 +521,22 @@ public override ArmMetadata GenerateMetadata() { return meta; } - float ConvertAngleToZeroCentricRange(float degrees) { - if (degrees < 0) { + float ConvertAngleToZeroCentricRange(float degrees) + { + if (degrees < 0) + { degrees = (degrees % 360f) + 360f; } - if (degrees > 180f) { + if (degrees > 180f) + { degrees = (degrees % 360f) - 360f; } return degrees; } #if UNITY_EDITOR - public class GizmoDrawCapsule { + public class GizmoDrawCapsule + { public Vector3 p0; public Vector3 p1; public float radius; @@ -461,9 +544,12 @@ public class GizmoDrawCapsule { List debugCapsules = new List(); - private void OnDrawGizmos() { - if (debugCapsules.Count > 0) { - foreach (GizmoDrawCapsule thing in debugCapsules) { + private void OnDrawGizmos() + { + if (debugCapsules.Count > 0) + { + foreach (GizmoDrawCapsule thing in debugCapsules) + { Gizmos.DrawWireSphere(thing.p0, thing.radius); Gizmos.DrawWireSphere(thing.p1, thing.radius); } diff --git a/unity/Assets/Scripts/StructureObject.cs b/unity/Assets/Scripts/StructureObject.cs index d102b57bab..5f6f78d78d 100644 --- a/unity/Assets/Scripts/StructureObject.cs +++ b/unity/Assets/Scripts/StructureObject.cs @@ -6,7 +6,8 @@ // 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. -public class StructureObject : MonoBehaviour { +public class StructureObject : MonoBehaviour +{ [SerializeField] public StructureObjectTag WhatIsMyStructureObjectTag; @@ -18,7 +19,8 @@ void Update() { } } [Serializable] -public enum StructureObjectTag : int { +public enum StructureObjectTag : int +{ Undefined = 0, Wall = 1, Floor = 2, diff --git a/unity/Assets/Scripts/SyncTransform.cs b/unity/Assets/Scripts/SyncTransform.cs index e888c945ca..52df75b300 100644 --- a/unity/Assets/Scripts/SyncTransform.cs +++ b/unity/Assets/Scripts/SyncTransform.cs @@ -2,8 +2,10 @@ using System.Collections.Generic; using UnityEngine; -public class SyncTransform : MonoBehaviour { - protected enum WhatToTrack { +public class SyncTransform : MonoBehaviour +{ + protected enum WhatToTrack + { Rotation, Position }; @@ -21,11 +23,16 @@ protected enum WhatToTrack { void Start() { } // Update is called once per frame - void Update() { - if (!StopSyncingForASecond) { - if (WhichTransformPropertyAmITracking == WhatToTrack.Rotation) { + void Update() + { + if (!StopSyncingForASecond) + { + if (WhichTransformPropertyAmITracking == WhatToTrack.Rotation) + { gameObject.transform.rotation = ThingIamTracking.transform.rotation; - } else if (WhichTransformPropertyAmITracking == WhatToTrack.Position) { + } + else if (WhichTransformPropertyAmITracking == WhatToTrack.Position) + { gameObject.transform.localPosition = ThingIamTracking.transform.localPosition; } } diff --git a/unity/Assets/Scripts/THORDocumentationExporter.cs b/unity/Assets/Scripts/THORDocumentationExporter.cs index 88a310bab6..83d9ace9e4 100644 --- a/unity/Assets/Scripts/THORDocumentationExporter.cs +++ b/unity/Assets/Scripts/THORDocumentationExporter.cs @@ -8,10 +8,12 @@ using UnityEditor; using UnityEditor.SceneManagement; -public class THORDocumentationExporter : MonoBehaviour { +public class THORDocumentationExporter : MonoBehaviour +{ // export the placement restrictions for each pickupable object [MenuItem("SimObjectPhysics/Generate Placement Restrictions to Text File")] - private static void ExportPlacementRestrictionsToTextFile() { + private static void ExportPlacementRestrictionsToTextFile() + { var file = "PlacementRestrictions.txt"; var create = File.CreateText("Assets/DebugTextFiles/" + file); @@ -21,10 +23,12 @@ private static void ExportPlacementRestrictionsToTextFile() { SimObjType, List > kvp in ReceptacleRestrictions.PlacementRestrictions - ) { + ) + { // create.WriteLine("/////////////////////////////"); create.WriteLine("Receptacle Restrictions for: " + kvp.Key.ToString()); - foreach (SimObjType sop in kvp.Value) { + foreach (SimObjType sop in kvp.Value) + { create.Write(sop.ToString() + ", "); } create.WriteLine("\n"); @@ -33,7 +37,8 @@ private static void ExportPlacementRestrictionsToTextFile() { create.Close(); } - public class TotalSimObjectsInScene { + public class TotalSimObjectsInScene + { // count of total number of sim objects in this scene public int TotalSimObjCountInScene; @@ -41,7 +46,8 @@ public class TotalSimObjectsInScene { public Dictionary ObjectType_to_Count = new Dictionary(); } - public class UniqueSimObjectsInScene { + 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 @@ -56,7 +62,8 @@ public class UniqueSimObjectsInScene { // print("original source: " + PrefabUtility.GetCorrespondingObjectFromOriginalSource(gameObject)); [MenuItem("SimObjectPhysics/Generate Sim Obj Instance Count Text Files")] - private static void GetInstanceCount() { + private static void GetInstanceCount() + { // keep track of total number of sim objects across all scenes int totalInstanceCount = 0; @@ -79,7 +86,8 @@ private static void GetInstanceCount() { // 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++) { + for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; i++) + { UnityEditor.SceneManagement.EditorSceneManager.OpenScene( SceneUtility.GetScenePathByBuildIndex(i), OpenSceneMode.Single @@ -95,35 +103,47 @@ private static void GetInstanceCount() { string currentSceneName = UnityEngine .SceneManagement.SceneManager.GetActiveScene() .name; - if (!SceneName_to_Counts.ContainsKey(currentSceneName)) { + if (!SceneName_to_Counts.ContainsKey(currentSceneName)) + { TotalSimObjectsInScene tsois = new TotalSimObjectsInScene(); tsois.TotalSimObjCountInScene = simObjects.Length; tsois.ObjectType_to_Count = sceneObjectTypeCounts; SceneName_to_Counts.Add(currentSceneName, tsois); } - foreach (SimObjPhysics currentSimObject in simObjects) { + foreach (SimObjPhysics currentSimObject in simObjects) + { // keep track of total object type count - if (ObjectTypeInAllScenes_to_Count.ContainsKey(currentSimObject.Type)) { + if (ObjectTypeInAllScenes_to_Count.ContainsKey(currentSimObject.Type)) + { ObjectTypeInAllScenes_to_Count[currentSimObject.Type]++; - } else { + } + else + { ObjectTypeInAllScenes_to_Count.Add(currentSimObject.Type, 1); } // keep track of object type count for this scene only - if (sceneObjectTypeCounts.ContainsKey(currentSimObject.Type)) { + if (sceneObjectTypeCounts.ContainsKey(currentSimObject.Type)) + { sceneObjectTypeCounts[currentSimObject.Type]++; - } else { + } + else + { sceneObjectTypeCounts.Add(currentSimObject.Type, 1); } // keep track of which scenes contain this object type // key already exists, don't worry about creating new list - if (ObjectType_To_Scenes.ContainsKey(currentSimObject.Type)) { - if (!ObjectType_To_Scenes[currentSimObject.Type].Contains(currentSceneName)) { + if (ObjectType_To_Scenes.ContainsKey(currentSimObject.Type)) + { + if (!ObjectType_To_Scenes[currentSimObject.Type].Contains(currentSceneName)) + { ObjectType_To_Scenes[currentSimObject.Type].Add(currentSceneName); } - } else { + } + else + { List listOfScenes = new List(); listOfScenes.Add(currentSceneName); ObjectType_To_Scenes.Add(currentSimObject.Type, listOfScenes); @@ -138,15 +158,18 @@ private static void GetInstanceCount() { currentSimObject.gameObject ); - if (testObj != null) { + if (testObj != null) + { // this prefab already exists in our dictionary - if (UniquePrefab_to_Count.ContainsKey(testObj)) { + 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) - ) { + ) + { // add any scenes where this prefab shows up UniquePrefab_to_Count[testObj] .Scenes_To_hName.Add( @@ -154,7 +177,9 @@ private static void GetInstanceCount() { currentSimObject.gameObject.name ); } - } else { + } + else + { UniqueSimObjectsInScene usois = new UniqueSimObjectsInScene(); usois.count = 1; usois.Scenes_To_hName = new Dictionary(); @@ -167,7 +192,8 @@ private static void GetInstanceCount() { } } // this sim object is not a prefab so assume it is unique to this scene only - else { + else + { UniqueSimObjectsInScene usois = new UniqueSimObjectsInScene(); usois.count = 1; usois.Scenes_To_hName = new Dictionary(); @@ -192,7 +218,8 @@ private static void GetInstanceCount() { 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) { + foreach (KeyValuePair typeSet in ObjectTypeInAllScenes_to_Count) + { create.WriteLine(typeSet.Key + ": " + typeSet.Value); } create.Close(); @@ -201,7 +228,8 @@ private static void GetInstanceCount() { var file2 = "ObjectTypesPerScene.txt"; var create2 = File.CreateText("Assets/DebugTextFiles/" + file2); create2.WriteLine("The following is the Total count of Sim Objects by Scene"); - foreach (KeyValuePair entry in SceneName_to_Counts) { + 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( @@ -210,7 +238,8 @@ private static void GetInstanceCount() { + ": " + entry.Value.TotalSimObjCountInScene ); - foreach (KeyValuePair pair in entry.Value.ObjectType_to_Count) { + foreach (KeyValuePair pair in entry.Value.ObjectType_to_Count) + { create2.WriteLine( pair.Key + " | Total Instances In " + entry.Key + ": " + pair.Value ); @@ -225,9 +254,11 @@ private static void GetInstanceCount() { 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) { + foreach (KeyValuePair> typeToScene in ObjectType_To_Scenes) + { create3.WriteLine("\n" + typeToScene.Key + ":"); - foreach (string s in typeToScene.Value) { + foreach (string s in typeToScene.Value) + { create3.WriteLine(s); } } @@ -250,13 +281,15 @@ private static void GetInstanceCount() { create4.WriteLine( "\nTotal number of UNIQUE Sim Object instances: " + UniquePrefab_to_Count.Count ); - foreach (KeyValuePair p in UniquePrefab_to_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("list of scenes that this unique object shows up in: "); - foreach (KeyValuePair s in p.Value.Scenes_To_hName) { + foreach (KeyValuePair s in p.Value.Scenes_To_hName) + { create4.WriteLine( s.Key + " | name of instance of this object in scene: " + s.Value ); diff --git a/unity/Assets/Scripts/Television.cs b/unity/Assets/Scripts/Television.cs index 462b5fa536..ecc01bad62 100644 --- a/unity/Assets/Scripts/Television.cs +++ b/unity/Assets/Scripts/Television.cs @@ -3,7 +3,8 @@ using UnityEngine; [ExecuteInEditMode] -public class Television : MonoBehaviour { +public class Television : MonoBehaviour +{ public SimObj ParentSimObj; public Renderer[] ScreenRenderers; public int[] ScreenMatIndexes; @@ -17,27 +18,38 @@ public class Television : MonoBehaviour { // 2 - On, Unsynced // 3 - On, Synced - public void Update() { - if (ParentSimObj == null) { + public void Update() + { + if (ParentSimObj == null) + { return; } - if (OffScreenMat == null || OnScreenMat == null) { + if (OffScreenMat == null || OnScreenMat == null) + { return; } Material mat = OffScreenMat; - if (!Application.isPlaying) { - if (EditorOn) { - if (EditorConnected) { + if (!Application.isPlaying) + { + if (EditorOn) + { + if (EditorConnected) + { mat = SyncedScreenMat; - } else { + } + else + { mat = OnScreenMat; } } - } else { - switch (ParentSimObj.Animator.GetInteger("AnimState1")) { + } + else + { + switch (ParentSimObj.Animator.GetInteger("AnimState1")) + { case 1: default: break; @@ -52,7 +64,8 @@ public void Update() { } } - for (int i = 0; i < ScreenRenderers.Length; i++) { + for (int i = 0; i < ScreenRenderers.Length; i++) + { Material[] sharedMats = ScreenRenderers[i].sharedMaterials; sharedMats[ScreenMatIndexes[i]] = mat; ScreenRenderers[i].sharedMaterials = sharedMats; diff --git a/unity/Assets/Scripts/TestCabinetVisibility.cs b/unity/Assets/Scripts/TestCabinetVisibility.cs index 3dae38ed40..94f7286e8e 100644 --- a/unity/Assets/Scripts/TestCabinetVisibility.cs +++ b/unity/Assets/Scripts/TestCabinetVisibility.cs @@ -6,7 +6,8 @@ using UnityEditor; #endif -public class TestCabinetVisibility : MonoBehaviour { +public class TestCabinetVisibility : MonoBehaviour +{ #if UNITY_EDITOR public float MinDistance = 0.75f; public float MaxDistance = 2f; @@ -24,28 +25,34 @@ public class TestCabinetVisibility : MonoBehaviour { SimObj currentCabinet; List positions = new List(); - void OnDrawGizmos() { + void OnDrawGizmos() + { Gizmos.color = Color.white; - foreach (Vector3 pos in positions) { + foreach (Vector3 pos in positions) + { Gizmos.DrawWireCube(pos + Vector3.down, Vector3.one * 0.05f); } Gizmos.color = Color.Lerp(Color.red, Color.clear, 0.5f); - if (ProblemCabinets.Count > 0 && ProblemIndex < ProblemCabinets.Count) { + if (ProblemCabinets.Count > 0 && ProblemIndex < ProblemCabinets.Count) + { Gizmos.DrawSphere(ProblemCabinets[ProblemIndex].CenterPoint, 0.2f); } Gizmos.color = Color.green; - if (currentCabinet != null) { + if (currentCabinet != null) + { Gizmos.DrawSphere(currentCabinet.CenterPoint, 0.2f); } } - void OnDisable() { + void OnDisable() + { EditorUtility.ClearProgressBar(); } - public IEnumerator Start() { + public IEnumerator Start() + { // wait for cabinets to set their startup positions yield return new WaitForSeconds(0.1f); @@ -57,15 +64,18 @@ public IEnumerator Start() { EditorUtility.DisplayProgressBar("Testing cabinets", "Loading", 0f); Camera cam = gameObject.GetComponentInChildren(); HashSet cabinets = new HashSet(); - foreach (SimObj o in SceneManager.Current.ObjectsInScene) { - if (o.Type == SimObjType.Cabinet) { + foreach (SimObj o in SceneManager.Current.ObjectsInScene) + { + if (o.Type == SimObjType.Cabinet) + { cabinets.Add(o); } } int cabinetNum = 0; Vector3 startPos = transform.position; - foreach (SimObj c in cabinets) { + foreach (SimObj c in cabinets) + { // bool seenAtLeastOnce = false; currentCabinet = c; // close the cabinet @@ -75,14 +85,16 @@ public IEnumerator Start() { cabinetPos.y = startPos.y; positions.Clear(); int numSkippedPositions = 0; - while (positions.Count < ChecksPerCabinet && numSkippedPositions < MaxSkippedPositions) { + while (positions.Count < ChecksPerCabinet && numSkippedPositions < MaxSkippedPositions) + { // get a point inside a circle Vector3 randomPos = cabinetPos; randomPos.x += (Random.value - 0.5f) * MaxDistance; randomPos.z += (Random.value - 0.5f) * MaxDistance; randomPos.y = startPos.y; // if the circle is too close to the cabinet, move away - if (Vector3.Distance(cabinetPos, randomPos) < MinDistance) { + if (Vector3.Distance(cabinetPos, randomPos) < MinDistance) + { // don't include it continue; } @@ -100,9 +112,12 @@ public IEnumerator Start() { !aboveGround || !hit.collider.CompareTag(SimUtil.StructureTag) || !hit.collider.name.Equals("Floor") - ) { + ) + { numSkippedPositions++; - } else { + } + else + { aboveGround = true; } bool hasOverlap = false; @@ -113,24 +128,31 @@ public IEnumerator Start() { SimUtil.RaycastVisibleLayerMask, QueryTriggerInteraction.Ignore ); - foreach (Collider collider in overlap) { - if (!collider.name.Equals("Floor")) { + foreach (Collider collider in overlap) + { + if (!collider.name.Equals("Floor")) + { hasOverlap = true; break; } } - if (aboveGround && !hasOverlap) { + if (aboveGround && !hasOverlap) + { positions.Add(randomPos); - } else { + } + else + { numSkippedPositions++; - if (numSkippedPositions >= MaxSkippedPositions) { + if (numSkippedPositions >= MaxSkippedPositions) + { Debug.Log("Skipped too many positions, total is " + positions.Count); } } } // start moving float progressInterval = 1f / cabinets.Count; - for (int i = 0; i < positions.Count; i++) { + for (int i = 0; i < positions.Count; i++) + { // move the agent to the random position transform.position = positions[i]; // look around the world in 60-degree increments @@ -140,10 +162,12 @@ public IEnumerator Start() { ((float)cabinetNum / cabinets.Count) + (((float)i / ChecksPerCabinet) * progressInterval) ); - for (int j = 0; j < horizonAngles.Length; j++) { + for (int j = 0; j < horizonAngles.Length; j++) + { float horizonAngle = horizonAngles[j]; float headingAngle = 0f; - for (int k = 0; k < headingAngles.Length; k++) { + for (int k = 0; k < headingAngles.Length; k++) + { headingAngle = headingAngles[k]; // at each step, check whether we can see the cabinet bool cabinetVisibleClosed = false; @@ -157,15 +181,18 @@ public IEnumerator Start() { // get visible again foreach ( SimObj visibleSimObj in SimUtil.GetAllVisibleSimObjs(cam, MaxDistance) - ) { - if (visibleSimObj == currentCabinet) { + ) + { + if (visibleSimObj == currentCabinet) + { cabinetVisibleClosed = true; // seenAtLeastOnce = true; break; } } // don't bother if we didn't see anything - if (!cabinetVisibleClosed) { + if (!cabinetVisibleClosed) + { yield return null; continue; } @@ -177,24 +204,29 @@ SimObj visibleSimObj in SimUtil.GetAllVisibleSimObjs(cam, MaxDistance) // get visible objects again foreach ( SimObj visibleSimObj in SimUtil.GetAllVisibleSimObjs(cam, MaxDistance) - ) { - if (visibleSimObj == currentCabinet) { + ) + { + if (visibleSimObj == currentCabinet) + { cabinetVisibleOpen = true; // seenAtLeastOnce = true; break; } } // now check to see if there were any we could see closed that we CAN'T see open - if (cabinetVisibleClosed && !cabinetVisibleOpen) { + if (cabinetVisibleClosed && !cabinetVisibleOpen) + { // we found one we could see before, but can't see now - if (!ProblemCabinets.Contains(currentCabinet)) { + if (!ProblemCabinets.Contains(currentCabinet)) + { ProblemCabinets.Add(currentCabinet); ProblemPositions.Add(positions[i]); ProblemHeadingAngles.Add(headingAngle); ProblemhHorizonAngles.Add(horizonAngle); } yield return new WaitForSeconds(1f); - if (StopOnError) { + if (StopOnError) + { UnityEditor.Selection.activeGameObject = currentCabinet.gameObject; EditorUtility.ClearProgressBar(); yield break; diff --git a/unity/Assets/Scripts/ThorContractlessStandardResolver.cs b/unity/Assets/Scripts/ThorContractlessStandardResolver.cs index bfcaf6d5ef..ede8f6daaf 100644 --- a/unity/Assets/Scripts/ThorContractlessStandardResolver.cs +++ b/unity/Assets/Scripts/ThorContractlessStandardResolver.cs @@ -17,19 +17,23 @@ This resolver is necessary because the MessagePack library does not allow modifi the UnityResolver and we want our output to match the json output for Vector3. */ -namespace MessagePack.Resolvers { +namespace MessagePack.Resolvers +{ public class NavMeshPathFormatter - : global::MessagePack.Formatters.IMessagePackFormatter { + : 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); Vector3Formatter f = new Vector3Formatter(); - foreach (Vector3 c in value.corners) { + foreach (Vector3 c in value.corners) + { f.Serialize(ref writer, c, options); } writer.Write("status"); @@ -39,7 +43,8 @@ public void Serialize( public global::UnityEngine.AI.NavMeshPath Deserialize( ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options - ) { + ) + { throw new System.NotImplementedException(); } } @@ -48,7 +53,8 @@ public void Serialize( // 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 { + : global::MessagePack.Formatters.IMessagePackFormatter + { private IMessagePackFormatter formatter = DynamicGenericResolver.Instance.GetFormatter(); private IMessagePackFormatter droneFormatter = @@ -58,17 +64,23 @@ public void Serialize( ref MessagePackWriter writer, ObjectMetadata[] value, global::MessagePack.MessagePackSerializerOptions options - ) { - if (value == null) { + ) + { + if (value == null) + { writer.WriteNil(); return; } - if (value.Length > 0 && value[0].GetType() == typeof(DroneObjectMetadata)) { + if (value.Length > 0 && value[0].GetType() == typeof(DroneObjectMetadata)) + { writer.WriteArrayHeader(value.Length); - foreach (var v in value) { + foreach (var v in value) + { droneFormatter.Serialize(ref writer, (DroneObjectMetadata)v, options); } - } else { + } + else + { formatter.Serialize(ref writer, value, options); } } @@ -76,18 +88,21 @@ public void Serialize( public ObjectMetadata[] Deserialize( ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options - ) { + ) + { throw new System.NotImplementedException(); } } public class Vector4Formatter - : global::MessagePack.Formatters.IMessagePackFormatter { + : 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); @@ -102,8 +117,10 @@ public void Serialize( public global::UnityEngine.Vector4 Deserialize( ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options - ) { - if (reader.TryReadNil()) { + ) + { + if (reader.TryReadNil()) + { throw new InvalidOperationException("Cannot deserialize a nil value to a Vector3."); } @@ -113,10 +130,12 @@ public void Serialize( z = 0, w = 0; - for (int i = 0; i < mapLength; i++) { + for (int i = 0; i < mapLength; i++) + { string property = reader.ReadString(); - switch (property) { + switch (property) + { case "x": x = reader.ReadSingle(); break; @@ -140,7 +159,8 @@ public void Serialize( } public class AgentMetadataFormatter - : global::MessagePack.Formatters.IMessagePackFormatter { + : global::MessagePack.Formatters.IMessagePackFormatter + { private IMessagePackFormatter formatter = DynamicObjectResolver.Instance.GetFormatter(); private IMessagePackFormatter droneFormatter = @@ -150,15 +170,20 @@ public void Serialize( ref MessagePackWriter writer, AgentMetadata value, global::MessagePack.MessagePackSerializerOptions options - ) { - if (value == null) { + ) + { + if (value == null) + { writer.WriteNil(); return; } Type type = value.GetType(); - if (type == typeof(DroneAgentMetadata)) { + if (type == typeof(DroneAgentMetadata)) + { droneFormatter.Serialize(ref writer, (DroneAgentMetadata)value, options); - } else { + } + else + { formatter.Serialize(ref writer, value, options); } } @@ -166,18 +191,21 @@ public void Serialize( public AgentMetadata Deserialize( ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options - ) { + ) + { throw new System.NotImplementedException(); } } public class Vector3Formatter - : global::MessagePack.Formatters.IMessagePackFormatter { + : 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); @@ -190,8 +218,10 @@ public void Serialize( public global::UnityEngine.Vector3 Deserialize( ref MessagePackReader reader, global::MessagePack.MessagePackSerializerOptions options - ) { - if (reader.TryReadNil()) { + ) + { + if (reader.TryReadNil()) + { throw new InvalidOperationException("Cannot deserialize a nil value to a Vector3."); } @@ -200,10 +230,12 @@ public void Serialize( y = 0, z = 0; - for (int i = 0; i < mapLength; i++) { + for (int i = 0; i < mapLength; i++) + { string property = reader.ReadString(); - switch (property) { + switch (property) + { case "x": x = reader.ReadSingle(); break; @@ -223,7 +255,8 @@ public void Serialize( } } - public class ThorContractlessStandardResolver : IFormatterResolver { + public class ThorContractlessStandardResolver : IFormatterResolver + { public static readonly MessagePackSerializerOptions Options; public static readonly ThorContractlessStandardResolver Instance; @@ -240,22 +273,27 @@ public class ThorContractlessStandardResolver : IFormatterResolver { #endif }; - static ThorContractlessStandardResolver() { + static ThorContractlessStandardResolver() + { Instance = new ThorContractlessStandardResolver(); Options = MessagePackSerializerOptions.Standard.WithResolver(Instance); } private ThorContractlessStandardResolver() { } - public IMessagePackFormatter GetFormatter() { + public IMessagePackFormatter GetFormatter() + { return FormatterCache.Formatter; } - private static class FormatterCache { + private static class FormatterCache + { public static readonly IMessagePackFormatter Formatter; - static FormatterCache() { - if (typeof(T) == typeof(object)) { + static FormatterCache() + { + if (typeof(T) == typeof(object)) + { // final fallback #if !ENABLE_IL2CPP Formatter = @@ -263,10 +301,14 @@ static FormatterCache() { #else Formatter = PrimitiveObjectResolver.Instance.GetFormatter(); #endif - } else { - foreach (IFormatterResolver item in Resolvers) { + } + else + { + foreach (IFormatterResolver item in Resolvers) + { IMessagePackFormatter f = item.GetFormatter(); - if (f != null) { + if (f != null) + { Formatter = f; return; } @@ -277,16 +319,19 @@ static FormatterCache() { } } -public class ThorUnityResolver : IFormatterResolver { +public class ThorUnityResolver : IFormatterResolver +{ public static readonly ThorUnityResolver Instance = new ThorUnityResolver(); private ThorUnityResolver() { } - public IMessagePackFormatter GetFormatter() { + public IMessagePackFormatter GetFormatter() + { return FormatterCache.Formatter; } - private static class FormatterCache { + private static class FormatterCache + { public static readonly IMessagePackFormatter Formatter; private static readonly Dictionary FormatterMap = new Dictionary< Type, @@ -301,13 +346,16 @@ private static class FormatterCache { { typeof(ObjectMetadata[]), new ObjectMetadataFormatter() } }; - static FormatterCache() { + static FormatterCache() + { Formatter = (IMessagePackFormatter)GetFormatter(typeof(T)); } - static object GetFormatter(Type t) { + static object GetFormatter(Type t) + { object formatter; - if (FormatterMap.TryGetValue(t, out formatter)) { + if (FormatterMap.TryGetValue(t, out formatter)) + { return formatter; } diff --git a/unity/Assets/Scripts/Toaster.cs b/unity/Assets/Scripts/Toaster.cs index 1ffb2eec6f..a33c7c531e 100644 --- a/unity/Assets/Scripts/Toaster.cs +++ b/unity/Assets/Scripts/Toaster.cs @@ -2,16 +2,19 @@ using System.Collections; using UnityEngine; -public class Toaster : MonoBehaviour { +public class Toaster : MonoBehaviour +{ // private ObjectSpecificReceptacle osr; // private CanToggleOnOff onOff; - void Start() { + void Start() + { // osr = gameObject.GetComponent(); // onOff = gameObject.GetComponent(); } - void Update() { + void Update() + { // Note: Moved This call to the HeatZone that is turned on when the toaster is turned on diff --git a/unity/Assets/Scripts/Toilet.cs b/unity/Assets/Scripts/Toilet.cs index 20a2957b3e..579960752e 100644 --- a/unity/Assets/Scripts/Toilet.cs +++ b/unity/Assets/Scripts/Toilet.cs @@ -3,7 +3,8 @@ using UnityEngine; [ExecuteInEditMode] -public class Toilet : MonoBehaviour { +public class Toilet : MonoBehaviour +{ public SimObj ParentSimObj; public Transform Lid; public Vector3 OpenRotation; @@ -13,16 +14,20 @@ public class Toilet : MonoBehaviour { [Range(0, 2)] public int EditorState = 0; - void OnEnable() { + void OnEnable() + { ParentSimObj = gameObject.GetComponent(); - if (ParentSimObj == null) { + if (ParentSimObj == null) + { ParentSimObj = gameObject.AddComponent(); } ParentSimObj.Type = SimObjType.Toilet; - if (!Application.isPlaying) { + if (!Application.isPlaying) + { Animator a = ParentSimObj.gameObject.GetComponent(); - if (a == null) { + if (a == null) + { a = ParentSimObj.gameObject.AddComponent(); a.runtimeAnimatorController = Resources.Load("StateAnimController") as RuntimeAnimatorController; @@ -31,9 +36,11 @@ void OnEnable() { } // Update is called once per frame - void Update() { + void Update() + { int state = EditorState; - if (Application.isPlaying) { + if (Application.isPlaying) + { state = ParentSimObj.Animator.GetInteger("AnimState1"); } @@ -41,7 +48,8 @@ void Update() { // 1 - open, dirty // 2 - open, clean - switch (state) { + switch (state) + { case 0: default: Lid.localEulerAngles = ClosedRotation; diff --git a/unity/Assets/Scripts/TransformExtension.cs b/unity/Assets/Scripts/TransformExtension.cs index eaff8b3a74..95f1af6992 100644 --- a/unity/Assets/Scripts/TransformExtension.cs +++ b/unity/Assets/Scripts/TransformExtension.cs @@ -1,13 +1,19 @@ using System; using UnityEngine; -public static class TransformExtension { - public static Transform FirstChildOrDefault(this Transform parent, Func query) { - if (query(parent)) { +public static class TransformExtension +{ + public static Transform FirstChildOrDefault(this Transform parent, Func query) + { + if (query(parent)) + { return parent; - } else { + } + else + { Transform result = null; - for (int i = 0; i < parent.childCount; i++) { + for (int i = 0; i < parent.childCount; i++) + { var child = parent.GetChild(i); var match = child.FirstChildOrDefault(query); result = match != null ? match : result; diff --git a/unity/Assets/Scripts/UsedUp.cs b/unity/Assets/Scripts/UsedUp.cs index 90dc9d5f09..c65e2dbdef 100644 --- a/unity/Assets/Scripts/UsedUp.cs +++ b/unity/Assets/Scripts/UsedUp.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class UsedUp : MonoBehaviour { +public class UsedUp : MonoBehaviour +{ [SerializeField] protected MeshRenderer usedUpRenderer; @@ -26,16 +27,19 @@ void Start() { } // Update is called once per frame void Update() { } - public void UseUp() { + public void UseUp() + { usedUpRenderer.enabled = false; // disable all colliders that are used up - foreach (Collider col in usedUpColliders) { + foreach (Collider col in usedUpColliders) + { col.enabled = false; } // disable all trigger colliders that are used up - foreach (Collider col in usedUpTriggerColliders) { + foreach (Collider col in usedUpTriggerColliders) + { col.enabled = false; } diff --git a/unity/Assets/Scripts/UtilityFunctions.cs b/unity/Assets/Scripts/UtilityFunctions.cs index de2407d4e2..257bce7e6b 100644 --- a/unity/Assets/Scripts/UtilityFunctions.cs +++ b/unity/Assets/Scripts/UtilityFunctions.cs @@ -14,12 +14,14 @@ using UnityEditor.SceneManagement; #endif -public static class UtilityFunctions { +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() { + public static Bounds CreateEmptyBounds() + { Bounds b = new Bounds(); Vector3 inf = new Vector3( float.PositiveInfinity, @@ -30,20 +32,24 @@ public static Bounds CreateEmptyBounds() { return b; } - private static IEnumerable Combinations(int m, int n) { + private static IEnumerable Combinations(int m, int n) + { // Enumerate all possible m-size combinations of [0, 1, ..., n-1] array // in lexicographic order (first [0, 1, 2, ..., m-1]). // Taken from https://codereview.stackexchange.com/questions/194967/get-all-combinations-of-selecting-k-elements-from-an-n-sized-array int[] result = new int[m]; Stack stack = new Stack(m); stack.Push(0); - while (stack.Count > 0) { + while (stack.Count > 0) + { int index = stack.Count - 1; int value = stack.Pop(); - while (value < n) { + while (value < n) + { result[index++] = value++; stack.Push(value); - if (index != m) { + if (index != m) + { continue; } @@ -54,19 +60,24 @@ private static IEnumerable Combinations(int m, int n) { } } - public static IEnumerable Combinations(T[] array, int m) { + 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) { + if (array.Length < m) + { throw new ArgumentException( "Array length can't be less than number of selected elements" ); } - if (m < 1) { + if (m < 1) + { throw new ArgumentException("Number of selected elements can't be less than 1"); } T[] result = new T[m]; - foreach (int[] j in Combinations(m, array.Length)) { - for (int i = 0; i < m; i++) { + foreach (int[] j in Combinations(m, array.Length)) + { + for (int i = 0; i < m; i++) + { result[i] = array[j[i]]; } yield return result; @@ -78,7 +89,8 @@ public static bool isObjectColliding( List ignoreGameObjects = null, float expandBy = 0.0f, bool useBoundingBoxInChecks = false - ) { + ) + { return null != firstColliderObjectCollidingWith( go: go, @@ -93,14 +105,18 @@ public static Collider firstColliderObjectCollidingWith( List ignoreGameObjects = null, float expandBy = 0.0f, bool useBoundingBoxInChecks = false - ) { - if (ignoreGameObjects == null) { + ) + { + if (ignoreGameObjects == null) + { ignoreGameObjects = new List(); } ignoreGameObjects.Add(go); HashSet ignoreColliders = new HashSet(); - foreach (GameObject toIgnoreGo in ignoreGameObjects) { - foreach (Collider c in toIgnoreGo.GetComponentsInChildren()) { + foreach (GameObject toIgnoreGo in ignoreGameObjects) + { + foreach (Collider c in toIgnoreGo.GetComponentsInChildren()) + { ignoreColliders.Add(c); } } @@ -113,8 +129,10 @@ public static Collider firstColliderObjectCollidingWith( "Procedural3", "Procedural0" ); - foreach (CapsuleCollider cc in go.GetComponentsInChildren()) { - if (cc.isTrigger) { + foreach (CapsuleCollider cc in go.GetComponentsInChildren()) + { + if (cc.isTrigger) + { continue; } foreach ( @@ -124,14 +142,18 @@ Collider c in PhysicsExtensions.OverlapCapsule( QueryTriggerInteraction.Ignore, expandBy ) - ) { - if (!ignoreColliders.Contains(c)) { + ) + { + if (!ignoreColliders.Contains(c)) + { return c; } } } - foreach (BoxCollider bc in go.GetComponentsInChildren()) { - if (bc.isTrigger || ("BoundingBox" == bc.gameObject.name && (!useBoundingBoxInChecks))) { + foreach (BoxCollider bc in go.GetComponentsInChildren()) + { + if (bc.isTrigger || ("BoundingBox" == bc.gameObject.name && (!useBoundingBoxInChecks))) + { continue; } foreach ( @@ -141,14 +163,18 @@ Collider c in PhysicsExtensions.OverlapBox( QueryTriggerInteraction.Ignore, expandBy ) - ) { - if (!ignoreColliders.Contains(c)) { + ) + { + if (!ignoreColliders.Contains(c)) + { return c; } } } - foreach (SphereCollider sc in go.GetComponentsInChildren()) { - if (sc.isTrigger) { + foreach (SphereCollider sc in go.GetComponentsInChildren()) + { + if (sc.isTrigger) + { continue; } foreach ( @@ -158,8 +184,10 @@ Collider c in PhysicsExtensions.OverlapSphere( QueryTriggerInteraction.Ignore, expandBy ) - ) { - if (!ignoreColliders.Contains(c)) { + ) + { + if (!ignoreColliders.Contains(c)) + { return c; } } @@ -172,21 +200,26 @@ public static Collider[] collidersObjectCollidingWith( List ignoreGameObjects = null, float expandBy = 0.0f, bool useBoundingBoxInChecks = false - ) { - if (ignoreGameObjects == null) { + ) + { + if (ignoreGameObjects == null) + { ignoreGameObjects = new List(); } ignoreGameObjects.Add(go); HashSet ignoreColliders = new HashSet(); - foreach (GameObject toIgnoreGo in ignoreGameObjects) { - foreach (Collider c in toIgnoreGo.GetComponentsInChildren()) { + foreach (GameObject toIgnoreGo in ignoreGameObjects) + { + foreach (Collider c in toIgnoreGo.GetComponentsInChildren()) + { ignoreColliders.Add(c); } } HashSet collidersSet = new HashSet(); int layerMask = LayerMask.GetMask("SimObjVisible", "Agent"); - foreach (CapsuleCollider cc in go.GetComponentsInChildren()) { + foreach (CapsuleCollider cc in go.GetComponentsInChildren()) + { foreach ( Collider c in PhysicsExtensions.OverlapCapsule( cc, @@ -194,14 +227,18 @@ Collider c in PhysicsExtensions.OverlapCapsule( QueryTriggerInteraction.Ignore, expandBy ) - ) { - if (!ignoreColliders.Contains(c)) { + ) + { + if (!ignoreColliders.Contains(c)) + { collidersSet.Add(c); } } } - foreach (BoxCollider bc in go.GetComponentsInChildren()) { - if ("BoundingBox" == bc.gameObject.name && (!useBoundingBoxInChecks)) { + foreach (BoxCollider bc in go.GetComponentsInChildren()) + { + if ("BoundingBox" == bc.gameObject.name && (!useBoundingBoxInChecks)) + { continue; } foreach ( @@ -211,13 +248,16 @@ Collider c in PhysicsExtensions.OverlapBox( QueryTriggerInteraction.Ignore, expandBy ) - ) { - if (!ignoreColliders.Contains(c)) { + ) + { + if (!ignoreColliders.Contains(c)) + { collidersSet.Add(c); } } } - foreach (SphereCollider sc in go.GetComponentsInChildren()) { + foreach (SphereCollider sc in go.GetComponentsInChildren()) + { foreach ( Collider c in PhysicsExtensions.OverlapSphere( sc, @@ -225,8 +265,10 @@ Collider c in PhysicsExtensions.OverlapSphere( QueryTriggerInteraction.Ignore, expandBy ) - ) { - if (!ignoreColliders.Contains(c)) { + ) + { + if (!ignoreColliders.Contains(c)) + { collidersSet.Add(c); } } @@ -240,13 +282,16 @@ public static RaycastHit[] CastAllPrimitiveColliders( float maxDistance = Mathf.Infinity, int layerMask = Physics.DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal - ) { + ) + { HashSet transformsToIgnore = new HashSet(); - foreach (Transform t in go.GetComponentsInChildren()) { + foreach (Transform t in go.GetComponentsInChildren()) + { transformsToIgnore.Add(t); } List hits = new List(); - foreach (CapsuleCollider cc in go.GetComponentsInChildren()) { + foreach (CapsuleCollider cc in go.GetComponentsInChildren()) + { foreach ( RaycastHit h in PhysicsExtensions.CapsuleCastAll( cc, @@ -255,13 +300,16 @@ RaycastHit h in PhysicsExtensions.CapsuleCastAll( layerMask, queryTriggerInteraction ) - ) { - if (!transformsToIgnore.Contains(h.transform)) { + ) + { + if (!transformsToIgnore.Contains(h.transform)) + { hits.Add(h); } } } - foreach (BoxCollider bc in go.GetComponentsInChildren()) { + foreach (BoxCollider bc in go.GetComponentsInChildren()) + { foreach ( RaycastHit h in PhysicsExtensions.BoxCastAll( bc, @@ -270,13 +318,16 @@ RaycastHit h in PhysicsExtensions.BoxCastAll( layerMask, queryTriggerInteraction ) - ) { - if (!transformsToIgnore.Contains(h.transform)) { + ) + { + if (!transformsToIgnore.Contains(h.transform)) + { hits.Add(h); } } } - foreach (SphereCollider sc in go.GetComponentsInChildren()) { + foreach (SphereCollider sc in go.GetComponentsInChildren()) + { foreach ( RaycastHit h in PhysicsExtensions.SphereCastAll( sc, @@ -285,8 +336,10 @@ RaycastHit h in PhysicsExtensions.SphereCastAll( layerMask, queryTriggerInteraction ) - ) { - if (!transformsToIgnore.Contains(h.transform)) { + ) + { + if (!transformsToIgnore.Contains(h.transform)) + { hits.Add(h); } } @@ -297,9 +350,11 @@ RaycastHit h in PhysicsExtensions.SphereCastAll( // 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 { + where T : Component + { Type type = comp.GetType(); - if (type != other.GetType()) { + if (type != other.GetType()) + { return null; // type mis-match } @@ -310,15 +365,20 @@ public static T GetCopyOf(this Component comp, T other) | BindingFlags.Default | BindingFlags.DeclaredOnly; PropertyInfo[] pinfos = type.GetProperties(flags); - foreach (var pinfo in pinfos) { - if (pinfo.CanWrite) { - try { + foreach (var pinfo in pinfos) + { + if (pinfo.CanWrite) + { + try + { pinfo.SetValue(comp, pinfo.GetValue(other, null), null); - } catch { } // In case of NotImplementedException being thrown. For some reason specifying that exception didn't seem to catch it, so I didn't catch anything specific. + } + catch { } // In case of NotImplementedException being thrown. For some reason specifying that exception didn't seem to catch it, so I didn't catch anything specific. } } FieldInfo[] finfos = type.GetFields(flags); - foreach (var finfo in finfos) { + foreach (var finfo in finfos) + { finfo.SetValue(comp, finfo.GetValue(other)); } return comp as T; @@ -326,14 +386,17 @@ public static T GetCopyOf(this Component comp, T other) // usage: Health myHealth = gameObject.AddComponent(enemy.health); or something like that public static T AddComponent(this GameObject go, T toAdd) - where T : Component { + 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) { + public static Vector3 Round(this Vector3 vector3, int decimalPlaces = 2) + { float multiplier = 1; - for (int i = 0; i < decimalPlaces; i++) { + for (int i = 0; i < decimalPlaces; i++) + { multiplier *= 10f; } return new Vector3( @@ -343,7 +406,8 @@ public static Vector3 Round(this Vector3 vector3, int decimalPlaces = 2) { ); } - public static Vector3[] CornerCoordinatesOfBoxColliderToWorld(BoxCollider b) { + public static Vector3[] CornerCoordinatesOfBoxColliderToWorld(BoxCollider b) + { Vector3[] corners = new Vector3[8]; corners[0] = b.transform.TransformPoint( @@ -375,14 +439,16 @@ public static Vector3[] CornerCoordinatesOfBoxColliderToWorld(BoxCollider b) { return corners; } - public static List GetLightPropertiesOfScene() { + public static List GetLightPropertiesOfScene() + { 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) { + foreach (Light hikari in lightsInScene) + { LightParameters lp = new LightParameters(); lp.id = hikari.transform.name; @@ -396,11 +462,14 @@ public static List GetLightPropertiesOfScene() { //culling mask stuff List cullingMaskOff = new List(); - for (int i = 0; i < UtilityFunctions.maxUnityLayerCount; ++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) { + if (((1 << i) & hikari.cullingMask) == 0) + { //check if this layer is actually being used (ie: has a name) - if (LayerMask.LayerToName(i).Length != 0) { + if (LayerMask.LayerToName(i).Length != 0) + { cullingMaskOff.Add(LayerMask.LayerToName(i)); } } @@ -417,11 +486,13 @@ public static List GetLightPropertiesOfScene() { lp.range = hikari.range; //only do this if this is a spot light - if (hikari.type == LightType.Spot) { + if (hikari.type == LightType.Spot) + { lp.spotAngle = hikari.spotAngle; } - lp.rgb = new SerializableColor() { + lp.rgb = new SerializableColor() + { r = hikari.color.r, g = hikari.color.g, b = hikari.color.b, @@ -429,7 +500,8 @@ public static List GetLightPropertiesOfScene() { }; //generate shadow params - ShadowParameters xemnas = new ShadowParameters() { + ShadowParameters xemnas = new ShadowParameters() + { strength = hikari.shadowStrength, type = Enum.GetName(typeof(LightShadows), hikari.shadows), normalBias = hikari.shadowNormalBias, @@ -448,7 +520,8 @@ public static List GetLightPropertiesOfScene() { lp.enabled = hikari.enabled; - if (hikari.GetComponentInParent()) { + if (hikari.GetComponentInParent()) + { lp.parentSimObjId = hikari.GetComponentInParent().objectID; lp.parentSimObjName = hikari.GetComponentInParent().transform.name; } @@ -463,7 +536,8 @@ public static List GetLightPropertiesOfScene() { #if UNITY_EDITOR - public static void debugGetLightPropertiesOfScene(List lights) { + public static void debugGetLightPropertiesOfScene(List lights) + { Debug.Log("we are inside debugGetLightProperties..."); var file = "debugLightProperties.txt"; @@ -471,7 +545,8 @@ public static void debugGetLightPropertiesOfScene(List lights) create.WriteLine($"Total number of Lights in scene: {lights.Count()}"); - foreach (LightParameters lp in lights) { + foreach (LightParameters lp in lights) + { create.WriteLine($"ID: {lp.id}"); create.WriteLine($"Type: {lp.type}"); @@ -480,13 +555,17 @@ public static void debugGetLightPropertiesOfScene(List lights) create.WriteLine($"localPosition: {lp.localPosition}"); - if (lp.cullingMaskOff.Length > 0) { + if (lp.cullingMaskOff.Length > 0) + { create.WriteLine($"Culling Mask Off Layers:"); - foreach (string s in lp.cullingMaskOff) { + foreach (string s in lp.cullingMaskOff) + { create.WriteLine(" " + s); } - } else { + } + else + { create.WriteLine($"Culling Mask Off Layers: none"); } @@ -501,15 +580,19 @@ public static void debugGetLightPropertiesOfScene(List lights) create.WriteLine($"range: {lp.range}"); //this should be 0 if not a spotlight - if (Mathf.Approximately(lp.spotAngle, 0.0f)) { + if (Mathf.Approximately(lp.spotAngle, 0.0f)) + { create.WriteLine("spotAngle: not a spot light!"); - } else { + } + else + { create.WriteLine($"spotAngle: {lp.spotAngle}"); } create.WriteLine($"rgba: {lp.rgb.r} {lp.rgb.g} {lp.rgb.b} {lp.rgb.a}"); - if (lp.shadow != null) { + if (lp.shadow != null) + { create.WriteLine($"shadow params:"); create.WriteLine($" shadow type: {lp.shadow.type}"); create.WriteLine($" shadow strength: {lp.shadow.strength}"); @@ -517,7 +600,9 @@ public static void debugGetLightPropertiesOfScene(List lights) create.WriteLine($" shadow bias: {lp.shadow.bias}"); create.WriteLine($" shadow nearPlane: {lp.shadow.nearPlane}"); create.WriteLine($" shadow resolution: {lp.shadow.resolution}"); - } else { + } + else + { create.WriteLine($"shadow params NULL!!!"); } @@ -536,16 +621,20 @@ 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++) { + private static void ToggleOffPlaceableSurface() + { + for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; i++) + { UnityEditor.SceneManagement.EditorSceneManager.OpenScene( SceneUtility.GetScenePathByBuildIndex(i), OpenSceneMode.Single ); var meshes = UnityEngine.Object.FindObjectsOfType(); - foreach (MeshRenderer m in meshes) { - if (m.sharedMaterial.ToString() == "Placeable_Surface_Mat (UnityEngine.Material)") { + foreach (MeshRenderer m in meshes) + { + if (m.sharedMaterial.ToString() == "Placeable_Surface_Mat (UnityEngine.Material)") + { m.enabled = false; } } @@ -556,16 +645,20 @@ private static void ToggleOffPlaceableSurface() { } [MenuItem("SimObjectPhysics/Toggle On PlaceableSurface Material")] - private static void ToggleOnPlaceableSurface() { - for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; i++) { + private static void ToggleOnPlaceableSurface() + { + for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; i++) + { UnityEditor.SceneManagement.EditorSceneManager.OpenScene( SceneUtility.GetScenePathByBuildIndex(i), OpenSceneMode.Single ); var meshes = UnityEngine.Object.FindObjectsOfType(); - foreach (MeshRenderer m in meshes) { - if (m.sharedMaterial.ToString() == "Placeable_Surface_Mat (UnityEngine.Material)") { + foreach (MeshRenderer m in meshes) + { + if (m.sharedMaterial.ToString() == "Placeable_Surface_Mat (UnityEngine.Material)") + { m.enabled = true; } } @@ -576,8 +669,10 @@ private static void ToggleOnPlaceableSurface() { } [UnityEditor.MenuItem("AI2-THOR/Add GUID to Object Names")] - public static void AddGUIDToSimObjPhys() { - for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; i++) { + public static void AddGUIDToSimObjPhys() + { + for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; i++) + { UnityEditor.SceneManagement.EditorSceneManager.OpenScene( SceneUtility.GetScenePathByBuildIndex(i), OpenSceneMode.Single @@ -587,21 +682,26 @@ public static void AddGUIDToSimObjPhys() { //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 List usedGuidsJustInCaseCauseIDunnoThisIsRandom = new List(); - foreach (SimObjPhysics sop in objects) { + foreach (SimObjPhysics sop in objects) + { Guid g; 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!?!?"); } } @@ -619,8 +719,10 @@ public static void AddGUIDToSimObjPhys() { //light naming convention: {PrefabName/scene}|{Light Type}|{instance} //Editor-only function used to set names of all light assets in scenes that have Lights in them prior to any additional lights being //dynamically spawned in by something like a Procedural action. - private static void NameAllSceneLightObjects() { - for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; i++) { + private static void NameAllSceneLightObjects() + { + for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCountInBuildSettings; i++) + { UnityEditor.SceneManagement.EditorSceneManager.OpenScene( SceneUtility.GetScenePathByBuildIndex(i), OpenSceneMode.Single @@ -632,14 +734,18 @@ private static void NameAllSceneLightObjects() { Dictionary sceneLights = new Dictionary(); Dictionary simObjChildLights = new Dictionary(); - foreach (Light l in lights) { - if (!l.GetComponentInParent()) { + foreach (Light l in lights) + { + 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); } } @@ -650,19 +756,27 @@ private static void NameAllSceneLightObjects() { int areaInstance = 0; //sort the scene lights into point, directional, or spot - foreach (KeyValuePair l in sceneLights) { + foreach (KeyValuePair l in sceneLights) + { //Debug.Log(directionalInstance); - if (l.Value == LightType.Spot) { + if (l.Value == LightType.Spot) + { l.Key.name = "scene|" + l.Value.ToString() + "|" + spotInstance.ToString(); spotInstance++; - } else if (l.Value == LightType.Directional) { + } + else if (l.Value == LightType.Directional) + { l.Key.name = "scene|" + l.Value.ToString() + "|" + directionalInstance.ToString(); directionalInstance++; - } else if (l.Value == LightType.Point) { + } + else if (l.Value == LightType.Point) + { l.Key.name = "scene|" + l.Value.ToString() + "|" + pointInstance.ToString(); pointInstance++; - } else if (l.Value == LightType.Area) { + } + else if (l.Value == LightType.Area) + { l.Key.name = "scene|" + l.Value.ToString() + "|" + areaInstance.ToString(); areaInstance++; } @@ -673,7 +787,8 @@ private static void NameAllSceneLightObjects() { new Dictionary, SimObjPhysics>(); //map each light/lightType pair to the sim object that they are associated with - foreach (KeyValuePair l in simObjChildLights) { + foreach (KeyValuePair l in simObjChildLights) + { lightAndTypeToSimObjPhys.Add(l, l.Key.GetComponentInParent()); } @@ -692,12 +807,17 @@ private static void NameAllSceneLightObjects() { KeyValuePair, SimObjPhysics > light in lightAndTypeToSimObjPhys - ) { - if (light.Key.Value == LightType.Spot) { - if (!simObjToSpotInstanceCountInThatSimObj.ContainsKey(light.Value)) { + ) + { + 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]++; } @@ -708,11 +828,16 @@ private static void NameAllSceneLightObjects() { + light.Key.Value.ToString() + "|" + simObjToSpotInstanceCountInThatSimObj[light.Value].ToString(); - } else if (light.Key.Value == LightType.Directional) { - if (!simObjToDirectionalInstanceCountInThatSimObj.ContainsKey(light.Value)) { + } + 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]++; } @@ -723,11 +848,16 @@ private static void NameAllSceneLightObjects() { + light.Key.Value.ToString() + "|" + simObjToDirectionalInstanceCountInThatSimObj[light.Value].ToString(); - } else if (light.Key.Value == LightType.Point) { - if (!simObjToPointInstanceCountInThatSimObj.ContainsKey(light.Value)) { + } + 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]++; } @@ -739,11 +869,15 @@ private static void NameAllSceneLightObjects() { + "|" + 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]++; } diff --git a/unity/Assets/Scripts/VisualizationHeatmapCSV.cs b/unity/Assets/Scripts/VisualizationHeatmapCSV.cs index 6a0f99e550..377d0b1782 100644 --- a/unity/Assets/Scripts/VisualizationHeatmapCSV.cs +++ b/unity/Assets/Scripts/VisualizationHeatmapCSV.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class VisualizationHeatmapCSV : MonoBehaviour { +public class VisualizationHeatmapCSV : MonoBehaviour +{ public TextAsset CSVFile; public List xvalues; @@ -14,13 +15,15 @@ public class VisualizationHeatmapCSV : MonoBehaviour { public GameObject prefabHeavy; // Use this for initialization - void Start() { + void Start() + { string[] data = CSVFile.text.Split(new char[] { '\n' }); float x, z, r; - for (int i = 1; i < data.Length - 1; i++) { + for (int i = 1; i < data.Length - 1; i++) + { string[] row = data[i].Split(new char[] { ',' }); float.TryParse(row[0], out x); @@ -33,7 +36,8 @@ void Start() { rotationvalues.Add(r); } - for (int i = 0; i < xvalues.Count; i++) { + for (int i = 0; i < xvalues.Count; i++) + { Vector3 pos = new Vector3(xvalues[i], 1, zvalues[i]); Vector3 rot = new Vector3(0, rotationvalues[i], 0); diff --git a/unity/Assets/Scripts/WallProperties.cs b/unity/Assets/Scripts/WallProperties.cs index f07ebf44ac..be9a464293 100644 --- a/unity/Assets/Scripts/WallProperties.cs +++ b/unity/Assets/Scripts/WallProperties.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using UnityEngine; -public class WallProperties : MonoBehaviour { +public class WallProperties : MonoBehaviour +{ public string RoomId; } diff --git a/unity/Assets/Scripts/WhatIsInsideMagnetSphere.cs b/unity/Assets/Scripts/WhatIsInsideMagnetSphere.cs index 00fd8d4b48..3cd94bff03 100644 --- a/unity/Assets/Scripts/WhatIsInsideMagnetSphere.cs +++ b/unity/Assets/Scripts/WhatIsInsideMagnetSphere.cs @@ -3,7 +3,8 @@ using System.Linq; using UnityEngine; -public class WhatIsInsideMagnetSphere : MonoBehaviour { +public class WhatIsInsideMagnetSphere : MonoBehaviour +{ [SerializeField] protected List CurrentlyContainedSOP = new List(); SphereCollider sphereCol = null; @@ -11,13 +12,16 @@ public class WhatIsInsideMagnetSphere : MonoBehaviour { // check if the sphere is actively colliding with anything // public bool isColliding; // Start is called before the first frame update - void Start() { - if (sphereCol == null) { + void Start() + { + if (sphereCol == null) + { sphereCol = gameObject.GetComponent(); } } - public List CurrentlyContainedSimObjects(bool onlyPickupable) { + public List CurrentlyContainedSimObjects(bool onlyPickupable) + { // clear lists of contained objects // create overlap sphere same location and dimensions as sphere collider @@ -37,10 +41,13 @@ public List CurrentlyContainedSimObjects(bool onlyPickupable) { ), queryTriggerInteraction: QueryTriggerInteraction.Ignore ); - foreach (var col in hitColliders) { + foreach (var col in hitColliders) + { SimObjPhysics sop = col.GetComponentInParent(); - if (sop != null) { - if ((!onlyPickupable) || sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup) { + if (sop != null) + { + if ((!onlyPickupable) || sop.PrimaryProperty == SimObjPrimaryProperty.CanPickup) + { currentlyContainedObjects.Add(sop); } } diff --git a/unity/Assets/Scripts/agent_trackball_rotation.cs b/unity/Assets/Scripts/agent_trackball_rotation.cs index 1c2e0e5cdc..78dabc8519 100644 --- a/unity/Assets/Scripts/agent_trackball_rotation.cs +++ b/unity/Assets/Scripts/agent_trackball_rotation.cs @@ -2,7 +2,8 @@ using System.Collections.Generic; using UnityEngine; -public class agent_trackball_rotation : MonoBehaviour { +public class agent_trackball_rotation : MonoBehaviour +{ float ballPositionToRotationRatio = 3 * Mathf.PI / 1200; // Circumference over 360 euler degrees float changeInPosition; // How far agent has moved Vector3 currentPosition; // Ball's current position @@ -25,7 +26,8 @@ void Start() // Initialize "previous" values prevLookDirection = gameObject.transform.parent.transform.rotation.eulerAngles.y; } - void Update() { + void Update() + { currentPosition = new Vector3( gameObject.transform.position.x, 0, @@ -44,8 +46,9 @@ void Update() { .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 - { + } + else // If agent is still + { lookRotation = currentLookDirection - prevLookDirection; // How far agent has rotated between frames if (lookRotation != 0) // If agent has rotated diff --git a/unity/Assets/Scripts/childcollider.cs b/unity/Assets/Scripts/childcollider.cs index efcced8b7c..6140d60694 100644 --- a/unity/Assets/Scripts/childcollider.cs +++ b/unity/Assets/Scripts/childcollider.cs @@ -2,14 +2,16 @@ using System.Collections.Generic; using UnityEngine; -public class childcollider : MonoBehaviour { +public class childcollider : MonoBehaviour +{ // Use this for initialization void Start() { } // Update is called once per frame void Update() { } - void OnCollisionEnter(Collision collision) { + void OnCollisionEnter(Collision collision) + { print("collision enteR!"); this.GetComponent().attachedRigidbody.SendMessage("OnCollisionEnter", collision); } diff --git a/unity/Assets/Scripts/coffeemachine.cs b/unity/Assets/Scripts/coffeemachine.cs index cdef27f6e3..2d30319d81 100644 --- a/unity/Assets/Scripts/coffeemachine.cs +++ b/unity/Assets/Scripts/coffeemachine.cs @@ -2,33 +2,39 @@ using System.Collections.Generic; using UnityEngine; -public class coffeemachine : MonoBehaviour { +public class coffeemachine : MonoBehaviour +{ private ObjectSpecificReceptacle osr; private CanToggleOnOff onOff; // Start is called before the first frame update - void Start() { + void Start() + { osr = gameObject.GetComponent(); onOff = gameObject.GetComponent(); } // Update is called once per frame - void Update() { + void Update() + { Serve(); } - public void Serve() { + public void Serve() + { SimObjPhysics target; if ( osr.attachPoint.transform.GetComponentInChildren() && onOff.isTurnedOnOrOff() - ) { + ) + { target = osr.attachPoint.transform.GetComponentInChildren(); Fill f = target.GetComponent(); // if not already toasted, toast it! - if (!f.IsFilled()) { + if (!f.IsFilled()) + { f.FillObject("coffee"); } } From 5c23fc6daa41ce554e8de283083d96167b78d5be Mon Sep 17 00:00:00 2001 From: AlvaroHG Date: Tue, 6 Aug 2024 18:04:33 -0700 Subject: [PATCH 7/7] private scenes for stretch_with_many_cameras branch --- tasks.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tasks.py b/tasks.py index e747f03b13..e45683d3e2 100644 --- a/tasks.py +++ b/tasks.py @@ -1144,7 +1144,7 @@ def ci_build( "id": None, } - novelty_thor_add_branches = ["new_cam_adjust"] + novelty_thor_add_branches = ["new_cam_adjust", "stretch_with_many_cameras"] if is_travis_build and build and build["branch"] in novelty_thor_add_branches: novelty_thor_scenes = True private_repos.append(novelty_thor_repo)