Beispiel #1
0
 /// <summary>
 /// Initializes the given AppDefinedVideoSource object.
 /// </summary>
 /// <param name="appDefinedVideoSource">The AppDefinedVideoSource object to initialize.</param>
 /// <param name="result">The MLResult object of the inner platform call(s).</param>
 /// <returns>An AppDefinedVideoSource object with the given handle.</returns>
 public static MLResult InitializeLocal(AppDefinedVideoSource appDefinedVideoSource)
 {
     MLWebRTC.Instance.localTracks.Add(appDefinedVideoSource);
     MLResult.Code resultCode = NativeBindings.InitializeAppDefinedVideoSource(appDefinedVideoSource);
     DidNativeCallSucceed(resultCode, "InitializeAppDefinedVideoSource()");
     return(MLResult.Create(resultCode));
 }
Beispiel #2
0
        /// <summary>
        /// Register a unique schema for <c>OAuth</c> redirect handler. The caller needs to ensure that the schema is unique.
        /// If the schema is already registered the function will return an error. The handler
        /// will be called once the authorization procedure has been completed.
        /// The caller should register two schema callbacks. The first will be for
        /// authorization redirect and the second schema will in case the user cancels
        /// the authentication.
        /// </summary>
        /// <param name="schema">A unique string that will match the redirect uri schema</param>
        /// <param name="callback">MLDispatch <c>OAuth</c> callback function</param>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if the new schema has been registered correctly.
        /// MLResult.Result will be <c>MLResult.Code.PrivilegeDenied</c> if SecureBrowserWindow privilege is denied.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if the operation failed with an unspecified error.
        /// MLResult.Result will be <c>MLResult.Code.SchemaAlreadyRegistered</c> if the schema already is registered.
        /// MLResult.Result will be <c>MLResult.Code.Dispatch*</c> if a dispatch specific error occurred.
        /// </returns>
        public static MLResult OAuthRegisterSchema(string schema, ref OAuthHandler callback)
        {
            try
            {
                NativeBindings.OAuthCallbacksNative newSchema = NativeBindings.OAuthCallbacksNative.Create();
                newSchema.OnReplyComplete = OAuthOnReplyNative;

                int newID = uniqueID + 1;

                MLResult.Code resultCode = NativeBindings.MLDispatchOAuthRegisterSchemaEx(schema, ref newSchema, new IntPtr(newID));

                if (MLResult.IsOK(resultCode))
                {
                    OAuthPair newEntry = new OAuthPair(schema, callback);
                    oAuthCallbacks.Add(newID, newEntry);
                    uniqueID = newID;
                }

                return(MLResult.Create(resultCode));
            }
            catch (System.DllNotFoundException)
            {
                MLPluginLog.Error(DllNotFoundExceptionError);
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure, DllNotFoundExceptionError));
            }
            catch (System.EntryPointNotFoundException)
            {
                MLPluginLog.Error("MLDispatch API symbols not found");
                return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "MLDispatch API symbols not found"));
            }
        }
        /// <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));
        }
                /// <summary>
                /// Creates an initialized Track object.
                /// </summary>
                /// <param name="result">The MLResult object of the inner platform call(s).</param>
                /// <returns> An initialized Track object.</returns>
                public static Track CreateAudioTrackFromMicrophone(out MLResult result, string trackId = "")
                {
                    Track track  = null;
                    ulong handle = MagicLeapNativeBindings.InvalidHandle;

                    MLResult.Code resultCode = MLResult.Code.Ok;

                    resultCode = Source.NativeBindings.MLWebRTCSourceCreateLocalSourceForMicrophoneEx(trackId, out handle);

                    if (!DidNativeCallSucceed(resultCode, "MLWebRTCSourceCreateLocalSourceForMicrophoneEx()"))
                    {
                        result = MLResult.Create(resultCode);
                        return(track);
                    }

                    track = new Track(trackId)
                    {
                        Handle    = handle,
                        TrackType = Type.Audio,
                        IsLocal   = true,
                    };

                    MLWebRTC.Instance.localTracks.Add(track);
                    result = MLResult.Create(resultCode);
                    return(track);
                }
        /// <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;
            }
        }
        private MLResult InternalGetScreensInfo(out List <MLScreensScreenInfo> info)
        {
            info = new List <MLScreensScreenInfo>();
            _screenInfoList.Initialize();
            MLResult.Code resultCode = MLScreensNativeBindings.MLScreensGetScreenInfoListEx(ref _screenInfoList);
            var           result     = MLResult.Create(resultCode);

            if (!result.IsOk)
            {
                return(result);
            }

            long screensArrayAddress = _screenInfoList.Entries.ToInt64();

            for (var i = 0; i < _screenInfoList.Count; ++i)
            {
                long entryAddress = screensArrayAddress +
                                    i * Marshal.SizeOf(typeof(MLScreensNativeBindings.MLScreensScreenInfoExNative));
                var entryPtr    = new IntPtr(entryAddress);
                var entryNative = (MLScreensNativeBindings.MLScreensScreenInfoExNative)Marshal.PtrToStructure(entryPtr,
                                                                                                              typeof(MLScreensNativeBindings.MLScreensScreenInfoExNative));
                MLScreensScreenInfo entry = entryNative.Data;
                info.Add(entry);
            }
            resultCode = MLScreensNativeBindings.MLScreensReleaseScreenInfoListEx(ref _screenInfoList);
            result     = MLResult.Create(resultCode);
            return(result);
        }
Beispiel #7
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>
        /// Retrieves the data associated with the specified key.
        /// </summary>
        /// <param name="dataKey">The key for the data that is being requested.</param>
        /// <param name="data">A valid array of bytes to store retrieved data.</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 internal invalid input parameter.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
        /// MLResult.Result will be <c>MLResult.Code.SecureStorageBlobNotFound</c> if the dataKey was not found.
        /// MLResult.Result will be <c>MLResult.Code.SecureStorageIOFailure</c> if an I/O failure occurred.
        /// </returns>
        public static MLResult GetData(string dataKey, ref byte[] data)
        {
            try
            {
                MLResult result = CheckKey(dataKey);
                if (!result.IsOk)
                {
                    return(result);
                }

                IntPtr outputBytes = IntPtr.Zero;
                ulong  dataLength  = 0;

                MLResult.Code resultCode = MLSecureStorageNativeBindings.MLSecureStorageGetBlob(dataKey, ref outputBytes, ref dataLength);
                result = MLResult.Create(resultCode);

                // Are there situations where the result is Ok but no data is available?
                if (result.IsOk && dataLength > 0 && outputBytes != IntPtr.Zero)
                {
                    data = new byte[dataLength];
                    Marshal.Copy(outputBytes, data, 0, (int)dataLength);

                    MLSecureStorageNativeBindings.MLSecureStorageFreeBlobBuffer(outputBytes);
                }

                return(result);
            }
            catch (System.DllNotFoundException)
            {
                MLPluginLog.Error(DllNotFoundError);
                throw;
            }
        }
        /// <summary>
        /// Stores the specified data under the specified key. An existing key would be overwritten.
        /// </summary>
        /// <param name="dataKey">The key string associated with the data.</param>
        /// <param name="data">The data byte array to store.</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 internal invalid input parameter.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
        /// MLResult.Result will be <c>MLResult.Code.SecureStorageIOFailure</c> if an I/O failure occurred.
        /// </returns>
        public static MLResult StoreData(string dataKey, byte[] data)
        {
            try
            {
                // Early exit if array is invalid.
                if (data == null)
                {
                    return(MLResult.Create(MLResult.Code.InvalidParam, "Data parameter was null"));
                }

                // Early exit if string key is invalid.
                MLResult result = CheckKey(dataKey);
                if (!result.IsOk)
                {
                    return(result);
                }

                MLResult.Code resultCode = MLSecureStorageNativeBindings.MLSecureStoragePutBlob(dataKey, data, (uint)data.Length);
                result = MLResult.Create(resultCode);

                return(result);
            }
            catch (System.DllNotFoundException)
            {
                MLPluginLog.Error(DllNotFoundError);
                throw;
            }
        }
Beispiel #10
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);
                }
Beispiel #11
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 an update for the request.
            /// </summary>
            protected void Update()
            {
                if (this.Status == PageStatus.Pending)
                {
                    MLResult.Code resultCode = MLContacts.GetListResult(this.RequestHandle, out this.listResult);

                    switch (resultCode)
                    {
                    case MLResult.Code.ContactsHandleNotFound:
                    case MLResult.Code.InvalidParam:
                    {
                        this.PageFailed(resultCode);
                    }

                    break;

                    case MLResult.Code.ContactsCompleted:
                    {
                        this.PageReady();
                    }

                    break;

                    case MLResult.Code.Pending:
                    default:
                        break;
                    }
                }
            }
Beispiel #13
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"));
            }
        }
Beispiel #14
0
        private MLResult RequestPrivilegeAsyncInternal(MLPrivileges.Id privilegeId, CallbackDelegate callback)
        {
            if (callback == null)
            {
                return(MLResult.Create(MLResult.Code.InvalidParam, "MLPrivileges.RequestPrivilegeAsync failed. Reason: Must send a valid callback."));
            }

            if (!this.currentRequests.ContainsKey(privilegeId))
            {
                IntPtr newRequest = IntPtr.Zero;

                MLResult.Code resultCode = NativeBindings.MLPrivilegesRequestPrivilegeAsync(privilegeId, ref newRequest);
                if (resultCode == MLResult.Code.Ok)
                {
                    RequestPrivilegeQuery newQuery = new RequestPrivilegeQuery(callback, newRequest, privilegeId);
                    this.currentRequests.Add(privilegeId, newQuery);
                }

                return(MLResult.Create(resultCode));
            }
            else
            {
                return(MLResult.Create(MLResult.Code.Ok));
            }
        }
Beispiel #15
0
                /// <summary>
                /// Initialized a given appDefinedVideoSource object and sets it's callbacks.
                /// </summary>
                /// <param name="appDefinedVideoSource">The AppDefinedVideoSource object to initialize.</param>
                /// <returns>
                /// MLResult.Result will be <c>MLResult.Code.Ok</c> if the connection was successfully created.
                /// 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.
                /// </returns>
                public static MLResult.Code InitializeAppDefinedVideoSource(MLWebRTC.AppDefinedVideoSource appDefinedVideoSource)
                {
#if PLATFORM_LUMIN
                    appDefinedVideoSource.TrackType = Type.Video;
                    appDefinedVideoSource.IsLocal   = true;
                    appDefinedVideoSource.gcHandle  = GCHandle.Alloc(appDefinedVideoSource);
                    IntPtr gcHandlePtr = GCHandle.ToIntPtr(appDefinedVideoSource.gcHandle);

                    ulong appDefinedVideoSourceHandle = MagicLeapNativeBindings.InvalidHandle;

                    NativeBindings.MLWebRTCAppDefinedSourceEventCallbacks callbacks = NativeBindings.MLWebRTCAppDefinedSourceEventCallbacks.Create(gcHandlePtr);
                    MLResult.Code resultCode = NativeBindings.MLWebRTCSourceCreateAppDefinedVideoSource(in callbacks, out appDefinedVideoSourceHandle);
                    appDefinedVideoSource.Handle = appDefinedVideoSourceHandle;

                    if (!MLResult.IsOK(resultCode))
                    {
                        appDefinedVideoSource.gcHandle.Free();
                    }

                    return(resultCode);
#else
                    appDefinedVideoSource = null;
                    return(MLResult.Code.Ok);
#endif
                }
        /// <summary>
        /// Generic store function for all value types.
        /// Using BinaryFormatter.Serialize() to serialize data to bytes.
        /// </summary>
        /// <typeparam name="T">The type of data that is being retrieved.</typeparam>
        /// <param name="dataKey">The key string associated with the data.</param>
        /// <param name="value">The generic type value to store.</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 internal invalid input parameter.
        /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed due to internal error.
        /// MLResult.Result will be <c>MLResult.Code.SecureStorageIOFailure</c> if an I/O failure occurred.
        /// </returns>
        public static MLResult StoreData <T>(string dataKey, T value) where T : struct
        {
            // TODO: use non-template version of StoreData after converting value to byte array
            try
            {
                MLResult result = CheckKey(dataKey);
                if (!result.IsOk)
                {
                    return(result);
                }

                byte[] valueByteArray = SerializeData(value);
                if (valueByteArray == null)
                {
                    return(MLResult.Create(MLResult.Code.UnspecifiedFailure, "Data serialization failed"));
                }

                MLResult.Code resultCode = MLSecureStorageNativeBindings.MLSecureStoragePutBlob(dataKey, valueByteArray, (uint)valueByteArray.Length);
                result = MLResult.Create(resultCode);

                return(result);
            }
            catch (System.DllNotFoundException)
            {
                MLPluginLog.Error(DllNotFoundError);
                throw;
            }
        }
        /// <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);
        }
Beispiel #18
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);
        }
        private MLResult InternalGetThumbnail(long entryId, out Texture2D imageThumbnail)
        {
            imageThumbnail = null;

            if (!_watchHistory.ContainsKey(entryId))
            {
                return(MLResult.Create(MLResult.Code.InvalidParam, "Unknown entry Id"));
            }

            var thumbnail = new MLImageNativeBindings.MLImageNative();

            MLResult.Code resultCode = MLScreensNativeBindings.MLScreensGetWatchHistoryThumbnail(entryId, ref thumbnail);
            var           result     = MLResult.Create(resultCode);

            if (!result.IsOk)
            {
                return(result);
            }

            imageThumbnail =
                new Texture2D((int)thumbnail.Width,
                              (int)thumbnail.Height,
                              TextureFormat.RGB24,
                              false,
                              true);

            imageThumbnail.LoadRawTextureData(thumbnail.Image,
                                              (int)(thumbnail.Height * thumbnail.Width) * RGBBytesPerPixel);
            resultCode = MLScreensNativeBindings.MLScreensReleaseWatchHistoryThumbnail(ref thumbnail);
            result     = MLResult.Create(resultCode);
            return(result);
        }
        /// <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>
        /// 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>
                /// Sets a track to be enabled or disabled.
                /// </summary>
                /// <param name="isEnabled">True if the track should be enabled.</param>
                /// <returns>
                /// MLResult.Result will be <c>MLResult.Code.Ok</c> if destroying all handles was successful.
                /// MLResult.Result will be <c>MLResult.Code.WebRTCResultInstanceNotCreated</c> if MLWebRTC instance was not created.
                /// MLResult.Result will be <c>MLResult.Code.WebRTCResultMismatchingHandle</c> if an incorrect handle was sent.
                /// </returns>
                public MLResult SetEnabled(bool isEnabled)
                {
#if PLATFORM_LUMIN
                    if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle))
                    {
                        return(MLResult.Create(MLResult.Code.InvalidParam, "Source handle is invalid."));
                    }

                    MLResult result = this.GetEnabled(out bool trackEnabled);
                    if (!result.IsOk)
                    {
                        return(result);
                    }

                    if (trackEnabled != isEnabled)
                    {
                        MLResult.Code resultCode = Source.NativeBindings.MLWebRTCSourceSetEnabled(this.Handle, isEnabled);
                        DidNativeCallSucceed(resultCode, "MLWebRTCSourceSetEnabled");
                        result = MLResult.Create(resultCode);
                    }

                    return(result);
#else
                    return(new MLResult());
#endif
                }
        /// <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);
        }
Beispiel #25
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."));
                }
            }
Beispiel #26
0
        /// <summary>
        /// Connects to the MRCamera and prepares it for capturing.
        /// </summary>
        /// <returns>
        /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successfully initialized the MR camera.
        /// MLResult.Result will be <c>MLResult.Code.InvalidParam</c> if failed due to an invalid input parameter.
        /// MLResult.Result will be <c>MLResult.Code.MediaGenericAlreadyExists</c> if the MR camera was already initialized.
        /// MLResult.Result will be <c>MLResult.Code.MediaGenericNoInit</c> if the MR camera was not properly initialized.
        /// </returns>
        private MLResult.Code SetupMLMRCamera()
        {
            if (this.isConnected)
            {
                return(MLResult.Code.Ok);
            }

            NativeBindings.InputContextNative contextNative = new NativeBindings.InputContextNative();
            contextNative.Data = this.inputContext;
            MLResult.Code resultCode = NativeBindings.MLMRCameraConnect(ref contextNative);
            if (!MLMRCamera.DidNativeCallSucceed(resultCode, "MLMRCameraConnect"))
            {
                return(resultCode);
            }

            this.isConnected = true;

            NativeBindings.CallbacksNative callbacksNative = NativeBindings.CreateCallbacks();
            resultCode = NativeBindings.MLMRCameraSetCallbacks(ref callbacksNative, IntPtr.Zero);
            if (!MLMRCamera.DidNativeCallSucceed(resultCode, "MLMRCameraSetCallbacks"))
            {
                return(resultCode);
            }

            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."));
            }
        }
            /// <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);
                }
            }
        /// <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);
            }
        }
            /// <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.");
                    }
                }
            }