// %BANNER_BEGIN% // --------------------------------------------------------------------- // %COPYRIGHT_BEGIN% // Copyright (c) 2022 Magic Leap, Inc. All Rights Reserved. // Use of this file is governed by the Software License Agreement, located here: https://www.magicleap.com/software-license-agreement-ml2 // Terms and conditions applicable to third-party materials accompanying this distribution may also be found in the top-level NOTICE file appearing herein. // %COPYRIGHT_END% // --------------------------------------------------------------------- // %BANNER_END% using System; using System.Runtime.InteropServices; using UnityEngine.XR.MagicLeap.Native; namespace UnityEngine.XR.MagicLeap { public partial class MLDepthCamera { private class NativeBindings : MagicLeapNativeBindings { [StructLayout(LayoutKind.Sequential)] public struct MLDepthCameraSettings { /// /// Version of this structure /// public uint Version; /// /// The system may not be able to service all the requested streams at any /// given time. This parameter is treated as a hint and data will be /// provided for the requested streams if available. /// public uint Streams; /// /// Controls for each of the depth camera streams. /// Only controls for streams enabled via streams field will be read. /// Use MLDepthCamera.FrameType enumeration for indexing. /// [MarshalAs(UnmanagedType.ByValArray, SizeConst = FrameTypeCount)] public StreamConfig[] StreamConfig; public static MLDepthCameraSettings Init() { MLDepthCameraSettings settings = new MLDepthCameraSettings(); settings.Version = 2; settings.Streams = (uint)Stream.LongRange; StreamConfig[] config = new StreamConfig[2]; int i = (int)FrameType.LongRange; config[i].Flags = (uint)CaptureFlags.DepthImage; config[i].Exposure = 1600; config[i].FrameRateConfig = FrameRate.FPS_5; i = (int)FrameType.ShortRange; config[i].Flags = (uint)CaptureFlags.DepthImage; config[i].Exposure = 375; config[i].FrameRateConfig = FrameRate.FPS_5; settings.StreamConfig = config; return settings; } } [StructLayout(LayoutKind.Sequential)] public struct MLDepthCameraIntrinsics { public const int MaxDistortionCoefficients = 5; public uint Width; public uint Height; public MLVec2f FocalLength; public MLVec2f PrincipalPoint; public float FoV; [MarshalAs(UnmanagedType.ByValArray, SizeConst = MaxDistortionCoefficients)] public double[] Distortion; public static MLDepthCameraIntrinsics Init(Intrinsics managed) { var intrinsics = new MLDepthCameraIntrinsics { Width = managed.Width, Height = managed.Height, FocalLength = new MLVec2f() { X = managed.FocalLength.x, Y = managed.FocalLength.y }, PrincipalPoint = new MLVec2f() { X = managed.PrincipalPoint.x, Y = managed.PrincipalPoint.y }, FoV = managed.FoV, Distortion = managed.GetDistortionList().ToArray() }; return intrinsics; } public static Intrinsics ToManaged(MLDepthCameraIntrinsics nativeIntrinsics) { return new Intrinsics() { Width = nativeIntrinsics.Width, Height = nativeIntrinsics.Height, FocalLength = MLConvert.ToUnity(nativeIntrinsics.FocalLength), PrincipalPoint = MLConvert.ToUnity(nativeIntrinsics.PrincipalPoint), FoV = nativeIntrinsics.FoV, Distortion = new DistortionCoefficients(nativeIntrinsics.Distortion) }; } } [StructLayout(LayoutKind.Sequential)] public struct MLDepthCameraFrameBuffer { public uint Width; public uint Height; public uint Stride; public uint BytesPerUnit; public uint Size; public IntPtr Data; public static MLDepthCameraFrameBuffer Init(FrameBuffer? managed) { var result = new MLDepthCameraFrameBuffer(); if (managed != null) { result.Width = managed.Value.Width; result.Height = managed.Value.Height; result.Stride = managed.Value.Stride; result.BytesPerUnit = managed.Value.BytesPerUnit; result.Size = (managed.Value.Data != null) ? (uint)managed.Value.Data.Length : 0u; if (managed.Value.Data != null) { Marshal.Copy(managed.Value.Data, 0, result.Data, managed.Value.Data.Length); } return result; } else { result.Data = IntPtr.Zero; return result; } } } /// /// Structure to encapsulate output data for each camera sensor. /// [StructLayout(LayoutKind.Sequential)] public struct MLDepthCameraFrame { /// /// A 64bit integer to index the frame number associated with this frame. /// public long FrameNumber; /// /// Frame timestamp specifies the time at which the frame was captured. /// public long FrameTimestamp; /// /// Depth camera stream used for capturing this frame. /// public FrameType FrameType; /// /// Depth camera pose in the world co-ordinate system. /// public MLTransform CameraPose; /// /// Camera intrinsic parameters. /// public MLDepthCameraIntrinsics Intrinsics; /// /// Depth image. /// public IntPtr DepthImageFrameBufferPtr; /// /// Confidence score. /// public IntPtr ConfidenceBufferFrameBufferPtr; /// /// Depth flags. /// public IntPtr DepthFlagsBufferFrameBufferPtr; /// /// Ambient raw depth image. /// The illuminator in the sensor is modulated with a system determined frequency. /// This is the raw sensor data captured when the illuminator is off. /// public IntPtr AmbientRawDepthImageFrameBufferPtr; /// /// Raw depth image. /// The illuminator in the sensor is modulated with a system determined frequency. /// This is the raw sensor data captured when the illuminator is on. /// public IntPtr RawDepthImageFrameBufferPtr; public static MLDepthCameraFrame Init(Data managed) { var data = new MLDepthCameraFrame(); data.FrameNumber = managed.FrameNumber; data.FrameTimestamp = managed.FrameTimestamp; data.FrameType = managed.FrameType; data.CameraPose = new MLTransform() { Position = MLConvert.FromUnity(managed.Position), Rotation = MLConvert.FromUnity(managed.Rotation) }; data.Intrinsics = MLDepthCameraIntrinsics.Init(managed.Intrinsics); var depthMapPlaneInfo = MLDepthCameraFrameBuffer.Init(managed.DepthImage); Marshal.StructureToPtr(depthMapPlaneInfo, data.DepthImageFrameBufferPtr, true); var confidenceMapPlaneInfo = MLDepthCameraFrameBuffer.Init(managed.ConfidenceBuffer); Marshal.StructureToPtr(confidenceMapPlaneInfo, data.ConfidenceBufferFrameBufferPtr, true); var depthFlagsPlaneInfo = MLDepthCameraFrameBuffer.Init(managed.DepthFlagsBuffer); Marshal.StructureToPtr(depthFlagsPlaneInfo, data.DepthFlagsBufferFrameBufferPtr, true); var aiFlagsPlaneInfo = MLDepthCameraFrameBuffer.Init(managed.AmbientRawDepthImage); Marshal.StructureToPtr(aiFlagsPlaneInfo, data.AmbientRawDepthImageFrameBufferPtr, true); var rawDepthImageInfo = MLDepthCameraFrameBuffer.Init(managed.RawDepthImage); Marshal.StructureToPtr(rawDepthImageInfo, data.RawDepthImageFrameBufferPtr, true); return data; } } /// /// Structure to encapsulate output data for each camera stream. /// This structure must be initialized before use. /// [StructLayout(LayoutKind.Sequential)] public struct MLDepthCameraData { /// /// Version of this structure. /// public uint Version; /// /// Number of camera frames populated. /// public byte FrameCount; /// /// Camera frame data. The number of frames is specified by frame_count. /// public IntPtr Frames; public static MLDepthCameraData Init() { var data = new MLDepthCameraData(); data.Version = 3; return data; } } /// /// Structure to encapsulate a possible configuration for a single stream. /// Can be used to understand possible values for a specific StreamConfig element in MLDepthCameraSettings. /// The capabilities supported by the depth camera can be queried with MLDepthCameraGetCapabilities(). /// [StructLayout(LayoutKind.Sequential)] public struct MLDepthCameraStreamCapability { /// /// Stream for which this capability can be applied. /// public Stream Stream; /// /// Minimum sensor exposure in microseconds. /// public uint MinExposure; /// /// Maximum sensor exposure in microseconds. /// public uint MaxExposure; /// /// Frame rate. /// public FrameRate FrameRateCapability; } /// /// Structure to encapsulate a possible set of streams configuration. /// Such set describes a possible way of setting StreamConfig in MLDepthCameraSettings /// and may hold multiple MLDepthCameraStreamCapability for different streams. /// Whole StreamCapabilities array describe a single configuration. Using only part /// of it is not recommended. The capabilities supported by the depth camera can be queried /// with MLDepthCameraGetCapabilities(). /// [StructLayout(LayoutKind.Sequential)] public struct MLDepthCameraCapability { /// /// Size of StreamCapabilities array. /// public byte Size; /// /// Array of MLDepthCameraStreamCapability elements. /// public IntPtr StreamCapabilities; } /// /// Structure to encapsulate a list of possible stream configurations. /// User should be able to use any of the capabilities from the list. /// They are grouped in usable sets of configurations - one set may contain /// different MLDepthCameraStreamCapability for different streams. /// For more information see MLDepthCameraCapability. /// [StructLayout(LayoutKind.Sequential)] public struct MLDepthCameraCapabilityList { /// /// Size of Capabilities array. /// public byte Size; /// /// Array of MLDepthCameraCapability elements. /// public IntPtr Capabilities; } /// /// Structure to encapsulate camera capabilities filtering. /// The capabilities supported by the depth camera can be queried /// with MLDepthCameraGetCapabilities(). /// [StructLayout(LayoutKind.Sequential)] public struct MLDepthCameraCapabilityFilter { /// /// Version of this structure. /// public uint Version; /// /// Streams for which capabilities will be filtered. /// Can hold multiple Stream values. /// public uint Streams; public static MLDepthCameraCapabilityFilter Init() { var filter = new MLDepthCameraCapabilityFilter(); filter.Version = 1; return filter; } } /// /// Connect to depth camera. /// /// A pointer to MLDepthCameraSettings structure. /// A pointer to camera handle to be used in later APIs. /// /// MLResult_InvalidParam: One of the parameters is invalid. /// MLResult_LicenseError: Necessary license is missing. /// MLResult_Ok: Connected to camera device(s) successfully. /// MLResult_PermissionDenied: Necessary permission is missing. /// MLResult_UnspecifiedFailure: The operation failed with an unspecified error. /// /// /// apilevel: 29 /// permissions: com.magicleap.permission.DEPTH_CAMERA (protection level: dangerous) /// [DllImport(MLPerceptionClientDll, CallingConvention = CallingConvention.Cdecl)] public static extern MLResult.Code MLDepthCameraConnect(in MLDepthCameraSettings settings, out ulong handle); /// /// Update the depth camera settings. /// /// Camera handle obtained from MLDepthCameraConnect. /// Pointer to MLDepthCameraSettings. /// /// MLResult_InvalidParam: Invalid handle. /// MLResult_Ok: Settings updated successfully. /// MLResult_UnspecifiedFailure: Failed due to internal error. /// /// /// apilevel: 29 /// permissions: None /// [DllImport(MLPerceptionClientDll, CallingConvention = CallingConvention.Cdecl)] public static extern MLResult.Code MLDepthCameraUpdateSettings(ulong handle, in MLDepthCameraSettings settings); /// /// Query the depth camera stream capabilities. /// Retrieves the capabilities supported by the depth camera based on the provided filter. /// After each call, a corresponding call to MLDepthCameraReleaseCapabilities should be made /// to release allocated resources. /// /// Camera handle obtained from MLDepthCameraConnect. /// Pointer to initialized MLDepthCameraCapabilityFilter structure. Used for filtering. /// Pointer to initialized MLDepthCameraCapabilityList structure. /// /// MLResult_InvalidParam: One of the parameters is invalid. /// MLResult_Ok: API call completed successfully. /// /// /// apilevel: 29 /// permissions: None /// [DllImport(MLPerceptionClientDll, CallingConvention = CallingConvention.Cdecl)] public static extern MLResult.Code MLDepthCameraGetCapabilities(ulong handle, ref MLDepthCameraCapabilityFilter filter, out MLDepthCameraCapabilityList outCaps); /// /// Release resources allocated with MLDepthCameraGetCapabilities. /// /// Camera handle obtained from MLDepthCameraConnect. /// Pointer to MLDepthCameraCapabilityList filled by the call to MLDepthCameraGetCapabilities. /// /// MLResult_InvalidParam: One of the parameters is invalid. /// MLResult_Ok: API call completed successfully. /// /// /// apilevel: 29 /// permissions: None /// [DllImport(MLPerceptionClientDll, CallingConvention = CallingConvention.Cdecl)] public static extern MLResult.Code MLDepthCameraReleaseCapabilities(ulong handle, ref MLDepthCameraCapabilityList outCaps); /// /// Poll for Frames. /// Returns MLDepthCameraData with this latest data when available. The memory is /// owned by the system. Application should copy the data it needs to cache it /// and then release the memory by calling MLDepthCameraReleaseCameraData. /// This is a blocking call. API is not thread safe. /// If there are no new depth data frames within the timeoutMs duration then the /// API will return MLResult_Timeout. /// /// Camera handle obtained from MLDepthCameraConnect. /// Timeout in milliseconds. /// Depth camera data. Should be an initialized MLDepthCameraData object. /// /// MLResult_InvalidParam: Invalid handle. /// MLResult_Ok: Depth camera data fetched successfully. /// MLResult_Timeout: Returned because no new frame available at this time. /// MLResult_UnspecifiedFailure: Failed due to internal error. /// /// /// apilevel: 29 /// permissions: None /// [DllImport(MLPerceptionClientDll, CallingConvention = CallingConvention.Cdecl)] public static extern MLResult.Code MLDepthCameraGetLatestDepthData(ulong handle, ulong timeoutMs, out MLDepthCameraData data); /// /// Releases specified MLDepthCameraData object. /// This function should be called exactly once for each successfull call to /// MLDepthCameraGetLatestCameraData. /// /// Camera handle obtained from MLDepthCameraConnect. /// Pointer to a valid MLDepthCameraData object. /// /// MLResult_Ok: Successfully released depth camera data. /// MLResult_InvalidParam: data parameter was not valid (null). /// MLResult_UnspecifiedFailure: Failed due to internal error. /// /// /// apilevel: 29 /// permissions: None /// [DllImport(MLPerceptionClientDll, CallingConvention = CallingConvention.Cdecl)] public static extern MLResult.Code MLDepthCameraReleaseDepthData(ulong handle, ref MLDepthCameraData data); /// /// Disconnect from depth camera. /// This will disconnect from the depth camera. /// /// Camera handle obtained from MLDepthCameraConnect. /// /// MLResult_InvalidParam: Invalid handle. /// MLResult_Ok: Disconnected camera successfully. /// MLResult_UnspecifiedFailure: Failed to disconnect camera. /// /// /// apilevel: 29 /// permissions: None /// [DllImport(MLPerceptionClientDll, CallingConvention = CallingConvention.Cdecl)] public static extern MLResult.Code MLDepthCameraDisconnect(ulong handle); } } }