Beispiel #1
0
    // Update is called once per frame
    void Update()
    {
        if (m_AppMode == AppMode.WaitingForResolvedReferencePoint)
        {
            OutputText.text = m_AppMode.ToString();

            CloudAnchorState cloudReferenceState =
                m_CloudReferencePoint.cloudAnchorState;
            OutputText.text += " - " + cloudReferenceState.ToString();

            if (cloudReferenceState == CloudAnchorState.Success)
            {
                GameObject cloudAnchor = Instantiate(
                    ResolvedPointPrefab,
                    Vector3.zero,
                    Quaternion.identity);
                cloudAnchor.transform.SetParent(
                    m_CloudReferencePoint.transform, false);
                m_CloudReferencePoint = null;
                j++;
                if (j == paths.Count - 1)
                {
                    m_AppMode = AppMode.FinishApp;
                }
                printScreen(paths[j]);
            }
        }
        if (m_AppMode == AppMode.FinishApp)
        {
            OutputText.text = "Hedefe Ulaştınız!";
        }
    }
Beispiel #2
0
    void HostPending()
    {
        string mappingText = "";

        if (cloudAnchor.cloudAnchorState == CloudAnchorState.Success)
        {
            mappingText = $"클라우드 앵커 생성 성공, CloudAnchor ID = {cloudAnchor.cloudAnchorId}";
            // 앵커ID 저장
            strCloudAnchorId = cloudAnchor.cloudAnchorId;

            // 클라우드 앵커 ID를 공유하는 로직
            // 포톤 네트워크 : RPC호출
            // 파이어베이스  : 데이터 저장
            PlayerPrefs.SetString(cloudAnchorKey, strCloudAnchorId);

            // 초기화
            cloudAnchor = null;
            // 기존에 증강된 객체를 삭제
            Destroy(anchorGameObject);

            mode = Mode.READY;
        }
        else
        {
            mappingText = $"클라우드 앵커 생성 진행중... {cloudAnchor.cloudAnchorState}";
        }

        messageText.text = mappingText;
    }
Beispiel #3
0
    //public async void GetCameraPosition(CameraParameters cameraParams, string image, bool autoCalibrate = false) {
    //    try {
    //        // receive cameraPose from server
    //        IO.Swagger.Model.EstimatedPose cameraEstimatedPose = await WebsocketManager.Instance.GetCameraPose(cameraParams, image, inverse:false);
    //        IO.Swagger.Model.Pose cameraPose = cameraEstimatedPose.Pose;

    //        Vector3 cameraPositionReceived = new Vector3((float) cameraPose.Position.X, (float) cameraPose.Position.Y, (float) cameraPose.Position.Z);
    //        Quaternion cameraRotationReceived = new Quaternion((float) cameraPose.Orientation.X, (float) cameraPose.Orientation.Y,
    //                                                            (float) cameraPose.Orientation.Z, (float) cameraPose.Orientation.W);

    //        //Matrix4x4 cameraMatrix = AdjustMatrixByScreenOrientation(Matrix4x4.TRS(cameraPositionReceived, cameraRotationReceived, Vector3.one));
    //        Matrix4x4 cameraMatrix = Matrix4x4.TRS(cameraPositionReceived, cameraRotationReceived, Vector3.one);

    //        Vector3 cameraPosition = TransformConvertor.OpenCVToUnity(TransformConvertor.GetPositionFromMatrix(cameraMatrix));
    //        Quaternion cameraRotation = TransformConvertor.OpenCVToUnity(TransformConvertor.GetQuaternionFromMatrix(cameraMatrix));


    //        // Transformation Inversion to get Marker Position
    //        cameraMatrix = Matrix4x4.TRS(cameraPosition, cameraRotation, Vector3.one); // create translation, rotation and scaling matrix
    //        Matrix4x4 markerMatrix = cameraMatrix.inverse; // inverse to get marker rotation matrix
    //        markerMatrix.SetColumn(3, Vector4.zero); // set translation column to zeros
    //        Vector3 markerPos = markerMatrix.MultiplyPoint3x4(cameraPosition); // transform cameraPosition by marker matrix
    //        markerPos = -1 * markerPos;

    //        markerMatrix = AdjustMatrixByScreenOrientation(Matrix4x4.TRS(markerPos, TransformConvertor.GetQuaternionFromMatrix(markerMatrix), Vector3.one));

    //        // Marker Position
    //        GameObject marker = Instantiate(MarkerPositionGameObject); // create marker gameobject as child of the camera
    //        marker.transform.localPosition = ARCameraTransformMatrix.MultiplyPoint3x4(TransformConvertor.GetPositionFromMatrix(markerMatrix)); //ARCamera.TransformPoint(markerPos);
    //        marker.transform.localRotation = TransformConvertor.GetQuaternionFromMatrix(ARCameraTransformMatrix) * TransformConvertor.GetQuaternionFromMatrix(markerMatrix); //ARCamera.transform.rotation * Quaternion.LookRotation(markerMatrix.GetColumn(2), markerMatrix.GetColumn(1)); // get quaternion from rotation matrix
    //        marker.transform.localScale = new Vector3(1f, 1f, 1f);

    //        CreateLocalAnchor(marker);

    //        //if (WorldAnchorLocal != null) {
    //        //    // Camera Position
    //        //    GameObject camera = Instantiate(MarkerPositionGameObject, WorldAnchorLocal.transform);
    //        //    camera.transform.localPosition = cameraPosition;
    //        //    camera.transform.localRotation = cameraRotation;
    //        //    camera.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f);
    //        //}

    //        //Notifications.Instance.ShowNotification("Camera position", "GetCameraPose inverse false");

    //        markerDetectionState = MarkerDetectionState.Success;

    //    } catch (RequestFailedException ex) {
    //        markerDetectionState = MarkerDetectionState.Failure;
    //        Debug.Log("No markers visible");
    //        Notifications.Instance.ShowNotification("No markers visible", ex.Message);
    //    }
    //}

    public void CreateLocalAnchor(GameObject marker)
    {
#if (UNITY_ANDROID || UNITY_IOS) && AR_ON
        // remove all old local anchors, if there are some (in case we are recalibrating)
        RemoveLocalWorldAnchor();

        //FeatureMapQuality mapQuality = ARAnchorManager.EstimateFeatureMapQualityForHosting(new UnityEngine.Pose(marker.transform.position, marker.transform.rotation));
        //Debug.Log("FeatureMapQuality: " + mapQuality);
        //Notifications.Instance.ShowNotification("FeatureMapQuality", mapQuality.ToString());

        WorldAnchorLocal = marker.AddComponent <ARAnchor>();
        // immediately attach scene to local anchor (after cloud anchor is created, scene will be attached to it)
        AttachScene(WorldAnchorLocal.gameObject);
        GameManager.Instance.Scene.transform.localEulerAngles = new Vector3(0f, 90f, 90f);

        // Create cloud anchor
        if (Settings.Instance.UseCloudAnchors)
        {
            WorldAnchorCloud = ARAnchorManager.HostCloudAnchor(WorldAnchorLocal);
            StartCoroutine(HostCloudAnchor());
        }
        else
        {
            Calibrated        = true;
            UsingCloudAnchors = false;
            OnARCalibrated?.Invoke(this, new CalibrationEventArgs(true, WorldAnchorLocal.gameObject));
            //Notifications.Instance.ShowNotification("Calibration successful", "");
            worldAnchorVis = null;
            ActivateCalibrationElements((bool)MainSettingsMenu.Instance.CalibrationElements.GetValue());
        }

        GameManager.Instance.SceneSetActive(true);
        ActivateTrackableMarkers(false);
#endif
    }
    public IEnumerator ResolveAnchor()
    {
        check = true;
        ReadFile();
        cloudanchor = anchorManager.ResolveCloudAnchorId(cloudid);


        if (cloudanchor != null)
        {
            pendingcloudanchor.Add(cloudanchor);
            while (true)
            {
                if (cloudanchor.cloudAnchorState == CloudAnchorState.Success)
                {
                    checktext.text = "success";
                    Instantiate(anchorprefeb, cloudanchor.transform);

                    break;
                }
                checktext.text = cloudanchor.cloudAnchorState.ToString();
                yield return(null);
            }
        }
        else
        {
            yield return(new WaitForSeconds(1.0f));

            check = false;
            count++;
            checktext.text = "fail" + count;
        }
    }
Beispiel #5
0
    // Update is called once per frame
    void Update()
    {
        if (m_AppMode == AppMode.TouchToHostCloudReferencePoint)
        {
            OutputText.text = m_AppMode.ToString();

            if (Input.touchCount >= 1 &&
                Input.GetTouch(0).phase == TouchPhase.Began &&
                !EventSystem.current.IsPointerOverGameObject(
                    Input.GetTouch(0).fingerId))
            {
                List <ARRaycastHit> hitResults = new List <ARRaycastHit>();
                RaycastManager.Raycast(Input.GetTouch(0).position, hitResults);
                if (hitResults.Count > 0)
                {
                    Pose pose = hitResults[0].pose;

                    // dokundurulan yerde referans noktası oluşturuyor.
                    ARAnchor referencePoint =
                        AnchorManager.AddAnchor(hitResults[0].pose);

                    // bulut referans noktasını oluşturuyor.
                    m_CloudReferencePoint =
                        AnchorManager.HostCloudAnchor(referencePoint);
                    if (m_CloudReferencePoint == null)
                    {
                        OutputText.text = "Create Failed!";
                        return;
                    }

                    // Wait for the reference point to be ready.
                    m_AppMode = AppMode.WaitingForHostedReferencePoint;
                }
            }
        }
        else if (m_AppMode == AppMode.WaitingForHostedReferencePoint)
        {
            OutputText.text = m_AppMode.ToString();

            CloudAnchorState cloudReferenceState =
                m_CloudReferencePoint.cloudAnchorState;
            OutputText.text += " - " + cloudReferenceState.ToString();

            if (cloudReferenceState == CloudAnchorState.Success)
            {
                GameObject cloudAnchor = Instantiate(
                    HostedPointPrefab,
                    Vector3.zero,
                    Quaternion.identity);
                cloudAnchor.transform.SetParent(
                    m_CloudReferencePoint.transform, false);
                panel.gameObject.SetActive(true);
                m_CloudReferenceId    = m_CloudReferencePoint.cloudAnchorId;
                cloudAnchorId.text    = m_CloudReferenceId;
                m_CloudReferencePoint = null;
                m_AppMode             = AppMode.TouchToHostCloudReferencePoint;
            }
        }
    }
Beispiel #6
0
 /// <summary>
 /// Callback invoked once the Cloud Anchor Id changes.
 /// </summary>
 /// <param name="newId">New Cloud Anchor Id.</param>
 private void _OnChangeId(string newId)
 {
     if (!m_IsHost && newId != string.Empty)
     {
         m_ClouAnchorId  = newId;
         m_ShouldResolve = true;
         m_CloudAnchor   = null;
     }
 }
 /// <summary>
 /// Callback invoked once the Cloud Anchor Id changes.
 /// </summary>
 /// <param name="newId">New Cloud Anchor Id.</param>
 private void OnChangeId(string newId)
 {
     if (!_isHost && newId != string.Empty)
     {
         _clouAnchorId  = newId;
         _shouldResolve = true;
         _cloudAnchor   = null;
     }
 }
        /// <summary>
        /// Waits for the cloud anchor to be created so it can then send it's information to other users
        /// </summary>
        /// <param name="_cloudAnchor">The cloud anchor that is being created</param>
        /// <param name="_hitResult">The location where it was created</param>
        /// <param name="_anchorObjectPrefab">The object that will be attached to the cloud anchor</param>
        /// <param name="_myPostCreateCloudAnchorFunction">The function to call after creating the cloud anchor</param>
        /// <param name="_waitForAllUsersToResolve">Flag indicating to wait or not for all users to resolve before calling the post create function</param>
        /// <param name="_setWorldOrigin">Flag indicating to set this cloud anchor as the world origin or not</param>
        /// <returns>Nothing - just waits until the cloud anchor succeeds or fails</returns>
        public IEnumerator WaitForCloudAnchorToBeCreated(ARCloudAnchor _cloudAnchor, Pose _hitResult, ASLObject _anchorObjectPrefab = null,
                                                         ASLObject.PostCreateCloudAnchorFunction _myPostCreateCloudAnchorFunction   = null,
                                                         bool _waitForAllUsersToResolve = true, bool _setWorldOrigin = true)
        {
            while (_cloudAnchor.cloudAnchorState == CloudAnchorState.TaskInProgress)
            {
                yield return(new WaitForEndOfFrame());
            }

            if (_cloudAnchor.cloudAnchorState == CloudAnchorState.Success)
            {
                //Successful:
                Debug.Log("Successfully Resolved cloud anchor: " + _cloudAnchor.cloudAnchorId + " for object: " + _anchorObjectPrefab?.m_Id);
                if (_anchorObjectPrefab == null)
                {
                    //Uncomment the line below to aid in visual debugging (helps display the cloud anchor)
                    //_anchorObjectPrefab = GameObject.CreatePrimitive(PrimitiveType.Cube).AddComponent<ASLObject>(); //if null, then create empty game object
                    _anchorObjectPrefab = new GameObject().AddComponent <ASLObject>();
                    _anchorObjectPrefab._LocallySetAnchorID(_cloudAnchor.cloudAnchorId); //Add ASLObject component to this anchor and set its anchor id variable

                    _anchorObjectPrefab._LocallySetID(Guid.NewGuid().ToString());        //Locally set the id of this object to a new id

                    //Add this anchor object to our ASL dictionary using the anchor id as its key. All users will do this once they resolve this cloud anchor to ensure they still in sync.
                    ASLHelper.m_ASLObjects.Add(_anchorObjectPrefab.m_Id, _anchorObjectPrefab.GetComponent <ASLObject>());
                    //_anchorObjectPrefab.GetComponent<Material>().color = Color.magenta;
                    _anchorObjectPrefab.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f); //Set scale to be 5 cm
                }
                else
                {
                    _anchorObjectPrefab.GetComponent <ASLObject>()._LocallySetAnchorID(_cloudAnchor.cloudAnchorId); //Set anchor id variable
                    _anchorObjectPrefab.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f);                    //Set scale to be 5 cm
                }
                //Send Resolve packet using _anchorObjectPrefab
                _anchorObjectPrefab.GetComponent <ASLObject>().SendCloudAnchorToResolve(_setWorldOrigin, _waitForAllUsersToResolve);

                Debug.Log("Wait: " + _waitForAllUsersToResolve);

                if (_waitForAllUsersToResolve)
                {
                    byte[]    id      = Encoding.ASCII.GetBytes(_anchorObjectPrefab.m_Id);
                    RTMessage message = GameLiftManager.GetInstance().CreateRTMessage(GameLiftManager.OpCode.ResolvedCloudAnchor, id);
                    GameLiftManager.GetInstance().m_Client.SendMessage(message);

                    _anchorObjectPrefab.StartWaitForAllUsersToResolveCloudAnchor(_cloudAnchor, _setWorldOrigin, _myPostCreateCloudAnchorFunction, _hitResult);
                }
                else //Don't wait for users to know about this cloud anchor
                {
                    _anchorObjectPrefab.GetComponent <ASLObject>()._LocallySetCloudAnchorResolved(true);
                    _anchorObjectPrefab.StartWaitForAllUsersToResolveCloudAnchor(_cloudAnchor, _setWorldOrigin, _myPostCreateCloudAnchorFunction, _hitResult);
                }
            }
            else
            {
                Debug.LogError("Failed to host Cloud Anchor " + _cloudAnchor.name + " " + _cloudAnchor.cloudAnchorState.ToString());
            }
        }
Beispiel #9
0
 void OnResetClick()
 {
     if (anchorGameObject != null)
     {
         Destroy(anchorGameObject);
     }
     cloudAnchor      = null;
     localAnchor      = null;
     messageText.text = "준비 완료";
     mode             = Mode.READY;
 }
Beispiel #10
0
    /// <summary>
    /// Immediately creates local anchor after detected marker intersects detected plane beneath it.
    /// Cloud anchor is created afterwards, but it takes some time. When it is finished, scene will be attached to it.
    /// Called if user clicks on the calibration cube displayed over detected marker.
    /// </summary>
    /// <param name="tf"></param>
    public void CreateAnchor(Transform tf)
    {
#if (UNITY_ANDROID || UNITY_IOS) && AR_ON
        ARPlane          plane   = null;
        UnityEngine.Pose hitPose = new UnityEngine.Pose();

        // try to raycast straight down to intersect closest plane
        List <ARRaycastHit> raycastHits = new List <ARRaycastHit>();
        if (ARRaycastManager.Raycast(new Ray(tf.position, Vector3.down), raycastHits, TrackableType.PlaneWithinPolygon))
        {
            hitPose = raycastHits[0].pose;
            TrackableId hitPlaneId = raycastHits[0].trackableId;
            plane = ARPlaneManager.GetPlane(hitPlaneId);
        }

        // remove all old local anchors, if there are some (in case we are recalibrating)
        RemoveLocalWorldAnchor();
        RemoveCloudWorldAnchor();

        // set temporary world anchor
        //WorldAnchorLocal = ARAnchorManager.AttachAnchor(plane,
        //    new Pose(hitPose.position, Quaternion.FromToRotation(tf.up, plane.normal) * tf.rotation));

        //WorldAnchorLocal = ARAnchorManager.AddAnchor(new UnityEngine.Pose(hitPose != new UnityEngine.Pose() ? hitPose.position : tf.position,
        //    plane != null ? Quaternion.FromToRotation(tf.up, plane.normal) * tf.rotation : tf.rotation));

        WorldAnchorLocal = ARAnchorManager.AddAnchor(new UnityEngine.Pose(tf.position,
                                                                          plane != null ? Quaternion.FromToRotation(tf.up, plane.normal) * tf.rotation : tf.rotation));

        // immediately attach scene to local anchor (after cloud anchor is created, scene will be attached to it)
        AttachScene(WorldAnchorLocal.gameObject);

        // Create cloud anchor
        if (Settings.Instance.UseCloudAnchors)
        {
            WorldAnchorCloud = ARAnchorManager.HostCloudAnchor(WorldAnchorLocal);
            StartCoroutine(HostCloudAnchor());
        }
        else
        {
            Calibrated        = true;
            UsingCloudAnchors = false;
            OnARCalibrated?.Invoke(this, new CalibrationEventArgs(true, WorldAnchorLocal.gameObject));
            Notifications.Instance.ShowNotification("Calibration successful", "");
            worldAnchorVis = null;
            ActivateCalibrationElements((bool)MainSettingsMenu.Instance.CalibrationElements.GetValue());
        }

        GameManager.Instance.SceneSetActive(true);
        ActivateTrackableMarkers(false);
#endif
    }
Beispiel #11
0
    private void OnInputEndEdit(string text)
    {
        m_CloudReferenceId = text;

        m_CloudAnchor = AnchorManager.ResolveCloudAnchorId(text);

        if (m_CloudAnchor == null)
        {
            OutputText.text = "Could not resolve CloudAnchor with ID = " + text;
            return;
        }

        m_AppMode = AppMode.WaitingForResolvedReferencePoint;
    }
    public void Resolve()
    {
        debugtext.text = "Resolve executing";

        cloudanchor = anchormanager.ResolveCloudAnchorId(anchorToResolve);

        if (cloudanchor == null)
        {
            debugtext.text = "Failed to resolve cloud achor id " + cloudanchor.cloudAnchorId;
        }
        else
        {
            anchorHostInProgress = true;
        }
    }
Beispiel #13
0
    public void Resolve()
    {
        //ARDebugManager.Instance.LogInfo("Resolve executing");

        cloudAnchor = arAnchorManager.ResolveCloudAnchorId(anchorToResolve);

        if (cloudAnchor == null)
        {
            // ARDebugManager.Instance.LogError($"Failed to resolve cloud achor id {cloudAnchor.cloudAnchorId}");
        }
        else
        {
            anchorResolveInProgress = true;
        }
    }
Beispiel #14
0
    /// <summary>
    /// Immediately creates local anchor after detected marker intersects detected plane beneath it.
    /// Cloud anchor is created afterwards, but it takes some time. When it is finished, scene will be attached to it.
    /// Called if user clicks on the calibration cube displayed over detected marker.
    /// </summary>
    /// <param name="tf"></param>
    public void CreateAnchor(Transform tf)
    {
#if (UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR
        // try to raycast straight down to intersect closest plane
        List <ARRaycastHit> raycastHits = new List <ARRaycastHit>();
        if (ARRaycastManager.Raycast(new Ray(tf.position, Vector3.down), raycastHits, TrackableType.PlaneWithinPolygon))
        {
            // remove all old local anchors, if there are some (in case we are recalibrating)
            RemoveLocalWorldAnchor();
            RemoveCloudWorldAnchor();

            Pose        hitPose    = raycastHits[0].pose;
            TrackableId hitPlaneId = raycastHits[0].trackableId;
            ARPlane     plane      = ARPlaneManager.GetPlane(hitPlaneId);

            // set temporary world anchor
            WorldAnchorLocal = ARAnchorManager.AttachAnchor(plane,
                                                            new Pose(hitPose.position, Quaternion.FromToRotation(tf.up, plane.normal) * tf.rotation));
            // immediately attach scene to local anchor (after cloud anchor is created, scene will be attached to it)
            AttachScene(WorldAnchorLocal.gameObject);

            // Create cloud anchor
            if (Settings.Instance.UseCloudAnchors)
            {
                WorldAnchorCloud = ARAnchorManager.HostCloudAnchor(WorldAnchorLocal);

                StartCoroutine(HostCloudAnchor());
            }
            else
            {
                Calibrated     = true;
                worldAnchorVis = null;
                ActivateCalibrationElements(ControlBoxManager.Instance.CalibrationElementsToggle.isOn);
            }

            GameManager.Instance.Scene.SetActive(true);

            ActivateTrackableMarkers(false);
        }
        // if there is no plane beneath detected marker then display notification about unsufficient tracking
        else
        {
            Notifications.Instance.ShowNotification("Calibration error", "Plane beneath calibration marker is not detected");
            //Play animation for moving with the device
            TrackingLostAnimation.PlayVideo(5f);
        }
#endif
    }
    public void onPlaceOrigin()
    {
        if (Input.touchCount > 0 && Input.touches[0].phase == TouchPhase.Began)
        {
            List <ARRaycastHit> hitResults = new List <ARRaycastHit>();
            raycastManager.Raycast(Input.touches[0].position, hitResults);

            if (hitResults.Count > 0)
            {
                CmdChangeGameState(GameState.States.WaitingForOriginRegistration);

                ARAnchor localAnchor = anchorManager.AddAnchor(hitResults[0].pose);
                origin = anchorManager.HostCloudAnchor(localAnchor);
            }
        }
    }
Beispiel #16
0
    private void printScreen(Node key)
    {
        m_CloudReferenceId = string.Empty;

        m_CloudReferencePoint =
            AnchorManager.ResolveCloudAnchorId(key.cloudAnchorId);
        if (m_CloudReferencePoint == null)
        {
            OutputText.text = "Resolve Failed!";
            printScreen(key);
            return;
        }

        // Wait for the reference point to be ready.
        m_AppMode = AppMode.WaitingForResolvedReferencePoint;
    }
Beispiel #17
0
    private void OnInputEndEdit(string text)
    {
        m_CloudReferenceId = string.Empty;

        m_CloudReferencePoint =
            AnchorManager.ResolveCloudAnchorId(text);
        if (m_CloudReferencePoint == null)
        {
            OutputText.text = "Resolve Failed!";
            m_AppMode       = AppMode.TouchToHostCloudReferencePoint;
            return;
        }

        // Wait for the reference point to be ready.
        m_AppMode = AppMode.WaitingForResolvedReferencePoint;
    }
    public void HostAnchor()
    {
        debugtext.text = "HostAnchor executing";


        FeatureMapQuality quality = anchormanager.EstimateFeatureMapQualityForHosting(GetCameraPose());

        cloudanchor = anchormanager.HostCloudAnchor(pendingHostAnchor, 1);

        if (cloudanchor == null)
        {
            debugtext.text = "Unable to host cloud anchor";
        }
        else
        {
            anchorHostInProgress = true;
        }
    }
Beispiel #19
0
 /// <summary>
 /// Resolves the Cloud Anchor Id and instantiate a Cloud Anchor on it.
 /// </summary>
 /// <param name="cloudAnchorId">The Cloud Anchor Id to be resolved.</param>
 private void ResolveCloudAnchorId(string cloudAnchorId)
 {
     _cloudAnchorsExampleController.OnAnchorInstantiated(false);
     _cloudAnchor = _anchorManager.ResolveCloudAnchorId(cloudAnchorId);
     if (_cloudAnchor == null)
     {
         Debug.LogErrorFormat("Client could not resolve Cloud Anchor {0}.", cloudAnchorId);
         _cloudAnchorsExampleController.OnAnchorResolved(
             false, "Client could not resolve Cloud Anchor.");
         _shouldResolve     = true;
         _shouldUpdatePoint = false;
     }
     else
     {
         _shouldResolve     = false;
         _shouldUpdatePoint = true;
     }
 }
Beispiel #20
0
    public void HostAnchor()
    {
        //ARDebugManager.Instance.LogInfo($"HostAnchor executing");

        FeatureMapQuality quality =
            arAnchorManager.EstimateFeatureMapQualityForHosting(GetCameraPose());

        cloudAnchor = arAnchorManager.HostCloudAnchor(pendingHostAnchor, 1);

        if (cloudAnchor == null)
        {
            // ARDebugManager.Instance.LogError("Unable to host cloud anchor");
        }
        else
        {
            anchorUpdateInProgress = true;
        }
    }
    private bool LoadCloudAnchor()
    {
        string cloudAnchorId = PlayerPrefs.GetString("cloud_anchor_id");

        if (cloudAnchorId != null)
        {
            WorldAnchorCloud = ARAnchorManager.ResolveCloudAnchorId(cloudAnchorId);

            if (WorldAnchorCloud == null)
            {
                Notifications.Instance.ShowNotification("Cloud anchor fail", "Cloud anchor couldn't be loaded");
                Debug.Log("Cloud anchor fail: Cloud anchor couldn't be loaded " + cloudAnchorId);
                return(false);
            }

            return(true);
        }
        return(false);
    }
Beispiel #22
0
        /// <summary>
        /// Creates an ARCore Cloud Anchor at the location the user tapped and passed into it. This function can be used to set the world origin or just a normal cloud anchor.
        /// It is advisable to only have 1 user in your application set cloud anchors.
        /// </summary>
        /// <param name="_hitResults">Holds information about where the user tapped on the screen. This variable should be created using the ARWorldOriginHelper Raycast method </param>
        /// <param name="_anchorObjectPrefab">The ASL object you want to have located at the cloud anchor. If you don't want any object to be located at the cloud anchor, you can pass in null.
        /// Doing so will create an empty gameobject - thus making it invisible to users</param>
        /// <param name="_myPostCreateCloudAnchorFunction">This is the function you want to call after a cloud anchor has successfully been created. Only the user that called this function
        /// will execute this function - it is not sent to other users. This is a good way to move or create objects after a cloud anchor has been created.</param>
        /// <param name="_waitForAllUsersToResolve">This determines if users should wait to setup (and if they are the caller of this function, to execute the _myPostCreateCloudAnchorFunction)
        /// the cloud anchor once they receive and find it, or if they should wait for all users to receive and find it first before executing anything. The default is to wait for all users
        /// and is the suggested value as not waiting as the potential to cause synchronization problems.</param>
        /// <param name="_setWorldOrigin">This determines if this cloud anchor should be used to set the world origin for all users or not. If you are setting the world origin, you should do
        /// so right away in your app and as the first (if you have more than 1) cloud anchor created. You should never set the world origin more than once.</param>
        public static void CreateARCoreCloudAnchor(Pose?_hitResults, ASLObject _anchorObjectPrefab = null, ASLObject.PostCreateCloudAnchorFunction _myPostCreateCloudAnchorFunction = null,
                                                   bool _waitForAllUsersToResolve = true, bool _setWorldOrigin = true)
        {
#if UNITY_ANDROID || UNITY_IOS
            if (m_ARCloudAnchor != null)
            {
                Debug.LogError("You can only resolve 1 Cloud Anchor at a time. " + m_ARCloudAnchor.name + " is currently being resolved...");
                return;
            }
            if (_anchorObjectPrefab != null)
            {
                if (!_anchorObjectPrefab.m_Mine)
                {
                    Debug.LogError("You must claim the ASL object before setting it as an anchor");
                    return;
                }
            }
            Debug.Log("Creating the cloud anchor now...");

            //Create local anchor at hit location
            ARAnchor localAnchor = ARWorldOriginHelper.GetInstance().m_ARAnchorManager.AddAnchor((Pose)_hitResults);
            localAnchor.name = "Local anchor created when creating cloud anchor";

            //Create CLoud anchor
            m_ARCloudAnchor = ARWorldOriginHelper.GetInstance().m_ARAnchorManager.HostCloudAnchor(localAnchor);

            if (m_ARCloudAnchor == null)
            {
                Debug.LogError("Failed to create a cloud anchor.");
                return;
            }

            ARWorldOriginHelper.GetInstance().StartCoroutine(ARWorldOriginHelper.GetInstance().WaitForCloudAnchorToBeCreated(m_ARCloudAnchor, (Pose)_hitResults,
                                                                                                                             _anchorObjectPrefab, _myPostCreateCloudAnchorFunction,
                                                                                                                             _waitForAllUsersToResolve, _setWorldOrigin));

            //Reset
            m_ARCloudAnchor = null;
#else
            Debug.LogError("Can only create cloud anchors on mobile devices.");
#endif
        }
Beispiel #23
0
        /// <summary>
        /// Hosts the user placed cloud anchor and associates the resulting Id with this object.
        /// </summary>
        /// <param name="anchor">The last placed anchor.</param>
        public void HostAnchor(ARAnchor anchor)
        {
            _isHost        = true;
            _shouldResolve = false;
            transform.SetParent(anchor.transform);
            _anchorMesh.SetActive(true);

            _cloudAnchor = _anchorManager.HostCloudAnchor(anchor);
            if (_cloudAnchor == null)
            {
                Debug.LogError("Failed to add Cloud Anchor.");
                _cloudAnchorsExampleController.OnAnchorHosted(
                    false, "Failed to add Cloud Anchor.");
                _shouldUpdatePoint = false;
            }
            else
            {
                _shouldUpdatePoint = true;
            }
        }
    public void onOriginRegistered()
    {
        if (this.origin == null)
        {
            origin = anchorManager.ResolveCloudAnchorId(gameState.originId);
        }
        else if (this.origin.cloudAnchorState == CloudAnchorState.Success)
        {
            Vector3 localCameraPos = origin.transform.InverseTransformPoint(playerCamera.transform.position);
            Vector3 localCameraRot = origin.transform.InverseTransformDirection(playerCamera.transform.rotation.eulerAngles);

            CmdInstantiateInOriginSpace(localCameraPos, localCameraRot);
        }
        else if (this.origin.cloudAnchorState != CloudAnchorState.TaskInProgress)
        {
            Debug.Log("Had trouble resolving the origin: " + this.origin.cloudAnchorState.ToString());
            Debug.Log("Trying again...");
            this.origin = null;
        }
    }
        private void ResolvingCloudAnchors()
        {
            // No Cloud Anchor for resolving.
            if (Controller.ResolvingSet.Count == 0)
            {
                return;
            }

            // There are pending or finished resolving tasks.
            if (_pendingCloudAnchors.Count > 0 || _cachedCloudAnchors.Count > 0)
            {
                return;
            }

            // ARCore session is not ready for resolving.
            if (ARSession.state != ARSessionState.SessionTracking)
            {
                return;
            }

            Debug.LogFormat("Attempting to resolve {0} Cloud Anchor(s): {1}",
                            Controller.ResolvingSet.Count,
                            string.Join(",", new List <string>(Controller.ResolvingSet).ToArray()));
            foreach (string cloudId in Controller.ResolvingSet)
            {
                ARCloudAnchor cloudAnchor =
                    Controller.AnchorManager.ResolveCloudAnchorId(cloudId);
                if (cloudAnchor == null)
                {
                    Debug.LogFormat("Faild to resolve Cloud Anchor " + cloudId);
                    OnAnchorResolvedFinished(false, cloudId);
                }
                else
                {
                    _pendingCloudAnchors.Add(cloudAnchor);
                }
            }

            Controller.ResolvingSet.Clear();
        }
Beispiel #26
0
    // 클라우드 앵커 등록
    void HostProcessing()
    {
        // 로컬 앵커가 생성되지 않았을 때 리턴
        if (localAnchor == null)
        {
            return;
        }

        // 피쳐 포인트의 갯수 많을 수록 맵핑 퀄리티가 증가함.

        /*
         *  Insufficient = 0 // 불충분
         *  Sufficient   = 1 // 충분
         *  Good         = 2 // Good
         */
        FeatureMapQuality quality
            = anchorManager.EstimateFeatureMapQualityForHosting(GetCameraPose());

        string mappingText = string.Format("맵핑 품질 = {0}", quality);

        // 맵핑 퀄리티가 1이상일 때 호스팅 요청
        if (quality == FeatureMapQuality.Sufficient || quality == FeatureMapQuality.Good)
        {
            // Google Cloud Anchor API를 사용해 업로드(클라우드 앵커의 생성을 요청)
            cloudAnchor = anchorManager.HostCloudAnchor(localAnchor, 1);

            if (cloudAnchor == null)
            {
                mappingText = "클라우드 앵커 생성 실패";
            }
            else
            {
                mappingText = "클라우드 앵커 생성 시작";
                mode        = Mode.HOST_PENDING;
            }
        }

        messageText.text = mappingText;
    }
    public IEnumerator ParasiteCloud()
    {
        check = true;

        yield return(new WaitForSeconds(5));

        cloudanchor = anchorManager.HostCloudAnchor(anchor);


        if (cloudanchor != null)
        {
            Instantiate(anchorprefeb, cloudanchor.transform);
            StartCoroutine(CloudState());
            pendingcloudanchor.Add(cloudanchor);
        }
        else
        {
            checktext.text = "실패 : " + count;
        }



        check = false;
    }
Beispiel #28
0
    async void spawnCubeAtAnchorWithId(string id)
    {
        await Task.Run(() =>
        {
            ARCloudAnchor anchor = anchorManager.ResolveCloudAnchorId(id);

            while (anchor.cloudAnchorState == CloudAnchorState.TaskInProgress)
            {
            }                                                                   //Pause until the client gets a response from the cloud anchor service

            if (anchor.cloudAnchorState == CloudAnchorState.Success)
            {
                // Spawn a cube at the location of the cloud anchor
                GameObject newCube = Instantiate(cube, Vector3.zero, Quaternion.identity);
                newCube.transform.SetParent(anchor.transform, false);

                Debug.Log("Successfully instantiated cube at cloud anchor with id: " + id);
            }
            else
            {
                Debug.LogError("Failed to resolve cloud anchor with error: " + anchor.cloudAnchorState);
            }
        });
    }
Beispiel #29
0
    void Resolving()
    {
        if (PlayerPrefs.HasKey(cloudAnchorKey) == false)
        {
            return;
        }

        messageText.text = "";
        // 클라우드 앵커 ID 받아옴. (포톤, 파이어베이스)
        strCloudAnchorId = PlayerPrefs.GetString(cloudAnchorKey);

        // 클라우드 앵커 ID로 CloudAnchor 로드
        cloudAnchor = anchorManager.ResolveCloudAnchorId(strCloudAnchorId);

        if (cloudAnchor == null)
        {
            messageText.text = "클라우드 앵커 리졸브 실패";
        }
        else
        {
            messageText.text = $"클라우드 앵커 리졸브 성공 : {cloudAnchor.cloudAnchorId}";
            mode             = Mode.RESOLVE_PENDING;
        }
    }
        private void HostingCloudAnchor()
        {
            // There is no anchor for hosting.
            if (_anchor == null)
            {
                return;
            }

            // There is a pending or finished hosting task.
            if (_cachedCloudAnchors.Count > 0 || _pendingCloudAnchors.Count > 0)
            {
                return;
            }

            // Update map quality:
            int qualityState = 2;
            // Can pass in ANY valid camera pose to the mapping quality API.
            // Ideally, the pose should represent users’ expected perspectives.
            FeatureMapQuality quality =
                Controller.AnchorManager.EstimateFeatureMapQualityForHosting(GetCameraPose());

            DebugText.text = "Current mapping quality: " + quality;
            qualityState   = (int)quality;
            _qualityIndicator.UpdateQualityState(qualityState);

            // Hosting instructions:
            var cameraDist = (_qualityIndicator.transform.position -
                              Controller.MainCamera.transform.position).magnitude;

            if (cameraDist < _qualityIndicator.Radius * 1.5f)
            {
                InstructionText.text = "You are too close, move backward.";
                return;
            }
            else if (cameraDist > 10.0f)
            {
                InstructionText.text = "You are too far, come closer.";
                return;
            }
            else if (_qualityIndicator.ReachTopviewAngle)
            {
                InstructionText.text =
                    "You are looking from the top view, move around from all sides.";
                return;
            }
            else if (!_qualityIndicator.ReachQualityThreshold)
            {
                InstructionText.text = "Save the object here by capturing it from all sides.";
                return;
            }

            // Start hosting:
            InstructionText.text = "Processing...";
            DebugText.text       = "Mapping quality has reached sufficient threshold, " +
                                   "creating Cloud Anchor.";
            DebugText.text = string.Format(
                "FeatureMapQuality has reached {0}, triggering CreateCloudAnchor.",
                Controller.AnchorManager.EstimateFeatureMapQualityForHosting(GetCameraPose()));

            // Creating a Cloud Anchor with lifetime = 1 day.
            // This is configurable up to 365 days when keyless authentication is used.
            ARCloudAnchor cloudAnchor = Controller.AnchorManager.HostCloudAnchor(_anchor, 1);

            if (cloudAnchor == null)
            {
                Debug.LogFormat("Failed to create a Cloud Anchor.");
                OnAnchorHostedFinished(false);
            }
            else
            {
                _pendingCloudAnchors.Add(cloudAnchor);
            }
        }