using System;
using System.Collections.Generic;
using System.Linq;
using Unity.Collections;
using UnityEngine;
namespace MagicLeap.OpenXR.Features.PixelSensors
{
public partial class MagicLeapPixelSensorFeature
{
///
/// Get all the supported sensors on the device.
/// Note: This will return all the sensors the device supports, not sensors that are currently available
///
/// List of the supported sensors on the platform
public List GetSupportedSensors()
{
Debug.Log("Trying to fetch available sensors!");
if (!pathsFetched)
{
GetAvailableSensorsInternal();
}
return supportedSensors.Where(sensorType => !unavailableSensors.Contains(sensorType)).ToList();
}
///
/// Get a Pixel Sensor given an XrPath String
///
/// The XrPath string of the sensor. /pixelsensor/world/left for example
/// The PixelSensorId associated with the sensor
/// True if a sensor was found, false otherwise
public bool GetPixelSensorFromXrPath(string path, out PixelSensorId sensorId)
{
var xrPath = StringToPath(path);
if(!pathsFetched)
{
GetAvailableSensorsInternal();
}
sensorId = supportedSensors.FirstOrDefault(sensor => sensor.XrPath == xrPath);
return sensorId != default;
}
///
/// Create a pixel sensor of the given type
///
/// The type of the sensor to create
/// True if the sensor was created
public bool CreatePixelSensor(PixelSensorId sensorType)
{
if (!pathsFetched)
{
GetAvailableSensorsInternal();
}
if (!supportedSensors.Contains(sensorType))
{
Debug.LogError($"{sensorType} was not found.");
return false;
}
var pixelSensorOperations = new PixelSensor(sensorType, sensorType, nativeFunctions, this);
var creationResult = pixelSensorOperations.CreatePixelSensor();
if (!creationResult)
{
return false;
}
connectedSensors[sensorType] = pixelSensorOperations;
return true;
}
///
/// Destroys a created pixel sensor
///
/// The type of the sensor to create
/// True if the sensor was destroyed
public bool DestroyPixelSensor(PixelSensorId sensorType)
{
if (!IsSensorConnected(sensorType, out var sensorOperation))
{
return false;
}
var result = sensorOperation.DestroyPixelSensor();
if (result)
{
connectedSensors.Remove(sensorType);
}
return result;
}
///
/// Get all the capabilities that a pixel sensor supports
///
/// The type of the pixel sensor
/// The stream index for which to get the supported capabilities for
/// The array of capabilities supported
/// True if the capabilities were fetched
public bool GetPixelSensorCapabilities(PixelSensorId sensorType, uint streamIndex, out PixelSensorCapability[] capabilities)
{
capabilities = Array.Empty();
if (!IsSensorConnected(sensorType, out var sensorOperation))
{
return false;
}
sensorOperation.EnumerateSensorCapabilities(streamIndex, out capabilities);
capabilities = capabilities.OrderByDescending(capability => IsCapabilityRequired(capability.CapabilityType)).ToArray();
return true;
}
///
/// Query a particular capability of a sensor to get its valid range
///
/// The type of the sensor to query the capability for
/// The type of the capability to query
/// The stream for which to query the capability
/// The range of the capability. Use the return value to determine if this value is accurate or not
/// True if the query was successful
public bool QueryPixelSensorCapability(PixelSensorId sensorType, PixelSensorCapabilityType capabilityType, uint streamIndex, out PixelSensorCapabilityRange capabilityRange)
{
capabilityRange = default;
return IsSensorConnected(sensorType, out var sensorOperation) && sensorOperation.QuerySensorCapability(capabilityType, streamIndex, out capabilityRange);
}
///
/// Get a configured value for a sensor.
/// A configured value is the value that is applied to the sensor by calling
///
/// The type of the sensor
/// The stream index to get the configured value for
/// The type of the capability
/// The configured value
/// True if a valid configuration was found
public bool GetConfiguredValueForSensor(PixelSensorId sensorType, uint streamIndex, PixelSensorCapabilityType capabilityType, out PixelSensorConfigData result)
{
result = null;
if (!IsSensorConnected(sensorType, out var sensor))
{
return false;
}
return sensor.GetAppliedConfigForCapability(streamIndex, capabilityType, out result);
}
///
/// Gets the capability range type and the capability data type for a sensor's capability
///
/// The type of the sensor
/// The stream index to query the capability for
/// The capability type
/// The range type and the data type for the capability
public (PixelSensorCapabilityRangeType, PixelSensorCapabilityDataType) GetPixelSensorRangeAndDataTypeForCapability(PixelSensorId sensorType, uint streamIndex, PixelSensorCapabilityType capabilityType)
{
if (!IsSensorConnected(sensorType, out var sensor))
{
return default;
}
return sensor.GetRangeAndDataType(capabilityType, streamIndex);
}
///
/// Apply a configuration to a sensor
/// To configure a sensor, capabilities have to be configured iteratively
/// Each applied configuration can impact other capabilities.
/// So, when applying a sensor config, query for the other capabilities that have not been applied to get the updated range and to check if this applied config can configure the sensor
/// Note: Every subsequent application of the same capability for the same stream will overwrite the previous value
///
/// The type of the sensor
/// The config data to apply
public void ApplySensorConfig(PixelSensorId sensorType, PixelSensorConfigData configData)
{
if (!IsSensorConnected(sensorType, out var sensorOperation))
{
return;
}
sensorOperation.ApplySensorConfig(configData);
}
///
/// An overloaded ApplySensorConfig that applies a float value for a capability
///
/// The type of the sensor
/// The capability type
/// The float value to be applied
/// The stream index
public void ApplySensorConfig(PixelSensorId sensorType, PixelSensorCapabilityType capabilityType, float value, uint streamIndex)
{
var config = new PixelSensorConfigData(capabilityType, streamIndex)
{
FloatValue = value
};
ApplySensorConfig(sensorType, config);
}
///
/// An overloaded ApplySensorConfig that applies a bool value for a capability
///
/// The type of the sensor
/// The capability type
/// The bool value to be applied
/// The stream index
public void ApplySensorConfig(PixelSensorId sensorType, PixelSensorCapabilityType capabilityType, bool value, uint streamIndex)
{
var config = new PixelSensorConfigData(capabilityType, streamIndex)
{
BoolValue = value
};
ApplySensorConfig(sensorType, config);
}
///
/// An overloaded ApplySensorConfig that applies a unsigned int value for a capability
///
/// The type of the sensor
/// The capability type
/// The unsigned int value to be applied
/// The stream index
public void ApplySensorConfig(PixelSensorId sensorType, PixelSensorCapabilityType capabilityType, uint value, uint streamIndex)
{
var config = new PixelSensorConfigData(capabilityType, streamIndex)
{
IntValue = value
};
ApplySensorConfig(sensorType, config);
}
///
/// An overloaded ApplySensorConfig that applies a Vector2Int value for a capability
///
/// The type of the sensor
/// The capability type
/// The Vector2Int value to be applied
/// The stream index
public void ApplySensorConfig(PixelSensorId sensorType, PixelSensorCapabilityType capabilityType, Vector2Int value, uint streamIndex)
{
var config = new PixelSensorConfigData(capabilityType, streamIndex)
{
VectorValue = value
};
ApplySensorConfig(sensorType, config);
}
///
/// Clears an applied config for a capability
///
/// The type of the sensor
/// The capability type
/// The stream index of the capability
public void ClearSensorConfig(PixelSensorId sensorType, PixelSensorCapabilityType capabilityType, uint streamIndex)
{
if (!IsSensorConnected(sensorType, out var sensorOperation))
{
return;
}
sensorOperation.ClearAppliedConfig(capabilityType, streamIndex);
}
///
/// Clears all the applied configs for a sensor
///
/// The type of the sensor
public void ClearAllAppliedConfigs(PixelSensorId sensorType)
{
if (!IsSensorConnected(sensorType, out var sensorOperation))
{
return;
}
sensorOperation.ClearAllAppliedConfigs();
}
///
/// Configures a sensor with default capabilities
///
/// The type of the sensor
/// The streams to configure
/// An async operation object for this operation (See: )
public PixelSensorAsyncOperationResult ConfigureSensorWithDefaultCapabilities(PixelSensorId sensorType, params uint[] streams)
{
if (streams.Length == 0)
{
Debug.LogError($"At least one stream must be specified.");
return PixelSensorAsyncOperationResult.FailedOperationResult;
}
if (!IsSensorConnected(sensorType, out var sensorOperation))
{
return PixelSensorAsyncOperationResult.FailedOperationResult;
}
Debug.Log($"---Configuring {sensorType} with default configuration-----");
foreach (var streamIndex in streams)
{
if (streamIndex >= sensorOperation.StreamCount)
{
Debug.LogError($"Invalid stream index {streamIndex}");
return PixelSensorAsyncOperationResult.FailedOperationResult;
}
sensorOperation.EnumerateSensorCapabilities(streamIndex, out var capabilities);
var capabilitiesToConfigure = capabilities.Where(capability => IsCapabilityRequired(capability.CapabilityType));
foreach (var capability in capabilitiesToConfigure)
{
if (sensorOperation.QuerySensorCapability(capability.CapabilityType, streamIndex, out var range))
{
if (!range.IsValid)
{
Debug.LogError($"Invalid Setting for {capability.CapabilityType}");
continue;
}
var config = range.GetDefaultConfig(streamIndex);
sensorOperation.ApplySensorConfig(config);
}
else
{
return PixelSensorAsyncOperationResult.FailedOperationResult;
}
}
}
return sensorOperation.ConfigureSensor(streams);
}
///
/// Gets the number of streams supported by a sensor
///
/// The type of the sensor
/// The number of streams supported by the sensor
public uint GetStreamCount(PixelSensorId sensorType)
{
return !IsSensorConnected(sensorType, out var sensorOperation) ? 0 : sensorOperation.GetStreamCount();
}
///
/// Returns if a given capability is required to configure a sensor
///
/// The type of capability to check
/// True if the capability is required for a successful configuration of the sensor
public bool IsCapabilityRequired(PixelSensorCapabilityType capabilityType) => RequiredCapabilities.Contains(capabilityType);
#region Async Operations
///
/// Start a configured sensor
///
/// The type of the sensor to start
/// The streams to start for the sensor
/// The types of the metadata for each stream
/// An awaitable operation result to indicate the progress of this operation. (See )
public PixelSensorAsyncOperationResult StartSensor(PixelSensorId sensorType, IEnumerable streams, Dictionary metaDataTypes = null)
{
if (!IsSensorConnected(sensorType, out var sensor))
{
return PixelSensorAsyncOperationResult.FailedOperationResult;
}
return sensor.StartSensor(streams, metaDataTypes);
}
///
/// Configure a given sensor for the passed streams
///
/// The type of the sensor to configure
/// The streams to configure
/// An awaitable operation result to indicate the progress of this operation. (See )
public PixelSensorAsyncOperationResult ConfigureSensor(PixelSensorId sensorType, IEnumerable streams)
{
if (!IsSensorConnected(sensorType, out var sensor))
{
return PixelSensorAsyncOperationResult.FailedOperationResult;
}
return sensor.ConfigureSensor(streams);
}
///
/// Stops a given sensor for the passed streams
///
/// The type of the sensor to stop
/// The streams to stop
/// An awaitable operation result to indicate the progress of this operation. (See )
public PixelSensorAsyncOperationResult StopSensor(PixelSensorId sensorType, IEnumerable streams)
{
if (!IsSensorConnected(sensorType, out var sensor))
{
return PixelSensorAsyncOperationResult.FailedOperationResult;
}
return sensor.StopSensor(streams);
}
///
/// Get the sensor data of a started sensor
///
/// The type of the sensor to get the data for
/// The stream to get the data for
/// The current frame data of the sensor
/// The metadata for this frame
/// An allocator handle that will be used to allocate the memory for the underlying raw data
/// The expected timeout for the data fetch
/// Whether to fip the obtained texture. The data stored in the sensor could be flipped. Pass in false if the raw data is needed (NOTE: This flag will be a no-op if the format does not support flipping (for example, Jpeg)
/// True if a frame was obtained
public bool GetSensorData(PixelSensorId sensorType, uint streamIndex, out PixelSensorFrame frame, out PixelSensorMetaData[] metaData, Allocator allocator, long timeOut = 10, bool shouldFlipTexture = true)
{
frame = default;
metaData = Array.Empty();
if (!IsSensorConnected(sensorType, out var sensor))
{
return false;
}
if (sensor.Status != PixelSensorStatus.Started)
{
Debug.LogError($"{sensorType} was not started. Please start the sensor to get its data");
return false;
}
if (sensor.StreamStatus[streamIndex] != PixelSensorStatus.Started)
{
Debug.LogError($"{streamIndex} was not started. Please start the stream of this sensor to get its data");
return false;
}
unsafe
{
if (!sensor.GetSensorData(streamIndex, out var sensorFrameInternal, out metaData, allocator, timeOut, shouldFlipTexture))
{
return false;
}
frame.CreateFromNativeFrame(sensorFrameInternal, allocator, shouldFlipTexture, sensor.StreamBuffers[streamIndex].LastCaptureTime);
return true;
}
}
///
/// Get the status of the sensor
///
/// The type of the sensor
/// The status of the sensor
public PixelSensorStatus GetSensorStatus(PixelSensorId sensorType)
{
return !IsSensorConnected(sensorType, out var sensor, false) ? PixelSensorStatus.Undefined : sensor.Status;
}
///
/// Get the sensor pose
///
/// The type of the sensor
/// The offset that should be considered for the pose calculation
/// The pose of the sensor
public Pose GetSensorPose(PixelSensorId sensorType, Pose offset = default)
{
if (!IsSensorConnected(sensorType, out var sensor))
{
return default;
}
return sensor.GetSensorPose(offset);
}
///
/// The sensor data stored can have differing orientations.
///
/// The type of the sensor to get the rotation for
/// The rotation of the frame data
public Quaternion GetSensorFrameRotation(PixelSensorId sensorType)
{
return sensorType.XrPathString switch
{
"/pixelsensor/eye/nasal/left" or "/pixelsensor/eye/nasal/right" => Quaternion.Euler(0, 0, 90),
"/pixelsensor/eye/temple/left" or "/pixelsensor/eye/temple/right" => Quaternion.Euler(0, 0, -90),
_ => Quaternion.identity
};
}
///
/// Gets the available metadata types for a sensor's stream.
/// Note: A sensor has to be configured in order to be able to get its supported metadata types
///
/// The type of the sensor
/// The stream to get the metadata for
/// The types of the metadata that are supported
/// True if the supported metadata types were fetched
public bool EnumeratePixelSensorMetaDataTypes(PixelSensorId sensorType, uint streamIndex, out PixelSensorMetaDataType[] metaDataTypes)
{
metaDataTypes = Array.Empty();
if (!IsSensorConnected(sensorType, out var sensor))
{
return false;
}
return sensor.EnumeratePixelSensorMetadata(streamIndex, out metaDataTypes);
}
#endregion
}
}