/// <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")); } }
/// <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> /// Start tracking hands with all key poses disabled. /// </summary> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if successful. /// MLResult.Result will be <c>MLResult.Code.UnspecifiedFailure</c> if failed to initialize the native hand tracker. /// </returns> protected override MLResult.Code StartAPI() { this.left = new Hand(MLHandTracking.HandType.Left); this.right = new Hand(MLHandTracking.HandType.Right); // Initialize KeyPoseManager, to register the gesture subsystem. this.keyposeManager = new KeyposeManager(Left, Right); try { // Attempt to start the tracker & validate. NativeBindings.SetHandGesturesEnabled(true); if (!NativeBindings.IsHandGesturesEnabled()) { MLPluginLog.Error("MLHandTracking.StartAPI failed to initialize the native hand tracker."); return(MLResult.Code.UnspecifiedFailure); } } catch (EntryPointNotFoundException) { MLPluginLog.Error("MLHandTracking.StartAPI failed. Reason: API symbols not found."); return(MLResult.Code.UnspecifiedFailure); } return(MLResult.Code.Ok); }
/// <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; } }
/// <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> /// Set custom key request key-value pair parameters used when generating default key request. /// </summary> /// <param name="messageData">(unused) Dictionary of optional key-value pair parameters</param> public void SetCustomLicenseMessageData(Dictionary <string, string> messageData) { if (messageData != null) { MLPluginLog.Warning("MLMediaPlayerEditor.SetCustomLicenseMessageData failed, editor version of MLMediaPlayer does not support DRM."); } }
/// <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> /// 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 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; } }
/// <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 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); }
/// <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)); }
/// <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> /// Enables or disables an array of key poses. /// Enabling too many key poses will currently lead to decreased sensitivity to each /// individual key pose. /// </summary> /// <param name="keyPoses">The list of key poses to affect.</param> /// <param name="enable">Enable or disable key poses.</param> /// <param name="exclusive"> /// When enabling and this is true, only the list of provided key poses /// are enabled, all other previously-enabled key poses get disabled. No effect if /// parameter enable is false. /// </param> /// <returns> /// True if the chosen key poses were successfully enabled/disabled and applied to the key pose config. /// </returns> public bool EnableKeyPoses(MLHandTracking.HandKeyPose[] keyPoses, bool enable, bool exclusive = false) { if (keyPoses == null || keyPoses.Length <= 0) { MLPluginLog.Error("KeyPoseManager.EnableKeyPoses passed key poses array is null or empty."); return(false); } if (enable) { // Enable the hand tracking pipeline. this.config.HandTrackingPipelineEnabled = true; if (exclusive) { // Disable all other previous key poses. this.SetKeyPoseConfig(0); } } foreach (var keyPoseType in keyPoses) { SetKeyPoseConfig(this.config, keyPoseType, enable); } return(this.ApplyConfig()); }
/// <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> /// Sets the license server for DRM videos (should not be called) /// </summary> /// <param name="licenseServer">(unused) URL of the License Server</param> public void SetLicenseServer(string licenseServer) { if (!string.IsNullOrEmpty(licenseServer)) { MLPluginLog.Warning("MLMediaPlayerEditor.SetLicenseServer failed, editor version of MLMediaPlayer does not support DRM."); } }
/// <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 custom function to custom parse the license response. /// The default implementation, setting this to null, will treat the entire response as the raw license data. /// </summary> /// <param name="responseParser"> /// (unused) Function to parse license response. /// First parameter is the DRM track being processed, either Video or Audio. /// Second parameter is the byte[] containing the response we received from the license server. /// Return is the byte[] which will be the raw license data, base64 decoding if necessary. /// </param> public void SetCustomLicenseResponseParser(MLMediaPlayer.MediaPlayerCustomLicenseDelegate responseParser) { if (responseParser != null) { MLPluginLog.Warning("MLMediaPlayerEditor.SetCustomLicenseResponseParser failed, editor version of MLMediaPlayer does not support DRM."); } }
/// <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); }
/// <summary> /// Ensures the camera transform is at the origin. /// </summary> /// <param name="scene">Current scene.</param> /// <param name="mode">Scene loading mode.</param> private void CheckMainCameraTransform(Scene scene, LoadSceneMode mode) { Camera mainCamera = Camera.main; // Return if there is no camera or if we are loading an additive scene. if (mainCamera == null || mode == LoadSceneMode.Additive) { return; } Transform cameraTransform = mainCamera.transform; if (cameraTransform.localPosition != Vector3.zero || cameraTransform.localRotation != Quaternion.identity || cameraTransform.localScale != Vector3.one) { MLPluginLog.WarningFormat( "The main camera's transform is not set to identity in scene \"{0}\": " + "position : {1}, rotation : {2}, scale : {3}. " + "Those changes can cause undesired effects.", scene.name, cameraTransform.localPosition, cameraTransform.localRotation.eulerAngles, cameraTransform.localScale); } }
/// <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> /// 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> /// 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); }
/// <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.")); } }
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 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."); } } }