protected override void OnCloudAnchorLocated(AnchorLocatedEventArgs args)
        {
            base.OnCloudAnchorLocated(args);

            Debug.Log("about to check expiration");
            // if ((args != null) && (args.Anchor != null))
            //    Debug.Log("Expiration Date for this anchor is " + args.Anchor.Expiration);


            if (args.Status == LocateAnchorStatus.Located)
            {
                CloudSpatialAnchor nextCsa = args.Anchor;
                currentCloudAnchor = args.Anchor;
                //         Debug.Log("Expiration Date for this anchor is " + nextCsa.Expiration);


                UnityDispatcher.InvokeOnAppThread(() =>
                {
                    anchorsLocated++;
                    currentCloudAnchor = nextCsa;
                    Pose anchorPose    = Pose.identity;

                    #if UNITY_ANDROID || UNITY_IOS
                    anchorPose = currentCloudAnchor.GetPose();
                    #endif
                    // HoloLens: The position will be set based on the unityARUserAnchor that was located.

                    GameObject nextObject = SpawnNewAnchoredObject(anchorPose.position, anchorPose.rotation, currentCloudAnchor);
                    //spawnedObjectMat = nextObject.GetComponent<MeshRenderer>().material;
                    Debug.Log("Setting goal in shareddemo");

                    //GameObject.Find("arrow").GetComponent<moveTo>().setGoal(nextObject.transform, nextObject.name);

#if !UNITY_EDITOR
                    //Instead of setting anchor is up as destination, add the game object to the flag list for later use
                    GameObject.Find("listOfFlagsGameObj").GetComponent <ListOps>().addFlag(nextObject);
                    Debug.Log("********************************************added next Object: " + nextObject.transform.position + ". Main camera's location is " + Camera.main.transform.position + ". other position is " + GameObject.Find("CameraParent").transform.position);

                    // Only start navigation if there are destination flags

                    //      AttachTextMesh(nextObject, _anchorNumberToFind);
#endif
                    otherSpawnedObjects.Add(nextObject);
                    Debug.Log("Adding " + nextObject);

                    if (anchorsLocated >= nbrOfDestinationAnchors)
                    {
                        currentAppState = AppState.DemoStepStopSessionForQuery;
                    }
                    else
                    {
                        Debug.Log("only " + anchorsLocated + " anchors have so far been located");
                    }
                });
            }
        }
    public void CreateAzureAnchor(GameObject theObject)
    {
        DebugWindowMessaging.Clear();
        Debug.Log("Create_Azure_Anchor button is pressed");
        Debug.Log("Wait for sometime and press Share_Azure_Anchor");
        //First we create a local anchor at the location of the object in question
        theObject.AddARAnchor();

        //Then we create a new local cloud anchor
        CloudSpatialAnchor localCloudAnchor = new CloudSpatialAnchor();

        //Now we set the local cloud anchor's position to the local anchor's position
        localCloudAnchor.LocalAnchor = theObject.GetNativeAnchorPointer();

        //Check to see if we got the local anchor pointer
        if (localCloudAnchor.LocalAnchor == IntPtr.Zero)
        {
            Debug.Log("Didn't get the local XR anchor pointer...");
            return;
        }

        // In this sample app we delete the cloud anchor explicitly, but here we show how to set an anchor to expire automatically
        localCloudAnchor.Expiration = DateTimeOffset.Now.AddDays(7);

        //Save anchor to cloud
        Task.Run(async() =>
        {
            while (!CloudManager.EnoughDataToCreate)
            {
                await Task.Delay(330);
            }

            bool success = false;
            try
            {
                currentCloudAnchor = await CloudManager.StoreAnchorInCloud(localCloudAnchor);

                //Save the Azure Anchor ID
                GenericNetworkManager.instance.AzureAnchorID = currentCloudAnchor.Identifier;
                Debug.Log("Azure anchor ID saved!");

                success          = currentCloudAnchor != null;
                localCloudAnchor = null;

                if (success)
                {
                    Debug.Log("Successfully Created Anchor");
                }
            }
            catch (Exception ex)
            {
                Debug.Log(ex);
                Debug.Log("Anchor creation failure");
            }
        });
    }
示例#3
0
    private void CloudManager_AnchorLocated(object sender, AnchorLocatedEventArgs args)
    {
        QueueOnUpdate(new Action(() => Debug.Log($"Anchor recognized as a possible Azure anchor")));

        if (args.Status == LocateAnchorStatus.Located || args.Status == LocateAnchorStatus.AlreadyTracked)
        {
            currentCloudAnchor = args.Anchor;

            QueueOnUpdate(() =>
            {
                Debug.Log($"Azure anchor located successfully");

                // Notify AnchorFeedbackScript
                OnASAAnchorLocated?.Invoke();

#if WINDOWS_UWP || UNITY_WSA
                // HoloLens: The position will be set based on the unityARUserAnchor that was located.

                // Create a local anchor at the location of the object in question
                gameObject.CreateNativeAnchor();

                // Notify AnchorFeedbackScript
                OnCreateLocalAnchor?.Invoke();

                // On HoloLens, if we do not have a cloudAnchor already, we will have already positioned the
                // object based on the passed in worldPos/worldRot and attached a new world anchor,
                // so we are ready to commit the anchor to the cloud if requested.
                // If we do have a cloudAnchor, we will use it's pointer to setup the world anchor,
                // which will position the object automatically.
                if (currentCloudAnchor != null)
                {
                    Debug.Log("Local anchor position successfully set to Azure anchor position");

                    gameObject.GetComponent <UnityEngine.XR.WSA.WorldAnchor>().SetNativeSpatialAnchorPtr(currentCloudAnchor.LocalAnchor);
                }
#elif UNITY_ANDROID || UNITY_IOS
                Pose anchorPose = Pose.identity;
                anchorPose      = currentCloudAnchor.GetPose();

                Debug.Log($"Setting object to anchor pose with position '{anchorPose.position}' and rotation '{anchorPose.rotation}'");
                transform.position = anchorPose.position;
                transform.rotation = anchorPose.rotation;

                // Create a native anchor at the location of the object in question
                gameObject.CreateNativeAnchor();

                // Notify AnchorFeedbackScript
                OnCreateLocalAnchor?.Invoke();
#endif
            });
        }
        else
        {
            QueueOnUpdate(new Action(() => Debug.Log($"Attempt to locate Anchor with ID '{args.Identifier}' failed, locate anchor status was not 'Located' but '{args.Status}'")));
        }
    }
示例#4
0
        /// <summary>
        /// Saves the current object anchor to the cloud.
        /// </summary>
        protected virtual async Task SaveCurrentObjectAnchorToCloudAsync()
        {
            // Get the cloud-native anchor behavior
            CloudNativeAnchor cna = spawnedObject.GetComponent <CloudNativeAnchor>();

            // If the cloud portion of the anchor hasn't been created yet, create it
            if (cna.CloudAnchor == null)
            {
                cna.NativeToCloud();
            }

            // Get the cloud portion of the anchor
            CloudSpatialAnchor cloudAnchor = cna.CloudAnchor;

            // In this sample app we delete the cloud anchor explicitly, but here we show how to set an anchor to expire automatically
            cloudAnchor.Expiration = DateTimeOffset.Now.AddDays(7);

            while (!CloudManager.IsReadyForCreate)
            {
                await Task.Delay(330);

                float createProgress = CloudManager.SessionStatus.RecommendedForCreateProgress;
                feedbackBox.text = $"Move your device to capture more environment data: {createProgress:0%}";
            }

            bool success = false;

            feedbackBox.text = "Saving...";

            try
            {
                // Actually save
                await CloudManager.CreateAnchorAsync(cloudAnchor);

                // Store
                currentCloudAnchor = cloudAnchor;

                // Success?
                success = currentCloudAnchor != null;

                if (success && !isErrorActive)
                {
                    // Await override, which may perform additional tasks
                    // such as storing the key in the AnchorExchanger
                    await OnSaveCloudAnchorSuccessfulAsync();
                }
                else
                {
                    OnSaveCloudAnchorFailed(new Exception("Failed to save, but no exception was thrown."));
                }
            }
            catch (Exception ex)
            {
                OnSaveCloudAnchorFailed(ex);
            }
        }
示例#5
0
    public void CleanupObjects()
    {
        if (_prefabInstance != null)
        {
            Destroy(_prefabInstance);
            _prefabInstance = null;
        }

        _currentCloudAnchor = null;
    }
示例#6
0
    public async Task <CloudSpatialAnchor> RefreshAnchorInCloud(CloudSpatialAnchor cloudSpatialAnchor)
    {
        if (SessionStatusIndicators[(int)SessionStatusIndicatorType.ReadyForCreate] < 1)
        {
            return(null);
        }
        await cloudSpatialAnchorSession.RefreshAnchorPropertiesAsync(cloudSpatialAnchor);

        return(cloudSpatialAnchor);
    }
示例#7
0
 private void UpdateAnchorProperties(CloudSpatialAnchor cloudAnchor, AnchorProperties anchorProperties)
 {
     Log.debug($"anchor properties local anchor local scale is : {anchorProperties.gameObject.transform.localScale.x.ToString()}");
     cloudAnchor.AppProperties[AnchorProperties.ScaleKey] = anchorProperties.gameObject.transform.localScale.x.ToString();
     cloudAnchor.AppProperties[AnchorProperties.DateKey]  = anchorProperties.dateSecondsString;
     if (anchorProperties.anchorLabel != null)
     {
         cloudAnchor.AppProperties[AnchorProperties.AnchorLabelKey] = anchorProperties.anchorLabel;
     }
 }
示例#8
0
        public async Task DeleteAnchorAsync(CloudSpatialAnchor cloudSpatialAnchor)
        {
            if (SessionValid())
            {
                await cloudSpatialAnchorSession.DeleteAnchorAsync(cloudSpatialAnchor);

                OnAnchorCreationfailed?.Invoke();
                Debug.Log("Anchor Creation Failed...Please try again...");
            }
        }
示例#9
0
        private void AnchorLookedUp(string anchorId)
        {
            Log.Debug("ASADemo", "anchor " + anchorId);
            this.anchorId = anchorId;
            this.DestroySession();

            bool anchorLocated = false;

            this.cloudAnchorManager = new AzureSpatialAnchorsManager(this.sceneView.Session);
            this.cloudAnchorManager.OnAnchorLocated += (sender, args) =>
                                                       this.RunOnUiThread(() =>
            {
                CloudSpatialAnchor anchor = args.Anchor;
                LocateAnchorStatus status = args.Status;

                if (status == LocateAnchorStatus.AlreadyTracked || status == LocateAnchorStatus.Located)
                {
                    anchorLocated = true;

                    AnchorVisual foundVisual = new AnchorVisual(anchor.LocalAnchor)
                    {
                        CloudAnchor = anchor
                    };
                    foundVisual.AnchorNode.SetParent(this.arFragment.ArSceneView.Scene);
                    string cloudAnchorIdentifier = foundVisual.CloudAnchor.Identifier;
                    foundVisual.SetColor(foundColor);
                    foundVisual.AddToScene(this.arFragment);
                    this.anchorVisuals[cloudAnchorIdentifier] = foundVisual;
                }
            });

            this.cloudAnchorManager.OnLocateAnchorsCompleted += (sender, args) =>
            {
                this.currentStep = DemoStep.Start;

                this.RunOnUiThread(() =>
                {
                    if (anchorLocated)
                    {
                        this.textView.Text = "Anchor located!";
                    }
                    else
                    {
                        this.textView.Text = "Anchor was not located. Check the logs for errors and\\or create a new anchor and try again.";
                    }

                    this.EnableCorrectUIControls();
                });
            };
            this.cloudAnchorManager.StartSession();
            AnchorLocateCriteria criteria = new AnchorLocateCriteria();

            criteria.SetIdentifiers(new string[] { anchorId });
            this.cloudAnchorManager.StartLocating(criteria);
        }
示例#10
0
    /// <summary>
    /// Creates an anchor at the Shared World Anchor's position and orientation
    /// </summary>
    /// <returns>The asynchronous Task that for this asynchronous function that will return the status of the anchor creation.</returns>
    public async Task <bool> CreateAnchorAsync()
    {
        // Set the LocalAnchor property of the CloudSpatialAnchor to the WorldAnchor component of our white sphere.
        WorldAnchor worldAnchor = SharedWorldAnchor.Instance.gameObject.AddComponent <WorldAnchor>();

        // In Editor, don't bother
        if (Application.isEditor)
        {
            // Simulate that we have found an anchor
            CloudSpatialAnchorId = FakeCloudSpatialAnchorId;
            return(true);
        }

        // Create the CloudSpatialAnchor.
        currentCloudAnchor            = new CloudSpatialAnchor();
        currentCloudAnchor.Expiration = DateTimeOffset.Now.AddDays(1);

        // Save the CloudSpatialAnchor to the cloud.
        currentCloudAnchor.LocalAnchor = worldAnchor.GetNativeSpatialAnchorPtr();

        // Wait for enough data about the environment.
        while (recommendedForCreate < 1.0F)
        {
            await Task.Delay(330);
        }

        bool success = false;

        try
        {
            await CloudSpatialAnchorSession.CreateAnchorAsync(currentCloudAnchor);

            success = currentCloudAnchor != null;

            if (success)
            {
                // Record the identifier to locate.
                CloudSpatialAnchorId = currentCloudAnchor.Identifier;

                Debug.Log("ASA Info: Saved anchor to Azure Spatial Anchors! Identifier: " + CloudSpatialAnchorId);
            }
            else
            {
                Debug.LogError("ASA Error: Failed to save, but no exception was thrown.");
            }

            return(success);
        }
        catch (Exception ex)
        {
            Debug.LogError("ASA Error: " + ex.Message);
        }

        return(false);
    }
示例#11
0
    // Public Task: Cloud Operation

    public async Task <CloudSpatialAnchor> StoreAnchorInCloud(CloudSpatialAnchor cloudSpatialAnchor)
    {
        if (SessionStatusIndicators[(int)SessionStatusIndicatorType.ReadyForCreate] < 1)
        {
            return(null);
        }

        await cloudSpatialAnchorSession.CreateAnchorAsync(cloudSpatialAnchor);

        return(cloudSpatialAnchor);  // to tell createanchor method is successful
    }
示例#12
0
 public void DeleteAzureAnchor(string AnchorIDtoDelete)
 {
     DebugWindowMessaging.Clear();
     //Delete the anchor with the ID specified off the server and locally
     Task.Run(async() =>
     {
         await CloudManager.DeleteAnchorAsync(currentCloudAnchor);
         currentCloudAnchor = null;
     });
     Debug.Log("Azure anchor deleted");
 }
示例#13
0
        private async Task <bool> SaveVirtualExplorerAnchor(string anchorSetId, CloudSpatialAnchor anchor)
        {
            var url = string.Format("{0}/{1}/{2}/{3}/{4}",
                                    Globals.ServiceBaseUrl,
                                    AnchorSetsRoute,
                                    VirtualExplorerRoute,
                                    anchorSetId,
                                    anchor.Identifier);

            return(await SaveAnchor(url));
        }
示例#14
0
 public void DeleteAzureAnchor(string AnchorIDtoDelete)
 {
     //Delete the anchor with the ID specified off the server and locally
     Task.Run(async() =>
     {
         await CloudManager.DeleteAnchorAsync(currentCloudAnchor);
         currentCloudAnchor = null;
         Debug.Log("Cloud anchor is deleted successfully.");
         OnDeleteASAAnchor?.Invoke();
     });
 }
示例#15
0
        /// <summary>
        /// Stores the specified cloud version of the anchor and creates or updates the native anchor
        /// to match.
        /// </summary>
        /// <param name="cloudAnchor">
        /// The cloud version of the anchor.
        /// </param>
        /// <remarks>
        /// When this method completes, <see cref="CloudAnchor"/> will point to the anchor specified
        /// by <paramref name="cloudAnchor"/> and <see cref="NativeAnchor"/> will return a new or updated
        /// native anchor with the same information.
        /// </remarks>
        public void CloudToNative(CloudSpatialAnchor cloudAnchor)
        {
            // Validate
            if (cloudAnchor == null)
            {
                throw new ArgumentNullException(nameof(cloudAnchor));
            }

            // Apply and store updated native anchor
            nativeAnchor = gameObject.ApplyCloudAnchor(cloudAnchor);
        }
        /// <summary>
        /// Applies the specified cloud anchor to the GameObject by
        /// creating or updating the native anchor.
        /// to match.
        /// </summary>
        /// <param name="gameObject">
        /// The <see cref="GameObject"/> where the cloud anchor should be
        /// applied.
        /// </param>
        /// <param name="cloudAnchor">
        /// The cloud anchor to apply.
        /// </param>
        /// <returns>
        /// The <see cref="NativeAnchor"/> created or updated during the
        /// operation.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown if <paramref name="gameObject"/> or <paramref name="cloudAnchor"/>
        /// are <see langword = "null" />.
        /// </exception>
        /// <exception cref="PlatformNotSupportedException">
        /// Thrown if the current platform is not supported by the SDK.
        /// </exception>
        static public NativeAnchor ApplyCloudAnchor(this GameObject gameObject, CloudSpatialAnchor cloudAnchor)
        {
            // Validate
            if (gameObject == null)
            {
                throw new ArgumentNullException(nameof(gameObject));
            }
            if (cloudAnchor == null)
            {
                throw new ArgumentNullException(nameof(cloudAnchor));
            }

            // Placeholder
            NativeAnchor nativeAnchor = null;

            #if WINDOWS_UWP || UNITY_WSA
            // On UWP we can just update the pointer on any existing WorldAnchor.
            // Doing so will also automatically update the objects pose.

            // Find or create the world anchor
            nativeAnchor = gameObject.FindOrCreateNativeAnchor();

            // Update the World Anchor to use the cloud-based native anchor
            nativeAnchor.SetNativeSpatialAnchorPtr(cloudAnchor.LocalAnchor);
            #elif UNITY_IOS || UNITY_ANDROID
            // On iOS and Android we need to remove any existing native anchor,
            // move the object to the new pose, and then re-apply the native anchor.

            // Delete any existing native anchor
            gameObject.DeleteNativeAnchor();

            // Get the pose from the cloud anchor
            Pose pose = cloudAnchor.GetPose();

            // Move the GameObject to match the new pose
            gameObject.transform.position = pose.position;
            gameObject.transform.rotation = pose.rotation;

            // Add the native anchor back on
            nativeAnchor = gameObject.CreateNativeAnchor();
            #else
            throw new PlatformNotSupportedException("Unable to apply the cloud anchor. The platform is not supported.");
#endif
#if UNITY_EDITOR
#pragma warning disable CS0162 // Conditional compile statements prevent reaching this code in the unity editor
#endif
            // Return the created or updated anchor
            return(nativeAnchor);

#if UNITY_EDITOR
#pragma warning restore CS0162
#endif
        }
示例#17
0
 public void SelectAnchor(string anchorIdentifier)
 {
     foreach (CloudSpatialAnchor csa in foundCloudSpatialAnchors)
     {
         if (csa.Identifier.Equals(anchorIdentifier))
         {
             Log.debug($"{csa.Identifier} is being selected");
             currentCloudSpatialAnchor = csa;
             break;
         }
     }
 }
示例#18
0
 // Start is called before the first frame update
 void Start()
 {
     aRRaycastManager          = GetComponent <ARRaycastManager>();
     aRAnchorManager           = GetComponent <ARAnchorManager>();
     indicator                 = Instantiate(placementIndicator);
     currentCloudSpatialAnchor = null;
     aRAnchors                 = new List <ARAnchor>();
     isPlacementValid          = false;
     tryingToUpdate            = false;
     inCreateAnchor            = false;
     movingAnchor              = false;
 }
示例#19
0
    async Task OnCreateCubeAsync()
    {
        var gazeHit = GazeManager.Instance.HitObject;

        if (gazeHit == null)
        {
            return;
        }
        if (gazeHit.layer != SpatialMappingManager.Instance.PhysicsLayer)
        {
            return;
        }

        RaycastHit hitInfo;

        if (!Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hitInfo, 30f))
        {
            return;
        }

        var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);

        cube.transform.localScale = new Vector3(0.1f, 0.1f, 0.1f);

        cube.transform.position = hitInfo.point;

        cube.GetComponent <Renderer>().material = this.cubeMaterial;

        this.cubes.Add(cube);

        //sample code
        //var worldAnchor = cube.AddComponent<WorldAnchor>();
        //var cloudSpatialAnchor = new CloudSpatialAnchor(worldAnchor.GetNativeSpatialAnchorPtr(), false);

        //fixed code
        cube.AddARAnchor();
        var cloudSpatialAnchor = new CloudSpatialAnchor();

        cloudSpatialAnchor.LocalAnchor = cube.GetNativeAnchorPointer();
        cloudSpatialAnchor.Expiration  = DateTimeOffset.Now.AddDays(1);


        await this.WaitForSessionReadyToCreateAsync();

        await this.cloudAnchorSession.CreateAnchorAsync(cloudSpatialAnchor);

        // for Load
        identifiers.Add(cloudSpatialAnchor.Identifier);

        this.logText.text = "local anchor created and " + Environment.NewLine + "cloud anchor created";
        this.msgText.text = "continue to create or clear local cubes or download cloud cubes";
        await this.SayAsync("cloud anchor created");
    }
        private void renderLocatedAnchor(CloudSpatialAnchor anchor)
        {
            AnchorVisual foundVisual = new AnchorVisual(anchor.LocalAnchor);

            foundVisual.SetCloudAnchor(anchor);
            foundVisual.AnchorNode.SetParent(arFragment.ArSceneView.Scene);
            String cloudAnchorIdentifier = foundVisual.CloudAnchor.Identifier;

            foundVisual.SetColor(foundColor);
            foundVisual.Render(arFragment);
            anchorVisuals[cloudAnchorIdentifier] = foundVisual;
        }
示例#21
0
        /// <summary>
        /// Sets the pose of the attached <see cref="GameObject"/>, modifying
        /// native anchors if necessary.
        /// </summary>
        /// <param name="gameObject">
        /// The <see cref="GameObject"/> to set the pose on.
        /// </param>
        /// <param name="position">
        /// The new position to set.
        /// </param>
        /// <param name="rotation">
        /// The new rotation to set.
        /// </param>
        public void SetPose(Vector3 position, Quaternion rotation)
        {
            // Changing the position resets both native and cloud anchors
            cloudAnchor  = null;
            nativeAnchor = null;

            // Use extension method to update position and native anchor
            gameObject.SetPose(position, rotation);

            // Get the native anchor back (if there was one)
            nativeAnchor = gameObject.FindNativeAnchor();
        }
示例#22
0
        /// <summary>
        /// Deletes the specified anchor.
        /// </summary>
        /// <param name="anchor">
        /// The anchor to delete.
        /// </param>
        /// <returns>
        /// A <see cref="Task"/> that represents the operation.
        /// </returns>
        /// <remarks>
        /// If there is no active <see cref="Session"/>, calling this method
        /// will result in an exception.
        /// </remarks>
        public async Task DeleteAnchorAsync(CloudSpatialAnchor anchor)
        {
            // Validate
            if (anchor == null)
            {
                throw new ArgumentNullException(nameof(anchor));
            }
            EnsureSessionStarted();

            // Actually delete
            await session.DeleteAnchorAsync(anchor);
        }
示例#23
0
    private void CreateAndSaveAnchor()
    {
        Log("Creating new anchor...");

        // Just in case clean up any visuals that have been placed.
        CleanupObjects();

        // Raycast to find a hitpoint where the anchor should be placed
        Ray gazeRay = new Ray(Camera.main.transform.position, Camera.main.transform.forward);

        Physics.Raycast(gazeRay, out RaycastHit hitPoint, float.MaxValue);

        // Instantiate the anchor visual Prefab
        _prefabInstance = Instantiate(Prefab, hitPoint.point, Quaternion.identity) as GameObject;
        var localAnchor = _prefabInstance.AddComponent <WorldAnchor>();

        Log("Created local anchor.");

        // Create CloudSpatialAnchor and link the local anchor
        _currentCloudAnchor = new CloudSpatialAnchor
        {
            LocalAnchor = localAnchor.GetNativeSpatialAnchorPtr()
        };

        _ = Task.Run(async() =>
        {
            // Wait for enough spatial data about the environment so the anchor can be relocalized later
            while (_recommendedSpatialDataForUpload < 1.0F)
            {
                Log($"Look around to capture enough anchor data: {_recommendedSpatialDataForUpload:P0}", Color.yellow);
                await Task.Delay(50);
            }

            try
            {
                Log($"Creating and uploading ASA anchor...", Color.yellow);
                await _cloudSpatialAnchorSession.CreateAnchorAsync(_currentCloudAnchor);

                if (_currentCloudAnchor != null)
                {
                    // Allow the user to tap again to clear the state and enter localization mode
                    _wasTapped            = false;
                    _currentCloudAnchorId = _currentCloudAnchor.Identifier;
                    Log($"Saved anchor to Azure Spatial Anchors: {_currentCloudAnchorId}\r\nTap to localize it.", Color.cyan);
                }
            }
            catch (Exception ex)
            {
                Log($"Failed to create ASA anchor: {ex.Message}", Color.red);
            }
        });
    }
        private void HandleAnchorLocated(object sender, AnchorLocatedEventArgs args)
        {
            Debug.Log($"Anchor recognized as a possible Azure anchor");

            if (args.Status == LocateAnchorStatus.Located || args.Status == LocateAnchorStatus.AlreadyTracked)
            {
                currentCloudAnchor = args.Anchor;

                AppDispatcher.Instance().Enqueue(() =>
                {
                    Debug.Log($"Azure anchor located successfully");
                    var indicator = Instantiate(anchorPositionPrefab);

#if WINDOWS_UWP || UNITY_WSA
                    indicator.gameObject.CreateNativeAnchor();

                    if (currentCloudAnchor == null)
                    {
                        return;
                    }
                    Debug.Log("Local anchor position successfully set to Azure anchor position");

                    indicator.GetComponent <UnityEngine.XR.WSA.WorldAnchor>().SetNativeSpatialAnchorPtr(currentCloudAnchor.LocalAnchor);
#elif UNITY_ANDROID || UNITY_IOS
                    Pose anchorPose = Pose.identity;
                    anchorPose      = currentCloudAnchor.GetPose();

                    Debug.Log($"Setting object to anchor pose with position '{anchorPose.position}' and rotation '{anchorPose.rotation}'");
                    indicator.transform.position = anchorPose.position;
                    indicator.transform.rotation = anchorPose.rotation;

                    // Create a native anchor at the location of the object in question
                    indicator.gameObject.CreateNativeAnchor();
#endif

                    indicator.Init(currentTrackedObject);
                    anchorArrowGuide.SetTargetObject(indicator.transform);
                    activeAnchors.Add(currentTrackedObject.SpatialAnchorId, indicator);

                    // Notify subscribers
                    OnFindAnchorSucceeded?.Invoke(this, EventArgs.Empty);
                    currentWatcher?.Stop();
                    currentTrackedObject = null;
                });
            }
            else
            {
                Debug.Log($"Attempt to locate Anchor with ID '{args.Identifier}' failed, locate anchor status was not 'Located' but '{args.Status}'");
            }

            StopAzureSession();
        }
    public async void DeleteAzureAnchor()
    {
        Debug.Log("\nAnchorModuleScript.DeleteAzureAnchor()");

        // Notify AnchorFeedbackScript
        OnDeleteASAAnchor?.Invoke();

        // Delete the Azure anchor with the ID specified off the server and locally
        await cloudManager.DeleteAnchorAsync(currentCloudAnchor);
        currentCloudAnchor = null;

        Debug.Log("Azure anchor deleted successfully");
    }
示例#26
0
        private void Construct(CloudSpatialAnchor cloudSpatialAnchor)
        {
            _cloudNativeAnchor = gameObject.AddComponent <CloudNativeAnchor>();

            // restore existing anchor if cloudSpatialAnchor is not null
            // otherwise it is new one
            if (cloudSpatialAnchor == null)
            {
                return;
            }

            _cloudNativeAnchor.CloudToNative(cloudSpatialAnchor);
        }
示例#27
0
    /// <summary>
    /// Deletes the currently loaded Azure Spatial Anchor. Destroys the slate game object and displays the Litecoin symbol.
    /// </summary>
    public async void DeleteAzureSpatialAnchorAsync()
    {
#if UNITY_EDITOR
        if (IsSlateActive)
        {
            Destroy(GameObject.FindGameObjectWithTag("Slate"));
            IsSlateActive = false;

            // This asynchronous task just prevents a warning due to this method being asynchronous and otherwise lacking an await operator.
            await Task.Delay(300);

            DisplayLitecoinSymbol();
        }

        return;
#else
        if (IsSlateActive && currentCloudAnchor != null)
        {
            Destroy(GameObject.FindGameObjectWithTag("Slate"));
            IsSlateActive = false;

            Instructions.text = $"Deleting Azure Spatial Anchor...\n\nIdentifier: {currentCloudAnchor.Identifier}";
            await Task.Delay(3000);

            try
            {
                await cloudSpatialAnchorSession.DeleteAnchorAsync(currentCloudAnchor);

                Instructions.text = "Azure Spatial Anchor deleted.";
                await Task.Delay(3000);
            }
            catch (Exception ex)
            {
                Instructions.text = $"Error deleting Azure Spatial Anchor.\n\n{ex.Message}";
                await Task.Delay(3000);
            }

            cloudSpatialAnchorId = null;
            currentCloudAnchor   = null;
            PlayerPrefs.SetString("Anchor ID", null);
            DisplayLitecoinSymbol();
        }
        else
        {
            Instructions.text = "No Azure Spatial Anchors exists. Please create an anchor before attempting to delete one.";
            await Task.Delay(3000);

            Instructions.text = "Use the ray coming from either hand to position the Litecoin currency symbol. Air tap to place the symbol. This will be the location where your mining stats will be displayed.\n\nWhen you're ready, turn either hand so that your palm is facing you to access the hand menu. Tap the \"Create Spatial Anchor\" button to save the Azure Spatial Anchor.";
        }
#endif
    }
示例#28
0
        /// <summary>
        /// Creates or updates the <see cref="CloudSpatialAnchor"/> returned by
        /// <see cref="CloudAnchor"/> to reflect the same data as the native anchor.
        /// </summary>
        /// <param name="useExisting">
        /// <c>true</c> to reuse any existing cloud anchor; <c>false</c> to
        /// always create a new one.
        /// </param>
        /// <returns>
        /// A <see cref="Task"/> that represents the operation.
        /// </returns>
        /// <remarks>
        /// <para>
        /// If no native anchor exists on the game object it will be created.
        /// </para>
        /// </remarks>
        public void NativeToCloud(bool useExisting)
        {
            // Make sure there's a native anchor
            if (nativeAnchor == null)
            {
                nativeAnchor = gameObject.FindOrCreateNativeAnchor();
            }

            // If there is no cloud anchor, create it
            if ((!useExisting) || (cloudAnchor == null))
            {
                cloudAnchor = nativeAnchor.ToCloud();
            }
        }
        private void RenderLocatedAnchor(CloudSpatialAnchor anchor)
        {
            AnchorVisual foundVisual = new AnchorVisual(arFragment, anchor.LocalAnchor)
            {
                CloudAnchor = anchor
            };

            foundVisual.AnchorNode.SetParent(this.arFragment.ArSceneView.Scene);
            string cloudAnchorIdentifier = foundVisual.CloudAnchor.Identifier;

            foundVisual.SetColor(this, Color.Red);
            foundVisual.AddToScene(this.arFragment);
            this.anchorVisuals[cloudAnchorIdentifier] = foundVisual;
        }
示例#30
0
        public async Task <CloudSpatialAnchor> StoreAnchorInCloud(CloudSpatialAnchor cloudSpatialAnchor)
        {
            if (SessionStatusIndicators[(int)SessionStatusIndicatorType.ReadyForCreate] < 1)
            {
                return(null);
            }

            await cloudSpatialAnchorSession.CreateAnchorAsync(cloudSpatialAnchor);

            OnAnchorCreatedSuccessfully?.Invoke();
            Debug.Log("Anchor Created Succesfully!");

            return(cloudSpatialAnchor);
        }