// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections.Generic; using UnityEngine;
namespaceHoloToolkit.Unity.SpatialMapping.Tests { publicclassSpatialProcessing : Singleton<SpatialProcessing> { [Tooltip("How much time (in seconds) that the SurfaceObserver will run after being started; used when 'Limit Scanning By Time' is checked.")] publicfloat scanTime = 30.0f;
[Tooltip("Material to use when rendering Spatial Mapping meshes while the observer is running.")] public Material defaultMaterial;
[Tooltip("Optional Material to use when rendering Spatial Mapping meshes after the observer has been stopped.")] public Material secondaryMaterial;
///<summary> /// Indicates if processing of the surface meshes is complete. ///</summary> privatebool meshesProcessed = false;
///<summary> /// GameObject initialization. ///</summary> privatevoidStart() { // Update surfaceObserver and storedMeshes to use the same material during scanning. SpatialMappingManager.Instance.SetSurfaceMaterial(defaultMaterial);
// Register for the MakePlanesComplete event. SurfaceMeshesToPlanes.Instance.MakePlanesComplete += SurfaceMeshesToPlanes_MakePlanesComplete; }
///<summary> /// Called once per frame. ///</summary> privatevoidUpdate() { // Check to see if the spatial mapping data has been processed yet. if (!meshesProcessed) { // Check to see if enough scanning time has passed // since starting the observer. if ((Time.unscaledTime - SpatialMappingManager.Instance.StartTime) < scanTime) { // If we have a limited scanning time, then we should wait until // enough time has passed before processing the mesh. } else { // The user should be done scanning their environment, // so start processing the spatial mapping data...
if (SpatialMappingManager.Instance.IsObserverRunning()) { // Stop the observer. SpatialMappingManager.Instance.StopObserver(); }
// Call CreatePlanes() to generate planes. CreatePlanes();
// Set meshesProcessed to true. meshesProcessed = true; } } }
///<summary> /// Handler for the SurfaceMeshesToPlanes MakePlanesComplete event. ///</summary> ///<param name="source">Source of the event.</param> ///<param name="args">Args for the event.</param> privatevoidSurfaceMeshesToPlanes_MakePlanesComplete(object source, System.EventArgs args) { // Collection of floor planes that we can use to set horizontal items on. List<GameObject> floors = new List<GameObject>(); floors = SurfaceMeshesToPlanes.Instance.GetActivePlanes(PlaneTypes.Floor);
// Check to see if we have enough floors (minimumFloors) to start processing. if (floors.Count >= minimumFloors) { // Reduce our triangle count by removing any triangles // from SpatialMapping meshes that intersect with active planes. RemoveVertices(SurfaceMeshesToPlanes.Instance.ActivePlanes);
// After scanning is over, switch to the secondary (occlusion) material. SpatialMappingManager.Instance.SetSurfaceMaterial(secondaryMaterial); } else { // Re-enter scanning mode so the user can find more surfaces before processing. SpatialMappingManager.Instance.StartObserver();
// Re-process spatial data after scanning completes. meshesProcessed = false; } }
///<summary> /// Creates planes from the spatial mapping surfaces. ///</summary> privatevoidCreatePlanes() { // Generate planes based on the spatial map. SurfaceMeshesToPlanes surfaceToPlanes = SurfaceMeshesToPlanes.Instance; if (surfaceToPlanes != null && surfaceToPlanes.enabled) { surfaceToPlanes.MakePlanes(); } }
///<summary> /// Removes triangles from the spatial mapping surfaces. ///</summary> ///<param name="boundingObjects"></param> privatevoidRemoveVertices(IEnumerable<GameObject> boundingObjects) { RemoveSurfaceVertices removeVerts = RemoveSurfaceVertices.Instance; if (removeVerts != null && removeVerts.enabled) { removeVerts.RemoveSurfaceVerticesWithinBounds(boundingObjects); } }
///<summary> /// Called when the GameObject is unloaded. ///</summary> protectedoverridevoidOnDestroy() { if (SurfaceMeshesToPlanes.Instance != null) { SurfaceMeshesToPlanes.Instance.MakePlanesComplete -= SurfaceMeshesToPlanes_MakePlanesComplete; }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections.Generic; using UnityEngine; using HoloToolkit.Unity.InputModule; using UnityEngine.XR.WSA.Persistence; using System.Linq; using UnityEngine.XR.WSA;
namespaceHoloToolkit.Unity.SpatialMapping { ///<summary> /// The TapToPlace class is a basic way to enable users to move objects /// and place them on real world surfaces. /// Put this script on the object you want to be able to move. /// Users will be able to tap objects, gaze elsewhere, and perform the tap gesture again to place. /// This script is used in conjunction with GazeManager, WorldAnchorManager, and SpatialMappingManager. ///</summary> [RequireComponent(typeof(Collider))] [RequireComponent(typeof(Interpolator))] publicclassTapToPlace : MonoBehaviour, IInputClickHandler { [Tooltip("Distance from camera to keep the object while placing it.")] publicfloat DefaultGazeDistance = 2.0f;
[Tooltip("Place parent on tap instead of current game object.")] publicbool PlaceParentOnTap;
[Tooltip("Specify the parent game object to be moved on tap, if the immediate parent is not desired.")] public GameObject ParentGameObjectToPlace;
///<summary> /// Keeps track of if the user is moving the object or not. /// Setting this to true will enable the user to move and place the object in the scene. /// Useful when you want to place an object immediately. ///</summary> [Tooltip("Setting this to true will enable the user to move and place the object in the scene without needing to tap on the object. Useful when you want to place an object immediately.")] publicbool IsBeingPlaced;
[Tooltip("Setting this to true will allow this behavior to control the DrawMesh property on the spatial mapping.")] publicbool AllowMeshVisualizationControl = true;
[Tooltip("Should the center of the Collider be used instead of the gameObjects world transform.")] publicbool UseColliderCenter;
private Interpolator interpolator;
WorldAnchorStore AnchorStore;
string ObjectAnchorStoreName;
///<summary> /// The default ignore raycast layer built into unity. ///</summary> privateconstint IgnoreRaycastLayer = 2;
privateDictionary<GameObject, int> layerCache = new Dictionary<GameObject, int>(); private Vector3 PlacementPosOffset;
if (IsBeingPlaced) { StartPlacing(); } else// If we are not starting out with actively placing the object, give it a World Anchor { AttachWorldAnchor(); } }
///<summary> /// Returns the predefined GameObject or the immediate parent when it exists ///</summary> ///<returns></returns> private GameObject GetParentToPlace() { if (ParentGameObjectToPlace) { return ParentGameObjectToPlace; }
///<summary> /// Ensures an interpolator on either the parent or on the GameObject itself and returns it. ///</summary> private Interpolator EnsureInterpolator() { var interpolatorHolder = PlaceParentOnTap ? ParentGameObjectToPlace : gameObject; return interpolatorHolder.EnsureComponent<Interpolator>(); }
if (UseColliderCenter) { placementPosition += PlacementPosOffset; }
// Here is where you might consider adding intelligence // to how the object is placed. For example, consider // placing based on the bottom of the object's // collider so it sits properly on surfaces.
// update the placement to match the user's gaze. interpolator.SetTargetPosition(placementPosition);
// Rotate this object to face the user. interpolator.SetTargetRotation(Quaternion.Euler(0, cameraTransform.localEulerAngles.y, 0)); }
publicvirtualvoidOnInputClicked(InputClickedEventData eventData) { // On each tap gesture, toggle whether the user is in placing mode. IsBeingPlaced = !IsBeingPlaced; HandlePlacement(); eventData.Use(); }
privatevoidHandlePlacement() { if (IsBeingPlaced) { StartPlacing(); } else { StopPlacing(); } } privatevoidStartPlacing() { var layerCacheTarget = PlaceParentOnTap ? ParentGameObjectToPlace : gameObject; layerCacheTarget.SetLayerRecursively(IgnoreRaycastLayer, out layerCache); InputManager.Instance.PushModalInputHandler(gameObject);
if (AnchorStore.GetAllIds().Contains(ObjectAnchorStoreName)) { AnchorStore.Delete(ObjectAnchorStoreName); } }
///<summary> /// If the user is in placing mode, display the spatial mapping mesh. ///</summary> privatevoidToggleSpatialMesh() { if (SpatialMappingManager.Instance != null && AllowMeshVisualizationControl) { SpatialMappingManager.Instance.DrawVisualMeshes = IsBeingPlaced; } }
///<summary> /// If we're using the spatial mapping, check to see if we got a hit, else use the gaze position. ///</summary> ///<returns>Placement position in front of the user</returns> privatestatic Vector3 GetPlacementPosition(Vector3 headPosition, Vector3 gazeDirection, float defaultGazeDistance) { RaycastHit hitInfo; if (SpatialMappingRaycast(headPosition, gazeDirection, out hitInfo)) { return hitInfo.point; } return GetGazePlacementPosition(headPosition, gazeDirection, defaultGazeDistance); }
///<summary> /// Does a raycast on the spatial mapping layer to try to find a hit. ///</summary> ///<param name="origin">Origin of the raycast</param> ///<param name="direction">Direction of the raycast</param> ///<param name="spatialMapHit">Result of the raycast when a hit occurred</param> ///<returns>Whether it found a hit or not</returns> privatestaticboolSpatialMappingRaycast(Vector3 origin, Vector3 direction, out RaycastHit spatialMapHit) { if (SpatialMappingManager.Instance != null) { RaycastHit hitInfo; if (Physics.Raycast(origin, direction, out hitInfo, 30.0f, SpatialMappingManager.Instance.LayerMask)) { spatialMapHit = hitInfo; returntrue; } } spatialMapHit = new RaycastHit(); returnfalse; }
///<summary> /// Get placement position either from GazeManager hit or in front of the user as backup ///</summary> ///<param name="headPosition">Position of the users head</param> ///<param name="gazeDirection">Gaze direction of the user</param> ///<param name="defaultGazeDistance">Default placement distance in front of the user</param> ///<returns>Placement position in front of the user</returns> privatestatic Vector3 GetGazePlacementPosition(Vector3 headPosition, Vector3 gazeDirection, float defaultGazeDistance) { if (GazeManager.Instance.HitObject != null) { return GazeManager.Instance.HitPosition; } return headPosition + gazeDirection * defaultGazeDistance; } } }
运行程序,将 Cube 放置在椅子上,重新运行程序,Cube 会被还原到椅子上。
PS:注意去除 is Being Placed 选项,不然程序每次启动 Cube 都会处于可移动状态。