/// <summary>
        /// <para>Submit a request to start the invite sending process. Request an invite to be sent for other connections to join a multi-user
        /// experience. This call will trigger a connections invite dialog requesting the user to select up to the specified number of online
        /// users to be invited. The system will then initiate a push notification to other online devices, start a copy of the application
        /// requesting the invite and deliver the given payload.</para>
        /// <para>Only one invite can be processed at a time. Will return an error if the first invite request is incomplete/pending in the service
        /// when a second request is sent.</para>
        /// <para>Will receive a DispatchFailed status if the invitee is not registered to receive invites for the specific application. If multiple invitees
        /// are selected, SendInvite will dispatch successfully if at least one of them is registered to receive invites for the specific application.</para>
        /// <para>Note: You cannot invite users who are not following the Sender.</para>
        /// </summary>
        /// <param name="inviteeCount">Max number of connections to be invited. Min limit is 1.</param>
        /// <param name="filterLevel">Type of filter applied by default to ML connections list in invitee selection dialog.</param>
        /// <param name="textPrompt">Text prompt to be displayed to the user with invitee selection dialog.</param>
        /// <param name="payload">Payload message to be delivered to remote copy of the application with invite.</param>
        /// <returns>
        /// <para>MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if a given argument is invalid.</para>
        /// <para>MLResult.Result will be <c>MLResult.Code.Ok</c> if successfully requested the start of the invite dialog.</para>
        /// <para>MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if there was an unexpected failure.</para>
        /// <para>MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if permissions haven't been granted to make this API call.</para>
        /// <para>MLResult.Result will be <c>MLResult.Code.Timeout</c> if the request to request sending an invite timed out.</para>
        /// <para>MLResult.Result will be <c>MLResult.Code.ConnectionsIllegalState</c> if there was an issue with the connections system, e.g. service is not available for any reason.</para>
        /// <para>MLResult.Result will be <c>MLResult.Code.ConnectionsInvalidInviteeCount</c> if number of invitees is invalid.</para>
        /// </returns>
        public static MLResult SendInvite(uint inviteeCount, InviteeFilter filterLevel, string textPrompt, string payload)
        {
            if (MLConnections.IsValidInstance())
            {
                MLResult requestResult = NativeBindings.InviteArgs.SendInviteHelper(inviteeCount, filterLevel, textPrompt, payload, ref _instance.requestHandle);

                if (!requestResult.IsOk)
                {
                    MLPluginLog.ErrorFormat("MLConnections.SendInvite failed to initialize resources for sending an invite. Reason: {0}", requestResult);
                }
                else
                {
                    if (_instance.activeInvite)
                    {
                        MLPluginLog.WarningFormat("MLConnections.SendInvite allowed multiple active invites.");
                    }

                    _instance.activeInvite = true;
                }

                return(requestResult);
            }
            else
            {
                MLPluginLog.ErrorFormat("MLConnections.SendInvite failed. Reason: No Instance for MLConnections");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLConnections.SendInvite failed. Reason: No Instance for MLConnections"));
            }
        }
示例#2
0
            /// <summary>
            /// Updates the state of the PCF.
            /// </summary>
            /// <returns>
            /// MLResult.Result will be <c>MLResult.Code.Ok</c> if operation completed successfully.
            /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if failed due to an invalid input parameter.
            /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if there was a lack of privileges.
            /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to other internal error.
            /// MLResult.Result will be <c>MLResult.Code.PassableWorldLowMapQuality</c> if map quality is too low for content persistence. Continue building the map.
            /// MLResult.Result will be <c>MLResult.Code.PassableWorldNotFound</c> if the passed CFUID is not available.
            /// MLResult.Result will be <c>MLResult.Code.PassableWorldUnableToLocalize</c> if currently unable to localize into any map. Continue building the map.
            /// </returns>
            private MLResult UpdateState()
            {
                if (MLPersistentCoordinateFrames.IsValidInstance())
                {
                    try
                    {
                        NativeBindings.FrameStateNative nativeState = NativeBindings.FrameStateNative.Create();
                        MLResult.Code resultCode = NativeBindings.MLPersistentCoordinateFramesGetFrameState(MLPersistentCoordinateFrames._instance.nativeTracker, in this.cfuid, ref nativeState);
                        if (!MLResult.IsOK(resultCode))
                        {
                            MLPluginLog.ErrorFormat("PCF.UpdateState failed to get frame state. Reason: {0}", MLResult.CodeToString(resultCode));
                            return(MLResult.Create(resultCode, string.Format("PCF.UpdateState failed to get frame state. Reason: {0}", MLResult.CodeToString(resultCode))));
                        }

                        this.FrameState = nativeState.Data();

                        return(MLResult.Create(resultCode));
                    }
                    catch (EntryPointNotFoundException)
                    {
                        MLPluginLog.Error("PCF.UpdateState failed. Reason: API symbols not found.");
                        return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "PCF.UpdateState failed. Reason: API symbols not found."));
                    }
                }
                else
                {
                    MLPluginLog.ErrorFormat("PCF.UpdateState failed. Reason: No Instance for MLPersistentCoordinateFrames.");
                    return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "PCF.UpdateState failed. Reason: No Instance for MLPersistentCoordinateFrames."));
                }
            }
        /// <summary>
        /// Starts the HeadTracking API.
        /// </summary>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if connected to MLContacts successfully.
        /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if necessary privilege is missing.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if the operation failed with an unspecified error.
        /// </returns>
        protected override MLResult StartAPI()
        {
            MLResult.Code resultCode = MLResult.Code.UnspecifiedFailure;

            try
            {
                resultCode = NativeBindings.MLHeadTrackingCreate(ref _instance.handle);
                if (resultCode != MLResult.Code.Ok)
                {
                    MLPluginLog.ErrorFormat("MLHeadTracking.StartAPI failed to create native head tracker.");
                }

                resultCode = NativeBindings.MLHeadTrackingGetStaticData(_instance.handle, ref _instance.staticDataNative);
                if (resultCode != MLResult.Code.Ok)
                {
                    MLPluginLog.ErrorFormat("MLHeadTracking.StartAPI failed to get static date from the native head tracker.");
                }
            }
            catch (EntryPointNotFoundException)
            {
                MLPluginLog.Error("MLHeadTracking.StartAPI failed. Reason: API symbols not found.");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure));
            }

            return(MLResult.Create(resultCode));
        }
示例#4
0
        public static MLResult GetDefaultSettings(out MLMovementSettings settings)
        {
            errorMsg = "MLMovement.GetDefaultSettings failed due to internal error";

            MLMovementSettings tempSettings = default;

            MLResult GetDefaultSettingsFunc()
            {
                NativeBindings.SettingsNative internalSettings = NativeBindings.SettingsNative.Create();
                MLResult.Code result = NativeBindings.MLMovementGetDefaultSettings(out internalSettings);
                if (result != MLResult.Code.Ok)
                {
                    MLPluginLog.ErrorFormat("MLMovement.GetDefaultSettings failed to get default movement settings. Reason: {0}", result);
                }
                else
                {
                    tempSettings = internalSettings.DataEx;
                }

                return(MLResult.Create(result));
            }

            MLResult finalResult = TryExecute(GetDefaultSettingsFunc);

            settings = tempSettings;

            return(finalResult);
        }
        /// <summary>
        /// Used to safely make native calls.
        /// </summary>
        /// <param name="resultCode">MLResult.Code enum that the wrappedPlatformCall should set.</param>
        /// <param name="platformFunctionName">Name of the function for the log to print on failure.</param>
        /// <param name="wrappedPlatformCall">Anonymous function for making your native call that you should set resultCode with.</param>
        /// <param name="successCase">Predicate delegate for determining when a call was successful.</param>
        /// <param name="checkInstance">Determines if this call should check for a valid instance before running.</param>
        protected static void PlatformInvoke(out MLResult.Code resultCode, string platformFunctionName, Action wrappedPlatformCall, Predicate <MLResult.Code> successCase = null, bool checkInstance = true)
        {
            resultCode = MLResult.Code.UnspecifiedFailure;

            if (checkInstance && !IsValidInstance())
            {
                MLPluginLog.ErrorFormat("{0} failed. Reason: {1} API has no valid instance.", platformFunctionName, typeof(T).Name);
                return;
            }

            try
            {
                wrappedPlatformCall?.Invoke();
                bool success = successCase != null?successCase(resultCode) : MLResult.IsOK(resultCode);

                if (!success)
                {
                    MLPluginLog.ErrorFormat("{0} failed. Reason: {1}", platformFunctionName, MLResult.CodeToString(resultCode));
                }
            }
            catch (DllNotFoundException)
            {
                MLPluginLog.ErrorFormat("{0} failed. Reason: {1} API is currently available only on device.", platformFunctionName, typeof(T).Name);
                resultCode = MLResult.Code.APIDLLNotFound;
            }
            catch (EntryPointNotFoundException)
            {
                MLPluginLog.ErrorFormat("{0} failed. Reason: {1} API symbols not found.", platformFunctionName, typeof(T).Name);
                resultCode = MLResult.Code.APISymbolsNotFound;
            }
        }
        /// <summary>
        /// Retrieves data from the current Wi-Fi network.
        /// </summary>
        /// <param name="wifiData">Reference to the struct to populate.</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successful.
        /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if the given parameter is invalid.
        /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if necessary privilege is missing.
        /// MLResult.Result will be <c>MLResult.Code.ServiceNotAvailable</c> if the corresponding service is not available.
        /// MLResult.Result will be <c>MLResult.Code.ServiceError</c> if the corresponding service returned with error.
        /// MLResult.Result will be <c>MLResult.Code.WiFiDataStructureVersionError</c> if the version number in the given struct is not recognized.
        /// MLResult.Result will be <c>MLResult.Code.WiFiServiceInvalidState</c> if the Wi-Fi service is not in the right state.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
        /// </returns>
        public static MLResult GetWifiData(ref MLNetworking.WifiData wifiData)
        {
            MLResult finalResult = MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLNetworking.GetWifiData failed due to internal error");

            try
            {
                MLNetworkingNativeBindings.WifiDataNative wifiDataInternal = MLNetworkingNativeBindings.WifiDataNative.Create();
                MLResult.Code result = MLNetworkingNativeBindings.MLNetworkingGetWiFiData(ref wifiDataInternal);
                if (result != MLResult.Code.Ok)
                {
                    MLPluginLog.ErrorFormat("MLNetworking.GetWifiData failed to get Wi-Fi data. Reason: {0}", result);
                    wifiData = new MLNetworking.WifiData();
                }
                else
                {
                    wifiData = wifiDataInternal.Data;
                }

                finalResult = MLResult.Create(result);
            }
            catch (System.DllNotFoundException)
            {
                MLPluginLog.Error("MLNetworking API is currently available only on device.");
                finalResult = MLResult.Create(MLResult.Code.UnspecifiedFailure, "Dll not found");
            }
            catch (System.EntryPointNotFoundException)
            {
                string errorMessage = string.Format("MLNetworking API symbols not found");
                finalResult = MLResult.Create(MLResult.Code.UnspecifiedFailure, errorMessage);
            }

            return(finalResult);
        }
            /// <summary>
            /// Initializes a new instance of the <see cref="Target" /> class.
            /// </summary>
            /// <param name="name"> Image target's name. </param>
            /// <param name="image"> Texture2D representing the image target. The size of the texture should not be changed. Set the "Non Power of 2" property of Texture2D to none. </param>
            /// <param name="longerDimension"> Longer dimension of the image target in scene units. Default is meters. </param>
            /// <param name="callback"> Tracking result callback for this image target. </param>
            /// <param name="handle"> Handle for the image tracker. </param>
            /// <param name="isStationary"> Set this to true if the position of this image target in the physical world is fixed and its surroundings are planar (ex: walls, floors, tables, etc). </param>
            public Target(string name, Texture2D image, float longerDimension, OnImageResultDelegate callback, ulong handle, bool isStationary = false)
            {
                this.targetSettings       = MLImageTracker.Target.Settings.Create();
                this.targetStaticData     = new NativeBindings.MLImageTrackerTargetStaticDataNative();
                this.nativeTrackingResult = new NativeBindings.MLImageTrackerTargetResultNative();

                // It is assumed that all the parameters are valid as this class should only be used by the MLImageTracker,
                // which already has checks for these values before it creates the MLImageTracker.Target.
                this.targetSettings.Name            = name;
                this.targetSettings.LongerDimension = longerDimension;
                this.targetSettings.IsStationary    = isStationary;
                this.trackerHandle = handle;
                this.OnImageResult = callback;

                this.imageData    = MLTextureUtils.ConvertToByteArray(image, out int numChannels);
                this.targetHandle = MagicLeapNativeBindings.InvalidHandle;

                MLResult.Code result = NativeBindings.MLImageTrackerAddTargetFromArray(this.trackerHandle, ref this.targetSettings, this.imageData, (uint)image.width, (uint)image.height, (numChannels == 4) ? MLImageTracker.ImageFormat.RGBA : MLImageTracker.ImageFormat.RGB, ref this.targetHandle);

                if (result == MLResult.Code.Ok && this.IsValid && MagicLeapNativeBindings.MLHandleIsValid(this.trackerHandle))
                {
                    result = NativeBindings.MLImageTrackerGetTargetStaticData(this.trackerHandle, this.targetHandle, ref this.targetStaticData);
                    if (result != MLResult.Code.Ok)
                    {
                        MLPluginLog.ErrorFormat("MLImageTracker.Target.Target failed to get static data for target. Reason: {0}", result);
                    }
                }
                else
                {
                    MLPluginLog.ErrorFormat("MLImageTracker.Target.Target failed, one or both handles are invalid: Tracker Handle: {0}, Existing Target Handle: {1}. Reason: {2}", this.trackerHandle, this.targetHandle, result);
                }
            }
示例#8
0
        /// <summary>
        /// Returns a list of all the PCFs of the types provided by the typesMask inside the current map.
        /// </summary>
        /// <param name="pcfList">Stores the resulting list of PCFs.</param>
        /// <param name="maxResults">The max number of PCFs to get.</param>
        /// <param name="typesMask">The bitmask of which PCF types to consider.</param>
        /// <param name="update">Determines if the PCFs should have their pose updated.</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if all the PCFs from the current map have been found successfully.
        /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if necessary privilege is missing.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to other internal error.
        /// MLResult.Result will be <c>MLResult.Code.PassableWorldLowMapQuality</c> if map quality is too low for content persistence. Continue building the map.
        /// MLResult.Result will be <c>MLResult.Code.PassableWorldUnableToLocalize</c> if currently unable to localize into any map. Continue building the map.
        /// </returns>
        public static MLResult FindAllPCFs(out List <PCF> pcfList, uint maxResults = int.MaxValue, PCF.Types typesMask = PCF.Types.SingleUserSingleSession | PCF.Types.SingleUserMultiSession | PCF.Types.MultiUserMultiSession, bool update = true)
        {
            pcfList = new List <PCF>();

            if (MLPersistentCoordinateFrames.IsValidInstance())
            {
                QueryFilter queryFilter = QueryFilter.Create();
                queryFilter.TypesMask  = typesMask;
                queryFilter.MaxResults = maxResults;
                queryFilter.Sorted     = false;

                MLResult result = FindPCFsByFilter(queryFilter, out pcfList, update);

                if (!result.IsOk)
                {
                    if (result.Result == MLResult.Code.PassableWorldLowMapQuality || result.Result == MLResult.Code.PassableWorldUnableToLocalize)
                    {
                        MLPluginLog.Warning("Map quality not sufficient enough for MLPersistentCoordinateFrames.FindAllPCFs.");
                    }
                    else
                    {
                        MLPluginLog.ErrorFormat("MLPersistentCoordinateFrames.FindAllPCFs failed. Reason: {0}", result);
                    }
                }

                return(result);
            }
            else
            {
                MLPluginLog.ErrorFormat("MLPersistentCoordinateFrames.FindAllPCFs failed. Reason: No Instance for MLPersistentCoordinateFrames.");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLPersistentCoordinateFrames.FindAllPCFs failed. Reason: No Instance for MLPersistentCoordinateFrames."));
            }
        }
示例#9
0
            /// <summary>
            /// Fetches client credentials, can be used with a callback or as a blocking call.
            /// </summary>
            /// <param name="callback">The callback to notify when the CurrentRequest is complete.</param>
            /// <returns>
            /// MLResult.Result will be <c>MLResult.Code.Ok</c> if the operation completed successfully.
            /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if the operation failed with an unspecified error.
            /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if the out_credentials was 0 (null).
            /// MLResult.Result will be <c>MLResult.Code.AllocFailed</c> if the operation failed to allocate memory.
            /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if the caller does not have the ClientCredentialsRead privilege.
            /// MLResult.Result will be <c>MLResult.Code.TokenAgent*</c> if a token specific failure occurred during the operation.
            /// </returns>
            public MLResult Fetch(MLTokenAgent.ClientCredentials.Request.RequestAttibutesDelegate callback = null)
            {
                if (callback == null)
                {
                    MLResult.Code resultCode = MLTokenAgent.NativeBindings.GetClientCredentials(this, ref this.credentials, ref this.tokens);
                    if (!MLResult.IsOK(resultCode))
                    {
                        MLPluginLog.ErrorFormat("MLTokenAgent.Fetch failed. Reason: {0}", MLResult.CodeToString(resultCode));
                    }

                    return(MLResult.Create(resultCode));
                }
                else
                {
                    this.CurrentRequest = new Request
                    {
                        Callback     = callback,
                        ResultCode   = MLResult.Code.Pending,
                        RequestState = Request.State.REQUEST_CREDENTIALS
                    };

                    MLTokenAgent.AddClientCredentials(this);

                    return(MLResult.Create(MLResult.Code.Ok));
                }
            }
示例#10
0
        /// <summary>
        /// Processes the current pending queries and adds them to the completed queries list when finished.
        /// Queries that are still pending are skipped from being added to the completed queries list until next Update loop.
        /// </summary>
        private void ProcessPendingQueries()
        {
            foreach (Query query in this.pendingQueries)
            {
                MLResult.Code resultCode = NativeBindings.MLHandMeshingGetResult(this.nativeTracker, query.RequestHandle, ref this.handMeshNativeStruct);
                if (resultCode == MLResult.Code.Pending)
                {
                    continue;
                }

                query.Result = MLResult.Create(resultCode);
                if (resultCode == MLResult.Code.Ok)
                {
                    query.HandMesh = this.handMeshNativeStruct.Data;
                }

                this.completedQueries.Add(query);

                ulong requestHandle = query.RequestHandle;
                resultCode = NativeBindings.MLHandMeshingFreeResource(this.nativeTracker, ref requestHandle);
                if (resultCode != MLResult.Code.Ok)
                {
                    MLPluginLog.ErrorFormat("MLHandMeshing.ProcessPendingQueries failed to free resource. Reason: {0}", resultCode);
                }
            }
        }
示例#11
0
        /// <summary>
        /// Requests the specified privileges. This may possibly solicit consent from the end-user.
        /// </summary>
        /// <param name="privilegeId">The privilege to request.</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.PrivilegeGranted</c> if the privilege is granted.
        /// MLResult.Result will be <c>MLResult.Code.PrivilegeNotGranted</c> if the privilege is denied.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if the privilege system was not started.
        /// </returns>
        public static MLResult RequestPrivilege(MLPrivileges.Id privilegeId)
        {
            try
            {
                if (MLPrivileges.IsValidInstance())
                {
                    MLResult.Code requestPrivilegeResult = NativeBindings.MLPrivilegesRequestPrivilege(privilegeId);

                    MLResult result = MLResult.Create(requestPrivilegeResult);

                    if (result.Result != MLResult.Code.PrivilegeGranted)
                    {
                        MLPluginLog.ErrorFormat("MLPrivileges.RequestPrivilege failed to request {0}. Reason: {1}", privilegeId, result);
                    }

                    return(result);
                }
                else
                {
                    MLPluginLog.ErrorFormat("MLPrivileges.RequestPrivilege failed. Reason: No Instance for MLPrivileges.");
                    return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLPrivileges.RequestPrivilege failed. Reason: No Instance for MLPrivileges."));
                }
            }
            catch (System.EntryPointNotFoundException)
            {
                MLPluginLog.Error("MLPrivileges.RequestPrivilege failed. Reason: API symbols not found");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLPrivileges.RequestPrivilege failed. Reason: API symbols not found."));
            }
        }
示例#12
0
        /// <summary>
        /// Begin querying for planes.
        /// </summary>
        /// <param name="queryParams">All values are required, omitting values may result in unexpected behavior.</param>
        /// <param name="callback">Callback used to report query results.</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successful.
        /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if failed due to invalid input parameter.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
        /// </returns>
        private MLResult BeginPlaneQuery(QueryParams queryParams, QueryResultsDelegate callback)
        {
            if (!NativeBindings.MLHandleIsValid(this.planesTracker))
            {
                MLPluginLog.Error("MLPlanes.BeginPlaneQuery failed to request planes. Reason: Tracker handle is invalid");
                return(MLResult.Create(MLResult.Code.InvalidParam));
            }

            // Convert to native plane query parameters.
            NativeBindings.QueryParamsNative planeQuery = NativeBindings.QueryParamsNative.Create();
            planeQuery.Data = queryParams;

            // Register the query with the native library and store native handle.
            ulong handle = MagicLeapNativeBindings.InvalidHandle;

            MLResult.Code resultCode = NativeBindings.MLPlanesQueryBegin(this.planesTracker, ref planeQuery, ref handle);
            if (resultCode != MLResult.Code.Ok)
            {
                MLResult result = MLResult.Create(resultCode);
                MLPluginLog.ErrorFormat("MLPlanes.BeginPlaneQuery failed to request planes. Reason: {0}", result);
                return(result);
            }

            // Create query object to prepresent this newly registered plane query.
            NativeBindings.Query query = new NativeBindings.Query((QueryResultsDelegate)callback, planeQuery.MaxResults, this.IsRequestingBoundaries(planeQuery.Flags));
            this.pendingQueries.Add(handle, query);
            return(MLResult.Create(MLResult.Code.Ok));
        }
        /// <summary>
        /// Creates an Image Target based on the provided parameters.
        /// </summary>
        /// <param name="name">The name to give the Image Target.</param>
        /// <param name="image">The image that represents the target.</param>
        /// <param name="width">The width of the Image Target.</param>
        /// <param name="callback">The callback to use for any status updates of the new Image Target.</param>
        /// <param name="isStationary">Set this to true if the position of this Image Target in the physical world is fixed and the local geometry is planar.</param>
        /// <returns>The newly created Image Target.</returns>
        private Target CreateTarget(string name, Texture2D image, float width, MLImageTracker.Target.OnImageResultDelegate callback, bool isStationary)
        {
            if (string.IsNullOrEmpty(name))
            {
                MLPluginLog.Error("MLImageTracker.CreateTarget failed to add MLImageTracker.Target to ImageTracker. Reason: The unique name provided is null or empty.");
                return(null);
            }

            if (image == null)
            {
                MLPluginLog.ErrorFormat("MLImageTracker.CreateTarget failed to add MLImageTracker.Target \"{0}\" to ImageTracker. Reason: The Texture2D image provided is null.", name);
                return(null);
            }

            if (callback == null)
            {
                MLPluginLog.ErrorFormat("MLImageTracker.CreateTarget failed to add MLImageTracker.Target \"{0}\" to ImageTracker. Reason: The callback function provided is null.", name);
                return(null);
            }

            // Check to see if a version of this image is already tracked.
            // Currently this only checks for unique names.
            if (this.targetList.FindIndex((Target target) => target.TargetSettings.Name.Equals(name)) > -1)
            {
                MLPluginLog.ErrorFormat("MLImageTracker.CreateTarget failed to add MLImageTracker.Target \"{0}\" to ImageTracker. Reason: A target with the same name is already added to this tracker.", name);
                return(null);
            }

            return(new Target(name, image, width, callback, this.handle, isStationary));
        }
        /// <summary>
        /// Called by MLAPISingleton on destruction
        /// </summary>
        /// <param name="isSafeToAccessManagedObjects">Used for cleanup</param>
        protected override void CleanupAPI(bool isSafeToAccessManagedObjects)
        {
            if (Native.MagicLeapNativeBindings.MLHandleIsValid(this.registerHandle))
            {
                MLResult.Code resultCode = NativeBindings.MLConnectionsRegistrationShutdown(this.registerHandle);

                if (!MLResult.IsOK(resultCode))
                {
                    MLPluginLog.ErrorFormat("MLConnections.Stop failed in CleapupAPI() to shutdown registration to receive invites. Reason: {0}", MLResult.CodeToString(resultCode));
                }
            }

            // Shutdown should only be called if Startup was successful.
            if (this.sendInviteHasStarted)
            {
                MLResult.Code shutdownResultCode = NativeBindings.MLConnectionsShutdown();

                if (!MLResult.IsOK(shutdownResultCode))
                {
                    MLPluginLog.ErrorFormat("MLConnections.Stop failed in CleapupAPI() to deinitialize all resources used for sending an invite. Reason: {0}", MLResult.CodeToString(shutdownResultCode));
                }
            }

            this.registerHandle       = Native.MagicLeapNativeBindings.InvalidHandle;
            this.activeRequest        = false;
            this.sendInviteHasStarted = false;
        }
        /// <summary>
        /// Request the list of detected found objects.
        /// Callback will never be called while request is still pending.
        /// </summary>
        /// <param name="queryFilter">Filter used to customize query results.</param>
        /// <param name="callback">
        /// Callback used to report query results.
        /// Callback MLResult code will never be <c>MLResult.Code.Pending</c>.
        /// </param>
        /// <returns>
        /// MLResult.Result inside callback will be <c>MLResult.Code.Ok</c> if successful.
        /// MLResult.Result inside callback will be <c>MLResult.Code.InvalidParam</c> if failed due to invalid input parameter.
        /// MLResult.Result inside callback will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
        /// </returns>
        public static MLResult GetObjectsAsync(Query.Filter queryFilter, QueryResultsDelegate callback)
        {
            if (MLFoundObjects.IsValidInstance())
            {
                // Don't allow null callbacks to be registered.
                if (callback == null)
                {
                    MLPluginLog.Error("MLFoundObjects.GetObjects failed. Reason: Passed input callback is null.");
                    return(MLResult.Create(MLResult.Code.InvalidParam));
                }

                MLThreadDispatch.ScheduleWork(() =>
                {
                    _instance.BeginObjectQueryAsync(queryFilter, callback);
                    return(true);
                });

                return(MLResult.Create(MLResult.Code.Ok));
            }
            else
            {
                MLPluginLog.ErrorFormat("MLFoundObjects.GetObjects failed. Reason: No Instance for MLFoundObjects");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLFoundObjects.GetFoundObjects failed. Reason: No Instance for MLFoundObjects"));
            }
        }
            /// <summary>
            /// Invokes the MLTokenAgentGetClientCredentials() function asynchronously (in a different thread).
            /// </summary>
            /// <param name="clientCredentials">Reference to the clientCredentials object.</param>
            /// <returns>
            /// MLResult.Result will be <c>MLResult.Code.Ok</c> if the operation completed successfully.
            /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if the operation failed with an unspecified error.
            /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if the profile or out_future were 0 (null).
            /// MLResult.Result will be <c>MLResult.Code.AllocFailed</c> if the operation failed to allocate memory.
            /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if the caller does not have the ClientCredentialsRead privilege.
            /// MLResult.Result will be <c>MLResult.Code.TokenAgent*</c> if a token specific failure occurred during the operation.
            /// </returns>
            public static MLResult.Code RequestClientCredentialsAsync(MLTokenAgent.ClientCredentials clientCredentials)
            {
                IntPtr clientCredentialsFuturePtr = clientCredentialsFuturePtrMap.ContainsKey(clientCredentials) ? clientCredentialsFuturePtrMap[clientCredentials] : IntPtr.Zero;

                try
                {
                    MLResult.Code resultCode = MLTokenAgent.NativeBindings.MLTokenAgentGetClientCredentialsAsync(ref clientCredentialsFuturePtr);

                    if (MLResult.IsOK(resultCode))
                    {
                        clientCredentialsFuturePtrMap.Remove(clientCredentials);
                        clientCredentialsFuturePtrMap.Add(clientCredentials, clientCredentialsFuturePtr);
                    }
                    else if (resultCode == MLResult.Code.PrivilegeDenied)
                    {
                        MLPluginLog.Warning("MLTokenAgent.NativeBindings.RequestClientCredentialsAsync failed. Reason: Caller does not have IdentityRead Privilege.");
                    }
                    else
                    {
                        MLPluginLog.ErrorFormat("MLTokenAgent.NativeBindings.RequestClientCredentialsAsync failed. Reason: {0}", resultCode);
                    }

                    return(resultCode);
                }
                catch (EntryPointNotFoundException)
                {
                    MLPluginLog.Error("MLTokenAgent.NativeBindings.RequestClientCredentialsAsync failed. Reason: API symbols not found.");
                    return(MLResult.Code.UnspecifiedFailure);
                }
            }
        /// <summary>
        /// Begin querying for found objects.
        /// </summary>
        /// <param name="filter">Filter to use for this query.</param>
        /// <param name="callback">Callback used to report query results.</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successful.
        /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if failed due to invalid input parameter.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
        /// </returns>
        private MLResult BeginObjectQueryAsync(Query.Filter filter, QueryResultsDelegate callback)
        {
            try
            {
                if (!MagicLeapNativeBindings.MLHandleIsValid(_instance.handle))
                {
                    MLPluginLog.Error("MLFoundObjects.BeginObjectQuery failed to request found objects. Reason: Tracker handle is invalid");
                    return(MLResult.Create(MLResult.Code.InvalidParam));
                }

                NativeBindings.QueryFilterNative nativeQueryFilter = new NativeBindings.QueryFilterNative();
                nativeQueryFilter.Data = filter;

                MLResult.Code resultCode = NativeBindings.MLFoundObjectQuery(_instance.handle, ref nativeQueryFilter, out ulong queryHandle);
                MLResult      result     = MLResult.Create(resultCode);

                if (!result.IsOk)
                {
                    MLPluginLog.ErrorFormat("MLFoundObjects.BeginObjectQuery failed to request objects. Reason: {0}", resultCode);
                    return(result);
                }

                // Add query to the list of pendingQueries.
                Query query = Query.Create(callback, filter);
                MLFoundObjects._instance.pendingQueries.TryAdd(queryHandle, query);

                return(result);
            }
            catch (System.EntryPointNotFoundException)
            {
                MLPluginLog.Error("MLFoundObjects.BeginObjectQuery failed. Reason: API symbols not found");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLFoundObjects.BeginObjectQuery failed. Reason: API symbols not found"));
            }
        }
            /// <summary>
            /// ReleaseClientCredentials releases all resources associated with the
            /// MLTokenAgentClientCredentials structure that was returned by the library.
            /// </summary>
            /// <param name="clientCredentials">Reference to the clientCredentials object.</param>
            public static void CleanupClientCredentialsMemory(MLTokenAgent.ClientCredentials clientCredentials)
            {
                if (clientCredentials.CurrentRequest != null)
                {
                    MLPluginLog.Warning("This client has an ongoing request and cannot have it's memory released.");
                }

                IntPtr clientCredentialsPtr = clientCredentialsPtrMap.ContainsKey(clientCredentials) ? clientCredentialsPtrMap[clientCredentials] : IntPtr.Zero;

                if (clientCredentialsPtr != IntPtr.Zero)
                {
                    try
                    {
                        MLResult.Code resultCode = MLTokenAgent.NativeBindings.MLTokenAgentReleaseClientCredentials(clientCredentialsPtr);

                        if (resultCode != MLResult.Code.Ok)
                        {
                            MLPluginLog.ErrorFormat("MLTokenAgent.CleanupClientCredentialsMemory failed. Reason: {0}", resultCode);
                        }
                    }
                    catch (EntryPointNotFoundException)
                    {
                        MLPluginLog.Error("MLTokenAgent.CleanupClientCredentialsMemory failed. Reason: API symbols not found.");
                    }
                }
            }
示例#19
0
        /// <summary>
        /// Retrieves if there's currently internet connection.
        /// </summary>
        /// <param name="isConnected">Reference to populate with whether or not there's internet connectivity.</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successful.
        /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if isConnected parameter is invalid.
        /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if necessary privilege is missing.
        /// MLResult.Result will be <c>MLResult.Code.ServiceNotAvailable</c> if the corresponding service is not available.
        /// MLResult.Result will be <c>MLResult.Code.ServiceError </c> if the corresponding service returned with error.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
        /// </returns>
        public static MLResult IsInternetConnected(ref bool isConnected)
        {
            MLResult finalResult = MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLNetworking.IsInternetConnected failed due to internal error");

            try
            {
                isConnected = false;
                MLResult.Code result = MLNetworkingNativeBindings.MLNetworkingIsInternetConnected(ref isConnected);
                if (result != MLResult.Code.Ok)
                {
                    MLPluginLog.ErrorFormat("MLNetworking.IsInternetConnected failed to check if device is connected to internet. Reason: {0}", result);
                    isConnected = false;
                }

                finalResult = MLResult.Create(result);
            }
            catch (System.DllNotFoundException)
            {
                MLPluginLog.Error("MLNetworking API is currently available only on device.");
                finalResult = MLResult.Create(MLResult.Code.UnspecifiedFailure, "Dll not found");
            }
            catch (System.EntryPointNotFoundException)
            {
                string errorMessage = string.Format("MLNetworking API symbols not found");
                finalResult = MLResult.Create(MLResult.Code.UnspecifiedFailure, errorMessage);
            }

            return(finalResult);
        }
示例#20
0
        /// <summary>
        /// Begin querying for found objects.
        /// </summary>
        /// <param name="callback">Callback used to report query results.</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successful.
        /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if failed due to invalid input parameter.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
        /// </returns>
        private MLResult BeginObjectQuery(QueryResultsDelegate callback)
        {
            try
            {
                if (!MagicLeapNativeBindings.MLHandleIsValid(_instance.tracker))
                {
                    MLPluginLog.Error("MLFoundObject.BeginObjectQuery failed to request found objects. Reason: Tracker handle is invalid");
                    return(MLResult.Create(MLResult.Code.InvalidParam));
                }

                NativeBindings.QueryFilterNative queryFilter = new NativeBindings.QueryFilterNative();

                MLResult.Code resultCode = NativeBindings.MLFoundObjectQuery(_instance.tracker, ref queryFilter, out ulong queryHandle);
                MLResult      result     = MLResult.Create(resultCode);

                if (!result.IsOk)
                {
                    MLPluginLog.ErrorFormat("MLFoundObject.BeginObjectQuery failed to request objects. Reason: {0}", resultCode);
                    return(result);
                }

                // Create query object to prepresent this newly registered found object query.
                NativeBindings.Query query = new NativeBindings.Query(callback, queryFilter, result);
                MLFoundObjects._instance.pendingQueries.Add(queryHandle, query);

                return(result);
            }
            catch (System.EntryPointNotFoundException)
            {
                MLPluginLog.Error("MLFoundObjects.BeginObjectQuery failed. Reason: API symbols not found");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLFoundObjects.BeginObjectQuery failed. Reason: API symbols not found"));
            }
        }
示例#21
0
        /// <summary>
        /// Gets the result string for a MLResult.Code. Use MLResult.CodeToString(MLResult.Code) to get the string value of any MLResult.Code.
        /// </summary>
        /// <param name="result">The MLResult.Code to be requested.</param>
        /// <returns>A pointer to the result string.</returns>
        internal static IntPtr GetResultString(MLResult.Code result)
        {
            try
            {
                if (MLIdentity.IsValidInstance())
                {
                    try
                    {
                        return(NativeBindings.MLIdentityGetResultString(result));
                    }
                    catch (EntryPointNotFoundException)
                    {
                        MLPluginLog.Error("MLIdentity.GetResultString failed. Reason: API symbols not found.");
                    }

                    return(IntPtr.Zero);
                }
                else
                {
                    MLPluginLog.ErrorFormat("MLIdentity.GetResultString failed. Reason: No Instance for MLIdentity.");
                }
            }
            catch (EntryPointNotFoundException)
            {
                MLPluginLog.Error("MLIdentity.GetResultString failed. Reason: API symbols not found.");
            }

            return(IntPtr.Zero);
        }
示例#22
0
        /// <summary>
        /// External call for querying the last known fine location.
        /// The accuracy field of the MLLocation.Location provides the estimate accuracy radius in meters.
        /// Returns the last known fine location data on success and returns the last queried fine location data on failure. Latitude and Longitude of
        /// 0 should be assumed an Invalid Location.
        /// </summary>
        /// <param name="fineLocation">Where to store the last known fine location. Only updates when getting the location succeeds. Latitude and Longitude of 0 should be assumed an Invalid Location.</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if the location was queried successfully.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if there was an internal error.
        /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if there was an invalid location.
        /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if there was a lack of privilege(s).
        /// MLResult.Result will be <c>MLResult.Code.LocationProviderNotFound</c> if there was no provider or an invalid request was made.
        /// MLResult.Result will be <c>MLResult.Code.LocationNetworkConnection</c> if there was no internet connection.
        /// MLResult.Result will be <c>MLResult.Code.LocationNoLocation</c> if the location could not be found.
        /// </returns>
        public static MLResult GetLastFineLocation(out Location fineLocation)
        {
            try
            {
                if (MLLocation.IsValidInstance())
                {
                    MLResult result = NativeBindings.MLLocationGetLastLocation(out fineLocation, true);

                    if (result.IsOk)
                    {
                        _instance.lastValidFineLocation = fineLocation;
                    }
                    else
                    {
                        MLPluginLog.ErrorFormat("MLLocation.GetLastFineLocation failed to get location. Reason: {0}", result);
                    }

                    return(result);
                }
                else
                {
                    fineLocation = new Location();
                    MLPluginLog.ErrorFormat("MLLocation.GetLastFineLocation failed. Reason: No Instance for MLLocation.");
                    return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLLocation.GetLastFineLocation failed. Reason: No Instance for MLLocation."));
                }
            }
            catch (System.EntryPointNotFoundException)
            {
                fineLocation = new Location();
                MLPluginLog.Error("MLLocation.GetLastFineLocation failed. Reason: API symbols not found");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLLocation.GetLastFineLocation failed. Reason: API symbols not found."));
            }
        }
            /// <summary>
            /// Apply any changes made to the MLCamera.GeneralSettings properties.
            /// </summary>
            /// <returns>
            /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successful.
            /// MLResult.Result will be <c>MLResult.Code.MediaGenericUnexpectedNull</c> if failed to connect to camera characteristic due to null pointer.
            /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
            /// MLResult.Result will be <c>MLResult.Code.AllocFailed</c> if failed to allocate memory.
            /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if necessary privilege is missing.
            /// </returns>
            public MLResult Apply()
            {
                MLResult.Code resultCode;

                if (this.SensorInfoExposureTimeRange.IsDirty)
                {
                    ulong cameraCharacteristicsHandle = MagicLeapNativeBindings.InvalidHandle;
                    resultCode = MLCameraNativeBindings.MLCameraGetCameraCharacteristics(ref cameraCharacteristicsHandle);

                    if (!MLResult.IsOK(resultCode))
                    {
                        MLResult result = MLResult.Create(resultCode);
                        MLPluginLog.ErrorFormat("MLCamera.GeneralSettings.Apply failed to get camera characteristics for MLCamera while applying. Reason: {0}", result);
                        return(result);
                    }

                    long[] sensorExposureTimeRange = new long[2];
                    sensorExposureTimeRange[0] = this.SensorInfoExposureTimeRange.Minimum;
                    sensorExposureTimeRange[1] = this.SensorInfoExposureTimeRange.Maximum;

                    resultCode = MLCameraNativeBindings.MLCameraMetadataSetSensorInfoExposureTimeRange(cameraCharacteristicsHandle, sensorExposureTimeRange);

                    if (!MLResult.IsOK(resultCode))
                    {
                        MLResult result = MLResult.Create(resultCode);
                        MLPluginLog.ErrorFormat("MLCamera.GeneralSettings.Apply failed to set sensor exposure time range. Reason: {0}", result);
                        return(result);
                    }
                }

                return(MLResult.Create(MLResult.Code.Ok));
            }
示例#24
0
                /// <summary>
                /// Gets a managed operation result for a specific operation handle.
                /// </summary>
                /// <param name="handle">Handle to a specific operation.</param>
                /// <param name="result">Managed operation result.</param>
                /// <returns>
                /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if any of the parameters are invalid.
                /// MLResult.Result will be <c>MLResult.Code.Pending</c> if the request is still pending.
                /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if the operation failed with an unspecified error.
                /// MLResult.Result will be <c>MLResult.Code.ContactsCompleted</c> if the request is completed.
                /// MLResult.Result will be <c>MLResult.Code.ContactsHandleNotFound</c> if the request corresponding to the handle was not found.
                /// </returns>
                public static MLResult.Code GetManagedOperationResult(ulong handle, out MLContacts.OperationResult result)
                {
                    MLResult.Code resultCode = NativeBindings.MLContactsTryGetOperationResult(handle, out IntPtr operationResultPtr);
                    if (resultCode != MLResult.Code.Pending)
                    {
                        if (resultCode != MLResult.Code.ContactsCompleted)
                        {
                            MLPluginLog.ErrorFormat("NativeBindings.GetManagedOperationResult failed to get operation result. Reason: {0}", MLResult.CodeToString(resultCode));
                        }

                        NativeBindings.OperationResultNative internalResult  = (NativeBindings.OperationResultNative)Marshal.PtrToStructure(operationResultPtr, typeof(NativeBindings.OperationResultNative));
                        NativeBindings.ContactNative         internalContact = (NativeBindings.ContactNative)Marshal.PtrToStructure(internalResult.Contact, typeof(NativeBindings.ContactNative));

                        result = new MLContacts.OperationResult()
                        {
                            Status  = internalResult.Status,
                            Contact = internalContact.Data,
                        };
                    }
                    else
                    {
                        result = new MLContacts.OperationResult();
                    }

                    return(resultCode);
                }
示例#25
0
        /// <summary>
        /// Retrieves the platform API level that the OS supports.
        /// </summary>
        private void GetPlatformLevel()
        {
            try
            {
                uint          level      = 0;
                MLResult.Code resultCode = MagicLeapNativeBindings.MLPlatformGetAPILevel(ref level);
                if (resultCode != MLResult.Code.Ok)
                {
                    MLPluginLog.ErrorFormat("MLDevice.GetPlatformLevel failed to get platform level. Reason: {0}", resultCode);
                }
                else
                {
                    this.platformLevel = level;
                }
            }
            catch (DllNotFoundException)
            {
                MLPluginLog.ErrorFormat("MLDevice.GetPlatformLevel failed. Reason: {0} library not found", MagicLeapNativeBindings.MLPlatformDll);
            }

            if (this.platformLevel == null)
            {
                this.platformLevel = 0;
            }
        }
示例#26
0
                /// <summary>
                /// Gets a managed operation result for a specific operation handle.
                /// </summary>
                /// <param name="handle">Handle to a specific operation.</param>
                /// <param name="listResult">Managed operation result.</param>
                /// <returns>
                /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if any of the parameters are invalid.
                /// MLResult.Result will be <c>MLResult.Code.Pending</c> if the request is still pending.
                /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if the operation failed with an unspecified error.
                /// MLResult.Result will be <c>MLResult.Code.ContactsCompleted</c> if the request is completed.
                /// MLResult.Result will be <c>MLResult.Code.ContactsHandleNotFound</c> if the request corresponding to the handle was not found.
                /// </returns>
                public static MLResult.Code GetManagedListResult(ulong handle, out MLContacts.ListResult listResult)
                {
                    MLResult.Code resultCode = NativeBindings.MLContactsTryGetListResult(handle, out IntPtr operationResultPtr);
                    if (resultCode != MLResult.Code.Pending)
                    {
                        if (resultCode != MLResult.Code.ContactsCompleted)
                        {
                            MLPluginLog.ErrorFormat("NativeBindings.GetManagedListResult failed to get list result. Reason: {0}", MLResult.CodeToString(resultCode));
                        }

                        NativeBindings.ListResultNative internalListResult = (NativeBindings.ListResultNative)Marshal.PtrToStructure(operationResultPtr, typeof(NativeBindings.ListResultNative));

                        listResult = new MLContacts.ListResult()
                        {
                            Status    = internalListResult.Status,
                            List      = internalListResult.List.Data,
                            Offset    = Marshal.PtrToStringAnsi(internalListResult.Offset),
                            TotalHits = internalListResult.TotalHits,
                        };
                    }
                    else
                    {
                        listResult = new MLContacts.ListResult();
                    }

                    return(resultCode);
                }
        /// <summary>
        /// Gets the most recent Head Tracking state.
        /// </summary>
        /// <param name="state">Some MLHeadTracking.State object to be filled with current state information.</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if the head tracking state was successfully received.
        /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if the outState parameter was not valid (null).
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed to receive head tracking state.
        /// </returns>
        public static MLResult GetState(out State state)
        {
            state = new State();

            if (MLHeadTracking.IsValidInstance())
            {
                try
                {
                    MLResult.Code resultCode = NativeBindings.MLHeadTrackingGetState(_instance.handle, ref _instance.stateNative);

                    state.Mode       = (TrackingMode)_instance.stateNative.Mode;
                    state.Confidence = _instance.stateNative.Confidence;
                    state.Error      = (TrackingError)_instance.stateNative.Error;
                    state.Handle     = _instance.handle;

                    return(MLResult.Create(resultCode));
                }
                catch (EntryPointNotFoundException)
                {
                    MLPluginLog.Error("MLHeadTracking.GetState failed. Reason: API symbols not found.");
                    return(MLResult.Create(MLResult.Code.UnspecifiedFailure));
                }
            }
            else
            {
                MLPluginLog.ErrorFormat("MLHeadTracking.GetState failed. Reason: No Instance for MLHeadTracking.");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLHeadTracking.GetState failed. Reason: No Instance for MLHeadTracking."));
            }
        }
示例#28
0
        /// <summary>
        /// Reads the country code of the system locale.
        /// </summary>
        /// <param name="country">Country code defined in ISO 3166, or an empty string. Valid only if <c>MLResult.Code.Ok</c> is returned, empty string otherwise.</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if the country code was retrieved successfully.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if there was an unspecified error.
        /// </returns>
        public static MLResult GetSystemCountry(out string country)
        {
            IntPtr   outCountry = IntPtr.Zero;
            MLResult result;

            try
            {
                MLResult.Code resultCode = NativeBindings.MLLocaleGetSystemCountry(ref outCountry);
                result = MLResult.Create(resultCode);
                if (result.IsOk)
                {
                    country = MLConvert.DecodeUTF8(outCountry);
                }
                else
                {
                    country = string.Empty;
                    MLPluginLog.ErrorFormat("MLLocale.GetSystemCountry failed. Reason: {0}", result);
                }
            }
            catch (System.DllNotFoundException)
            {
                MLPluginLog.Error("MLLocale.GetSystemCountry failed. Reason: MLLocale API is currently available only on device.");
                result  = MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLLocale.GetSystemCountry failed. Reason: Dll not found.");
                country = string.Empty;
            }
            catch (System.EntryPointNotFoundException)
            {
                MLPluginLog.Error("MLLocale.GetSystemCountry failed. Reason: API symbols not found.");
                result  = MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLLocale.GetSystemCountry failed. Reason: API symbols not found.");
                country = string.Empty;
            }

            return(result);
        }
        /// <summary>
        /// Retrieves the latest head-pose state.
        /// </summary>
        private void UpdateHeadposeState()
        {
            MLResult result = MLHeadTracking.GetState(out State headTrackingState);

            if (!result.IsOk)
            {
                if (this.headTrackingErrorTimer.LimitPassed)
                {
                    MLPluginLog.ErrorFormat("MLHeadTracking.UpdateHeadposeState failed to get head pose state. Reason: {0}", result);
                    this.headTrackingErrorTimer.Reset();
                }

                return;
            }
            else if (result.IsOk && this.lastHeadTrackingGetStateResult != MLResult.Code.Ok)
            {
                MLPluginLog.Warning("MLHeadTracking.UpdateHeadposeState is able to get head pose state again");
            }

            this.lastHeadTrackingGetStateResult = result.Result;

            bool headTrackingModeChanged = this.lastHeadTrackingState.Mode != headTrackingState.Mode;

            this.lastHeadTrackingState = headTrackingState;

            if (headTrackingModeChanged)
            {
                this.OnHeadTrackingModeChanged?.Invoke(headTrackingState);
            }
        }
示例#30
0
        /// <summary>
        /// Get the intrinsic calibration parameters.
        /// </summary>
        /// <param name="cameraId">The id of the camera.</param>
        /// <param name="outParameters">The intrinsic calibration parameters.</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if obtained result extras successfully.
        /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if failed to obtain result extras due to invalid input parameter.
        /// </returns>
        private MLResult InternalGetIntrinsicCalibrationParameters(MLCVCameraNativeBindings.CameraID cameraId, out MLCVCamera.IntrinsicCalibrationParameters outParameters)
        {
            outParameters = new MLCVCamera.IntrinsicCalibrationParameters();

            MLCVCameraNativeBindings.IntrinsicCalibrationParametersNative internalParameters =
                MLCVCameraNativeBindings.IntrinsicCalibrationParametersNative.Create();

            MLResult.Code resultCode = MLCVCameraNativeBindings.MLCVCameraGetIntrinsicCalibrationParameters(Handle, cameraId, ref internalParameters);

            MLResult parametersResult = MLResult.Create(resultCode);

            if (!parametersResult.IsOk)
            {
                MLPluginLog.ErrorFormat("MLCamera.InternalGetIntrinsicCalibrationParameters failed to get camera parameters. Reason: {0}", parametersResult);
            }
            else
            {
                outParameters.Width          = internalParameters.Width;
                outParameters.Height         = internalParameters.Height;
                outParameters.FocalLength    = new Vector2(internalParameters.FocalLength.X, internalParameters.FocalLength.Y);
                outParameters.PrincipalPoint = new Vector2(internalParameters.PrincipalPoint.X, internalParameters.PrincipalPoint.Y);
                outParameters.FOV            = internalParameters.FOV;
                outParameters.Distortion     = new double[internalParameters.Distortion.Length];
                internalParameters.Distortion.CopyTo(outParameters.Distortion, 0);
            }

            return(parametersResult);
        }