Пример #1
0
        public static bool FindCliBinaryPath(out string path)
        {
            string binaryName;

            if (m_ARAugImageDatabaseType == AREnginesType.HUAWEI_AR_ENGINE)
            {
                binaryName = UtilConstants.HWAugmentedImageCliBinaryName;
            }
            else
            {
                Debug.LogWarning("Wrong AREngine Type" + m_ARAugImageDatabaseType);
                path = string.Empty;
                return(false);
            }

            string[] cliBinaryGuid = AssetDatabase.FindAssets(binaryName);
            if (cliBinaryGuid.Length == 0)
            {
                ARDebug.LogInfo("Could not find required tool for building AugmentedImageDatabase: {0}. " +
                                "Was it removed from the SDK?", binaryName);
                path = string.Empty;
                return(false);
            }

            // Remove the '/Assets' from the project path since it will be added in the path below.
            string projectPath = Application.dataPath.Substring(0, Application.dataPath.Length - 6);

            path = Path.Combine(projectPath, AssetDatabase.GUIDToAssetPath(cliBinaryGuid[0]));
            return(!string.IsNullOrEmpty(path));
        }
Пример #2
0
        /// <summary>
        /// Unity Awake.
        /// </summary>
        public void Awake()
        {
            if (Application.isEditor)
            {
                enabled = false;
                return;
            }

            if (FindObjectsOfType <ARCoreSession>().Length > 1)
            {
                ARDebug.LogError("Multiple SessionComponents present in the game scene.  Destroying the gameobject " +
                                 "of the newest one.");
                Destroy(gameObject);
                return;
            }

            m_SessionManager = SessionManager.CreateSession();
            Session.Initialize(m_SessionManager);

            if (Session.ConnectionState != SessionConnectionState.Uninitialized)
            {
                ARDebug.LogError("Could not create an ARCore session.  The current Unity Editor may not support this " +
                                 "version of ARCore.");
                return;
            }

            if (ConnectOnAwake)
            {
                Connect();
            }
        }
Пример #3
0
    void ShowObject(GameObject obj)
    {
        if (!imageTracker.activeSelf)
        {
            imageTracker.SetActive(true);
        }

        if (currentObj == null || currentObj != obj)
        {
            currentObj = obj;

            BaiduARImageTrackable trackable = obj.GetComponent <BaiduARImageTrackable>();
            trackable.gameObject.SetActive(true);

            anim  = obj.GetComponent <Animator>();
            clips = obj.GetComponent <BaiduARImageTrackable>().clips;

            currentIndex = 0;
            if (audioSource.isPlaying)
            {
                audioSource.Stop();
            }

            ARDebug.Log("trackable.filePath: " + trackable.filePath);
            ARImageTracker.Instance.SetActiveTrack(trackable.filePath);
        }
    }
        public async Task <IActionResult> Remove(int id)
        {
            return(await Task.Run(() =>
            {
                try
                {
                    Warehouse wh = Warehouse.GetWarehouse(id);

                    if (wh == null)
                    {
                        ARDebug.Log("Warehouse with given ID not found. ID: " + id);
                        return StatusCode(500);
                    }
                    else
                    {
                        wh.DBRemove();
                        return Ok();
                    }
                }
                catch (Exception ex)
                {
                    ARDebug.Log(ex.ToString());
                    return StatusCode(500);
                }
            }));
        }
Пример #5
0
        private void trackTest(Touch touch)
        {
            List <ARHitResult> hitResults = ARFrame.HitTest(touch);

            foreach (ARHitResult singleHit in hitResults)
            {
                ARTrackable trackable = singleHit.GetTrackable();
                if ((trackable is ARPlane && ((ARPlane)trackable).IsPoseInPolygon(singleHit.HitPose)) ||
                    (trackable is ARPoint))
                {
                    ARAnchor anchor = singleHit.CreateAnchor();
                    ARDebug.LogInfo("GridARScript:trackTest anchor world position {0}", anchor.GetPose().position);
                    Vector3 screenPos = Camera.main.WorldToScreenPoint(anchor.GetPose().position);
                    ARDebug.LogInfo("GridARScript:trackTest anchor screen position {0}", screenPos);


                    if (m_touchIndex % 2 == 0)
                    {
                        m_touchBeginModel.GetComponent <disToolLogoVisualizer>().setAnchor(anchor);

                        var script = m_grid.GetComponent <GridARScpript>();
                        if (script)
                        {
                            script.setBeginAnchor(anchor);
                        }
                    }
                    else
                    {
                        m_touchEndModel.GetComponent <disToolLogoVisualizer>().setAnchor(anchor);
                    }
                    ++m_touchIndex;
                    break;
                }
            }
        }
        private void _Connect()
        {
            ARDebug.LogInfo("_connect begin");
            const string ANDROID_CAMERA_PERMISSION_NAME = "android.permission.CAMERA";

            if (AndroidPermissionsRequest.IsPermissionGranted(ANDROID_CAMERA_PERMISSION_NAME))
            {
                _ConnectToService();
                return;
            }
            var permissionsArray = new string[] { ANDROID_CAMERA_PERMISSION_NAME };

            AndroidPermissionsRequest.RequestPermission(permissionsArray).ThenAction((requestResult) =>
            {
                if (requestResult.IsAllGranted)
                {
                    _ConnectToService();
                }
                else
                {
                    ARDebug.LogError("connection failed because a needed permission was rejected.");
                    errorMessage = "This app require camera permission";
                    Log();
                    Invoke("_DoQuit", 0.5f);
                    return;
                }
            });
        }
 public void OnApplicationPause(bool isPaused)
 {
     if (isPaused)
     {
         ARSession.Pause();
     }
     else
     {
         if (!isSessionCreated)
         {
             Init();
         }
         if (isErrorHappendWhenInit)
         {
             return;
         }
         try
         {
             ARSession.Resume();
         }
         catch (ARCameraPermissionDeniedException e)
         {
             ARDebug.LogError("camera permission is denied");
             errorMessage = "This app require camera permission";
             Log();
             Invoke("_DoQuit", 0.5f);
         }
     }
 }
Пример #8
0
        private void _CreateWorld(Touch touch)
        {
            List <ARHitResult> hitResults = ARFrame.HitTest(touch);

            ARDebug.LogInfo("_DrawARLogo hitResults count {0}", hitResults.Count);
            foreach (ARHitResult singleHit in hitResults)
            {
                ARTrackable trackable = singleHit.GetTrackable();
                ARDebug.LogInfo("_DrawARLogo GetTrackable {0}", singleHit.GetTrackable());
                if (trackable is ARPlane && ((ARPlane)trackable).IsPoseInPolygon(singleHit.HitPose) ||
                    trackable is ARPoint)
                {
                    ARAnchor anchor = singleHit.CreateAnchor();

                    Vector3 anchorPosition = anchor.GetPose().position;

                    if (world)
                    {
                        world.transform.position = anchorPosition;
                    }
                    else
                    {
                        world = Instantiate(worldPrefab, anchorPosition, Quaternion.identity);
                    }
                    break;
                }
            }
        }
 public void OnApplicationPause(bool pause)
 {
     if (pause == true)
     {
         ARDebug.LogInfo("OnApplicationPause false, HelloARController _RemoveAnchorGameObject");
     }
 }
Пример #10
0
    //解析
    private ErrorInfo CreateFromJson(string json)
    {
        ErrorInfo info = JsonUtility.FromJson <ErrorInfo>(json);

        ARDebug.Log("error_code:" + info.error_code + " " + "error_msg:" + info.error_msg);
        return(info);
    }
Пример #11
0
        public void Connect_NoPermission(ARCoreSessionConfig sessionConfig)
        {
            if (m_SessionManager == null)
            {
                ARDebug.LogError("Cannot connect because ARCoreSession failed to initialize.");
            }

            if (sessionConfig == null)
            {
                ARDebug.LogError("Unable to connect ARSession session due to missing ARSessionConfig.");
                m_SessionManager.ConnectionState = SessionConnectionState.MissingConfiguration;
            }

            // We have already connected at least once.
            if (Session.ConnectionState != SessionConnectionState.Uninitialized)
            {
                ARDebug.LogError("Multiple attempts to connect to the ARSession.  Note that the ARSession connection " +
                                 "spans the lifetime of the application and cannot be reconfigured.  This will change in future " +
                                 "versions of ARCore.");
            }

            // Create an asynchronous task for the potential permissions flow and service connection.
            Action <SessionConnectionState> onTaskComplete;
            var returnTask = new AsyncTask <SessionConnectionState>(out onTaskComplete);

            returnTask.ThenAction((connectionState) =>
            {
                m_SessionManager.ConnectionState = connectionState;
            });

            _ResumeSession(sessionConfig, onTaskComplete);
        }
Пример #12
0
    // Use this for initialization
    void Start()
    {
        //ARLogin.Instance.OnStopCamera.AddListener (ErrorInfo);
        loading.SetActive(true);

        _sureButton.onClick.AddListener(ErrorOnClick);

        _cameraDevice = FindObjectOfType <BaiduARWebCamera>();
        Transform bg = transform.Find("ResetButton");

        if (bg != null)
        {
            resetBtn     = bg.GetComponent <RectTransform>();
            _resetButton = bg.GetComponent <Button>();
            _resetButton.onClick.AddListener(ResetOnClick);
            _arObjectTrackle = GameObject.FindObjectOfType <BaiduARObjectTrackable>();
        }

        int adjustHeight = 0;

        ARDebug.Log("SystemInfo.deviceModel = " + SystemInfo.deviceModel);

        ARDebug.Log("SystemInfo.nam = " + SystemInfo.deviceName);
        if (ARUtils.IsIPhoneX())
        {
            adjustHeight = 100;
        }

        if (null != resetBtn)
        {
            resetBtn.anchoredPosition3D = new Vector3(resetBtn.anchoredPosition3D.x, resetBtn.anchoredPosition3D.y + 2 * adjustHeight, resetBtn.anchoredPosition3D.z);
        }
        ;
    }
Пример #13
0
        /// <summary>
        /// Connects to the ARCore service.
        /// </summary>
        /// <param name="sessionConfig">The session configuration to connect with.</param>
        /// <param name="onComplete">A callback for when the result of the connection attempt is known.</param>
        private void _ResumeSession(ARCoreSessionConfig sessionConfig, Action <SessionConnectionState> onComplete)
        {
            if (!m_SessionManager.CheckSupported(sessionConfig))
            {
                ARDebug.LogError("The requested ARCore session configuration is not supported.");
                onComplete(SessionConnectionState.InvalidConfiguration);
                return;
            }

            if (!m_SessionManager.SetConfiguration(sessionConfig))
            {
                ARDebug.LogError("ARCore connection failed because the current configuration is not supported.");
                onComplete(SessionConnectionState.InvalidConfiguration);
                return;
            }

            Frame.Initialize(m_SessionManager.FrameManager);

            // ArSession_resume needs to be called in the UI thread due to b/69682628.
            AsyncTask.PerformActionInUIThread(() =>
            {
                if (!m_SessionManager.Resume())
                {
                    onComplete(SessionConnectionState.ConnectToServiceFailed);
                }
                else
                {
                    onComplete(SessionConnectionState.Connected);
                }
            });
        }
 private void LogError(ArCameraMetadataType requestedType)
 {
     ARDebug.LogErrorFormat(
         "Error getting value from CameraMetadataType due to type mismatch. " +
         "requested type = {0}, internal type = {1}\n" +
         "Are you sure you are querying the correct type?", requestedType, _type);
 }
Пример #15
0
    private void _ResumeSession(ARCoreSessionConfig sessionConfig, Action <SessionConnectionState> onComplete)
    {
        if (!m_SessionManager.CheckSupported(sessionConfig))
        {
            ARDebug.LogError("The requested ARCore session configuration is not supported.");
            onComplete(SessionConnectionState.InvalidConfiguration);
            return;
        }

        if (!m_SessionManager.SetConfiguration(sessionConfig))
        {
            ARDebug.LogError("ARCore connection failed because the current configuration is not supported.");
            onComplete(SessionConnectionState.InvalidConfiguration);
            return;
        }

        Frame.Initialize(m_SessionManager.FrameManager);

        if (!m_SessionManager.Resume(sessionConfig))
        {
            onComplete(SessionConnectionState.ConnectToServiceFailed);
        }
        else
        {
            onComplete(SessionConnectionState.Connected);
        }
    }
Пример #16
0
    // Use this for initialization
    void Start()
    {
        gestureRecog = gameObject.GetComponent <BaiduARGestureRecog> ();
        particle     = particleObj.transform.GetComponent <ParticleSystem> ();

        if (isStartHandTracking)
        {
            var main = particle.main;
            main.loop = true;

            //System.Type type = particle.main.GetType ();
            //PropertyInfo property = type.GetProperty ("loop");
            //property.SetValue (particle.main, true, null);
        }

        //手势识别
        gestureRecog.OnResultCallBack((bool result) => {
            if (!isStartHandTracking)
            {
                ShowObject(result);
            }
        });

        //实验室功能 手势跟踪
        gestureRecog.OnResultTrackCallBack((List <RecogGesture> lstRecg) => {
            ARDebug.Log("lstRecg.Count; " + lstRecg.Count);
            //recogList = lstRecg;
            if (isStartHandTracking)
            {
                MoveObject(lstRecg);
            }
        });
    }
Пример #17
0
    // Use this for initialization
    void Start()
    {
        results = GameObject.FindObjectsOfType <BaiduARImageRecognitionResult>();

        BaiduARImageTracker tracker = imageTracker.GetComponent <BaiduARImageTracker>();

        for (int i = 0; i < results.Length; i++)
        {
            for (int j = 0; j < imageTracker.transform.childCount; j++)
            {
                GameObject            obj       = imageTracker.transform.GetChild(j).gameObject;
                BaiduARImageTrackable trackable = obj.GetComponent <BaiduARImageTrackable>();

                if (results[i].filePath.Contains(trackable.filePath))
                {
                    ARDebug.Log("trackable object: " + trackable.name);
                    results[i].OnRespond.AddListener(
                        delegate()
                    {
                        this.ShowObject(trackable.gameObject);
                    });
                    break;
                }
            }
        }
        tracker.OnTrackFail.AddListener(OutFocus);
        ARDebug.Log("imageTracker.transform.childCount: " + imageTracker.transform.childCount);
    }
Пример #18
0
        private void BuildHWDatabase(string cliBinaryPath, out string error)
        {
            string output;

            error = null;
            var tempDirectoryPath = FileUtil.GetUniqueTempPathInProject();

            Directory.CreateDirectory(tempDirectoryPath);
            var rawDatabasePath = Path.Combine(tempDirectoryPath, "HwDatabase.bin");

            for (int i = 0; i < m_Images.Count; i++)
            {
                var imagePath = AssetDatabase.GetAssetPath(m_Images[i].Texture);
                ShellHelper.RunCommand(cliBinaryPath,
                                       string.Format("add-img --input_image_path {0} --input_database_path {1}",
                                                     imagePath, rawDatabasePath), out output, out error);
            }
            if (!string.IsNullOrEmpty(error))
            {
                ARDebug.LogInfo("RunCommand err" + error);
                return;
            }

            m_RawData = File.ReadAllBytes(rawDatabasePath);
        }
Пример #19
0
        /// <summary>
        /// 双掌向前推,左手
        /// </summary>
        /// <returns><c>true</c>, if in waist was fisted, <c>false</c> otherwise.</returns>
        public static bool fistFrontToLeft(Vector3 Wrist, Vector3 elbow, Vector3 shoulder, Vector3 lHip)
        {
            int yAdjust = (int)(lengthShoulder / 2);

            if ((shoulder.y - elbow.y) > yAdjust)
            {
                ARDebug.Log("RistL is too back");
                return(false);
            }

            //判断左手向外插
            if (LeftHandToExtern(Wrist, elbow, shoulder))
            {
                return(false);
            }
            float lLength = shoulder.y - lHip.y;

            if ((Wrist.y - lHip.y) < lLength / 2)
            {
                ARDebug.Log("Mydatasl Wrist 太低");
                return(false);
            }
            if ((elbow.y - lHip.y) < lLength / 1.7)
            {
                ARDebug.Log("Mydatasl elbow 太低");
                return(false);
            }
            int disAdjust = (int)(lengthShoulder / 2);

            //肩膀和肘的距离比较近
            float distance    = (float)Math.Sqrt(Math.Pow((shoulder.y - elbow.y), 2) + Math.Pow((shoulder.x - elbow.x), 2));
            float dist        = (float)Math.Sqrt(Math.Pow((Wrist.y - elbow.y), 2) + Math.Pow((Wrist.x - elbow.x), 2));
            float alldistance = distance + dist;

            ARDebug.Log("alldistance = " + alldistance);
            ARDebug.Log("alldistance disAdjust = " + disAdjust);

            if (alldistance < disAdjust)
            {
                return(true);
            }

            if (Wrist.y > shoulder.y && (alldistance < (100 + disAdjust)))
            {
                return(true);
            }

            //下推掌
            int xAdjust = (int)(lengthShoulder / 15);

            if (Math.Abs(elbow.x - shoulder.x) < xAdjust && (alldistance < (200 + disAdjust)))
            {
                ARDebug.Log("lashenl error");
                return(true);
            }

            return(false);
        }
Пример #20
0
        /// <summary>
        /// Connects an ARSession.  Note that if user permissions are needed they will be requested and thus this is an
        /// asynchronous method.
        /// </summary>
        /// <param name="sessionConfig">The session configuration.</param>
        /// <returns>An {@link AsyncTask<T>} that completes when the connection has been made or failed. </returns>
        public AsyncTask <SessionConnectionState> Connect(ARCoreSessionConfig sessionConfig)
        {
            const string androidCameraPermissionName = "android.permission.CAMERA";

            if (m_SessionManager == null)
            {
                ARDebug.LogError("Cannot connect because ARCoreSession failed to initialize.");
                return(new AsyncTask <SessionConnectionState>(SessionConnectionState.Uninitialized));
            }

            if (sessionConfig == null)
            {
                ARDebug.LogError("Unable to connect ARSession session due to missing ARSessionConfig.");
                m_SessionManager.ConnectionState = SessionConnectionState.MissingConfiguration;
                return(new AsyncTask <SessionConnectionState>(Session.ConnectionState));
            }

            // We have already connected at least once.
            if (Session.ConnectionState != SessionConnectionState.Uninitialized)
            {
                ARDebug.LogError("Multiple attempts to connect to the ARSession.  Note that the ARSession connection " +
                                 "spans the lifetime of the application and cannot be reconfigured.  This will change in future " +
                                 "versions of ARCore.");
                return(new AsyncTask <SessionConnectionState>(Session.ConnectionState));
            }

            // Create an asynchronous task for the potential permissions flow and service connection.
            Action <SessionConnectionState> onTaskComplete;
            var returnTask = new AsyncTask <SessionConnectionState>(out onTaskComplete);

            returnTask.ThenAction((connectionState) =>
            {
                m_SessionManager.ConnectionState = connectionState;
            });

            // Attempt service connection immediately if permissions are granted.
            if (AndroidPermissionsManager.IsPermissionGranted(androidCameraPermissionName))
            {
                _ResumeSession(sessionConfig, onTaskComplete);
                return(returnTask);
            }

            // Request needed permissions and attempt service connection if granted.
            AndroidPermissionsManager.RequestPermission(androidCameraPermissionName).ThenAction((requestResult) =>
            {
                if (requestResult.IsAllGranted)
                {
                    _ResumeSession(sessionConfig, onTaskComplete);
                }
                else
                {
                    ARDebug.LogError("ARCore connection failed because a needed permission was rejected.");
                    onTaskComplete(SessionConnectionState.UserRejectedNeededPermission);
                }
            });

            return(returnTask);
        }
Пример #21
0
        public static float GetAngle(Vector3 firstVet, Vector3 centerVet, Vector3 endVet)
        {
            Vector3 fromVet = firstVet - centerVet;
            Vector3 toVet   = endVet - centerVet;
            float   angle   = Vector3.Angle(fromVet, toVet);

            ARDebug.LogWarning("angles = " + angle);
            return(angle);
        }
Пример #22
0
    public void HandleTouch_Single(GameObject prefab)
    {
        Session.SetHitTestMode(ApiHitTestMode.PolygonPersistence);

        if (Input.touchCount == 0)
        {
            return;
        }

        if (Input.touches[0].phase == TouchPhase.Began)
        {
            if (EventSystem.current.IsPointerOverGameObject(Input.touches[0].fingerId) == false)
            {
                m_bOverGameObj = false;
            }
            else
            {
                m_bOverGameObj = true;
            }
        }

        if (slamController == null || Frame.TrackingState != TrackingState.Tracking)
        {
            return;
        }

        ARDebug.LogInfo("bPlaceModel" + bPlaceModel);
        ARDebug.LogInfo("HandleTouch_Single:IsPointerOverGameObject:" + m_bOverGameObj);

        TrackableHit      hit;
        TrackableHitFlags raycastFilter = TrackableHitFlags.PlaneWithinBounds | TrackableHitFlags.PlaneWithinPolygon;

        if (m_bOverGameObj == false && Session.Raycast(Input.touches[0].position.x, Input.touches[0].position.y, raycastFilter, out hit))
        {
            ARDebug.LogInfo("Raycast:" + Input.touches[0].position.x + "," + Input.touches[0].position.y);

            if (bPlaceModel)
            {
                m_ModelObj = MonoBehaviour.Instantiate(prefab, hit.Pose.position, hit.Pose.rotation);

                // Create an anchor to allow ARCore to track the hitpoint as understanding of the physical
                // world evolves.
                //Anchor anchor = hit.Trackable.CreateAnchor(hit.Pose);
                //m_AnchorObj = anchor.gameObject;
                m_AnchorObj = new GameObject("anchor");

                // Make Andy model a child of the anchor.
                m_ModelObj.transform.parent = m_AnchorObj.transform;
                m_ModelObj.tag   = "ARObj";
                m_ModelObj.layer = 10;

                bPlaceModel = false;
            }

            m_ModelObj.transform.position = hit.Pose.position;
        }
    }
Пример #23
0
        public List <ARAugmentedImageDatabaseEntry> GetDirtyQualityEntries()
        {
            var    dirtyEntries = new List <ARAugmentedImageDatabaseEntry>();
            string cliBinaryPath;

            if (!FindCliBinaryPath(out cliBinaryPath))
            {
                return(dirtyEntries);
            }

            string currentCliVersion;
            {
                string error;
#if !UNITY_EDITOR_WIN
                string output;
                ShellHelper.RunCommand("chmod", "+x " + cliBinaryPath, out output, out error);
                if (!string.IsNullOrEmpty(error))
                {
                    Debug.LogWarning(error);
                    return(dirtyEntries);
                }
#endif
                ShellHelper.RunCommand(cliBinaryPath, "version", out currentCliVersion, out error);
                if (!string.IsNullOrEmpty(error))
                {
                    ARDebug.LogInfo(error);
                    return(dirtyEntries);
                }
            }

            bool cliUpdated = m_CliVersion != currentCliVersion;
            // When CLI is updated, mark all entries dirty.
            if (cliUpdated)
            {
                for (int i = 0; i < m_Images.Count; ++i)
                {
                    ARAugmentedImageDatabaseEntry updatedImage = m_Images[i];
                    updatedImage.Quality = string.Empty;
                    m_Images[i]          = updatedImage;
                }

                m_CliVersion = currentCliVersion;
                EditorUtility.SetDirty(this);
            }

            for (int i = 0; i < m_Images.Count; ++i)
            {
                if (!string.IsNullOrEmpty(m_Images[i].Quality))
                {
                    continue;
                }

                dirtyEntries.Add(m_Images[i]);
            }

            return(dirtyEntries);
        }
Пример #24
0
        /// <summary>
        /// Update the plane's data with APIPlaneData
        /// Note that this will convert plane's pose from Tango space to Unity world space.
        /// </summary>
        /// <param name="apiPlaneData">ApiPlaneData source.</param>
        /// <param name="subsumedBy">The plane subsuming this plane or null.</param>
        /// <param name="forceUpdate">Force to update.</param>
        private void _UpdatePlaneIfNeeded(ApiPlaneData apiPlaneData, TrackedPlane subsumedBy, bool forceUpdate)
        {
            if (m_initialized && apiPlaneData.id != m_apiPlaneData.id)
            {
                ARDebug.LogError("Cannot update plane with mismatched id.");
                return;
            }
            else if (m_initialized && !forceUpdate && apiPlaneData.timestamp == m_apiPlaneData.timestamp)
            {
                return;
            }

            if (subsumedBy != null)
            {
                SubsumedBy = subsumedBy;
            }

            m_apiPlaneData     = apiPlaneData;
            m_initialized      = true;
            m_lastUpdatedFrame = Time.frameCount;

            Matrix4x4 startServiceTplane = Matrix4x4.TRS(apiPlaneData.pose.translation.ToVector3(),
                                                         apiPlaneData.pose.orientation.ToQuaternion(), Vector3.one);

            // Because startServiceTplane is a Pose (position, orientation), the multiplication of the first two terms
            // rotates plane orientation.  This must be undone with the last term (inverse) of the equation.
            m_unityWorldTPlane = Constants.UNITY_WORLD_T_START_SERVICE * startServiceTplane *
                                 Constants.UNITY_WORLD_T_START_SERVICE.inverse;

            Position  = m_unityWorldTPlane.GetColumn(3);
            Position += new Vector3((float)apiPlaneData.centerX, 0.0f, (float)apiPlaneData.centerY);

            Quaternion yaw = Quaternion.Euler(0.0f, -Mathf.Rad2Deg * (float)apiPlaneData.yaw, 0.0f);

            Rotation = yaw * Quaternion.LookRotation(m_unityWorldTPlane.GetColumn(2), m_unityWorldTPlane.GetColumn(1));

            m_boundaryPolygonPoints.Clear();
            int boudaryLength = m_apiPlaneData.boundaryPointNum;

            if (boudaryLength != 0)
            {
                double[] apiBoundaryPolygon = new double[boudaryLength * 2];
                Marshal.Copy(m_apiPlaneData.boundaryPolygon, apiBoundaryPolygon, 0, boudaryLength * 2);

                m_boundaryPolygonPoints.Clear();
                for (int i = 0; i < boudaryLength; ++i)
                {
                    Vector3 localPoint = new Vector3((float)apiBoundaryPolygon[2 * i],
                                                     0.0f, (float)apiBoundaryPolygon[2 * i + 1]);
                    m_boundaryPolygonPoints.Add(m_unityWorldTPlane.MultiplyPoint3x4(localPoint));
                }
            }

            // Reverse the m_boundaryPolygonPoints because the raw data is in counter-clockwise.
            // As Unity is left handed system, this should be clockwise.
            m_boundaryPolygonPoints.Reverse();
        }
        private void _DrawARLogo(Touch touch)
        {
            List <ARHitResult> hitResults = ARFrame.HitTest(touch);
            ARHitResult        hitResult  = null;
            ARTrackable        trackable  = null;
            Boolean            hasHitFlag = false;

            ARDebug.LogInfo("_DrawARLogo hitResults count {0}", hitResults.Count);
            foreach (ARHitResult singleHit in hitResults)
            {
                trackable = singleHit.GetTrackable();
                ARDebug.LogInfo("_DrawARLogo GetTrackable {0}", singleHit.GetTrackable());
                if ((trackable is ARPlane && ((ARPlane)trackable).IsPoseInPolygon(singleHit.HitPose)) ||
                    (trackable is ARPoint))
                {
                    hitResult  = singleHit;
                    hasHitFlag = true;
                    if (trackable is ARPlane)
                    {
                        break;
                    }
                }
            }

            if (hasHitFlag != true)
            {
                ARDebug.LogInfo("_DrawARLogo can't hit!");
                return;
            }

            if (addedAnchors.Count > 16)
            {
                ARAnchor toRemove = addedAnchors[0];
                toRemove.Detach();
                addedAnchors.RemoveAt(0);
            }

            GameObject prefab;

            trackable = hitResult.GetTrackable();
            if (trackable is ARPlane)
            {
                prefab = arDiscoveryLogoPlanePrefabs;
            }
            else
            {
                prefab = arDiscoveryLogoPointPrefabs;
            }

/*
 *          ARAnchor anchor = hitResult.CreateAnchor();
 *          var logoObject = Instantiate(prefab, anchor.GetPose().position, anchor.GetPose().rotation);
 *          logoObject.GetComponent<ARDiscoveryLogoVisualizer>().Initialize(anchor);
 *          addedAnchors.Add(anchor);
 */
        }
Пример #26
0
        private void renderMesh(Vector3 beginPos, Vector3 endPos)
        {
            var mat = gameObject.GetComponent <MeshRenderer>().material;

            float distance = Vector3.Distance(beginPos, endPos);

            float tilingW = distance / (float)mat.mainTexture.width;

            tilingW *= 100.0f;

            mat.SetTextureScale("_MainTex", new Vector2(tilingW, 1));


            Vector3 cro = Vector3.Cross(endPos - beginPos, new Vector3(0.0f, 1.0f, 0.0f));

            cro.Normalize();
            ARDebug.LogInfo("GridARScript: tilingW:{0},{1},{2},{3}", tilingW, beginPos, endPos, cro);
            cro *= mat.mainTexture.height;

            Vector3[] vertices = new Vector3[4];
            vertices [0] = beginPos;
            vertices [1] = endPos;
            vertices [2] = beginPos + cro;
            vertices [3] = endPos + cro;

            Vector2[] uv = new Vector2[vertices.Length];
            uv [0] = new Vector2(0, 0);
            uv [1] = new Vector2(1, 0);
            uv [2] = new Vector2(0, 1);
            uv [3] = new Vector2(1, 1);

            var mesh = GetComponent <MeshFilter>().mesh;

            if (null != mesh)
            {
                mesh.Clear();
            }

            //mesh.name = "Procedural Grid";

            mesh.vertices = vertices;
            mesh.uv       = uv;

            int[] triangles = new int[6];
            triangles [0] = 0;
            triangles [1] = 2;
            triangles [2] = 1;

            triangles [3] = 2;
            triangles [4] = 3;
            triangles [5] = 1;

            mesh.triangles = triangles;
        }
        /**
         * \if english
         * Creates an anchor attached to current trackable at given pose.<b>Note: if the trackable doest not support
         * attaching anchors, null will be returned.</b>
         * \else
         * 使用应用给定的位姿创建与trackable绑定的锚点。<b>注意:如果当期trackable不支持绑定锚点,将会返回null。</b>
         * \endif
         */
        public virtual ARAnchor CreateAnchor(Pose pose)
        {
            IntPtr anchorHandle = IntPtr.Zero;

            if (!m_ndkSession.TrackableAdapter.AcquireNewAnchor(m_trackableHandle, pose, out anchorHandle))
            {
                ARDebug.LogError("failed to create anchor on trackbale");
                return(null);
            }
            return(m_ndkSession.AnchorManager.ARAnchorFactory(anchorHandle, true));
        }
Пример #28
0
        //support for multiple permission request
        public static AsyncTask <AndroidPermissionsRequestResult> RequestPermission(string[] permissionNames)
        {
            if (m_currentRequest != null)
            {
                ARDebug.LogError("Do not make simultaneous permission requests.");
                return(null);
            }

            AndroidPermissionsService.Call("RequestPermissionAsync", UnityActivity, permissionNames, Instance);
            m_currentRequest = new AsyncTask <AndroidPermissionsRequestResult>(out m_onPermissionsRequestFinished);

            return(m_currentRequest);
        }
Пример #29
0
        //public static Queue<float>[] footDowns = new Queue<float>[2];
        public static bool FootDown(Vector3 firstVet, int index, Vector3 secondVet)
        {
            if (foots[index].Count < footsize)
            {
                return(false);
            }

            float firstFiveFrame = 0;
            float endFiveFrame   = 0;

            float[] footArray = foots[index].ToArray();

            for (int i = 0; i < footArray.Length; i++)
            {
                if (i < footsize / 2)
                {
                    endFiveFrame += footArray[i];
                }
                else
                {
                    firstFiveFrame += footArray[i];
                }
            }

            firstFiveFrame = firstFiveFrame * 2 / footsize;
            endFiveFrame   = endFiveFrame * 2 / footsize;

            float adjust = lengthShoulder / 12;

            if (ARGlobalDefs.IsIosPlatform())
            {
                adjust = lengthShoulder / 18;
            }
            ARDebug.Log("LiftDown adjust == " + adjust);
            ARDebug.Log("LiftDown endFiveFrame == " + endFiveFrame);
            ARDebug.Log("LiftDown firstFiveFrame == " + firstFiveFrame);
            ARDebug.Log("dowaLiftDown ffffirstVet.y == " + firstVet.y);
            float AdjustHeight = adjust * 2;

            if (ARGlobalDefs.IsIosPlatform())
            {
                AdjustHeight = adjust * 3;
            }
            if ((endFiveFrame - firstFiveFrame) > adjust && Math.Abs(firstVet.y - secondVet.y) < AdjustHeight)
            {
                ARDebug.Log("dowaddLiftDownfff datas footDown Dwon i = " + index);
                return(true);
            }
            return(false);
        }
Пример #30
0
    public void ErrorInfo(string num, string msg)
    {
        _infoUI.SetActive(true);

        ARDebug.LogWarning("msg =" + msg + "  error=" + num);
        if (num != null && msg != null)
        {
            _infoUI.transform.Find("Error").GetComponent <Text>().text = num + ": " + msg;
        }
        else
        {
            _infoUI.transform.Find("Error").GetComponent <Text>().text = "出错了!";
        }
    }