#define UNITY_ASSERTIONS using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using Unity.Baselib.LowLevel; using Unity.Burst; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.IL2CPP.CompilerServices; using Unity.Jobs; using Unity.Jobs.LowLevel.Unsafe; using Unity.Profiling; using Unity.Profiling.LowLevel; using Unity.Profiling.LowLevel.Unsafe; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.Assertions.Comparers; using UnityEngine.Bindings; using UnityEngine.Diagnostics; using UnityEngine.Events; using UnityEngine.Experimental.Rendering; using UnityEngine.Internal; using UnityEngine.Networking.PlayerConnection; using UnityEngine.Playables; using UnityEngine.Profiling; using UnityEngine.Profiling.Experimental; using UnityEngine.Rendering; using UnityEngine.Rendering.RendererUtils; using UnityEngine.SceneManagement; using UnityEngine.Scripting; using UnityEngine.Scripting.APIUpdating; using UnityEngine.Serialization; using UnityEngineInternal; [assembly: InternalsVisibleTo("UnityEngine.AIModule")] [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: InternalsVisibleTo("UnityEngine")] [assembly: InternalsVisibleTo("UnityEngine.SharedInternalsModule")] [assembly: InternalsVisibleTo("UnityEngine.CoreModule")] [assembly: InternalsVisibleTo("UnityEngine.AccessibilityModule")] [assembly: InternalsVisibleTo("UnityEngine.AndroidJNIModule")] [assembly: InternalsVisibleTo("UnityEngine.AudioModule")] [assembly: InternalsVisibleTo("UnityEngine.AnimationModule")] [assembly: InternalsVisibleTo("UnityEngine.PhysicsModule")] [assembly: InternalsVisibleTo("UnityEngine.JSONSerializeModule")] [assembly: InternalsVisibleTo("UnityEngine.InputModule")] [assembly: InternalsVisibleTo("UnityEngine.ARModule")] [assembly: InternalsVisibleTo("UnityEngine.HotReloadModule")] [assembly: InternalsVisibleTo("UnityEngine.ParticleSystemModule")] [assembly: InternalsVisibleTo("UnityEngine.ClothModule")] [assembly: InternalsVisibleTo("UnityEngine.LocalizationModule")] [assembly: InternalsVisibleTo("UnityEngine.AssetBundleModule")] [assembly: InternalsVisibleTo("UnityEngine.DSPGraphModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityConnectModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityAnalyticsCommonModule")] [assembly: InternalsVisibleTo("UnityEngine.TLSModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityAnalyticsModule")] [assembly: InternalsVisibleTo("UnityEngine.CrashReportingModule")] [assembly: InternalsVisibleTo("UnityEngine.ClusterRendererModule")] [assembly: InternalsVisibleTo("UnityEngine.DirectorModule")] [assembly: InternalsVisibleTo("UnityEngine.ClusterInputModule")] [assembly: InternalsVisibleTo("UnityEngine.GameCenterModule")] [assembly: InternalsVisibleTo("UnityEngine.GIModule")] [assembly: InternalsVisibleTo("UnityEngine.GridModule")] [assembly: InternalsVisibleTo("UnityEngine.TextRenderingModule")] [assembly: InternalsVisibleTo("UnityEngine.InputLegacyModule")] [assembly: InternalsVisibleTo("UnityEngine.IMGUIModule")] [assembly: InternalsVisibleTo("UnityEngine.ImageConversionModule")] [assembly: InternalsVisibleTo("UnityEngine.PS5VRModule")] [assembly: InternalsVisibleTo("UnityEngine.PerformanceReportingModule")] [assembly: InternalsVisibleTo("UnityEngine.Networking")] [assembly: InternalsVisibleTo("UnityEngine.UmbraModule")] [assembly: InternalsVisibleTo("UnityEngine.ProfilerModule")] [assembly: InternalsVisibleTo("UnityEngine.RuntimeInitializeOnLoadManagerInitializerModule")] [assembly: InternalsVisibleTo("UnityEngine.ScreenCaptureModule")] [assembly: InternalsVisibleTo("UnityEngine.SpriteMaskModule")] [assembly: InternalsVisibleTo("UnityEngine.SpriteShapeModule")] [assembly: InternalsVisibleTo("UnityEngine.StreamingModule")] [assembly: InternalsVisibleTo("UnityEngine.UNETModule")] [assembly: InternalsVisibleTo("UnityEngine.SubstanceModule")] [assembly: InternalsVisibleTo("UnityEngine.TerrainModule")] [assembly: InternalsVisibleTo("UnityEngine.TerrainPhysicsModule")] [assembly: InternalsVisibleTo("UnityEngine.TextCoreFontEngineModule")] [assembly: InternalsVisibleTo("UnityEngine.TextCoreTextEngineModule")] [assembly: InternalsVisibleTo("UnityEngine.TilemapModule")] [assembly: InternalsVisibleTo("UnityEngine.UIModule")] [assembly: InternalsVisibleTo("UnityEngine.UIElementsNativeModule")] [assembly: InternalsVisibleTo("UnityEngine.SubsystemsModule")] [assembly: InternalsVisibleTo("UnityEngine.NVIDIAModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityTestProtocolModule")] [assembly: InternalsVisibleTo("UnityEngine.PS5Module")] [assembly: InternalsVisibleTo("UnityEngine.VirtualTexturingModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestAssetBundleModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestAudioModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestTextureModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestWWWModule")] [assembly: InternalsVisibleTo("UnityEngine.VehiclesModule")] [assembly: InternalsVisibleTo("UnityEngine.VFXModule")] [assembly: InternalsVisibleTo("UnityEngine.Physics2DModule")] [assembly: InternalsVisibleTo("UnityEngine.VideoModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityCurlModule")] [assembly: InternalsVisibleTo("UnityEngine.VRModule")] [assembly: InternalsVisibleTo("UnityEngine.WindModule")] [assembly: InternalsVisibleTo("UnityEngine.SwitchModule")] [assembly: InternalsVisibleTo("UnityEngine.XboxOneModule")] [assembly: InternalsVisibleTo("UnityEngine.PS4Module")] [assembly: InternalsVisibleTo("UnityEngine.PS4VRModule")] [assembly: InternalsVisibleTo("UnityEngine.XRModule")] [assembly: InternalsVisibleTo("UnityEngine.Cloud.Service")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.011")] [assembly: InternalsVisibleTo("UnityEngine.UIElementsModule")] [assembly: InternalsVisibleTo("Unity.Burst")] [assembly: InternalsVisibleTo("Unity.Analytics")] [assembly: InternalsVisibleTo("UnityEngine.Analytics")] [assembly: InternalsVisibleTo("UnityEngine.UnityAnalyticsCommon")] [assembly: InternalsVisibleTo("UnityEngine.Advertisements")] [assembly: InternalsVisibleTo("UnityEngine.Purchasing")] [assembly: InternalsVisibleTo("UnityEngine.TestRunner")] [assembly: InternalsVisibleTo("Unity.ucg.QoS")] [assembly: InternalsVisibleTo("Unity.Automation")] [assembly: InternalsVisibleTo("Unity.RuntimeTests.Framework.Tests")] [assembly: InternalsVisibleTo("Unity.DeploymentTests.Services")] [assembly: InternalsVisibleTo("Unity.IntegrationTests")] [assembly: InternalsVisibleTo("Unity.IntegrationTests.UnityAnalytics")] [assembly: InternalsVisibleTo("Unity.IntegrationTests.Timeline")] [assembly: InternalsVisibleTo("Unity.IntegrationTests.Framework")] [assembly: InternalsVisibleTo("Unity.RuntimeTests")] [assembly: InternalsVisibleTo("Unity.Burst.Editor")] [assembly: InternalsVisibleTo("Unity.RuntimeTests.Framework")] [assembly: InternalsVisibleTo("Unity.PerformanceTests.RuntimeTestRunner.Tests")] [assembly: InternalsVisibleTo("UnityEngine.UI")] [assembly: InternalsVisibleTo("Unity.UI.Builder.Editor")] [assembly: InternalsVisibleTo("Assembly-CSharp-testable")] [assembly: InternalsVisibleTo("Assembly-CSharp-firstpass-testable")] [assembly: InternalsVisibleTo("UnityEngine.SpatialTracking")] [assembly: InternalsVisibleTo("GoogleAR.UnityNative")] [assembly: InternalsVisibleTo("Unity.WindowsMRAutomation")] [assembly: InternalsVisibleTo("Unity.2D.Sprite.Editor")] [assembly: InternalsVisibleTo("Unity.Timeline")] [assembly: InternalsVisibleTo("Unity.2D.Sprite.EditorTests")] [assembly: InternalsVisibleTo("Unity.RuntimeTests.AllIn1Runner")] [assembly: InternalsVisibleTo("Unity.UI.Builder.EditorTests")] [assembly: InternalsVisibleTo("Unity.UIElements")] [assembly: InternalsVisibleTo("UnityEngine.UIElementsGameObjectsModule")] [assembly: InternalsVisibleTo("Unity.UIElements.Editor")] [assembly: InternalsVisibleTo("Unity.UIElements.PlayModeTests")] [assembly: InternalsVisibleTo("Unity.UIElements.EditorTests")] [assembly: InternalsVisibleTo("UnityEditor.UIBuilderModule")] [assembly: InternalsVisibleTo("Unity.Networking.Transport")] [assembly: InternalsVisibleTo("UnityEngine.Cloud")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.003")] [assembly: InternalsVisibleTo("Unity.Entities")] [assembly: InternalsVisibleTo("Unity.Entities.Tests")] [assembly: InternalsVisibleTo("Unity.Collections")] [assembly: InternalsVisibleTo("Unity.Runtime")] [assembly: InternalsVisibleTo("Unity.Core")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.001")] [assembly: InternalsVisibleTo("Unity.Logging")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.002")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.012")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.005")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.006")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.007")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.008")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.009")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.010")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.004")] [assembly: InternalsVisibleTo("Unity.Services.QoS")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.013")] [assembly: UnityEngineModuleAssembly] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.023")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.016")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.017")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.018")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.019")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.020")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.021")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.015")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.022")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.014")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.001")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.002")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.003")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.004")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.005")] [assembly: InternalsVisibleTo("Unity.Subsystem.Registration")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.024")] [assembly: InternalsVisibleTo("Unity.2D.Entities.Hybrid")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [Embedded] [CompilerGenerated] internal sealed class IsUnmanagedAttribute : Attribute { } } namespace AOT { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class MonoPInvokeCallbackAttribute : Attribute { public MonoPInvokeCallbackAttribute(Type type) { } } } namespace UnityEditor.Experimental { public class RenderSettings { [Obsolete("Use UnityEngine.Experimental.GlobalIllumination.useRadianceAmbientProbe instead. (UnityUpgradable) -> UnityEngine.Experimental.GlobalIllumination.RenderSettings.useRadianceAmbientProbe", true)] public static bool useRadianceAmbientProbe { get; set; } } } namespace UnityEngineInternal { public enum GITextureType { Charting, Albedo, Emissive, Irradiance, Directionality, Baked, BakedDirectional, InputWorkspace, BakedShadowMask, BakedAlbedo, BakedEmissive, BakedCharting, BakedTexelValidity, BakedUVOverlap, BakedLightmapCulling } [NativeHeader("Runtime/Export/GI/GIDebugVisualisation.bindings.h")] public static class GIDebugVisualisation { public static extern bool cycleMode { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] get; } public static extern bool pauseCycleMode { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] get; } public static extern GITextureType texType { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] set; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void ResetRuntimeInputTextures(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void PlayCycleMode(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void PauseCycleMode(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void StopCycleMode(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void CycleSkipSystems(int skip); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void CycleSkipInstances(int skip); } public enum MemorylessMode { Unused, Forced, Automatic } [NativeHeader("Runtime/Misc/PlayerSettings.h")] public class MemorylessManager { public static MemorylessMode depthMemorylessMode { get { return GetFramebufferDepthMemorylessMode(); } set { SetFramebufferDepthMemorylessMode(value); } } [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeMethod(Name = "GetFramebufferDepthMemorylessMode")] internal static extern MemorylessMode GetFramebufferDepthMemorylessMode(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "SetFramebufferDepthMemorylessMode")] [StaticAccessor(/*Could not decode attribute arguments.*/)] internal static extern void SetFramebufferDepthMemorylessMode(MemorylessMode mode); } internal struct GraphicsDeviceDebugSettings { public float sleepAtStartOfGraphicsJobs; public float sleepBeforeTextureUpload; } [NativeHeader("Runtime/Export/Graphics/GraphicsDeviceDebug.bindings.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] internal static class GraphicsDeviceDebug { internal static GraphicsDeviceDebugSettings settings { get { get_settings_Injected(out var ret); return ret; } set { set_settings_Injected(ref value); } } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_settings_Injected(out GraphicsDeviceDebugSettings ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_settings_Injected(ref GraphicsDeviceDebugSettings value); } internal enum LightmapType { NoLightmap = -1, StaticLightmap, DynamicLightmap } [StructLayout(LayoutKind.Sequential, Size = 1)] [Il2CppEagerStaticClassConstruction] public struct MathfInternal { public static volatile float FloatMinNormal = 1.1754944E-38f; public static volatile float FloatMinDenormal = float.Epsilon; public static bool IsFlushToZeroEnabled = FloatMinDenormal == 0f; } public sealed class APIUpdaterRuntimeServices { [Obsolete("Method is not meant to be used at runtime. Please, replace this call with GameObject.AddComponent()/GameObject.AddComponent(Type).", true)] public static UnityEngine.Component AddComponent(GameObject go, string sourceInfo, string name) { throw new Exception(); } } public enum TypeInferenceRules { TypeReferencedByFirstArgument, TypeReferencedBySecondArgument, ArrayOfTypeReferencedByFirstArgument, TypeOfFirstArgument } [Serializable] [AttributeUsage(AttributeTargets.Method)] public class TypeInferenceRuleAttribute : Attribute { private readonly string _rule; public TypeInferenceRuleAttribute(TypeInferenceRules rule) : this(rule.ToString()) { } public TypeInferenceRuleAttribute(string rule) { _rule = rule; } public override string ToString() { return _rule; } } public class GenericStack : Stack { } } namespace Unity.Baselib { internal static class BaselibNativeLibrary { } internal struct ErrorState { private Binding.Baselib_ErrorState nativeErrorState; public Binding.Baselib_ErrorCode ErrorCode => nativeErrorState.code; public unsafe Binding.Baselib_ErrorState* NativeErrorStatePtr { get { fixed (Binding.Baselib_ErrorState* result = &nativeErrorState) { return result; } } } public void ThrowIfFailed() { if (ErrorCode != Binding.Baselib_ErrorCode.Success) { throw new BaselibException(this); } } public unsafe string Explain(Binding.Baselib_ErrorState_ExplainVerbosity verbosity = Binding.Baselib_ErrorState_ExplainVerbosity.ErrorType_SourceLocation_Explanation) { fixed (Binding.Baselib_ErrorState* errorState = &nativeErrorState) { uint num = Binding.Baselib_ErrorState_Explain(errorState, null, 0u, verbosity) + 1; IntPtr intPtr = Binding.Baselib_Memory_Allocate(new UIntPtr(num)); try { Binding.Baselib_ErrorState_Explain(errorState, (byte*)(void*)intPtr, num, verbosity); return Marshal.PtrToStringAnsi(intPtr); } finally { Binding.Baselib_Memory_Free(intPtr); } } } } internal class BaselibException : Exception { private readonly ErrorState errorState; public Binding.Baselib_ErrorCode ErrorCode => errorState.ErrorCode; internal BaselibException(ErrorState errorState) : base(errorState.Explain()) { this.errorState = errorState; } } } namespace Unity.Baselib.LowLevel { [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_RegisteredNetwork.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_Socket.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_ThreadLocalStorage.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_ErrorCode.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_NetworkAddress.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_DynamicLibrary.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_SourceLocation.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_Timer.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_FileIO.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_Memory.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_ErrorState.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_Thread.gen.binding.h")] internal static class Binding { public struct Baselib_DynamicLibrary_Handle { public IntPtr handle; } public enum Baselib_ErrorCode { Success = 0, OutOfMemory = 16777216, OutOfSystemResources = 16777217, InvalidAddressRange = 16777218, InvalidArgument = 16777219, InvalidBufferSize = 16777220, InvalidState = 16777221, NotSupported = 16777222, Timeout = 16777223, UnsupportedAlignment = 33554432, InvalidPageSize = 33554433, InvalidPageCount = 33554434, UnsupportedPageState = 33554435, ThreadCannotJoinSelf = 50331648, NetworkInitializationError = 67108864, AddressInUse = 67108865, AddressUnreachable = 67108866, AddressFamilyNotSupported = 67108867, Disconnected = 67108868, InvalidPathname = 83886080, RequestedAccessIsNotAllowed = 83886081, IOError = 83886082, FailedToOpenDynamicLibrary = 100663296, FunctionNotFound = 100663297, UnexpectedError = -1 } public enum Baselib_ErrorState_NativeErrorCodeType : byte { None, PlatformDefined } public enum Baselib_ErrorState_ExtraInformationType : byte { None, StaticString, GenerationCounter } public struct Baselib_ErrorState { public Baselib_SourceLocation sourceLocation; public ulong nativeErrorCode; public ulong extraInformation; public Baselib_ErrorCode code; public Baselib_ErrorState_NativeErrorCodeType nativeErrorCodeType; public Baselib_ErrorState_ExtraInformationType extraInformationType; } public enum Baselib_ErrorState_ExplainVerbosity { ErrorType, ErrorType_SourceLocation_Explanation } public struct Baselib_FileIO_EventQueue { public IntPtr handle; } public struct Baselib_FileIO_AsyncFile { public IntPtr handle; } public struct Baselib_FileIO_SyncFile { public IntPtr handle; } public enum Baselib_FileIO_OpenFlags : uint { Read = 1u, Write = 2u, OpenAlways = 4u, CreateAlways = 8u } public struct Baselib_FileIO_ReadRequest { public ulong offset; public IntPtr buffer; public ulong size; } public enum Baselib_FileIO_Priority { Normal, High } public enum Baselib_FileIO_EventQueue_ResultType { Baselib_FileIO_EventQueue_Callback = 1, Baselib_FileIO_EventQueue_OpenFile, Baselib_FileIO_EventQueue_ReadFile, Baselib_FileIO_EventQueue_CloseFile } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void EventQueueCallback(ulong arg0); public struct Baselib_FileIO_EventQueue_Result_Callback { public IntPtr callback; } public struct Baselib_FileIO_EventQueue_Result_OpenFile { public ulong fileSize; } public struct Baselib_FileIO_EventQueue_Result_ReadFile { public ulong bytesTransferred; } [StructLayout(LayoutKind.Explicit)] public struct Baselib_FileIO_EventQueue_Result { [FieldOffset(0)] public Baselib_FileIO_EventQueue_ResultType type; [FieldOffset(8)] public ulong userdata; [FieldOffset(16)] public Baselib_ErrorState errorState; [FieldOffset(64)] public Baselib_FileIO_EventQueue_Result_Callback callback; [FieldOffset(64)] [Ignore(DoesNotContributeToSize = true)] public Baselib_FileIO_EventQueue_Result_OpenFile openFile; [FieldOffset(64)] [Ignore(DoesNotContributeToSize = true)] public Baselib_FileIO_EventQueue_Result_ReadFile readFile; } public struct Baselib_Memory_PageSizeInfo { public ulong defaultPageSize; public ulong pageSizes0; public ulong pageSizes1; public ulong pageSizes2; public ulong pageSizes3; public ulong pageSizes4; public ulong pageSizes5; public ulong pageSizesLen; } public struct Baselib_Memory_PageAllocation { public IntPtr ptr; public ulong pageSize; public ulong pageCount; } public enum Baselib_Memory_PageState { Reserved = 0, NoAccess = 1, ReadOnly = 2, ReadWrite = 4, ReadOnly_Executable = 18, ReadWrite_Executable = 20 } public enum Baselib_NetworkAddress_Family { Invalid, IPv4, IPv6 } [StructLayout(LayoutKind.Explicit)] public struct Baselib_NetworkAddress { [FieldOffset(0)] public byte data0; [FieldOffset(1)] public byte data1; [FieldOffset(2)] public byte data2; [FieldOffset(3)] public byte data3; [FieldOffset(4)] public byte data4; [FieldOffset(5)] public byte data5; [FieldOffset(6)] public byte data6; [FieldOffset(7)] public byte data7; [FieldOffset(8)] public byte data8; [FieldOffset(9)] public byte data9; [FieldOffset(10)] public byte data10; [FieldOffset(11)] public byte data11; [FieldOffset(12)] public byte data12; [FieldOffset(13)] public byte data13; [FieldOffset(14)] public byte data14; [FieldOffset(15)] public byte data15; [FieldOffset(0)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_0; [FieldOffset(1)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_1; [FieldOffset(2)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_2; [FieldOffset(3)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_3; [FieldOffset(4)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_4; [FieldOffset(5)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_5; [FieldOffset(6)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_6; [FieldOffset(7)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_7; [FieldOffset(8)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_8; [FieldOffset(9)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_9; [FieldOffset(10)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_10; [FieldOffset(11)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_11; [FieldOffset(12)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_12; [FieldOffset(13)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_13; [FieldOffset(14)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_14; [FieldOffset(15)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_15; [FieldOffset(0)] [Ignore(DoesNotContributeToSize = true)] public byte ipv4_0; [FieldOffset(1)] [Ignore(DoesNotContributeToSize = true)] public byte ipv4_1; [FieldOffset(2)] [Ignore(DoesNotContributeToSize = true)] public byte ipv4_2; [FieldOffset(3)] [Ignore(DoesNotContributeToSize = true)] public byte ipv4_3; [FieldOffset(16)] public byte port0; [FieldOffset(17)] public byte port1; [FieldOffset(18)] public byte family; [FieldOffset(19)] public byte _padding; [FieldOffset(20)] public uint ipv6_scope_id; } public enum Baselib_NetworkAddress_AddressReuse { DoNotAllow, Allow } public struct Baselib_RegisteredNetwork_Buffer { public IntPtr id; public Baselib_Memory_PageAllocation allocation; } public struct Baselib_RegisteredNetwork_BufferSlice { public IntPtr id; public IntPtr data; public uint size; public uint offset; } public struct Baselib_RegisteredNetwork_Endpoint { public Baselib_RegisteredNetwork_BufferSlice slice; } public struct Baselib_RegisteredNetwork_Request { public Baselib_RegisteredNetwork_BufferSlice payload; public Baselib_RegisteredNetwork_Endpoint remoteEndpoint; public IntPtr requestUserdata; } public enum Baselib_RegisteredNetwork_CompletionStatus { Failed, Success } public struct Baselib_RegisteredNetwork_CompletionResult { public Baselib_RegisteredNetwork_CompletionStatus status; public uint bytesTransferred; public IntPtr requestUserdata; } public struct Baselib_RegisteredNetwork_Socket_UDP { public IntPtr handle; } public enum Baselib_RegisteredNetwork_ProcessStatus { NonePendingImmediately = 0, Done = 0, Pending = 1 } public enum Baselib_RegisteredNetwork_CompletionQueueStatus { NoResultsAvailable, ResultsAvailable } public struct Baselib_Socket_Handle { public IntPtr handle; } public enum Baselib_Socket_Protocol { UDP = 1, TCP } public struct Baselib_Socket_Message { public unsafe Baselib_NetworkAddress* address; public IntPtr data; public uint dataLen; } public enum Baselib_Socket_PollEvents { Readable = 1, Writable = 2, Connected = 4 } public struct Baselib_Socket_PollFd { public Baselib_Socket_Handle handle; public Baselib_Socket_PollEvents requestedEvents; public Baselib_Socket_PollEvents resultEvents; public unsafe Baselib_ErrorState* errorState; } public struct Baselib_SourceLocation { public unsafe byte* file; public unsafe byte* function; public uint lineNumber; } public struct Baselib_Timer_TickToNanosecondConversionRatio { public ulong ticksToNanosecondsNumerator; public ulong ticksToNanosecondsDenominator; } public static readonly UIntPtr Baselib_Memory_MaxAlignment = new UIntPtr(65536u); public static readonly UIntPtr Baselib_Memory_MinGuaranteedAlignment = new UIntPtr(8u); public const uint Baselib_NetworkAddress_IpMaxStringLength = 46u; public static readonly IntPtr Baselib_RegisteredNetwork_Buffer_Id_Invalid = IntPtr.Zero; public const uint Baselib_RegisteredNetwork_Endpoint_MaxSize = 28u; public static readonly IntPtr Baselib_Thread_InvalidId = IntPtr.Zero; public static readonly UIntPtr Baselib_Thread_MaxThreadNameLength = new UIntPtr(64u); public const uint Baselib_TLS_MinimumGuaranteedSlots = 100u; public const ulong Baselib_SecondsPerMinute = 60uL; public const ulong Baselib_MillisecondsPerSecond = 1000uL; public const ulong Baselib_MillisecondsPerMinute = 60000uL; public const ulong Baselib_MicrosecondsPerMillisecond = 1000uL; public const ulong Baselib_MicrosecondsPerSecond = 1000000uL; public const ulong Baselib_MicrosecondsPerMinute = 60000000uL; public const ulong Baselib_NanosecondsPerMicrosecond = 1000uL; public const ulong Baselib_NanosecondsPerMillisecond = 1000000uL; public const ulong Baselib_NanosecondsPerSecond = 1000000000uL; public const ulong Baselib_NanosecondsPerMinute = 60000000000uL; public const ulong Baselib_Timer_MaxNumberOfNanosecondsPerTick = 1000uL; public const double Baselib_Timer_MinNumberOfNanosecondsPerTick = 0.01; public static readonly Baselib_Memory_PageAllocation Baselib_Memory_PageAllocation_Invalid = default(Baselib_Memory_PageAllocation); public static readonly Baselib_RegisteredNetwork_Socket_UDP Baselib_RegisteredNetwork_Socket_UDP_Invalid = default(Baselib_RegisteredNetwork_Socket_UDP); public static readonly Baselib_Socket_Handle Baselib_Socket_Handle_Invalid = new Baselib_Socket_Handle { handle = (IntPtr)(-1) }; public static readonly Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_Handle_Invalid = new Baselib_DynamicLibrary_Handle { handle = (IntPtr)(-1) }; public static readonly Baselib_FileIO_EventQueue Baselib_FileIO_EventQueue_Invalid = new Baselib_FileIO_EventQueue { handle = (IntPtr)0 }; public static readonly Baselib_FileIO_AsyncFile Baselib_FileIO_AsyncFile_Invalid = new Baselib_FileIO_AsyncFile { handle = (IntPtr)0 }; public static readonly Baselib_FileIO_SyncFile Baselib_FileIO_SyncFile_Invalid = new Baselib_FileIO_SyncFile { handle = (IntPtr)(-1) }; [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_OpenUtf8(byte* pathnameUtf8, Baselib_ErrorState* errorState) { Baselib_DynamicLibrary_OpenUtf8_Injected(pathnameUtf8, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_OpenUtf16(char* pathnameUtf16, Baselib_ErrorState* errorState) { Baselib_DynamicLibrary_OpenUtf16_Injected(pathnameUtf16, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_OpenProgramHandle(Baselib_ErrorState* errorState) { Baselib_DynamicLibrary_OpenProgramHandle_Injected(errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_FromNativeHandle(ulong handle, uint type, Baselib_ErrorState* errorState) { Baselib_DynamicLibrary_FromNativeHandle_Injected(handle, type, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static IntPtr Baselib_DynamicLibrary_GetFunction(Baselib_DynamicLibrary_Handle handle, byte* functionName, Baselib_ErrorState* errorState) { return Baselib_DynamicLibrary_GetFunction_Injected(ref handle, functionName, errorState); } [FreeFunction(IsThreadSafe = true)] public static void Baselib_DynamicLibrary_Close(Baselib_DynamicLibrary_Handle handle) { Baselib_DynamicLibrary_Close_Injected(ref handle); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public unsafe static extern uint Baselib_ErrorState_Explain(Baselib_ErrorState* errorState, byte* buffer, uint bufferLen, Baselib_ErrorState_ExplainVerbosity verbosity); [FreeFunction(IsThreadSafe = true)] public static Baselib_FileIO_EventQueue Baselib_FileIO_EventQueue_Create() { Baselib_FileIO_EventQueue_Create_Injected(out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public static void Baselib_FileIO_EventQueue_Free(Baselib_FileIO_EventQueue eq) { Baselib_FileIO_EventQueue_Free_Injected(ref eq); } [FreeFunction(IsThreadSafe = true)] public unsafe static ulong Baselib_FileIO_EventQueue_Dequeue(Baselib_FileIO_EventQueue eq, Baselib_FileIO_EventQueue_Result* results, ulong count, uint timeoutInMilliseconds) { return Baselib_FileIO_EventQueue_Dequeue_Injected(ref eq, results, count, timeoutInMilliseconds); } [FreeFunction(IsThreadSafe = true)] public static void Baselib_FileIO_EventQueue_Shutdown(Baselib_FileIO_EventQueue eq, uint threadCount) { Baselib_FileIO_EventQueue_Shutdown_Injected(ref eq, threadCount); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_FileIO_AsyncFile Baselib_FileIO_AsyncOpen(Baselib_FileIO_EventQueue eq, byte* pathname, ulong userdata, Baselib_FileIO_Priority priority) { Baselib_FileIO_AsyncOpen_Injected(ref eq, pathname, userdata, priority, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_FileIO_AsyncRead(Baselib_FileIO_AsyncFile file, Baselib_FileIO_ReadRequest* requests, ulong count, ulong userdata, Baselib_FileIO_Priority priority) { Baselib_FileIO_AsyncRead_Injected(ref file, requests, count, userdata, priority); } [FreeFunction(IsThreadSafe = true)] public static void Baselib_FileIO_AsyncClose(Baselib_FileIO_AsyncFile file) { Baselib_FileIO_AsyncClose_Injected(ref file); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_FileIO_SyncFile Baselib_FileIO_SyncOpen(byte* pathname, Baselib_FileIO_OpenFlags openFlags, Baselib_ErrorState* errorState) { Baselib_FileIO_SyncOpen_Injected(pathname, openFlags, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public static Baselib_FileIO_SyncFile Baselib_FileIO_SyncFileFromNativeHandle(ulong handle, uint type) { Baselib_FileIO_SyncFileFromNativeHandle_Injected(handle, type, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static ulong Baselib_FileIO_SyncRead(Baselib_FileIO_SyncFile file, ulong offset, IntPtr buffer, ulong size, Baselib_ErrorState* errorState) { return Baselib_FileIO_SyncRead_Injected(ref file, offset, buffer, size, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static ulong Baselib_FileIO_SyncWrite(Baselib_FileIO_SyncFile file, ulong offset, IntPtr buffer, ulong size, Baselib_ErrorState* errorState) { return Baselib_FileIO_SyncWrite_Injected(ref file, offset, buffer, size, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_FileIO_SyncFlush(Baselib_FileIO_SyncFile file, Baselib_ErrorState* errorState) { Baselib_FileIO_SyncFlush_Injected(ref file, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_FileIO_SyncSetFileSize(Baselib_FileIO_SyncFile file, ulong size, Baselib_ErrorState* errorState) { Baselib_FileIO_SyncSetFileSize_Injected(ref file, size, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static ulong Baselib_FileIO_SyncGetFileSize(Baselib_FileIO_SyncFile file, Baselib_ErrorState* errorState) { return Baselib_FileIO_SyncGetFileSize_Injected(ref file, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_FileIO_SyncClose(Baselib_FileIO_SyncFile file, Baselib_ErrorState* errorState) { Baselib_FileIO_SyncClose_Injected(ref file, errorState); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public unsafe static extern void Baselib_Memory_GetPageSizeInfo(Baselib_Memory_PageSizeInfo* outPagesSizeInfo); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern IntPtr Baselib_Memory_Allocate(UIntPtr size); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern IntPtr Baselib_Memory_Reallocate(IntPtr ptr, UIntPtr newSize); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_Memory_Free(IntPtr ptr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern IntPtr Baselib_Memory_AlignedAllocate(UIntPtr size, UIntPtr alignment); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern IntPtr Baselib_Memory_AlignedReallocate(IntPtr ptr, UIntPtr newSize, UIntPtr alignment); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_Memory_AlignedFree(IntPtr ptr); [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_Memory_PageAllocation Baselib_Memory_AllocatePages(ulong pageSize, ulong pageCount, ulong alignmentInMultipleOfPageSize, Baselib_Memory_PageState pageState, Baselib_ErrorState* errorState) { Baselib_Memory_AllocatePages_Injected(pageSize, pageCount, alignmentInMultipleOfPageSize, pageState, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_Memory_ReleasePages(Baselib_Memory_PageAllocation pageAllocation, Baselib_ErrorState* errorState) { Baselib_Memory_ReleasePages_Injected(ref pageAllocation, errorState); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public unsafe static extern void Baselib_Memory_SetPageState(IntPtr addressOfFirstPage, ulong pageSize, ulong pageCount, Baselib_Memory_PageState pageState, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public unsafe static extern void Baselib_NetworkAddress_Encode(Baselib_NetworkAddress* dstAddress, Baselib_NetworkAddress_Family family, byte* ip, ushort port, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public unsafe static extern void Baselib_NetworkAddress_Decode(Baselib_NetworkAddress* srcAddress, Baselib_NetworkAddress_Family* family, byte* ipAddressBuffer, uint ipAddressBufferLen, ushort* port, Baselib_ErrorState* errorState); [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_Buffer Baselib_RegisteredNetwork_Buffer_Register(Baselib_Memory_PageAllocation pageAllocation, Baselib_ErrorState* errorState) { Baselib_RegisteredNetwork_Buffer_Register_Injected(ref pageAllocation, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public static void Baselib_RegisteredNetwork_Buffer_Deregister(Baselib_RegisteredNetwork_Buffer buffer) { Baselib_RegisteredNetwork_Buffer_Deregister_Injected(ref buffer); } [FreeFunction(IsThreadSafe = true)] public static Baselib_RegisteredNetwork_BufferSlice Baselib_RegisteredNetwork_BufferSlice_Create(Baselib_RegisteredNetwork_Buffer buffer, uint offset, uint size) { Baselib_RegisteredNetwork_BufferSlice_Create_Injected(ref buffer, offset, size, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public static Baselib_RegisteredNetwork_BufferSlice Baselib_RegisteredNetwork_BufferSlice_Empty() { Baselib_RegisteredNetwork_BufferSlice_Empty_Injected(out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_Endpoint Baselib_RegisteredNetwork_Endpoint_Create(Baselib_NetworkAddress* srcAddress, Baselib_RegisteredNetwork_BufferSlice dstSlice, Baselib_ErrorState* errorState) { Baselib_RegisteredNetwork_Endpoint_Create_Injected(srcAddress, ref dstSlice, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public static Baselib_RegisteredNetwork_Endpoint Baselib_RegisteredNetwork_Endpoint_Empty() { Baselib_RegisteredNetwork_Endpoint_Empty_Injected(out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_RegisteredNetwork_Endpoint_GetNetworkAddress(Baselib_RegisteredNetwork_Endpoint endpoint, Baselib_NetworkAddress* dstAddress, Baselib_ErrorState* errorState) { Baselib_RegisteredNetwork_Endpoint_GetNetworkAddress_Injected(ref endpoint, dstAddress, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_Socket_UDP Baselib_RegisteredNetwork_Socket_UDP_Create(Baselib_NetworkAddress* bindAddress, Baselib_NetworkAddress_AddressReuse endpointReuse, uint sendQueueSize, uint recvQueueSize, Baselib_ErrorState* errorState) { Baselib_RegisteredNetwork_Socket_UDP_Create_Injected(bindAddress, endpointReuse, sendQueueSize, recvQueueSize, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_RegisteredNetwork_Socket_UDP_ScheduleRecv(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_Request* requests, uint requestsCount, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_ScheduleRecv_Injected(ref socket, requests, requestsCount, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_RegisteredNetwork_Socket_UDP_ScheduleSend(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_Request* requests, uint requestsCount, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_ScheduleSend_Injected(ref socket, requests, requestsCount, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_ProcessStatus Baselib_RegisteredNetwork_Socket_UDP_ProcessRecv(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_ProcessRecv_Injected(ref socket, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_ProcessStatus Baselib_RegisteredNetwork_Socket_UDP_ProcessSend(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_ProcessSend_Injected(ref socket, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_CompletionQueueStatus Baselib_RegisteredNetwork_Socket_UDP_WaitForCompletedRecv(Baselib_RegisteredNetwork_Socket_UDP socket, uint timeoutInMilliseconds, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_WaitForCompletedRecv_Injected(ref socket, timeoutInMilliseconds, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_CompletionQueueStatus Baselib_RegisteredNetwork_Socket_UDP_WaitForCompletedSend(Baselib_RegisteredNetwork_Socket_UDP socket, uint timeoutInMilliseconds, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_WaitForCompletedSend_Injected(ref socket, timeoutInMilliseconds, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_RegisteredNetwork_Socket_UDP_DequeueRecv(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_CompletionResult* results, uint resultsCount, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_DequeueRecv_Injected(ref socket, results, resultsCount, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_RegisteredNetwork_Socket_UDP_DequeueSend(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_CompletionResult* results, uint resultsCount, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_DequeueSend_Injected(ref socket, results, resultsCount, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_RegisteredNetwork_Socket_UDP_GetNetworkAddress(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_NetworkAddress* dstAddress, Baselib_ErrorState* errorState) { Baselib_RegisteredNetwork_Socket_UDP_GetNetworkAddress_Injected(ref socket, dstAddress, errorState); } [FreeFunction(IsThreadSafe = true)] public static void Baselib_RegisteredNetwork_Socket_UDP_Close(Baselib_RegisteredNetwork_Socket_UDP socket) { Baselib_RegisteredNetwork_Socket_UDP_Close_Injected(ref socket); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_Socket_Handle Baselib_Socket_Create(Baselib_NetworkAddress_Family family, Baselib_Socket_Protocol protocol, Baselib_ErrorState* errorState) { Baselib_Socket_Create_Injected(family, protocol, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_Socket_Bind(Baselib_Socket_Handle socket, Baselib_NetworkAddress* address, Baselib_NetworkAddress_AddressReuse addressReuse, Baselib_ErrorState* errorState) { Baselib_Socket_Bind_Injected(ref socket, address, addressReuse, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_Socket_TCP_Connect(Baselib_Socket_Handle socket, Baselib_NetworkAddress* address, Baselib_NetworkAddress_AddressReuse addressReuse, Baselib_ErrorState* errorState) { Baselib_Socket_TCP_Connect_Injected(ref socket, address, addressReuse, errorState); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public unsafe static extern void Baselib_Socket_Poll(Baselib_Socket_PollFd* sockets, uint socketsCount, uint timeoutInMilliseconds, Baselib_ErrorState* errorState); [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_Socket_GetAddress(Baselib_Socket_Handle socket, Baselib_NetworkAddress* address, Baselib_ErrorState* errorState) { Baselib_Socket_GetAddress_Injected(ref socket, address, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_Socket_TCP_Listen(Baselib_Socket_Handle socket, Baselib_ErrorState* errorState) { Baselib_Socket_TCP_Listen_Injected(ref socket, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_Socket_Handle Baselib_Socket_TCP_Accept(Baselib_Socket_Handle socket, Baselib_ErrorState* errorState) { Baselib_Socket_TCP_Accept_Injected(ref socket, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_Socket_UDP_Send(Baselib_Socket_Handle socket, Baselib_Socket_Message* messages, uint messagesCount, Baselib_ErrorState* errorState) { return Baselib_Socket_UDP_Send_Injected(ref socket, messages, messagesCount, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_Socket_TCP_Send(Baselib_Socket_Handle socket, IntPtr data, uint dataLen, Baselib_ErrorState* errorState) { return Baselib_Socket_TCP_Send_Injected(ref socket, data, dataLen, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_Socket_UDP_Recv(Baselib_Socket_Handle socket, Baselib_Socket_Message* messages, uint messagesCount, Baselib_ErrorState* errorState) { return Baselib_Socket_UDP_Recv_Injected(ref socket, messages, messagesCount, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_Socket_TCP_Recv(Baselib_Socket_Handle socket, IntPtr data, uint dataLen, Baselib_ErrorState* errorState) { return Baselib_Socket_TCP_Recv_Injected(ref socket, data, dataLen, errorState); } [FreeFunction(IsThreadSafe = true)] public static void Baselib_Socket_Close(Baselib_Socket_Handle socket) { Baselib_Socket_Close_Injected(ref socket); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_Thread_YieldExecution(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern IntPtr Baselib_Thread_GetCurrentThreadId(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern UIntPtr Baselib_TLS_Alloc(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_TLS_Free(UIntPtr handle); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_TLS_Set(UIntPtr handle, UIntPtr value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern UIntPtr Baselib_TLS_Get(UIntPtr handle); [FreeFunction(IsThreadSafe = true)] public static Baselib_Timer_TickToNanosecondConversionRatio Baselib_Timer_GetTicksToNanosecondsConversionRatio() { Baselib_Timer_GetTicksToNanosecondsConversionRatio_Injected(out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern ulong Baselib_Timer_GetHighPrecisionTimerTicks(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_Timer_WaitForAtLeast(uint timeInMilliseconds); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern double Baselib_Timer_GetTimeSinceStartupInSeconds(); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_DynamicLibrary_OpenUtf8_Injected(byte* pathnameUtf8, Baselib_ErrorState* errorState, out Baselib_DynamicLibrary_Handle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_DynamicLibrary_OpenUtf16_Injected(char* pathnameUtf16, Baselib_ErrorState* errorState, out Baselib_DynamicLibrary_Handle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_DynamicLibrary_OpenProgramHandle_Injected(Baselib_ErrorState* errorState, out Baselib_DynamicLibrary_Handle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_DynamicLibrary_FromNativeHandle_Injected(ulong handle, uint type, Baselib_ErrorState* errorState, out Baselib_DynamicLibrary_Handle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern IntPtr Baselib_DynamicLibrary_GetFunction_Injected(ref Baselib_DynamicLibrary_Handle handle, byte* functionName, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_DynamicLibrary_Close_Injected(ref Baselib_DynamicLibrary_Handle handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_FileIO_EventQueue_Create_Injected(out Baselib_FileIO_EventQueue ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_FileIO_EventQueue_Free_Injected(ref Baselib_FileIO_EventQueue eq); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern ulong Baselib_FileIO_EventQueue_Dequeue_Injected(ref Baselib_FileIO_EventQueue eq, Baselib_FileIO_EventQueue_Result* results, ulong count, uint timeoutInMilliseconds); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_FileIO_EventQueue_Shutdown_Injected(ref Baselib_FileIO_EventQueue eq, uint threadCount); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_FileIO_AsyncOpen_Injected(ref Baselib_FileIO_EventQueue eq, byte* pathname, ulong userdata, Baselib_FileIO_Priority priority, out Baselib_FileIO_AsyncFile ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_FileIO_AsyncRead_Injected(ref Baselib_FileIO_AsyncFile file, Baselib_FileIO_ReadRequest* requests, ulong count, ulong userdata, Baselib_FileIO_Priority priority); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_FileIO_AsyncClose_Injected(ref Baselib_FileIO_AsyncFile file); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_FileIO_SyncOpen_Injected(byte* pathname, Baselib_FileIO_OpenFlags openFlags, Baselib_ErrorState* errorState, out Baselib_FileIO_SyncFile ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_FileIO_SyncFileFromNativeHandle_Injected(ulong handle, uint type, out Baselib_FileIO_SyncFile ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern ulong Baselib_FileIO_SyncRead_Injected(ref Baselib_FileIO_SyncFile file, ulong offset, IntPtr buffer, ulong size, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern ulong Baselib_FileIO_SyncWrite_Injected(ref Baselib_FileIO_SyncFile file, ulong offset, IntPtr buffer, ulong size, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_FileIO_SyncFlush_Injected(ref Baselib_FileIO_SyncFile file, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_FileIO_SyncSetFileSize_Injected(ref Baselib_FileIO_SyncFile file, ulong size, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern ulong Baselib_FileIO_SyncGetFileSize_Injected(ref Baselib_FileIO_SyncFile file, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_FileIO_SyncClose_Injected(ref Baselib_FileIO_SyncFile file, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Memory_AllocatePages_Injected(ulong pageSize, ulong pageCount, ulong alignmentInMultipleOfPageSize, Baselib_Memory_PageState pageState, Baselib_ErrorState* errorState, out Baselib_Memory_PageAllocation ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Memory_ReleasePages_Injected(ref Baselib_Memory_PageAllocation pageAllocation, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_RegisteredNetwork_Buffer_Register_Injected(ref Baselib_Memory_PageAllocation pageAllocation, Baselib_ErrorState* errorState, out Baselib_RegisteredNetwork_Buffer ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_RegisteredNetwork_Buffer_Deregister_Injected(ref Baselib_RegisteredNetwork_Buffer buffer); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_RegisteredNetwork_BufferSlice_Create_Injected(ref Baselib_RegisteredNetwork_Buffer buffer, uint offset, uint size, out Baselib_RegisteredNetwork_BufferSlice ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_RegisteredNetwork_BufferSlice_Empty_Injected(out Baselib_RegisteredNetwork_BufferSlice ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_RegisteredNetwork_Endpoint_Create_Injected(Baselib_NetworkAddress* srcAddress, ref Baselib_RegisteredNetwork_BufferSlice dstSlice, Baselib_ErrorState* errorState, out Baselib_RegisteredNetwork_Endpoint ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_RegisteredNetwork_Endpoint_Empty_Injected(out Baselib_RegisteredNetwork_Endpoint ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_RegisteredNetwork_Endpoint_GetNetworkAddress_Injected(ref Baselib_RegisteredNetwork_Endpoint endpoint, Baselib_NetworkAddress* dstAddress, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_RegisteredNetwork_Socket_UDP_Create_Injected(Baselib_NetworkAddress* bindAddress, Baselib_NetworkAddress_AddressReuse endpointReuse, uint sendQueueSize, uint recvQueueSize, Baselib_ErrorState* errorState, out Baselib_RegisteredNetwork_Socket_UDP ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_RegisteredNetwork_Socket_UDP_ScheduleRecv_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_Request* requests, uint requestsCount, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_RegisteredNetwork_Socket_UDP_ScheduleSend_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_Request* requests, uint requestsCount, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern Baselib_RegisteredNetwork_ProcessStatus Baselib_RegisteredNetwork_Socket_UDP_ProcessRecv_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern Baselib_RegisteredNetwork_ProcessStatus Baselib_RegisteredNetwork_Socket_UDP_ProcessSend_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern Baselib_RegisteredNetwork_CompletionQueueStatus Baselib_RegisteredNetwork_Socket_UDP_WaitForCompletedRecv_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, uint timeoutInMilliseconds, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern Baselib_RegisteredNetwork_CompletionQueueStatus Baselib_RegisteredNetwork_Socket_UDP_WaitForCompletedSend_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, uint timeoutInMilliseconds, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_RegisteredNetwork_Socket_UDP_DequeueRecv_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_CompletionResult* results, uint resultsCount, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_RegisteredNetwork_Socket_UDP_DequeueSend_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_CompletionResult* results, uint resultsCount, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_RegisteredNetwork_Socket_UDP_GetNetworkAddress_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_NetworkAddress* dstAddress, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_RegisteredNetwork_Socket_UDP_Close_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Socket_Create_Injected(Baselib_NetworkAddress_Family family, Baselib_Socket_Protocol protocol, Baselib_ErrorState* errorState, out Baselib_Socket_Handle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Socket_Bind_Injected(ref Baselib_Socket_Handle socket, Baselib_NetworkAddress* address, Baselib_NetworkAddress_AddressReuse addressReuse, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Socket_TCP_Connect_Injected(ref Baselib_Socket_Handle socket, Baselib_NetworkAddress* address, Baselib_NetworkAddress_AddressReuse addressReuse, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Socket_GetAddress_Injected(ref Baselib_Socket_Handle socket, Baselib_NetworkAddress* address, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Socket_TCP_Listen_Injected(ref Baselib_Socket_Handle socket, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Socket_TCP_Accept_Injected(ref Baselib_Socket_Handle socket, Baselib_ErrorState* errorState, out Baselib_Socket_Handle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_Socket_UDP_Send_Injected(ref Baselib_Socket_Handle socket, Baselib_Socket_Message* messages, uint messagesCount, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_Socket_TCP_Send_Injected(ref Baselib_Socket_Handle socket, IntPtr data, uint dataLen, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_Socket_UDP_Recv_Injected(ref Baselib_Socket_Handle socket, Baselib_Socket_Message* messages, uint messagesCount, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_Socket_TCP_Recv_Injected(ref Baselib_Socket_Handle socket, IntPtr data, uint dataLen, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_Socket_Close_Injected(ref Baselib_Socket_Handle socket); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_Timer_GetTicksToNanosecondsConversionRatio_Injected(out Baselib_Timer_TickToNanosecondConversionRatio ret); } } namespace Unity.Profiling { [StructLayout(LayoutKind.Explicit, Size = 2)] [UsedByNativeCode] public readonly struct ProfilerCategory { [FieldOffset(0)] private readonly ushort m_CategoryId; public unsafe string Name { get { ProfilerCategoryDescription categoryDescription = ProfilerUnsafeUtility.GetCategoryDescription(m_CategoryId); return ProfilerUnsafeUtility.Utf8ToString(categoryDescription.NameUtf8, categoryDescription.NameUtf8Len); } } public Color32 Color => ProfilerUnsafeUtility.GetCategoryDescription(m_CategoryId).Color; public static ProfilerCategory Render => new ProfilerCategory(0); public static ProfilerCategory Scripts => new ProfilerCategory(1); public static ProfilerCategory Gui => new ProfilerCategory(4); public static ProfilerCategory Physics => new ProfilerCategory(5); public static ProfilerCategory Animation => new ProfilerCategory(6); public static ProfilerCategory Ai => new ProfilerCategory(7); public static ProfilerCategory Audio => new ProfilerCategory(8); public static ProfilerCategory Video => new ProfilerCategory(11); public static ProfilerCategory Particles => new ProfilerCategory(12); public static ProfilerCategory Lighting => new ProfilerCategory(13); public static ProfilerCategory Network => new ProfilerCategory(14); public static ProfilerCategory Loading => new ProfilerCategory(15); public static ProfilerCategory Vr => new ProfilerCategory(22); public static ProfilerCategory Input => new ProfilerCategory(30); public static ProfilerCategory Memory => new ProfilerCategory(23); public static ProfilerCategory VirtualTexturing => new ProfilerCategory(31); public static ProfilerCategory FileIO => new ProfilerCategory(25); public static ProfilerCategory Internal => new ProfilerCategory(24); internal static ProfilerCategory Any => new ProfilerCategory(ushort.MaxValue); internal static ProfilerCategory GPU => new ProfilerCategory(32); public ProfilerCategory(string categoryName) { m_CategoryId = ProfilerUnsafeUtility.CreateCategory(categoryName, ProfilerCategoryColor.Scripts); } public ProfilerCategory(string categoryName, ProfilerCategoryColor color) { m_CategoryId = ProfilerUnsafeUtility.CreateCategory(categoryName, color); } internal ProfilerCategory(ushort category) { m_CategoryId = category; } public override string ToString() { return Name; } public static implicit operator ushort(ProfilerCategory category) { return category.m_CategoryId; } } [Flags] public enum ProfilerCategoryFlags : ushort { None = 0, Builtin = 1 } public enum ProfilerCategoryColor : ushort { Render, Scripts, BurstJobs, Other, Physics, Animation, Audio, AudioJob, AudioUpdateJob, Lighting, GC, VSync, Memory, Internal, UI, Build, Input } [UsedByNativeCode] public struct ProfilerMarker { [UsedByNativeCode] public struct AutoScope : IDisposable { [NativeDisableUnsafePtrRestriction] internal readonly IntPtr m_Ptr; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal AutoScope(IntPtr markerPtr) { m_Ptr = markerPtr; if (m_Ptr != IntPtr.Zero) { ProfilerUnsafeUtility.BeginSample(markerPtr); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { if (m_Ptr != IntPtr.Zero) { ProfilerUnsafeUtility.EndSample(m_Ptr); } } } [NonSerialized] [NativeDisableUnsafePtrRestriction] internal readonly IntPtr m_Ptr; public IntPtr Handle => m_Ptr; [MethodImpl(MethodImplOptions.AggressiveInlining)] public ProfilerMarker(string name) { m_Ptr = ProfilerUnsafeUtility.CreateMarker(name, 1, MarkerFlags.Default, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe ProfilerMarker(char* name, int nameLen) { m_Ptr = ProfilerUnsafeUtility.CreateMarker(name, nameLen, 1, MarkerFlags.Default, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ProfilerMarker(ProfilerCategory category, string name) { m_Ptr = ProfilerUnsafeUtility.CreateMarker(name, category, MarkerFlags.Default, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe ProfilerMarker(ProfilerCategory category, char* name, int nameLen) { m_Ptr = ProfilerUnsafeUtility.CreateMarker(name, nameLen, category, MarkerFlags.Default, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ProfilerMarker(ProfilerCategory category, string name, MarkerFlags flags) { m_Ptr = ProfilerUnsafeUtility.CreateMarker(name, category, flags, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe ProfilerMarker(ProfilerCategory category, char* name, int nameLen, MarkerFlags flags) { m_Ptr = ProfilerUnsafeUtility.CreateMarker(name, nameLen, category, flags, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("ENABLE_PROFILER")] [Pure] public void Begin() { ProfilerUnsafeUtility.BeginSample(m_Ptr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("ENABLE_PROFILER")] public void Begin(UnityEngine.Object contextUnityObject) { ProfilerUnsafeUtility.Internal_BeginWithObject(m_Ptr, contextUnityObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Pure] [Conditional("ENABLE_PROFILER")] public void End() { ProfilerUnsafeUtility.EndSample(m_Ptr); } [Conditional("ENABLE_PROFILER")] internal void GetName(ref string name) { name = ProfilerUnsafeUtility.Internal_GetName(m_Ptr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Pure] public AutoScope Auto() { return new AutoScope(m_Ptr); } } public enum ProfilerFlowEventType : byte { Begin, ParallelNext, End, Next } public enum ProfilerMarkerDataUnit : byte { Undefined, TimeNanoseconds, Bytes, Count, Percent, FrequencyHz } [Flags] public enum ProfilerCounterOptions : ushort { None = 0, FlushOnEndOfFrame = 2, ResetToZeroOnFlush = 4 } internal struct ProfilerMarkerWithStringData { public struct AutoScope : IDisposable { private IntPtr _marker; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal AutoScope(IntPtr marker) { _marker = marker; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Pure] public void Dispose() { if (_marker != IntPtr.Zero) { ProfilerUnsafeUtility.EndSample(_marker); } } } private const MethodImplOptions AggressiveInlining = MethodImplOptions.AggressiveInlining; private IntPtr _marker; public static ProfilerMarkerWithStringData Create(string name, string parameterName) { IntPtr intPtr = ProfilerUnsafeUtility.CreateMarker(name, 16, MarkerFlags.Default, 1); ProfilerUnsafeUtility.SetMarkerMetadata(intPtr, 0, parameterName, 9, 0); return new ProfilerMarkerWithStringData { _marker = intPtr }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Pure] public AutoScope Auto(bool enabled, Func parameterValue) { if (enabled) { return Auto(parameterValue()); } return new AutoScope(IntPtr.Zero); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Pure] public unsafe AutoScope Auto(string value) { if (value == null) { throw new ArgumentNullException("value"); } fixed (char* ptr = value) { ProfilerMarkerData profilerMarkerData = new ProfilerMarkerData { Type = 9, Size = (uint)(value.Length * 2 + 2) }; profilerMarkerData.Ptr = ptr; ProfilerUnsafeUtility.BeginSampleWithMetadata(_marker, 1, &profilerMarkerData); } return new AutoScope(_marker); } } [Flags] public enum ProfilerRecorderOptions { None = 0, StartImmediately = 1, KeepAliveDuringDomainReload = 2, CollectOnlyOnCurrentThread = 4, WrapAroundWhenCapacityReached = 8, SumAllSamplesInFrame = 0x10, GpuRecorder = 0x40, Default = 0x18 } [DebuggerDisplay("Value = {Value}; Count = {Count}")] [UsedByNativeCode] public struct ProfilerRecorderSample { private long value; private long count; private long refValue; public long Value => value; public long Count => count; } [NativeHeader("Runtime/Profiler/ScriptBindings/ProfilerRecorder.bindings.h")] [DebuggerTypeProxy(typeof(ProfilerRecorderDebugView))] [UsedByNativeCode] [DebuggerDisplay("Count = {Count}")] public struct ProfilerRecorder : IDisposable { internal enum ControlOptions { Start = 0, Stop = 1, Reset = 2, Release = 4, SetFilterToCurrentThread = 5, SetToCollectFromAllThreads = 6 } internal enum CountOptions { Count, MaxCount } internal ulong handle; internal const ProfilerRecorderOptions SharedRecorder = (ProfilerRecorderOptions)128; public bool Valid => handle != 0L && GetValid(this); public ProfilerMarkerDataType DataType { get { CheckInitializedAndThrow(); return GetValueDataType(this); } } public ProfilerMarkerDataUnit UnitType { get { CheckInitializedAndThrow(); return GetValueUnitType(this); } } public long CurrentValue { get { CheckInitializedAndThrow(); return GetCurrentValue(this); } } public double CurrentValueAsDouble { get { CheckInitializedAndThrow(); return GetCurrentValueAsDouble(this); } } public long LastValue { get { CheckInitializedAndThrow(); return GetLastValue(this); } } public double LastValueAsDouble { get { CheckInitializedAndThrow(); return GetLastValueAsDouble(this); } } public int Capacity { get { CheckInitializedAndThrow(); return GetCount(this, CountOptions.MaxCount); } } public int Count { get { CheckInitializedAndThrow(); return GetCount(this, CountOptions.Count); } } public bool IsRunning { get { CheckInitializedAndThrow(); return GetRunning(this); } } public bool WrappedAround { get { CheckInitializedAndThrow(); return GetWrapped(this); } } internal ProfilerRecorder(ProfilerRecorderOptions options) { this = Create(default(ProfilerRecorderHandle), 0, options); } public ProfilerRecorder(string statName, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) : this(ProfilerCategory.Any, statName, capacity, options) { } public ProfilerRecorder(string categoryName, string statName, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) : this(new ProfilerCategory(categoryName), statName, capacity, options) { } public ProfilerRecorder(ProfilerCategory category, string statName, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) { ProfilerRecorderHandle byName = ProfilerRecorderHandle.GetByName(category, statName); this = Create(byName, capacity, options); } public unsafe ProfilerRecorder(ProfilerCategory category, char* statName, int statNameLen, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) { ProfilerRecorderHandle byName = ProfilerRecorderHandle.GetByName(category, statName, statNameLen); this = Create(byName, capacity, options); } public ProfilerRecorder(ProfilerMarker marker, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) { this = Create(ProfilerRecorderHandle.Get(marker), capacity, options); } public ProfilerRecorder(ProfilerRecorderHandle statHandle, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) { this = Create(statHandle, capacity, options); } public unsafe static ProfilerRecorder StartNew(ProfilerCategory category, string statName, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) { fixed (char* statName2 = statName) { return new ProfilerRecorder(category, statName2, statName.Length, capacity, options | ProfilerRecorderOptions.StartImmediately); } } public static ProfilerRecorder StartNew(ProfilerMarker marker, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) { return new ProfilerRecorder(marker, capacity, options | ProfilerRecorderOptions.StartImmediately); } internal static ProfilerRecorder StartNew() { return Create(default(ProfilerRecorderHandle), 0, ProfilerRecorderOptions.StartImmediately); } public void Start() { CheckInitializedAndThrow(); Control(this, ControlOptions.Start); } public void Stop() { CheckInitializedAndThrow(); Control(this, ControlOptions.Stop); } public void Reset() { CheckInitializedAndThrow(); Control(this, ControlOptions.Reset); } public ProfilerRecorderSample GetSample(int index) { CheckInitializedAndThrow(); return GetSampleInternal(this, index); } public void CopyTo(List outSamples, bool reset = false) { if (outSamples == null) { throw new ArgumentNullException("outSamples"); } CheckInitializedAndThrow(); CopyTo_List(this, outSamples, reset); } public unsafe int CopyTo(ProfilerRecorderSample* dest, int destSize, bool reset = false) { CheckInitializedWithParamsAndThrow(dest); return CopyTo_Pointer(this, dest, destSize, reset); } public unsafe ProfilerRecorderSample[] ToArray() { CheckInitializedAndThrow(); int count = Count; ProfilerRecorderSample[] array = new ProfilerRecorderSample[count]; fixed (ProfilerRecorderSample* outSamples = array) { CopyTo_Pointer(this, outSamples, count, reset: false); } return array; } internal void FilterToCurrentThread() { CheckInitializedAndThrow(); Control(this, ControlOptions.SetFilterToCurrentThread); } internal void CollectFromAllThreads() { CheckInitializedAndThrow(); Control(this, ControlOptions.SetToCollectFromAllThreads); } [NativeMethod(IsThreadSafe = true, ThrowsException = true)] private static ProfilerRecorder Create(ProfilerRecorderHandle statHandle, int maxSampleCount, ProfilerRecorderOptions options) { Create_Injected(ref statHandle, maxSampleCount, options, out var ret); return ret; } [NativeMethod(IsThreadSafe = true)] private static void Control(ProfilerRecorder handle, ControlOptions options) { Control_Injected(ref handle, options); } [NativeMethod(IsThreadSafe = true)] private static ProfilerMarkerDataUnit GetValueUnitType(ProfilerRecorder handle) { return GetValueUnitType_Injected(ref handle); } [NativeMethod(IsThreadSafe = true)] private static ProfilerMarkerDataType GetValueDataType(ProfilerRecorder handle) { return GetValueDataType_Injected(ref handle); } [NativeMethod(IsThreadSafe = true)] private static long GetCurrentValue(ProfilerRecorder handle) { return GetCurrentValue_Injected(ref handle); } [NativeMethod(IsThreadSafe = true)] private static double GetCurrentValueAsDouble(ProfilerRecorder handle) { return GetCurrentValueAsDouble_Injected(ref handle); } [NativeMethod(IsThreadSafe = true)] private static long GetLastValue(ProfilerRecorder handle) { return GetLastValue_Injected(ref handle); } [NativeMethod(IsThreadSafe = true)] private static double GetLastValueAsDouble(ProfilerRecorder handle) { return GetLastValueAsDouble_Injected(ref handle); } [NativeMethod(IsThreadSafe = true)] private static int GetCount(ProfilerRecorder handle, CountOptions countOptions) { return GetCount_Injected(ref handle, countOptions); } [NativeMethod(IsThreadSafe = true)] private static bool GetValid(ProfilerRecorder handle) { return GetValid_Injected(ref handle); } [NativeMethod(IsThreadSafe = true)] private static bool GetWrapped(ProfilerRecorder handle) { return GetWrapped_Injected(ref handle); } [NativeMethod(IsThreadSafe = true)] private static bool GetRunning(ProfilerRecorder handle) { return GetRunning_Injected(ref handle); } [NativeMethod(IsThreadSafe = true, ThrowsException = true)] private static ProfilerRecorderSample GetSampleInternal(ProfilerRecorder handle, int index) { GetSampleInternal_Injected(ref handle, index, out var ret); return ret; } [NativeMethod(IsThreadSafe = true)] private static void CopyTo_List(ProfilerRecorder handle, List outSamples, bool reset) { CopyTo_List_Injected(ref handle, outSamples, reset); } [NativeMethod(IsThreadSafe = true)] private unsafe static int CopyTo_Pointer(ProfilerRecorder handle, ProfilerRecorderSample* outSamples, int outSamplesSize, bool reset) { return CopyTo_Pointer_Injected(ref handle, outSamples, outSamplesSize, reset); } public void Dispose() { if (handle != 0) { Control(this, ControlOptions.Release); handle = 0uL; } } [BurstDiscard] private unsafe void CheckInitializedWithParamsAndThrow(ProfilerRecorderSample* dest) { if (handle == 0) { throw new InvalidOperationException("ProfilerRecorder object is not initialized or has been disposed."); } if (dest == null) { throw new ArgumentNullException("dest"); } } [BurstDiscard] private void CheckInitializedAndThrow() { if (handle == 0) { throw new InvalidOperationException("ProfilerRecorder object is not initialized or has been disposed."); } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Create_Injected(ref ProfilerRecorderHandle statHandle, int maxSampleCount, ProfilerRecorderOptions options, out ProfilerRecorder ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Control_Injected(ref ProfilerRecorder handle, ControlOptions options); [MethodImpl(MethodImplOptions.InternalCall)] private static extern ProfilerMarkerDataUnit GetValueUnitType_Injected(ref ProfilerRecorder handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern ProfilerMarkerDataType GetValueDataType_Injected(ref ProfilerRecorder handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern long GetCurrentValue_Injected(ref ProfilerRecorder handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern double GetCurrentValueAsDouble_Injected(ref ProfilerRecorder handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern long GetLastValue_Injected(ref ProfilerRecorder handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern double GetLastValueAsDouble_Injected(ref ProfilerRecorder handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetCount_Injected(ref ProfilerRecorder handle, CountOptions countOptions); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool GetValid_Injected(ref ProfilerRecorder handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool GetWrapped_Injected(ref ProfilerRecorder handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool GetRunning_Injected(ref ProfilerRecorder handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetSampleInternal_Injected(ref ProfilerRecorder handle, int index, out ProfilerRecorderSample ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CopyTo_List_Injected(ref ProfilerRecorder handle, List outSamples, bool reset); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern int CopyTo_Pointer_Injected(ref ProfilerRecorder handle, ProfilerRecorderSample* outSamples, int outSamplesSize, bool reset); } internal sealed class ProfilerRecorderDebugView { private ProfilerRecorder m_Recorder; public ProfilerRecorderSample[] Items => m_Recorder.ToArray(); public ProfilerRecorderDebugView(ProfilerRecorder r) { m_Recorder = r; } } } namespace Unity.Profiling.LowLevel { [Flags] public enum MarkerFlags : ushort { Default = 0, Script = 2, ScriptInvoke = 0x20, ScriptDeepProfiler = 0x40, AvailabilityEditor = 4, AvailabilityNonDevelopment = 8, Warning = 0x10, Counter = 0x80, SampleGPU = 0x100 } public enum ProfilerMarkerDataType : byte { Int32 = 2, UInt32 = 3, Int64 = 4, UInt64 = 5, Float = 6, Double = 7, String16 = 9, Blob8 = 11 } } namespace Unity.Profiling.LowLevel.Unsafe { [StructLayout(LayoutKind.Explicit, Size = 24)] [UsedByNativeCode] public readonly struct ProfilerRecorderDescription { [FieldOffset(0)] private readonly ProfilerCategory category; [FieldOffset(2)] private readonly MarkerFlags flags; [FieldOffset(4)] private readonly ProfilerMarkerDataType dataType; [FieldOffset(5)] private readonly ProfilerMarkerDataUnit unitType; [FieldOffset(8)] private readonly int reserved0; [FieldOffset(12)] private readonly int nameUtf8Len; [FieldOffset(16)] private unsafe readonly byte* nameUtf8; public ProfilerCategory Category => category; public MarkerFlags Flags => flags; public ProfilerMarkerDataType DataType => dataType; public ProfilerMarkerDataUnit UnitType => unitType; public int NameUtf8Len => nameUtf8Len; public unsafe byte* NameUtf8 => nameUtf8; public unsafe string Name => ProfilerUnsafeUtility.Utf8ToString(nameUtf8, nameUtf8Len); } [StructLayout(LayoutKind.Explicit, Size = 8)] [UsedByNativeCode] public readonly struct ProfilerRecorderHandle { private const ulong k_InvalidHandle = ulong.MaxValue; [FieldOffset(0)] internal readonly ulong handle; public bool Valid => handle != 0L && handle != ulong.MaxValue; internal ProfilerRecorderHandle(ulong handle) { this.handle = handle; } internal static ProfilerRecorderHandle Get(ProfilerMarker marker) { return new ProfilerRecorderHandle((ulong)marker.Handle.ToInt64()); } internal static ProfilerRecorderHandle Get(ProfilerCategory category, string statName) { if (string.IsNullOrEmpty(statName)) { throw new ArgumentException("String must be not null or empty", "statName"); } return GetByName(category, statName); } public static ProfilerRecorderDescription GetDescription(ProfilerRecorderHandle handle) { if (!handle.Valid) { throw new ArgumentException("ProfilerRecorderHandle is not initialized or is not available", "handle"); } return GetDescriptionInternal(handle); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true, ThrowsException = true)] public static extern void GetAvailable(List outRecorderHandleList); [NativeMethod(IsThreadSafe = true)] internal static ProfilerRecorderHandle GetByName(ProfilerCategory category, string name) { GetByName_Injected(ref category, name, out var ret); return ret; } [NativeMethod(IsThreadSafe = true)] internal unsafe static ProfilerRecorderHandle GetByName__Unmanaged(ProfilerCategory category, byte* name, int nameLen) { GetByName__Unmanaged_Injected(ref category, name, nameLen, out var ret); return ret; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe static ProfilerRecorderHandle GetByName(ProfilerCategory category, char* name, int nameLen) { return GetByName_Unsafe(category, name, nameLen); } [NativeMethod(IsThreadSafe = true)] private unsafe static ProfilerRecorderHandle GetByName_Unsafe(ProfilerCategory category, char* name, int nameLen) { GetByName_Unsafe_Injected(ref category, name, nameLen, out var ret); return ret; } [NativeMethod(IsThreadSafe = true)] private static ProfilerRecorderDescription GetDescriptionInternal(ProfilerRecorderHandle handle) { GetDescriptionInternal_Injected(ref handle, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetByName_Injected(ref ProfilerCategory category, string name, out ProfilerRecorderHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void GetByName__Unmanaged_Injected(ref ProfilerCategory category, byte* name, int nameLen, out ProfilerRecorderHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void GetByName_Unsafe_Injected(ref ProfilerCategory category, char* name, int nameLen, out ProfilerRecorderHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetDescriptionInternal_Injected(ref ProfilerRecorderHandle handle, out ProfilerRecorderDescription ret); } [StructLayout(LayoutKind.Explicit, Size = 16)] public struct ProfilerMarkerData { [FieldOffset(0)] public byte Type; [FieldOffset(1)] private readonly byte reserved0; [FieldOffset(2)] private readonly ushort reserved1; [FieldOffset(4)] public uint Size; [FieldOffset(8)] public unsafe void* Ptr; } [StructLayout(LayoutKind.Explicit, Size = 24)] public readonly struct ProfilerCategoryDescription { [FieldOffset(0)] public readonly ushort Id; [FieldOffset(2)] public readonly ushort Flags; [FieldOffset(4)] public readonly Color32 Color; [FieldOffset(8)] private readonly int reserved0; [FieldOffset(12)] public readonly int NameUtf8Len; [FieldOffset(16)] public unsafe readonly byte* NameUtf8; public unsafe string Name => ProfilerUnsafeUtility.Utf8ToString(NameUtf8, NameUtf8Len); } [UsedByNativeCode] [NativeHeader("Runtime/Profiler/ScriptBindings/ProfilerUnsafeUtility.bindings.h")] public static class ProfilerUnsafeUtility { public struct TimestampConversionRatio { public long Numerator; public long Denominator; } public const ushort CategoryRender = 0; public const ushort CategoryScripts = 1; public const ushort CategoryGUI = 4; public const ushort CategoryPhysics = 5; public const ushort CategoryAnimation = 6; public const ushort CategoryAi = 7; public const ushort CategoryAudio = 8; public const ushort CategoryVideo = 11; public const ushort CategoryParticles = 12; public const ushort CategoryLighting = 13; [Obsolete("CategoryLightning has been renamed. Use CategoryLighting instead (UnityUpgradable) -> CategoryLighting", false)] public const ushort CategoryLightning = 13; public const ushort CategoryNetwork = 14; public const ushort CategoryLoading = 15; public const ushort CategoryOther = 16; public const ushort CategoryVr = 22; public const ushort CategoryAllocation = 23; public const ushort CategoryInternal = 24; public const ushort CategoryFileIO = 25; public const ushort CategoryInput = 30; public const ushort CategoryVirtualTexturing = 31; internal const ushort CategoryGPU = 32; internal const ushort CategoryAny = ushort.MaxValue; public static extern long Timestamp { [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] get; } public static TimestampConversionRatio TimestampToNanosecondsConversionRatio { [ThreadSafe] get { get_TimestampToNanosecondsConversionRatio_Injected(out var ret); return ret; } } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] internal static extern ushort CreateCategory(string name, ProfilerCategoryColor colorIndex); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] internal unsafe static extern ushort CreateCategory__Unmanaged(byte* name, int nameLen, ProfilerCategoryColor colorIndex); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static ushort CreateCategory(char* name, int nameLen, ProfilerCategoryColor colorIndex) { return CreateCategory_Unsafe(name, nameLen, colorIndex); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] private unsafe static extern ushort CreateCategory_Unsafe(char* name, int nameLen, ProfilerCategoryColor colorIndex); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static ushort GetCategoryByName(char* name, int nameLen) { return GetCategoryByName_Unsafe(name, nameLen); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] private unsafe static extern ushort GetCategoryByName_Unsafe(char* name, int nameLen); [ThreadSafe] public static ProfilerCategoryDescription GetCategoryDescription(ushort categoryId) { GetCategoryDescription_Injected(categoryId, out var ret); return ret; } [ThreadSafe] internal static Color32 GetCategoryColor(ProfilerCategoryColor colorIndex) { GetCategoryColor_Injected(colorIndex, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern IntPtr CreateMarker(string name, ushort categoryId, MarkerFlags flags, int metadataCount); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] internal unsafe static extern IntPtr CreateMarker__Unmanaged(byte* name, int nameLen, ushort categoryId, MarkerFlags flags, int metadataCount); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static IntPtr CreateMarker(char* name, int nameLen, ushort categoryId, MarkerFlags flags, int metadataCount) { return CreateMarker_Unsafe(name, nameLen, categoryId, flags, metadataCount); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] private unsafe static extern IntPtr CreateMarker_Unsafe(char* name, int nameLen, ushort categoryId, MarkerFlags flags, int metadataCount); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] internal static extern IntPtr GetMarker(string name); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern void SetMarkerMetadata(IntPtr markerPtr, int index, string name, byte type, byte unit); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] internal unsafe static extern void SetMarkerMetadata__Unmanaged(IntPtr markerPtr, int index, byte* name, int nameLen, byte type, byte unit); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void SetMarkerMetadata(IntPtr markerPtr, int index, char* name, int nameLen, byte type, byte unit) { SetMarkerMetadata_Unsafe(markerPtr, index, name, nameLen, type, unit); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] private unsafe static extern void SetMarkerMetadata_Unsafe(IntPtr markerPtr, int index, char* name, int nameLen, byte type, byte unit); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern void BeginSample(IntPtr markerPtr); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public unsafe static extern void BeginSampleWithMetadata(IntPtr markerPtr, int metadataCount, void* metadata); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern void EndSample(IntPtr markerPtr); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public unsafe static extern void SingleSampleWithMetadata(IntPtr markerPtr, int metadataCount, void* metadata); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public unsafe static extern void* CreateCounterValue(out IntPtr counterPtr, string name, ushort categoryId, MarkerFlags flags, byte dataType, byte dataUnit, int dataSize, ProfilerCounterOptions counterOptions); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] internal unsafe static extern void* CreateCounterValue__Unmanaged(out IntPtr counterPtr, byte* name, int nameLen, ushort categoryId, MarkerFlags flags, byte dataType, byte dataUnit, int dataSize, ProfilerCounterOptions counterOptions); [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void* CreateCounterValue(out IntPtr counterPtr, char* name, int nameLen, ushort categoryId, MarkerFlags flags, byte dataType, byte dataUnit, int dataSize, ProfilerCounterOptions counterOptions) { return CreateCounterValue_Unsafe(out counterPtr, name, nameLen, categoryId, flags, dataType, dataUnit, dataSize, counterOptions); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] private unsafe static extern void* CreateCounterValue_Unsafe(out IntPtr counterPtr, char* name, int nameLen, ushort categoryId, MarkerFlags flags, byte dataType, byte dataUnit, int dataSize, ProfilerCounterOptions counterOptions); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public unsafe static extern void FlushCounterValue(void* counterValuePtr); internal unsafe static string Utf8ToString(byte* chars, int charsLen) { if (chars == null) { return null; } byte[] array = new byte[charsLen]; Marshal.Copy((IntPtr)chars, array, 0, charsLen); return Encoding.UTF8.GetString(array, 0, charsLen); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern uint CreateFlow(ushort categoryId); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern void FlowEvent(uint flowId, ProfilerFlowEventType flowEventType); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] internal static extern void Internal_BeginWithObject(IntPtr markerPtr, UnityEngine.Object contextUnityObject); [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("ENABLE_PROFILER")] internal static extern string Internal_GetName(IntPtr markerPtr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetCategoryDescription_Injected(ushort categoryId, out ProfilerCategoryDescription ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetCategoryColor_Injected(ProfilerCategoryColor colorIndex, out Color32 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_TimestampToNanosecondsConversionRatio_Injected(out TimestampConversionRatio ret); } } namespace Unity.Jobs { [JobProducerType(typeof(IJobExtensions.JobStruct<>))] public interface IJob { void Execute(); } public static class IJobExtensions { [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct JobStruct where T : struct, IJob { public delegate void ExecuteJobFunction(ref T data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); public static readonly IntPtr jobReflectionData = JobsUtility.CreateJobReflectionData(typeof(T), new ExecuteJobFunction(Execute)); public static void Execute(ref T data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) { data.Execute(); } } public unsafe static JobHandle Schedule(this T jobData, JobHandle dependsOn = default(JobHandle)) where T : struct, IJob { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), JobStruct.jobReflectionData, dependsOn, ScheduleMode.Single); return JobsUtility.Schedule(ref parameters); } public unsafe static void Run(this T jobData) where T : struct, IJob { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), JobStruct.jobReflectionData, default(JobHandle), ScheduleMode.Run); JobsUtility.Schedule(ref parameters); } } [JobProducerType(typeof(IJobForExtensions.ForJobStruct<>))] public interface IJobFor { void Execute(int index); } public static class IJobForExtensions { [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct ForJobStruct where T : struct, IJobFor { public delegate void ExecuteJobFunction(ref T data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); public static readonly IntPtr jobReflectionData = JobsUtility.CreateJobReflectionData(typeof(T), new ExecuteJobFunction(Execute)); public static void Execute(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) { int beginIndex; int endIndex; while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out beginIndex, out endIndex)) { int num = endIndex; for (int i = beginIndex; i < num; i++) { jobData.Execute(i); } } } } public unsafe static JobHandle Schedule(this T jobData, int arrayLength, JobHandle dependency) where T : struct, IJobFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), ForJobStruct.jobReflectionData, dependency, ScheduleMode.Single); return JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, arrayLength); } public unsafe static JobHandle ScheduleParallel(this T jobData, int arrayLength, int innerloopBatchCount, JobHandle dependency) where T : struct, IJobFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), ForJobStruct.jobReflectionData, dependency, ScheduleMode.Batched); return JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, innerloopBatchCount); } public unsafe static void Run(this T jobData, int arrayLength) where T : struct, IJobFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), ForJobStruct.jobReflectionData, default(JobHandle), ScheduleMode.Run); JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, arrayLength); } } [JobProducerType(typeof(IJobParallelForExtensions.ParallelForJobStruct<>))] public interface IJobParallelFor { void Execute(int index); } public static class IJobParallelForExtensions { [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct ParallelForJobStruct where T : struct, IJobParallelFor { public delegate void ExecuteJobFunction(ref T data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); public static readonly IntPtr jobReflectionData = JobsUtility.CreateJobReflectionData(typeof(T), new ExecuteJobFunction(Execute)); public static void Execute(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) { int beginIndex; int endIndex; while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out beginIndex, out endIndex)) { int num = endIndex; for (int i = beginIndex; i < num; i++) { jobData.Execute(i); } } } } public unsafe static JobHandle Schedule(this T jobData, int arrayLength, int innerloopBatchCount, JobHandle dependsOn = default(JobHandle)) where T : struct, IJobParallelFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), ParallelForJobStruct.jobReflectionData, dependsOn, ScheduleMode.Batched); return JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, innerloopBatchCount); } public unsafe static void Run(this T jobData, int arrayLength) where T : struct, IJobParallelFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), ParallelForJobStruct.jobReflectionData, default(JobHandle), ScheduleMode.Run); JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, arrayLength); } } [NativeType(Header = "Runtime/Jobs/ScriptBindings/JobsBindings.h")] public struct JobHandle { [NativeDisableUnsafePtrRestriction] internal IntPtr jobGroup; internal int version; public bool IsCompleted => ScheduleBatchedJobsAndIsCompleted(ref this); public void Complete() { if (!(jobGroup == IntPtr.Zero)) { ScheduleBatchedJobsAndComplete(ref this); } } public unsafe static void CompleteAll(ref JobHandle job0, ref JobHandle job1) { JobHandle* ptr = stackalloc JobHandle[2]; *ptr = job0; ptr[1] = job1; ScheduleBatchedJobsAndCompleteAll(ptr, 2); job0 = default(JobHandle); job1 = default(JobHandle); } public unsafe static void CompleteAll(ref JobHandle job0, ref JobHandle job1, ref JobHandle job2) { JobHandle* ptr = stackalloc JobHandle[3]; *ptr = job0; ptr[1] = job1; ptr[2] = job2; ScheduleBatchedJobsAndCompleteAll(ptr, 3); job0 = default(JobHandle); job1 = default(JobHandle); job2 = default(JobHandle); } public unsafe static void CompleteAll(NativeArray jobs) { ScheduleBatchedJobsAndCompleteAll(jobs.GetUnsafeReadOnlyPtr(), jobs.Length); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("ScheduleBatchedScriptingJobs", IsFreeFunction = true, IsThreadSafe = true)] public static extern void ScheduleBatchedJobs(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("ScheduleBatchedScriptingJobsAndComplete", IsFreeFunction = true, IsThreadSafe = true, ThrowsException = true)] private static extern void ScheduleBatchedJobsAndComplete(ref JobHandle job); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("ScheduleBatchedScriptingJobsAndIsCompleted", IsFreeFunction = true, IsThreadSafe = true, ThrowsException = true)] private static extern bool ScheduleBatchedJobsAndIsCompleted(ref JobHandle job); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("ScheduleBatchedScriptingJobsAndCompleteAll", IsFreeFunction = true, IsThreadSafe = true, ThrowsException = true)] private unsafe static extern void ScheduleBatchedJobsAndCompleteAll(void* jobs, int count); public static JobHandle CombineDependencies(JobHandle job0, JobHandle job1) { return CombineDependenciesInternal2(ref job0, ref job1); } public static JobHandle CombineDependencies(JobHandle job0, JobHandle job1, JobHandle job2) { return CombineDependenciesInternal3(ref job0, ref job1, ref job2); } public unsafe static JobHandle CombineDependencies(NativeArray jobs) { return CombineDependenciesInternalPtr(jobs.GetUnsafeReadOnlyPtr(), jobs.Length); } public unsafe static JobHandle CombineDependencies(NativeSlice jobs) { return CombineDependenciesInternalPtr(jobs.GetUnsafeReadOnlyPtr(), jobs.Length); } [NativeMethod(IsFreeFunction = true, IsThreadSafe = true, ThrowsException = true)] private static JobHandle CombineDependenciesInternal2(ref JobHandle job0, ref JobHandle job1) { CombineDependenciesInternal2_Injected(ref job0, ref job1, out var ret); return ret; } [NativeMethod(IsFreeFunction = true, IsThreadSafe = true, ThrowsException = true)] private static JobHandle CombineDependenciesInternal3(ref JobHandle job0, ref JobHandle job1, ref JobHandle job2) { CombineDependenciesInternal3_Injected(ref job0, ref job1, ref job2, out var ret); return ret; } [NativeMethod(IsFreeFunction = true, IsThreadSafe = true, ThrowsException = true)] internal unsafe static JobHandle CombineDependenciesInternalPtr(void* jobs, int count) { CombineDependenciesInternalPtr_Injected(jobs, count, out var ret); return ret; } [NativeMethod(IsFreeFunction = true, IsThreadSafe = true)] public static bool CheckFenceIsDependencyOrDidSyncFence(JobHandle jobHandle, JobHandle dependsOn) { return CheckFenceIsDependencyOrDidSyncFence_Injected(ref jobHandle, ref dependsOn); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CombineDependenciesInternal2_Injected(ref JobHandle job0, ref JobHandle job1, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CombineDependenciesInternal3_Injected(ref JobHandle job0, ref JobHandle job1, ref JobHandle job2, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void CombineDependenciesInternalPtr_Injected(void* jobs, int count, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool CheckFenceIsDependencyOrDidSyncFence_Injected(ref JobHandle jobHandle, ref JobHandle dependsOn); } } namespace Unity.Jobs.LowLevel.Unsafe { public struct BatchQueryJob where CommandT : struct where ResultT : struct { [Unity.Collections.ReadOnly] internal NativeArray commands; internal NativeArray results; public BatchQueryJob(NativeArray commands, NativeArray results) { this.commands = commands; this.results = results; } } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct BatchQueryJobStruct where T : struct { internal static IntPtr jobReflectionData; public static IntPtr Initialize() { if (jobReflectionData == IntPtr.Zero) { jobReflectionData = JobsUtility.CreateJobReflectionData(typeof(T), null); } return jobReflectionData; } } public static class JobHandleUnsafeUtility { public unsafe static JobHandle CombineDependencies(JobHandle* jobs, int count) { return JobHandle.CombineDependenciesInternalPtr(jobs, count); } } [AttributeUsage(AttributeTargets.Interface)] public sealed class JobProducerTypeAttribute : Attribute { public Type ProducerType { get; } public JobProducerTypeAttribute(Type producerType) { ProducerType = producerType; } } public struct JobRanges { internal int BatchSize; internal int NumJobs; public int TotalIterationCount; internal int NumPhases; internal IntPtr StartEndIndex; internal IntPtr PhaseData; } public enum ScheduleMode { Run = 0, [Obsolete("Batched is obsolete, use Parallel or Single depending on job type. (UnityUpgradable) -> Parallel", false)] Batched = 1, Parallel = 1, Single = 2 } [Obsolete("Reflection data is now universal between job types. The parameter can be removed.", false)] public enum JobType { Single, ParallelFor } [NativeType(Header = "Runtime/Jobs/ScriptBindings/JobsBindings.h")] [NativeHeader("Runtime/Jobs/JobSystem.h")] public static class JobsUtility { public struct JobScheduleParameters { public JobHandle Dependency; public int ScheduleMode; public IntPtr ReflectionData; public IntPtr JobDataPtr; public unsafe JobScheduleParameters(void* i_jobData, IntPtr i_reflectionData, JobHandle i_dependency, ScheduleMode i_scheduleMode) { Dependency = i_dependency; JobDataPtr = (IntPtr)i_jobData; ReflectionData = i_reflectionData; ScheduleMode = (int)i_scheduleMode; } } internal delegate void PanicFunction_(); public const int MaxJobThreadCount = 128; public const int CacheLineSize = 64; internal static PanicFunction_ PanicFunction; public static extern bool IsExecutingJob { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsFreeFunction = true, IsThreadSafe = true)] get; } public static extern bool JobDebuggerEnabled { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] set; } public static extern bool JobCompilerEnabled { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] set; } public static extern int JobWorkerMaximumCount { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobSystem::GetJobQueueMaximumThreadCount")] get; } public static int JobWorkerCount { get { return GetJobQueueWorkerThreadCount(); } set { if (value < 0 || value > JobWorkerMaximumCount) { throw new ArgumentOutOfRangeException("JobWorkerCount", $"Invalid JobWorkerCount {value} must be in the range 0 -> {JobWorkerMaximumCount}"); } SetJobQueueMaximumActiveThreadCount(value); } } public unsafe static void GetJobRange(ref JobRanges ranges, int jobIndex, out int beginIndex, out int endIndex) { int* ptr = (int*)(void*)ranges.StartEndIndex; beginIndex = ptr[jobIndex * 2]; endIndex = ptr[jobIndex * 2 + 1]; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsFreeFunction = true, IsThreadSafe = true)] public static extern bool GetWorkStealingRange(ref JobRanges ranges, int jobIndex, out int beginIndex, out int endIndex); [FreeFunction("ScheduleManagedJob", ThrowsException = true, IsThreadSafe = true)] public static JobHandle Schedule(ref JobScheduleParameters parameters) { Schedule_Injected(ref parameters, out var ret); return ret; } [FreeFunction("ScheduleManagedJobParallelFor", ThrowsException = true, IsThreadSafe = true)] public static JobHandle ScheduleParallelFor(ref JobScheduleParameters parameters, int arrayLength, int innerloopBatchCount) { ScheduleParallelFor_Injected(ref parameters, arrayLength, innerloopBatchCount, out var ret); return ret; } [FreeFunction("ScheduleManagedJobParallelForDeferArraySize", ThrowsException = true, IsThreadSafe = true)] public unsafe static JobHandle ScheduleParallelForDeferArraySize(ref JobScheduleParameters parameters, int innerloopBatchCount, void* listData, void* listDataAtomicSafetyHandle) { ScheduleParallelForDeferArraySize_Injected(ref parameters, innerloopBatchCount, listData, listDataAtomicSafetyHandle, out var ret); return ret; } [FreeFunction("ScheduleManagedJobParallelForTransform", ThrowsException = true)] public static JobHandle ScheduleParallelForTransform(ref JobScheduleParameters parameters, IntPtr transfromAccesssArray) { ScheduleParallelForTransform_Injected(ref parameters, transfromAccesssArray, out var ret); return ret; } [FreeFunction("ScheduleManagedJobParallelForTransformReadOnly", ThrowsException = true)] public static JobHandle ScheduleParallelForTransformReadOnly(ref JobScheduleParameters parameters, IntPtr transfromAccesssArray, int innerloopBatchCount) { ScheduleParallelForTransformReadOnly_Injected(ref parameters, transfromAccesssArray, innerloopBatchCount, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] [NativeMethod(IsThreadSafe = true, IsFreeFunction = true)] public unsafe static extern void PatchBufferMinMaxRanges(IntPtr bufferRangePatchData, void* jobdata, int startIndex, int rangeSize); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(ThrowsException = true, IsThreadSafe = true)] private static extern IntPtr CreateJobReflectionData(Type wrapperJobType, Type userJobType, object managedJobFunction0, object managedJobFunction1, object managedJobFunction2); [Obsolete("JobType is obsolete. The parameter should be removed. (UnityUpgradable) -> !1")] public static IntPtr CreateJobReflectionData(Type type, JobType jobType, object managedJobFunction0, object managedJobFunction1 = null, object managedJobFunction2 = null) { return CreateJobReflectionData(type, type, managedJobFunction0, managedJobFunction1, managedJobFunction2); } public static IntPtr CreateJobReflectionData(Type type, object managedJobFunction0, object managedJobFunction1 = null, object managedJobFunction2 = null) { return CreateJobReflectionData(type, type, managedJobFunction0, managedJobFunction1, managedJobFunction2); } [Obsolete("JobType is obsolete. The parameter should be removed. (UnityUpgradable) -> !2")] public static IntPtr CreateJobReflectionData(Type wrapperJobType, Type userJobType, JobType jobType, object managedJobFunction0) { return CreateJobReflectionData(wrapperJobType, userJobType, managedJobFunction0, null, null); } public static IntPtr CreateJobReflectionData(Type wrapperJobType, Type userJobType, object managedJobFunction0) { return CreateJobReflectionData(wrapperJobType, userJobType, managedJobFunction0, null, null); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobSystem::GetJobQueueWorkerThreadCount")] private static extern int GetJobQueueWorkerThreadCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobSystem::ForceSetJobQueueWorkerThreadCount")] private static extern void SetJobQueueMaximumActiveThreadCount(int count); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobSystem::ResetJobQueueWorkerThreadCount")] public static extern void ResetJobWorkerCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobDebuggerGetSystemIdCellPtr")] internal static extern IntPtr GetSystemIdCellPtr(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobDebuggerClearSystemIds")] internal static extern void ClearSystemIds(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobDebuggerGetSystemIdMappings")] internal unsafe static extern int GetSystemIdMappings(JobHandle* handles, int* systemIds, int maxCount); [RequiredByNativeCode] private static void InvokePanicFunction() { PanicFunction?.Invoke(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Schedule_Injected(ref JobScheduleParameters parameters, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ScheduleParallelFor_Injected(ref JobScheduleParameters parameters, int arrayLength, int innerloopBatchCount, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void ScheduleParallelForDeferArraySize_Injected(ref JobScheduleParameters parameters, int innerloopBatchCount, void* listData, void* listDataAtomicSafetyHandle, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ScheduleParallelForTransform_Injected(ref JobScheduleParameters parameters, IntPtr transfromAccesssArray, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ScheduleParallelForTransformReadOnly_Injected(ref JobScheduleParameters parameters, IntPtr transfromAccesssArray, int innerloopBatchCount, out JobHandle ret); } } namespace Unity.Rendering.HybridV2 { public struct DOTSInstancingCbuffer { public int NameID; public int CbufferIndex; public int SizeBytes; } public enum DOTSInstancingPropertyType { Unknown, Float, Half, Int, Short, Uint, Bool, Struct } public struct DOTSInstancingProperty { public int MetadataNameID; public int ConstantNameID; public int CbufferIndex; public int MetadataOffset; public int SizeBytes; public DOTSInstancingPropertyType ConstantType; public int Cols; public int Rows; } public class HybridV2ShaderReflection { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetDOTSInstancingCbuffersPointer")] private static extern IntPtr GetDOTSInstancingCbuffersPointer([NotNull("ArgumentNullException")] Shader shader, ref int cbufferCount); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetDOTSInstancingPropertiesPointer")] private static extern IntPtr GetDOTSInstancingPropertiesPointer([NotNull("ArgumentNullException")] Shader shader, ref int propertyCount); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Shader::GetDOTSReflectionVersionNumber")] public static extern uint GetDOTSReflectionVersionNumber(); public unsafe static NativeArray GetDOTSInstancingCbuffers(Shader shader) { if (shader == null) { return default(NativeArray); } int cbufferCount = 0; IntPtr dOTSInstancingCbuffersPointer = GetDOTSInstancingCbuffersPointer(shader, ref cbufferCount); if (dOTSInstancingCbuffersPointer == IntPtr.Zero) { return default(NativeArray); } return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)dOTSInstancingCbuffersPointer, cbufferCount, Allocator.Temp); } public unsafe static NativeArray GetDOTSInstancingProperties(Shader shader) { if (shader == null) { return default(NativeArray); } int propertyCount = 0; IntPtr dOTSInstancingPropertiesPointer = GetDOTSInstancingPropertiesPointer(shader, ref propertyCount); if (dOTSInstancingPropertiesPointer == IntPtr.Zero) { return default(NativeArray); } return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)dOTSInstancingPropertiesPointer, propertyCount, Allocator.Temp); } } } namespace Unity.IL2CPP.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = false)] internal class Il2CppEagerStaticClassConstructionAttribute : Attribute { } } namespace Unity.IO.LowLevel.Unsafe { public struct ReadCommand { public unsafe void* Buffer; public long Offset; public long Size; } public struct ReadCommandArray { public unsafe ReadCommand* ReadCommands; public int CommandCount; } [RequiredByNativeCode] public enum FileState { Absent, Exists } public enum FileStatus { Closed, Pending, Open, OpenFailed } public struct FileInfoResult { public long FileSize; public FileState FileState; } public enum AssetLoadingSubsystem { Other, Texture, VirtualTexture, Mesh, Audio, Scripts, EntitiesScene, EntitiesStreamBinaryReader, FileInfo } public enum ReadStatus { Complete = 0, InProgress = 1, Failed = 2, Truncated = 4, Canceled = 5 } [RequiredByNativeCode] public enum Priority { PriorityLow, PriorityHigh } public readonly struct FileHandle { [NativeDisableUnsafePtrRestriction] internal readonly IntPtr fileCommandPtr; internal readonly int version; public FileStatus Status { get { if (!IsFileHandleValid(in this)) { throw new InvalidOperationException("FileHandle.Status cannot be called on a closed FileHandle"); } return GetFileStatus_Internal(in this); } } public JobHandle JobHandle { get { if (!IsFileHandleValid(in this)) { throw new InvalidOperationException("FileHandle.JobHandle cannot be called on a closed FileHandle"); } return GetJobHandle_Internal(in this); } } public bool IsValid() { return IsFileHandleValid(in this); } public JobHandle Close(JobHandle dependency = default(JobHandle)) { if (!IsFileHandleValid(in this)) { throw new InvalidOperationException("FileHandle.Close cannot be called twice on the same FileHandle"); } return AsyncReadManager.CloseFileAsync(in this, dependency); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("AsyncReadManagerManaged::IsFileHandleValid")] private static extern bool IsFileHandleValid(in FileHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("AsyncReadManagerManaged::GetFileStatusFromManagedHandle")] private static extern FileStatus GetFileStatus_Internal(in FileHandle handle); [FreeFunction("AsyncReadManagerManaged::GetJobFenceFromManagedHandle")] private static JobHandle GetJobHandle_Internal(in FileHandle handle) { GetJobHandle_Internal_Injected(in handle, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetJobHandle_Internal_Injected(in FileHandle handle, out JobHandle ret); } public struct ReadHandle : IDisposable { [NativeDisableUnsafePtrRestriction] internal IntPtr ptr; internal int version; public JobHandle JobHandle { get { if (!IsReadHandleValid(this)) { throw new InvalidOperationException("ReadHandle.JobHandle cannot be called after the ReadHandle has been disposed"); } return GetJobHandle(this); } } public ReadStatus Status { get { if (!IsReadHandleValid(this)) { throw new InvalidOperationException("Cannot use a ReadHandle that has been disposed"); } return GetReadStatus(this); } } public long ReadCount { get { if (!IsReadHandleValid(this)) { throw new InvalidOperationException("Cannot use a ReadHandle that has been disposed"); } return GetReadCount(this); } } public bool IsValid() { return IsReadHandleValid(this); } public void Dispose() { if (!IsReadHandleValid(this)) { throw new InvalidOperationException("ReadHandle.Dispose cannot be called twice on the same ReadHandle"); } if (Status == ReadStatus.InProgress) { throw new InvalidOperationException("ReadHandle.Dispose cannot be called until the read operation completes"); } ReleaseReadHandle(this); } public void Cancel() { if (!IsReadHandleValid(this)) { throw new InvalidOperationException("ReadHandle.Cancel cannot be called on a disposed ReadHandle"); } CancelInternal(this); } [FreeFunction("AsyncReadManagerManaged::CancelReadRequest")] private static void CancelInternal(ReadHandle handle) { CancelInternal_Injected(ref handle); } public long GetBytesRead() { if (!IsReadHandleValid(this)) { throw new InvalidOperationException("ReadHandle.GetBytesRead cannot be called after the ReadHandle has been disposed"); } return GetBytesRead(this); } public long GetBytesRead(uint readCommandIndex) { if (!IsReadHandleValid(this)) { throw new InvalidOperationException("ReadHandle.GetBytesRead cannot be called after the ReadHandle has been disposed"); } return GetBytesReadForCommand(this, readCommandIndex); } public unsafe ulong* GetBytesReadArray() { if (!IsReadHandleValid(this)) { throw new InvalidOperationException("ReadHandle.GetBytesReadArray cannot be called after the ReadHandle has been disposed"); } return GetBytesReadArray(this); } [FreeFunction("AsyncReadManagerManaged::GetReadStatus", IsThreadSafe = true)] [ThreadAndSerializationSafe] private static ReadStatus GetReadStatus(ReadHandle handle) { return GetReadStatus_Injected(ref handle); } [FreeFunction("AsyncReadManagerManaged::GetReadCount", IsThreadSafe = true)] [ThreadAndSerializationSafe] private static long GetReadCount(ReadHandle handle) { return GetReadCount_Injected(ref handle); } [ThreadAndSerializationSafe] [FreeFunction("AsyncReadManagerManaged::GetBytesRead", IsThreadSafe = true)] private static long GetBytesRead(ReadHandle handle) { return GetBytesRead_Injected(ref handle); } [ThreadAndSerializationSafe] [FreeFunction("AsyncReadManagerManaged::GetBytesReadForCommand", IsThreadSafe = true)] private static long GetBytesReadForCommand(ReadHandle handle, uint readCommandIndex) { return GetBytesReadForCommand_Injected(ref handle, readCommandIndex); } [FreeFunction("AsyncReadManagerManaged::GetBytesReadArray", IsThreadSafe = true)] [ThreadAndSerializationSafe] private unsafe static ulong* GetBytesReadArray(ReadHandle handle) { return GetBytesReadArray_Injected(ref handle); } [FreeFunction("AsyncReadManagerManaged::ReleaseReadHandle", IsThreadSafe = true)] [ThreadAndSerializationSafe] private static void ReleaseReadHandle(ReadHandle handle) { ReleaseReadHandle_Injected(ref handle); } [FreeFunction("AsyncReadManagerManaged::IsReadHandleValid", IsThreadSafe = true)] [ThreadAndSerializationSafe] private static bool IsReadHandleValid(ReadHandle handle) { return IsReadHandleValid_Injected(ref handle); } [ThreadAndSerializationSafe] [FreeFunction("AsyncReadManagerManaged::GetJobHandle", IsThreadSafe = true)] private static JobHandle GetJobHandle(ReadHandle handle) { GetJobHandle_Injected(ref handle, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CancelInternal_Injected(ref ReadHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern ReadStatus GetReadStatus_Injected(ref ReadHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern long GetReadCount_Injected(ref ReadHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern long GetBytesRead_Injected(ref ReadHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern long GetBytesReadForCommand_Injected(ref ReadHandle handle, uint readCommandIndex); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern ulong* GetBytesReadArray_Injected(ref ReadHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ReleaseReadHandle_Injected(ref ReadHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsReadHandleValid_Injected(ref ReadHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetJobHandle_Injected(ref ReadHandle handle, out JobHandle ret); } [NativeHeader("Runtime/File/AsyncReadManagerManagedApi.h")] public static class AsyncReadManager { [ThreadAndSerializationSafe] [FreeFunction("AsyncReadManagerManaged::Read", IsThreadSafe = true)] private unsafe static ReadHandle ReadInternal(string filename, void* cmds, uint cmdCount, string assetName, ulong typeID, AssetLoadingSubsystem subsystem) { ReadInternal_Injected(filename, cmds, cmdCount, assetName, typeID, subsystem, out var ret); return ret; } public unsafe static ReadHandle Read(string filename, ReadCommand* readCmds, uint readCmdCount, string assetName = "", ulong typeID = 0uL, AssetLoadingSubsystem subsystem = AssetLoadingSubsystem.Scripts) { return ReadInternal(filename, readCmds, readCmdCount, assetName, typeID, subsystem); } [FreeFunction("AsyncReadManagerManaged::GetFileInfo", IsThreadSafe = true)] [ThreadAndSerializationSafe] private unsafe static ReadHandle GetFileInfoInternal(string filename, void* cmd) { GetFileInfoInternal_Injected(filename, cmd, out var ret); return ret; } public unsafe static ReadHandle GetFileInfo(string filename, FileInfoResult* result) { if (result == null) { throw new NullReferenceException("GetFileInfo must have a valid FileInfoResult to write into."); } return GetFileInfoInternal(filename, result); } [FreeFunction("AsyncReadManagerManaged::ReadWithHandles_NativePtr", IsThreadSafe = true)] [ThreadAndSerializationSafe] private unsafe static ReadHandle ReadWithHandlesInternal_NativePtr(in FileHandle fileHandle, void* readCmdArray, JobHandle dependency) { ReadWithHandlesInternal_NativePtr_Injected(in fileHandle, readCmdArray, ref dependency, out var ret); return ret; } [ThreadAndSerializationSafe] [FreeFunction("AsyncReadManagerManaged::ReadWithHandles_NativeCopy", IsThreadSafe = true)] private unsafe static ReadHandle ReadWithHandlesInternal_NativeCopy(in FileHandle fileHandle, void* readCmdArray) { ReadWithHandlesInternal_NativeCopy_Injected(in fileHandle, readCmdArray, out var ret); return ret; } public unsafe static ReadHandle ReadDeferred(in FileHandle fileHandle, ReadCommandArray* readCmdArray, JobHandle dependency) { if (!fileHandle.IsValid()) { throw new InvalidOperationException("FileHandle is invalid and may not be read from."); } return ReadWithHandlesInternal_NativePtr(in fileHandle, readCmdArray, dependency); } public unsafe static ReadHandle Read(in FileHandle fileHandle, ReadCommandArray readCmdArray) { if (!fileHandle.IsValid()) { throw new InvalidOperationException("FileHandle is invalid and may not be read from."); } return ReadWithHandlesInternal_NativeCopy(in fileHandle, UnsafeUtility.AddressOf(ref readCmdArray)); } [ThreadAndSerializationSafe] [FreeFunction("AsyncReadManagerManaged::ScheduleOpenRequest", IsThreadSafe = true)] private static FileHandle OpenFileAsync_Internal(string fileName) { OpenFileAsync_Internal_Injected(fileName, out var ret); return ret; } public static FileHandle OpenFileAsync(string fileName) { if (fileName.Length == 0) { throw new InvalidOperationException("FileName is empty"); } return OpenFileAsync_Internal(fileName); } [FreeFunction("AsyncReadManagerManaged::ScheduleCloseRequest", IsThreadSafe = true)] [ThreadAndSerializationSafe] internal static JobHandle CloseFileAsync(in FileHandle fileHandle, JobHandle dependency) { CloseFileAsync_Injected(in fileHandle, ref dependency, out var ret); return ret; } [ThreadAndSerializationSafe] [FreeFunction("AsyncReadManagerManaged::ScheduleCloseCachedFileRequest", IsThreadSafe = true)] public static JobHandle CloseCachedFileAsync(string fileName, JobHandle dependency = default(JobHandle)) { CloseCachedFileAsync_Injected(fileName, ref dependency, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void ReadInternal_Injected(string filename, void* cmds, uint cmdCount, string assetName, ulong typeID, AssetLoadingSubsystem subsystem, out ReadHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void GetFileInfoInternal_Injected(string filename, void* cmd, out ReadHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void ReadWithHandlesInternal_NativePtr_Injected(in FileHandle fileHandle, void* readCmdArray, ref JobHandle dependency, out ReadHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void ReadWithHandlesInternal_NativeCopy_Injected(in FileHandle fileHandle, void* readCmdArray, out ReadHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void OpenFileAsync_Internal_Injected(string fileName, out FileHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CloseFileAsync_Injected(in FileHandle fileHandle, ref JobHandle dependency, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CloseCachedFileAsync_Injected(string fileName, [Optional][DefaultParameterValue(null)] ref JobHandle dependency, out JobHandle ret); } [NativeHeader("Runtime/File/AsyncReadManagerMetrics.h")] public enum ProcessingState { Unknown, InQueue, Reading, Completed, Failed, Canceled } public enum FileReadType { Sync, Async } [RequiredByNativeCode] [NativeConditional("ENABLE_PROFILER")] public struct AsyncReadManagerRequestMetric { [NativeName("assetName")] public string AssetName { get; } [NativeName("fileName")] public string FileName { get; } [NativeName("offsetBytes")] public ulong OffsetBytes { get; } [NativeName("sizeBytes")] public ulong SizeBytes { get; } [NativeName("assetTypeId")] public ulong AssetTypeId { get; } [NativeName("currentBytesRead")] public ulong CurrentBytesRead { get; } [NativeName("batchReadCount")] public uint BatchReadCount { get; } [NativeName("isBatchRead")] public bool IsBatchRead { get; } [NativeName("state")] public ProcessingState State { get; } [NativeName("readType")] public FileReadType ReadType { get; } [NativeName("priorityLevel")] public Priority PriorityLevel { get; } [NativeName("subsystem")] public AssetLoadingSubsystem Subsystem { get; } [NativeName("requestTimeMicroseconds")] public double RequestTimeMicroseconds { get; } [NativeName("timeInQueueMicroseconds")] public double TimeInQueueMicroseconds { get; } [NativeName("totalTimeMicroseconds")] public double TotalTimeMicroseconds { get; } } [NativeConditional("ENABLE_PROFILER")] public static class AsyncReadManagerMetrics { [Flags] public enum Flags { None = 0, ClearOnRead = 1 } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("AreMetricsEnabled_Internal")] public static extern bool IsEnabled(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetAsyncReadManagerMetrics()->ClearMetrics")] [ThreadSafe] private static extern void ClearMetrics_Internal(); public static void ClearCompletedMetrics() { ClearMetrics_Internal(); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetAsyncReadManagerMetrics()->GetMarshalledMetrics")] [ThreadSafe] internal static extern AsyncReadManagerRequestMetric[] GetMetrics_Internal(bool clear); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetAsyncReadManagerMetrics()->GetMetrics_NoAlloc")] [ThreadSafe] internal static extern void GetMetrics_NoAlloc_Internal([NotNull("ArgumentNullException")] List metrics, bool clear); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetAsyncReadManagerMetrics()->GetMarshalledMetrics_Filtered_Managed")] [ThreadSafe] internal static extern AsyncReadManagerRequestMetric[] GetMetrics_Filtered_Internal(AsyncReadManagerMetricsFilters filters, bool clear); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetAsyncReadManagerMetrics()->GetMetrics_NoAlloc_Filtered_Managed")] [ThreadSafe] internal static extern void GetMetrics_NoAlloc_Filtered_Internal([NotNull("ArgumentNullException")] List metrics, AsyncReadManagerMetricsFilters filters, bool clear); public static AsyncReadManagerRequestMetric[] GetMetrics(AsyncReadManagerMetricsFilters filters, Flags flags) { bool clear = (flags & Flags.ClearOnRead) == Flags.ClearOnRead; return GetMetrics_Filtered_Internal(filters, clear); } public static void GetMetrics(List outMetrics, AsyncReadManagerMetricsFilters filters, Flags flags) { bool clear = (flags & Flags.ClearOnRead) == Flags.ClearOnRead; GetMetrics_NoAlloc_Filtered_Internal(outMetrics, filters, clear); } public static AsyncReadManagerRequestMetric[] GetMetrics(Flags flags) { bool clear = (flags & Flags.ClearOnRead) == Flags.ClearOnRead; return GetMetrics_Internal(clear); } public static void GetMetrics(List outMetrics, Flags flags) { bool clear = (flags & Flags.ClearOnRead) == Flags.ClearOnRead; GetMetrics_NoAlloc_Internal(outMetrics, clear); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetAsyncReadManagerMetrics()->StartCollecting")] public static extern void StartCollectingMetrics(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetAsyncReadManagerMetrics()->StopCollecting")] public static extern void StopCollectingMetrics(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetAsyncReadManagerMetrics()->GetCurrentSummaryMetrics")] internal static extern AsyncReadManagerSummaryMetrics GetSummaryMetrics_Internal(bool clear); public static AsyncReadManagerSummaryMetrics GetCurrentSummaryMetrics(Flags flags) { bool clear = (flags & Flags.ClearOnRead) == Flags.ClearOnRead; return GetSummaryMetrics_Internal(clear); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetAsyncReadManagerMetrics()->GetCurrentSummaryMetricsWithFilters")] internal static extern AsyncReadManagerSummaryMetrics GetSummaryMetricsWithFilters_Internal(AsyncReadManagerMetricsFilters metricsFilters, bool clear); public static AsyncReadManagerSummaryMetrics GetCurrentSummaryMetrics(AsyncReadManagerMetricsFilters metricsFilters, Flags flags) { bool clear = (flags & Flags.ClearOnRead) == Flags.ClearOnRead; return GetSummaryMetricsWithFilters_Internal(metricsFilters, clear); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetAsyncReadManagerMetrics()->GetSummaryOfMetrics_Managed")] [ThreadSafe] internal static extern AsyncReadManagerSummaryMetrics GetSummaryOfMetrics_Internal(AsyncReadManagerRequestMetric[] metrics); public static AsyncReadManagerSummaryMetrics GetSummaryOfMetrics(AsyncReadManagerRequestMetric[] metrics) { return GetSummaryOfMetrics_Internal(metrics); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [FreeFunction("GetAsyncReadManagerMetrics()->GetSummaryOfMetrics_FromContainer_Managed", ThrowsException = true)] internal static extern AsyncReadManagerSummaryMetrics GetSummaryOfMetrics_FromContainer_Internal(List metrics); public static AsyncReadManagerSummaryMetrics GetSummaryOfMetrics(List metrics) { return GetSummaryOfMetrics_FromContainer_Internal(metrics); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [FreeFunction("GetAsyncReadManagerMetrics()->GetSummaryOfMetricsWithFilters_Managed")] internal static extern AsyncReadManagerSummaryMetrics GetSummaryOfMetricsWithFilters_Internal(AsyncReadManagerRequestMetric[] metrics, AsyncReadManagerMetricsFilters metricsFilters); public static AsyncReadManagerSummaryMetrics GetSummaryOfMetrics(AsyncReadManagerRequestMetric[] metrics, AsyncReadManagerMetricsFilters metricsFilters) { return GetSummaryOfMetricsWithFilters_Internal(metrics, metricsFilters); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetAsyncReadManagerMetrics()->GetSummaryOfMetricsWithFilters_FromContainer_Managed", ThrowsException = true)] [ThreadSafe] internal static extern AsyncReadManagerSummaryMetrics GetSummaryOfMetricsWithFilters_FromContainer_Internal(List metrics, AsyncReadManagerMetricsFilters metricsFilters); public static AsyncReadManagerSummaryMetrics GetSummaryOfMetrics(List metrics, AsyncReadManagerMetricsFilters metricsFilters) { return GetSummaryOfMetricsWithFilters_FromContainer_Internal(metrics, metricsFilters); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [FreeFunction("GetAsyncReadManagerMetrics()->GetTotalSizeNonASRMReadsBytes")] public static extern ulong GetTotalSizeOfNonASRMReadsBytes(bool emptyAfterRead); } [StructLayout(LayoutKind.Sequential)] [NativeAsStruct] [NativeConditional("ENABLE_PROFILER")] public class AsyncReadManagerSummaryMetrics { [NativeName("totalBytesRead")] public ulong TotalBytesRead { get; } [NativeName("averageBandwidthMBPerSecond")] public float AverageBandwidthMBPerSecond { get; } [NativeName("averageReadSizeInBytes")] public float AverageReadSizeInBytes { get; } [NativeName("averageWaitTimeMicroseconds")] public float AverageWaitTimeMicroseconds { get; } [NativeName("averageReadTimeMicroseconds")] public float AverageReadTimeMicroseconds { get; } [NativeName("averageTotalRequestTimeMicroseconds")] public float AverageTotalRequestTimeMicroseconds { get; } [NativeName("averageThroughputMBPerSecond")] public float AverageThroughputMBPerSecond { get; } [NativeName("longestWaitTimeMicroseconds")] public float LongestWaitTimeMicroseconds { get; } [NativeName("longestReadTimeMicroseconds")] public float LongestReadTimeMicroseconds { get; } [NativeName("longestReadAssetType")] public ulong LongestReadAssetType { get; } [NativeName("longestWaitAssetType")] public ulong LongestWaitAssetType { get; } [NativeName("longestReadSubsystem")] public AssetLoadingSubsystem LongestReadSubsystem { get; } [NativeName("longestWaitSubsystem")] public AssetLoadingSubsystem LongestWaitSubsystem { get; } [NativeName("numberOfInProgressRequests")] public int NumberOfInProgressRequests { get; } [NativeName("numberOfCompletedRequests")] public int NumberOfCompletedRequests { get; } [NativeName("numberOfFailedRequests")] public int NumberOfFailedRequests { get; } [NativeName("numberOfWaitingRequests")] public int NumberOfWaitingRequests { get; } [NativeName("numberOfCanceledRequests")] public int NumberOfCanceledRequests { get; } [NativeName("totalNumberOfRequests")] public int TotalNumberOfRequests { get; } [NativeName("numberOfCachedReads")] public int NumberOfCachedReads { get; } [NativeName("numberOfAsyncReads")] public int NumberOfAsyncReads { get; } [NativeName("numberOfSyncReads")] public int NumberOfSyncReads { get; } } [StructLayout(LayoutKind.Sequential)] [NativeConditional("ENABLE_PROFILER")] [NativeAsStruct] [RequiredByNativeCode] public class AsyncReadManagerMetricsFilters { [NativeName("typeIDs")] internal ulong[] TypeIDs; [NativeName("states")] internal ProcessingState[] States; [NativeName("readTypes")] internal FileReadType[] ReadTypes; [NativeName("priorityLevels")] internal Priority[] PriorityLevels; [NativeName("subsystems")] internal AssetLoadingSubsystem[] Subsystems; public AsyncReadManagerMetricsFilters() { ClearFilters(); } public AsyncReadManagerMetricsFilters(ulong typeID) { ClearFilters(); SetTypeIDFilter(typeID); } public AsyncReadManagerMetricsFilters(ProcessingState state) { ClearFilters(); SetStateFilter(state); } public AsyncReadManagerMetricsFilters(FileReadType readType) { ClearFilters(); SetReadTypeFilter(readType); } public AsyncReadManagerMetricsFilters(Priority priorityLevel) { ClearFilters(); SetPriorityFilter(priorityLevel); } public AsyncReadManagerMetricsFilters(AssetLoadingSubsystem subsystem) { ClearFilters(); SetSubsystemFilter(subsystem); } public AsyncReadManagerMetricsFilters(ulong[] typeIDs) { ClearFilters(); SetTypeIDFilter(typeIDs); } public AsyncReadManagerMetricsFilters(ProcessingState[] states) { ClearFilters(); SetStateFilter(states); } public AsyncReadManagerMetricsFilters(FileReadType[] readTypes) { ClearFilters(); SetReadTypeFilter(readTypes); } public AsyncReadManagerMetricsFilters(Priority[] priorityLevels) { ClearFilters(); SetPriorityFilter(priorityLevels); } public AsyncReadManagerMetricsFilters(AssetLoadingSubsystem[] subsystems) { ClearFilters(); SetSubsystemFilter(subsystems); } public AsyncReadManagerMetricsFilters(ulong[] typeIDs, ProcessingState[] states, FileReadType[] readTypes, Priority[] priorityLevels, AssetLoadingSubsystem[] subsystems) { ClearFilters(); SetTypeIDFilter(typeIDs); SetStateFilter(states); SetReadTypeFilter(readTypes); SetPriorityFilter(priorityLevels); SetSubsystemFilter(subsystems); } public void SetTypeIDFilter(ulong[] _typeIDs) { TypeIDs = _typeIDs; } public void SetStateFilter(ProcessingState[] _states) { States = _states; } public void SetReadTypeFilter(FileReadType[] _readTypes) { ReadTypes = _readTypes; } public void SetPriorityFilter(Priority[] _priorityLevels) { PriorityLevels = _priorityLevels; } public void SetSubsystemFilter(AssetLoadingSubsystem[] _subsystems) { Subsystems = _subsystems; } public void SetTypeIDFilter(ulong _typeID) { TypeIDs = new ulong[1] { _typeID }; } public void SetStateFilter(ProcessingState _state) { States = new ProcessingState[1] { _state }; } public void SetReadTypeFilter(FileReadType _readType) { ReadTypes = new FileReadType[1] { _readType }; } public void SetPriorityFilter(Priority _priorityLevel) { PriorityLevels = new Priority[1] { _priorityLevel }; } public void SetSubsystemFilter(AssetLoadingSubsystem _subsystem) { Subsystems = new AssetLoadingSubsystem[1] { _subsystem }; } public void RemoveTypeIDFilter() { TypeIDs = null; } public void RemoveStateFilter() { States = null; } public void RemoveReadTypeFilter() { ReadTypes = null; } public void RemovePriorityFilter() { PriorityLevels = null; } public void RemoveSubsystemFilter() { Subsystems = null; } public void ClearFilters() { RemoveTypeIDFilter(); RemoveStateFilter(); RemoveReadTypeFilter(); RemovePriorityFilter(); RemoveSubsystemFilter(); } } [NativeHeader("Runtime/VirtualFileSystem/VirtualFileSystem.h")] public static class VirtualFileSystem { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool GetLocalFileSystemName(string vfsFileName, out string localFileName, out ulong localFileOffset, out ulong localFileSize); } } namespace Unity.Collections { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] [RequiredByNativeCode] public sealed class ReadOnlyAttribute : Attribute { } [RequiredByNativeCode] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] public sealed class WriteOnlyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field)] [RequiredByNativeCode] public sealed class DeallocateOnJobCompletionAttribute : Attribute { } [RequiredByNativeCode] [AttributeUsage(AttributeTargets.Field)] public sealed class NativeFixedLengthAttribute : Attribute { public int FixedLength; public NativeFixedLengthAttribute(int fixedLength) { FixedLength = fixedLength; } } [AttributeUsage(AttributeTargets.Field)] [RequiredByNativeCode] public sealed class NativeMatchesParallelForLengthAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field)] [RequiredByNativeCode] public sealed class NativeDisableParallelForRestrictionAttribute : Attribute { } [UsedByNativeCode] public enum Allocator { Invalid, None, Temp, TempJob, Persistent, AudioKernel } [UsedByNativeCode] internal enum LeakCategory { Invalid, Malloc, TempJob, Persistent, LightProbesQuery, NativeTest, MeshDataArray, TransformAccessArray, NavMeshQuery } public enum NativeLeakDetectionMode { EnabledWithStackTrace = 3, Enabled = 2, Disabled = 1 } public static class NativeLeakDetection { private static int s_NativeLeakDetectionMode; private const string kNativeLeakDetectionModePrefsString = "Unity.Colletions.NativeLeakDetection.Mode"; public static NativeLeakDetectionMode Mode { get { if (s_NativeLeakDetectionMode == 0) { Initialize(); } return (NativeLeakDetectionMode)s_NativeLeakDetectionMode; } set { if (s_NativeLeakDetectionMode != (int)value) { s_NativeLeakDetectionMode = (int)value; } } } [RuntimeInitializeOnLoadMethod] private static void Initialize() { s_NativeLeakDetectionMode = 1; } } public enum NativeArrayOptions { UninitializedMemory, ClearMemory } [DebuggerDisplay("Length = {Length}")] [NativeContainer] [NativeContainerSupportsMinMaxWriteRestriction] [DebuggerTypeProxy(typeof(NativeArrayDebugView<>))] [NativeContainerSupportsDeferredConvertListToArray] [NativeContainerSupportsDeallocateOnJobCompletion] public struct NativeArray : IDisposable, IEnumerable, IEnumerable, IEquatable> where T : struct { [ExcludeFromDocs] public struct Enumerator : IEnumerator, IEnumerator, IDisposable { private NativeArray m_Array; private int m_Index; private T value; public T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return value; } } object IEnumerator.Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Current; } } public Enumerator(ref NativeArray array) { m_Array = array; m_Index = -1; value = default(T); } public void Dispose() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe bool MoveNext() { m_Index++; if (m_Index < m_Array.m_Length) { value = UnsafeUtility.ReadArrayElement(m_Array.m_Buffer, m_Index); return true; } value = default(T); return false; } public void Reset() { m_Index = -1; } } [NativeContainer] [DebuggerDisplay("Length = {Length}")] [DebuggerTypeProxy(typeof(NativeArrayReadOnlyDebugView<>))] [NativeContainerIsReadOnly] public struct ReadOnly : IEnumerable, IEnumerable { [ExcludeFromDocs] public struct Enumerator : IEnumerator, IEnumerator, IDisposable { private ReadOnly m_Array; private int m_Index; private T value; public T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return value; } } object IEnumerator.Current => Current; public Enumerator(in ReadOnly array) { m_Array = array; m_Index = -1; value = default(T); } public void Dispose() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe bool MoveNext() { m_Index++; if (m_Index < m_Array.m_Length) { value = UnsafeUtility.ReadArrayElement(m_Array.m_Buffer, m_Index); return true; } value = default(T); return false; } public void Reset() { m_Index = -1; } } [NativeDisableUnsafePtrRestriction] internal unsafe void* m_Buffer; internal int m_Length; public int Length { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_Length; } } public unsafe T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return UnsafeUtility.ReadArrayElement(m_Buffer, index); } } public unsafe bool IsCreated { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_Buffer != null; } } internal unsafe ReadOnly(void* buffer, int length) { m_Buffer = buffer; m_Length = length; } public void CopyTo(T[] array) { NativeArray.Copy(this, array); } public void CopyTo(NativeArray array) { NativeArray.Copy(this, array); } public T[] ToArray() { T[] array = new T[m_Length]; NativeArray.Copy(this, array, m_Length); return array; } public unsafe NativeArray.ReadOnly Reinterpret() where U : struct { return new NativeArray.ReadOnly(m_Buffer, m_Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private void CheckElementReadAccess(int index) { if ((uint)index >= (uint)m_Length) { throw new IndexOutOfRangeException($"Index {index} is out of range (must be between 0 and {m_Length - 1})."); } } public Enumerator GetEnumerator() { return new Enumerator(in this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [NativeDisableUnsafePtrRestriction] internal unsafe void* m_Buffer; internal int m_Length; internal Allocator m_AllocatorLabel; public int Length { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_Length; } } public unsafe T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return UnsafeUtility.ReadArrayElement(m_Buffer, index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [WriteAccessRequired] set { UnsafeUtility.WriteArrayElement(m_Buffer, index, value); } } public unsafe bool IsCreated { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_Buffer != null; } } public unsafe NativeArray(int length, Allocator allocator, NativeArrayOptions options = NativeArrayOptions.ClearMemory) { Allocate(length, allocator, out this); if ((options & NativeArrayOptions.ClearMemory) == NativeArrayOptions.ClearMemory) { UnsafeUtility.MemClear(m_Buffer, (long)Length * (long)UnsafeUtility.SizeOf()); } } public NativeArray(T[] array, Allocator allocator) { Allocate(array.Length, allocator, out this); Copy(array, this); } public NativeArray(NativeArray array, Allocator allocator) { Allocate(array.Length, allocator, out this); Copy(array, 0, this, 0, array.Length); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private static void CheckAllocateArguments(int length, Allocator allocator, long totalSize) { if (allocator <= Allocator.None) { throw new ArgumentException("Allocator must be Temp, TempJob or Persistent", "allocator"); } if (length < 0) { throw new ArgumentOutOfRangeException("length", "Length must be >= 0"); } IsUnmanagedAndThrow(); } private unsafe static void Allocate(int length, Allocator allocator, out NativeArray array) { long size = (long)UnsafeUtility.SizeOf() * (long)length; array = default(NativeArray); array.m_Buffer = UnsafeUtility.Malloc(size, UnsafeUtility.AlignOf(), allocator); array.m_Length = length; array.m_AllocatorLabel = allocator; } [BurstDiscard] internal static void IsUnmanagedAndThrow() { if (!UnsafeUtility.IsValidNativeContainerElementType()) { throw new InvalidOperationException($"{typeof(T)} used in NativeArray<{typeof(T)}> must be unmanaged (contain no managed types) and cannot itself be a native container type."); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private void CheckElementReadAccess(int index) { } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private void CheckElementWriteAccess(int index) { } [WriteAccessRequired] public unsafe void Dispose() { if (m_Buffer == null) { throw new ObjectDisposedException("The NativeArray is already disposed."); } if (m_AllocatorLabel == Allocator.Invalid) { throw new InvalidOperationException("The NativeArray can not be Disposed because it was not allocated with a valid allocator."); } if (m_AllocatorLabel > Allocator.None) { UnsafeUtility.Free(m_Buffer, m_AllocatorLabel); m_AllocatorLabel = Allocator.Invalid; } m_Buffer = null; } public unsafe JobHandle Dispose(JobHandle inputDeps) { if (m_AllocatorLabel == Allocator.Invalid) { throw new InvalidOperationException("The NativeArray can not be Disposed because it was not allocated with a valid allocator."); } if (m_Buffer == null) { throw new InvalidOperationException("The NativeArray is already disposed."); } if (m_AllocatorLabel > Allocator.None) { JobHandle result = new NativeArrayDisposeJob { Data = new NativeArrayDispose { m_Buffer = m_Buffer, m_AllocatorLabel = m_AllocatorLabel } }.Schedule(inputDeps); m_Buffer = null; m_AllocatorLabel = Allocator.Invalid; return result; } m_Buffer = null; return inputDeps; } [WriteAccessRequired] public void CopyFrom(T[] array) { Copy(array, this); } [WriteAccessRequired] public void CopyFrom(NativeArray array) { Copy(array, this); } public void CopyTo(T[] array) { Copy(this, array); } public void CopyTo(NativeArray array) { Copy(this, array); } public T[] ToArray() { T[] array = new T[Length]; Copy(this, array, Length); return array; } public Enumerator GetEnumerator() { return new Enumerator(ref this); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(ref this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public unsafe bool Equals(NativeArray other) { return m_Buffer == other.m_Buffer && m_Length == other.m_Length; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is NativeArray && Equals((NativeArray)obj); } public unsafe override int GetHashCode() { return ((int)m_Buffer * 397) ^ m_Length; } public static bool operator ==(NativeArray left, NativeArray right) { return left.Equals(right); } public static bool operator !=(NativeArray left, NativeArray right) { return !left.Equals(right); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private static void CheckCopyLengths(int srcLength, int dstLength) { if (srcLength != dstLength) { throw new ArgumentException("source and destination length must be the same"); } } public static void Copy(NativeArray src, NativeArray dst) { Copy(src, 0, dst, 0, src.Length); } public static void Copy(ReadOnly src, NativeArray dst) { Copy(src, 0, dst, 0, src.Length); } public static void Copy(T[] src, NativeArray dst) { Copy(src, 0, dst, 0, src.Length); } public static void Copy(NativeArray src, T[] dst) { Copy(src, 0, dst, 0, src.Length); } public static void Copy(ReadOnly src, T[] dst) { Copy(src, 0, dst, 0, src.Length); } public static void Copy(NativeArray src, NativeArray dst, int length) { Copy(src, 0, dst, 0, length); } public static void Copy(ReadOnly src, NativeArray dst, int length) { Copy(src, 0, dst, 0, length); } public static void Copy(T[] src, NativeArray dst, int length) { Copy(src, 0, dst, 0, length); } public static void Copy(NativeArray src, T[] dst, int length) { Copy(src, 0, dst, 0, length); } public static void Copy(ReadOnly src, T[] dst, int length) { Copy(src, 0, dst, 0, length); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private static void CheckCopyArguments(int srcLength, int srcIndex, int dstLength, int dstIndex, int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length", "length must be equal or greater than zero."); } if (srcIndex < 0 || srcIndex > srcLength || (srcIndex == srcLength && srcLength > 0)) { throw new ArgumentOutOfRangeException("srcIndex", "srcIndex is outside the range of valid indexes for the source NativeArray."); } if (dstIndex < 0 || dstIndex > dstLength || (dstIndex == dstLength && dstLength > 0)) { throw new ArgumentOutOfRangeException("dstIndex", "dstIndex is outside the range of valid indexes for the destination NativeArray."); } if (srcIndex + length > srcLength) { throw new ArgumentException("length is greater than the number of elements from srcIndex to the end of the source NativeArray.", "length"); } if (srcIndex + length < 0) { throw new ArgumentException("srcIndex + length causes an integer overflow"); } if (dstIndex + length > dstLength) { throw new ArgumentException("length is greater than the number of elements from dstIndex to the end of the destination NativeArray.", "length"); } if (dstIndex + length < 0) { throw new ArgumentException("dstIndex + length causes an integer overflow"); } } public unsafe static void Copy(NativeArray src, int srcIndex, NativeArray dst, int dstIndex, int length) { UnsafeUtility.MemCpy((byte*)dst.m_Buffer + dstIndex * UnsafeUtility.SizeOf(), (byte*)src.m_Buffer + srcIndex * UnsafeUtility.SizeOf(), length * UnsafeUtility.SizeOf()); } public unsafe static void Copy(ReadOnly src, int srcIndex, NativeArray dst, int dstIndex, int length) { UnsafeUtility.MemCpy((byte*)dst.m_Buffer + dstIndex * UnsafeUtility.SizeOf(), (byte*)src.m_Buffer + srcIndex * UnsafeUtility.SizeOf(), length * UnsafeUtility.SizeOf()); } public unsafe static void Copy(T[] src, int srcIndex, NativeArray dst, int dstIndex, int length) { GCHandle gCHandle = GCHandle.Alloc(src, GCHandleType.Pinned); IntPtr intPtr = gCHandle.AddrOfPinnedObject(); UnsafeUtility.MemCpy((byte*)dst.m_Buffer + dstIndex * UnsafeUtility.SizeOf(), (byte*)(void*)intPtr + srcIndex * UnsafeUtility.SizeOf(), length * UnsafeUtility.SizeOf()); gCHandle.Free(); } public unsafe static void Copy(NativeArray src, int srcIndex, T[] dst, int dstIndex, int length) { GCHandle gCHandle = GCHandle.Alloc(dst, GCHandleType.Pinned); IntPtr intPtr = gCHandle.AddrOfPinnedObject(); UnsafeUtility.MemCpy((byte*)(void*)intPtr + dstIndex * UnsafeUtility.SizeOf(), (byte*)src.m_Buffer + srcIndex * UnsafeUtility.SizeOf(), length * UnsafeUtility.SizeOf()); gCHandle.Free(); } public unsafe static void Copy(ReadOnly src, int srcIndex, T[] dst, int dstIndex, int length) { GCHandle gCHandle = GCHandle.Alloc(dst, GCHandleType.Pinned); IntPtr intPtr = gCHandle.AddrOfPinnedObject(); UnsafeUtility.MemCpy((byte*)(void*)intPtr + dstIndex * UnsafeUtility.SizeOf(), (byte*)src.m_Buffer + srcIndex * UnsafeUtility.SizeOf(), length * UnsafeUtility.SizeOf()); gCHandle.Free(); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private void CheckReinterpretLoadRange(int sourceIndex) where U : struct { } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private void CheckReinterpretStoreRange(int destIndex) where U : struct { } public unsafe U ReinterpretLoad(int sourceIndex) where U : struct { byte* source = (byte*)m_Buffer + (long)UnsafeUtility.SizeOf() * (long)sourceIndex; return UnsafeUtility.ReadArrayElement(source, 0); } public unsafe void ReinterpretStore(int destIndex, U data) where U : struct { byte* destination = (byte*)m_Buffer + (long)UnsafeUtility.SizeOf() * (long)destIndex; UnsafeUtility.WriteArrayElement(destination, 0, data); } private unsafe NativeArray InternalReinterpret(int length) where U : struct { return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(m_Buffer, length, m_AllocatorLabel); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private static void CheckReinterpretSize() where U : struct { if (UnsafeUtility.SizeOf() != UnsafeUtility.SizeOf()) { throw new InvalidOperationException($"Types {typeof(T)} and {typeof(U)} are different sizes - direct reinterpretation is not possible. If this is what you intended, use Reinterpret()"); } } public NativeArray Reinterpret() where U : struct { return InternalReinterpret(Length); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private void CheckReinterpretSize(long tSize, long uSize, int expectedTypeSize, long byteLen, long uLen) { if (tSize != expectedTypeSize) { throw new InvalidOperationException($"Type {typeof(T)} was expected to be {expectedTypeSize} but is {tSize} bytes"); } if (uLen * uSize != byteLen) { throw new InvalidOperationException($"Types {typeof(T)} (array length {Length}) and {typeof(U)} cannot be aliased due to size constraints. The size of the types and lengths involved must line up."); } } public NativeArray Reinterpret(int expectedTypeSize) where U : struct { long num = UnsafeUtility.SizeOf(); long num2 = UnsafeUtility.SizeOf(); long num3 = Length * num; long num4 = num3 / num2; return InternalReinterpret((int)num4); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private void CheckGetSubArrayArguments(int start, int length) { if (start < 0) { throw new ArgumentOutOfRangeException("start", "start must be >= 0"); } if (start + length > Length) { throw new ArgumentOutOfRangeException("length", $"sub array range {start}-{start + length - 1} is outside the range of the native array 0-{Length - 1}"); } if (start + length < 0) { throw new ArgumentException($"sub array range {start}-{start + length - 1} caused an integer overflow and is outside the range of the native array 0-{Length - 1}"); } } public unsafe NativeArray GetSubArray(int start, int length) { return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((byte*)m_Buffer + (long)UnsafeUtility.SizeOf() * (long)start, length, Allocator.None); } public unsafe ReadOnly AsReadOnly() { return new ReadOnly(m_Buffer, m_Length); } } [NativeContainer] internal struct NativeArrayDispose { [NativeDisableUnsafePtrRestriction] internal unsafe void* m_Buffer; internal Allocator m_AllocatorLabel; public unsafe void Dispose() { UnsafeUtility.Free(m_Buffer, m_AllocatorLabel); } } internal struct NativeArrayDisposeJob : IJob { internal NativeArrayDispose Data; public void Execute() { Data.Dispose(); } } internal sealed class NativeArrayDebugView where T : struct { private NativeArray m_Array; public T[] Items => m_Array.ToArray(); public NativeArrayDebugView(NativeArray array) { m_Array = array; } } internal sealed class NativeArrayReadOnlyDebugView where T : struct { private NativeArray.ReadOnly m_Array; public T[] Items => m_Array.ToArray(); public NativeArrayReadOnlyDebugView(NativeArray.ReadOnly array) { m_Array = array; } } public static class NativeSliceExtensions { public static NativeSlice Slice(this NativeArray thisArray) where T : struct { return new NativeSlice(thisArray); } public static NativeSlice Slice(this NativeArray thisArray, int start) where T : struct { return new NativeSlice(thisArray, start); } public static NativeSlice Slice(this NativeArray thisArray, int start, int length) where T : struct { return new NativeSlice(thisArray, start, length); } public static NativeSlice Slice(this NativeSlice thisSlice) where T : struct { return thisSlice; } public static NativeSlice Slice(this NativeSlice thisSlice, int start) where T : struct { return new NativeSlice(thisSlice, start); } public static NativeSlice Slice(this NativeSlice thisSlice, int start, int length) where T : struct { return new NativeSlice(thisSlice, start, length); } } [NativeContainer] [NativeContainerSupportsMinMaxWriteRestriction] [DebuggerTypeProxy(typeof(NativeSliceDebugView<>))] [DebuggerDisplay("Length = {Length}")] public struct NativeSlice : IEnumerable, IEnumerable, IEquatable> where T : struct { [ExcludeFromDocs] public struct Enumerator : IEnumerator, IEnumerator, IDisposable { private NativeSlice m_Array; private int m_Index; public T Current => m_Array[m_Index]; object IEnumerator.Current => Current; public Enumerator(ref NativeSlice array) { m_Array = array; m_Index = -1; } public void Dispose() { } public bool MoveNext() { m_Index++; return m_Index < m_Array.Length; } public void Reset() { m_Index = -1; } } [NativeDisableUnsafePtrRestriction] internal unsafe byte* m_Buffer; internal int m_Stride; internal int m_Length; public unsafe T this[int index] { get { return UnsafeUtility.ReadArrayElementWithStride(m_Buffer, index, m_Stride); } [WriteAccessRequired] set { UnsafeUtility.WriteArrayElementWithStride(m_Buffer, index, m_Stride, value); } } public int Stride => m_Stride; public int Length => m_Length; public NativeSlice(NativeSlice slice, int start) : this(slice, start, slice.Length - start) { } public unsafe NativeSlice(NativeSlice slice, int start, int length) { m_Stride = slice.m_Stride; m_Buffer = slice.m_Buffer + m_Stride * start; m_Length = length; } public NativeSlice(NativeArray array) : this(array, 0, array.Length) { } public NativeSlice(NativeArray array, int start) : this(array, start, array.Length - start) { } public static implicit operator NativeSlice(NativeArray array) { return new NativeSlice(array); } public unsafe NativeSlice(NativeArray array, int start, int length) { m_Stride = UnsafeUtility.SizeOf(); byte* buffer = (byte*)array.m_Buffer + m_Stride * start; m_Buffer = buffer; m_Length = length; } public unsafe NativeSlice SliceConvert() where U : struct { int num = UnsafeUtility.SizeOf(); NativeSlice result = default(NativeSlice); result.m_Buffer = m_Buffer; result.m_Stride = num; result.m_Length = m_Length * m_Stride / num; return result; } public unsafe NativeSlice SliceWithStride(int offset) where U : struct { NativeSlice result = default(NativeSlice); result.m_Buffer = m_Buffer + offset; result.m_Stride = m_Stride; result.m_Length = m_Length; return result; } public NativeSlice SliceWithStride() where U : struct { return SliceWithStride(0); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private void CheckReadIndex(int index) { } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private void CheckWriteIndex(int index) { } [WriteAccessRequired] public unsafe void CopyFrom(NativeSlice slice) { UnsafeUtility.MemCpyStride(this.GetUnsafePtr(), Stride, slice.GetUnsafeReadOnlyPtr(), slice.Stride, UnsafeUtility.SizeOf(), m_Length); } [WriteAccessRequired] public unsafe void CopyFrom(T[] array) { GCHandle gCHandle = GCHandle.Alloc(array, GCHandleType.Pinned); IntPtr intPtr = gCHandle.AddrOfPinnedObject(); int num = UnsafeUtility.SizeOf(); UnsafeUtility.MemCpyStride(this.GetUnsafePtr(), Stride, (void*)intPtr, num, num, m_Length); gCHandle.Free(); } public unsafe void CopyTo(NativeArray array) { int num = UnsafeUtility.SizeOf(); UnsafeUtility.MemCpyStride(array.GetUnsafePtr(), num, this.GetUnsafeReadOnlyPtr(), Stride, num, m_Length); } public unsafe void CopyTo(T[] array) { GCHandle gCHandle = GCHandle.Alloc(array, GCHandleType.Pinned); IntPtr intPtr = gCHandle.AddrOfPinnedObject(); int num = UnsafeUtility.SizeOf(); UnsafeUtility.MemCpyStride((void*)intPtr, num, this.GetUnsafeReadOnlyPtr(), Stride, num, m_Length); gCHandle.Free(); } public T[] ToArray() { T[] array = new T[Length]; CopyTo(array); return array; } public Enumerator GetEnumerator() { return new Enumerator(ref this); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(ref this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public unsafe bool Equals(NativeSlice other) { return m_Buffer == other.m_Buffer && m_Stride == other.m_Stride && m_Length == other.m_Length; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is NativeSlice && Equals((NativeSlice)obj); } public unsafe override int GetHashCode() { int num = (int)m_Buffer; num = (num * 397) ^ m_Stride; return (num * 397) ^ m_Length; } public static bool operator ==(NativeSlice left, NativeSlice right) { return left.Equals(right); } public static bool operator !=(NativeSlice left, NativeSlice right) { return !left.Equals(right); } } internal sealed class NativeSliceDebugView where T : struct { private NativeSlice m_Array; public T[] Items => m_Array.ToArray(); public NativeSliceDebugView(NativeSlice array) { m_Array = array; } } } namespace Unity.Collections.LowLevel.Unsafe { [NativeHeader("Runtime/Export/BurstLike/BurstLike.bindings.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] internal static class BurstLike { [MethodImpl(MethodImplOptions.InternalCall)] [BurstAuthorizedExternalMethod] [ThreadSafe(ThrowsException = false)] internal static extern int NativeFunctionCall_Int_IntPtr_IntPtr(IntPtr function, IntPtr p0, IntPtr p1, out int error); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = false)] [BurstAuthorizedExternalMethod] internal static extern IntPtr StaticDataGetOrCreate(int key, int sizeInBytes, out int error); } [AttributeUsage(AttributeTargets.Struct)] [RequiredByNativeCode] public sealed class NativeContainerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Struct)] [RequiredByNativeCode] public sealed class NativeContainerIsReadOnlyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Struct)] [RequiredByNativeCode] public sealed class NativeContainerIsAtomicWriteOnlyAttribute : Attribute { } [AttributeUsage(AttributeTargets.Struct)] [RequiredByNativeCode] public sealed class NativeContainerSupportsMinMaxWriteRestrictionAttribute : Attribute { } [AttributeUsage(AttributeTargets.Struct)] [RequiredByNativeCode] public sealed class NativeContainerSupportsDeallocateOnJobCompletionAttribute : Attribute { } [AttributeUsage(AttributeTargets.Struct)] [RequiredByNativeCode] public sealed class NativeContainerSupportsDeferredConvertListToArray : Attribute { } [RequiredByNativeCode] [AttributeUsage(AttributeTargets.Field)] public sealed class NativeSetThreadIndexAttribute : Attribute { } [Obsolete("Use NativeSetThreadIndexAttribute instead")] [RequiredByNativeCode] [AttributeUsage(AttributeTargets.Struct)] public sealed class NativeContainerNeedsThreadIndexAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)] public class WriteAccessRequiredAttribute : Attribute { } [RequiredByNativeCode] [AttributeUsage(AttributeTargets.Field)] public sealed class NativeDisableUnsafePtrRestrictionAttribute : Attribute { } [RequiredByNativeCode] [AttributeUsage(AttributeTargets.Field)] public sealed class NativeDisableContainerSafetyRestrictionAttribute : Attribute { } [RequiredByNativeCode] [AttributeUsage(AttributeTargets.Field)] public sealed class NativeSetClassTypeToNullOnScheduleAttribute : Attribute { } public static class NativeArrayUnsafeUtility { [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private static void CheckConvertArguments(int length, Allocator allocator) where T : struct { if (length < 0) { throw new ArgumentOutOfRangeException("length", "Length must be >= 0"); } NativeArray.IsUnmanagedAndThrow(); } public unsafe static NativeArray ConvertExistingDataToNativeArray(void* dataPointer, int length, Allocator allocator) where T : struct { return new NativeArray { m_Buffer = dataPointer, m_Length = length, m_AllocatorLabel = allocator }; } public unsafe static void* GetUnsafePtr(this NativeArray nativeArray) where T : struct { return nativeArray.m_Buffer; } public unsafe static void* GetUnsafeReadOnlyPtr(this NativeArray nativeArray) where T : struct { return nativeArray.m_Buffer; } public unsafe static void* GetUnsafeReadOnlyPtr(this NativeArray.ReadOnly nativeArray) where T : struct { return nativeArray.m_Buffer; } public unsafe static void* GetUnsafeBufferPointerWithoutChecks(NativeArray nativeArray) where T : struct { return nativeArray.m_Buffer; } } public static class NativeSliceUnsafeUtility { public unsafe static NativeSlice ConvertExistingDataToNativeSlice(void* dataPointer, int stride, int length) where T : struct { if (length < 0) { throw new ArgumentException($"Invalid length of '{length}'. It must be greater than 0.", "length"); } if (stride < 0) { throw new ArgumentException($"Invalid stride '{stride}'. It must be greater than 0.", "stride"); } return new NativeSlice { m_Stride = stride, m_Buffer = (byte*)dataPointer, m_Length = length }; } public unsafe static void* GetUnsafePtr(this NativeSlice nativeSlice) where T : struct { return nativeSlice.m_Buffer; } public unsafe static void* GetUnsafeReadOnlyPtr(this NativeSlice nativeSlice) where T : struct { return nativeSlice.m_Buffer; } } [NativeHeader("Runtime/Export/Unsafe/UnsafeUtility.bindings.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static class UnsafeUtility { [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct IsUnmanagedCache { internal static int value; } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct IsValidNativeContainerElementTypeCache { internal static int value; } private struct AlignOfHelper where T : struct { public byte dummy; public T data; } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] private static extern int GetFieldOffsetInStruct(FieldInfo field); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] private static extern int GetFieldOffsetInClass(FieldInfo field); public static int GetFieldOffset(FieldInfo field) { if (field.DeclaringType.IsValueType) { return GetFieldOffsetInStruct(field); } if (field.DeclaringType.IsClass) { return GetFieldOffsetInClass(field); } return -1; } public unsafe static void* PinGCObjectAndGetAddress(object target, out ulong gcHandle) { return PinSystemObjectAndGetAddress(target, out gcHandle); } public unsafe static void* PinGCArrayAndGetDataAddress(Array target, out ulong gcHandle) { return PinSystemArrayAndGetAddress(target, out gcHandle); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] private unsafe static extern void* PinSystemArrayAndGetAddress(object target, out ulong gcHandle); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] private unsafe static extern void* PinSystemObjectAndGetAddress(object target, out ulong gcHandle); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern void ReleaseGCObject(ulong gcHandle); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = true)] public unsafe static extern void CopyObjectAddressToPtr(object target, void* dstPtr); public static bool IsBlittable() where T : struct { return IsBlittable(typeof(T)); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = false)] public static extern int CheckForLeaks(); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = false)] public static extern int ForgiveLeaks(); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = false)] [BurstAuthorizedExternalMethod] public static extern NativeLeakDetectionMode GetLeakDetectionMode(); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = false)] [BurstAuthorizedExternalMethod] public static extern void SetLeakDetectionMode(NativeLeakDetectionMode value); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = false)] [BurstAuthorizedExternalMethod] internal static extern int LeakRecord(IntPtr handle, LeakCategory category, int callstacksToSkip); [MethodImpl(MethodImplOptions.InternalCall)] [BurstAuthorizedExternalMethod] [ThreadSafe(ThrowsException = false)] internal static extern int LeakErase(IntPtr handle, LeakCategory category); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = true)] public unsafe static extern void* MallocTracked(long size, int alignment, Allocator allocator, int callstacksToSkip); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = true)] public unsafe static extern void FreeTracked(void* memory, Allocator allocator); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = true)] public unsafe static extern void* Malloc(long size, int alignment, Allocator allocator); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = true)] public unsafe static extern void Free(void* memory, Allocator allocator); public static bool IsValidAllocator(Allocator allocator) { return allocator > Allocator.None; } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = true)] public unsafe static extern void MemCpy(void* destination, void* source, long size); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = true)] public unsafe static extern void MemCpyReplicate(void* destination, void* source, int size, int count); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = true)] public unsafe static extern void MemCpyStride(void* destination, int destinationStride, void* source, int sourceStride, int elementSize, int count); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = true)] public unsafe static extern void MemMove(void* destination, void* source, long size); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = true)] public unsafe static extern void MemSet(void* destination, byte value, long size); public unsafe static void MemClear(void* destination, long size) { MemSet(destination, 0, size); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe(ThrowsException = true)] public unsafe static extern int MemCmp(void* ptr1, void* ptr2, long size); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern int SizeOf(Type type); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern bool IsBlittable(Type type); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern bool IsUnmanaged(Type type); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern bool IsValidNativeContainerElementType(Type type); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] internal static extern void LogError(string msg, string filename, int linenumber); private static bool IsBlittableValueType(Type t) { return t.IsValueType && IsBlittable(t); } private static string GetReasonForTypeNonBlittableImpl(Type t, string name) { if (!t.IsValueType) { return $"{name} is not blittable because it is not of value type ({t})\n"; } if (t.IsPrimitive) { return $"{name} is not blittable ({t})\n"; } string text = ""; FieldInfo[] fields = t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (!IsBlittableValueType(fieldInfo.FieldType)) { text += GetReasonForTypeNonBlittableImpl(fieldInfo.FieldType, $"{name}.{fieldInfo.Name}"); } } return text; } internal static bool IsArrayBlittable(Array arr) { return IsBlittableValueType(arr.GetType().GetElementType()); } internal static bool IsGenericListBlittable() where T : struct { return IsBlittable(); } internal static string GetReasonForArrayNonBlittable(Array arr) { Type elementType = arr.GetType().GetElementType(); return GetReasonForTypeNonBlittableImpl(elementType, elementType.Name); } internal static string GetReasonForGenericListNonBlittable() where T : struct { Type typeFromHandle = typeof(T); return GetReasonForTypeNonBlittableImpl(typeFromHandle, typeFromHandle.Name); } internal static string GetReasonForTypeNonBlittable(Type t) { return GetReasonForTypeNonBlittableImpl(t, t.Name); } internal static string GetReasonForValueTypeNonBlittable() where T : struct { Type typeFromHandle = typeof(T); return GetReasonForTypeNonBlittableImpl(typeFromHandle, typeFromHandle.Name); } public static bool IsUnmanaged() { int num = IsUnmanagedCache.value; switch (num) { case 1: return true; case 0: num = (IsUnmanagedCache.value = (IsUnmanaged(typeof(T)) ? 1 : (-1))); break; } return num == 1; } public static bool IsValidNativeContainerElementType() { int num = IsValidNativeContainerElementTypeCache.value; switch (num) { case -1: return false; case 0: num = (IsValidNativeContainerElementTypeCache.value = (IsValidNativeContainerElementType(typeof(T)) ? 1 : (-1))); break; } return num == 1; } public static int AlignOf() where T : struct { return SizeOf>() - SizeOf(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void CopyPtrToStructure(void* ptr, out T output) where T : struct { InternalCopyPtrToStructure(ptr, out output); } private unsafe static void InternalCopyPtrToStructure(void* ptr, out T output) where T : struct { output = System.Runtime.CompilerServices.Unsafe.Read(ptr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void CopyStructureToPtr(ref T input, void* ptr) where T : struct { InternalCopyStructureToPtr(ref input, ptr); } private unsafe static void InternalCopyStructureToPtr(ref T input, void* ptr) where T : struct { System.Runtime.CompilerServices.Unsafe.Write(ptr, input); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static T ReadArrayElement(void* source, int index) { return ((T*)source)[index]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static T ReadArrayElementWithStride(void* source, int index, int stride) { return System.Runtime.CompilerServices.Unsafe.Read((byte*)source + (long)index * (long)stride); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void WriteArrayElement(void* destination, int index, T value) { System.Runtime.CompilerServices.Unsafe.Write((byte*)destination + (long)index * (long)System.Runtime.CompilerServices.Unsafe.SizeOf(), value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void WriteArrayElementWithStride(void* destination, int index, int stride, T value) { System.Runtime.CompilerServices.Unsafe.Write((byte*)destination + (long)index * (long)stride, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void* AddressOf(ref T output) where T : struct { return System.Runtime.CompilerServices.Unsafe.AsPointer(ref output); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SizeOf() where T : struct { return System.Runtime.CompilerServices.Unsafe.SizeOf(); } public static ref T As(ref U from) { return ref System.Runtime.CompilerServices.Unsafe.As(ref from); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static ref T AsRef(void* ptr) where T : struct { return ref *(T*)ptr; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static ref T ArrayElementAsRef(void* ptr, int index) where T : struct { return ref *(T*)((byte*)ptr + (long)index * (long)System.Runtime.CompilerServices.Unsafe.SizeOf()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int EnumToInt(T enumValue) where T : struct, IConvertible { int intValue = 0; InternalEnumToInt(ref enumValue, ref intValue); return intValue; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void InternalEnumToInt(ref T enumValue, ref int intValue) { intValue = System.Runtime.CompilerServices.Unsafe.As(ref enumValue); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EnumEquals(T lhs, T rhs) where T : struct, IConvertible { return (long)lhs == (long)rhs; } } } namespace Unity.Burst { [AttributeUsage(AttributeTargets.Method)] public class BurstAuthorizedExternalMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)] public class BurstDiscardAttribute : Attribute { } } namespace Unity.Burst.LowLevel { [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("Runtime/Burst/Burst.h")] [NativeHeader("Runtime/Burst/BurstDelegateCache.h")] internal static class BurstCompilerService { public delegate bool ExtractCompilerFlags(Type jobType, out string flags); public enum BurstLogType { Info, Warning, Error } public static extern bool IsInitialized { [MethodImpl(MethodImplOptions.InternalCall)] get; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("Initialize")] private static extern string InitializeInternal(string path, ExtractCompilerFlags extractCompilerFlags); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern string GetDisassembly(MethodInfo m, string compilerOptions); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern int CompileAsyncDelegateMethod(object delegateMethod, string compilerOptions); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public unsafe static extern void* GetAsyncCompiledAsyncDelegateMethod(int userID); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public unsafe static extern void* GetOrCreateSharedMemory(ref Hash128 key, uint size_of, uint alignment); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern string GetMethodSignature(MethodInfo method); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern void SetCurrentExecutionMode(uint environment); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public static extern uint GetCurrentExecutionMode(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("DefaultBurstLogCallback", true)] public unsafe static extern void Log(void* userData, BurstLogType logType, byte* message, byte* filename, int lineNumber); [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool LoadBurstLibrary(string fullPathToLibBurstGenerated); public static void Initialize(string folderRuntime, ExtractCompilerFlags extractCompilerFlags) { if (folderRuntime == null) { throw new ArgumentNullException("folderRuntime"); } if (extractCompilerFlags == null) { throw new ArgumentNullException("extractCompilerFlags"); } if (!Directory.Exists(folderRuntime)) { UnityEngine.Debug.LogError("Unable to initialize the burst JIT compiler. The folder `" + folderRuntime + "` does not exist"); return; } string text = InitializeInternal(folderRuntime, extractCompilerFlags); if (!string.IsNullOrEmpty(text)) { UnityEngine.Debug.LogError("Unexpected error while trying to initialize the burst JIT compiler: " + text); } } } } namespace JetBrains.Annotations { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.GenericParameter)] public sealed class CanBeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.GenericParameter)] public sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Delegate)] public sealed class ItemNotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Delegate)] public sealed class ItemCanBeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Delegate)] public sealed class StringFormatMethodAttribute : Attribute { [NotNull] public string FormatParameterName { get; } public StringFormatMethodAttribute([NotNull] string formatParameterName) { FormatParameterName = formatParameterName; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true)] public sealed class ValueProviderAttribute : Attribute { [NotNull] public string Name { get; } public ValueProviderAttribute([NotNull] string name) { Name = name; } } [AttributeUsage(AttributeTargets.Parameter)] public sealed class InvokerParameterNameAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] public sealed class NotifyPropertyChangedInvocatorAttribute : Attribute { [CanBeNull] public string ParameterName { get; } public NotifyPropertyChangedInvocatorAttribute() { } public NotifyPropertyChangedInvocatorAttribute([NotNull] string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class ContractAnnotationAttribute : Attribute { [NotNull] public string Contract { get; } public bool ForceFullStates { get; } public ContractAnnotationAttribute([NotNull] string contract) : this(contract, forceFullStates: false) { } public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates) { Contract = contract; ForceFullStates = forceFullStates; } } [AttributeUsage(AttributeTargets.All)] public sealed class LocalizationRequiredAttribute : Attribute { public bool Required { get; } public LocalizationRequiredAttribute() : this(required: true) { } public LocalizationRequiredAttribute(bool required) { Required = required; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class CannotApplyEqualityOperatorAttribute : Attribute { } [BaseTypeRequired(typeof(Attribute))] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class BaseTypeRequiredAttribute : Attribute { [NotNull] public Type BaseType { get; } public BaseTypeRequiredAttribute([NotNull] Type baseType) { BaseType = baseType; } } [AttributeUsage(AttributeTargets.All, Inherited = false)] public sealed class UsedImplicitlyAttribute : Attribute { public ImplicitUseKindFlags UseKindFlags { get; } public ImplicitUseTargetFlags TargetFlags { get; } public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter | AttributeTargets.GenericParameter)] public sealed class MeansImplicitUseAttribute : Attribute { [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; } [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; } public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } } [Flags] public enum ImplicitUseKindFlags { Default = 7, Access = 1, Assign = 2, InstantiatedWithFixedConstructorSignature = 4, InstantiatedNoFixedConstructorSignature = 8 } [Flags] public enum ImplicitUseTargetFlags { Default = 1, Itself = 1, Members = 2, WithMembers = 3 } [MeansImplicitUse(ImplicitUseTargetFlags.WithMembers)] [AttributeUsage(AttributeTargets.All, Inherited = false)] public sealed class PublicAPIAttribute : Attribute { [CanBeNull] public string Comment { get; } public PublicAPIAttribute() { } public PublicAPIAttribute([NotNull] string comment) { Comment = comment; } } [AttributeUsage(AttributeTargets.Parameter)] public sealed class InstantHandleAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] public sealed class PureAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] public sealed class MustUseReturnValueAttribute : Attribute { [CanBeNull] public string Justification { get; } public MustUseReturnValueAttribute() { } public MustUseReturnValueAttribute([NotNull] string justification) { Justification = justification; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.GenericParameter)] public sealed class ProvidesContextAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] public sealed class PathReferenceAttribute : Attribute { [CanBeNull] public string BasePath { get; } public PathReferenceAttribute() { } public PathReferenceAttribute([PathReference][NotNull] string basePath) { BasePath = basePath; } } [AttributeUsage(AttributeTargets.Method)] public sealed class SourceTemplateAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true)] public sealed class MacroAttribute : Attribute { [CanBeNull] public string Expression { get; set; } public int Editable { get; set; } [CanBeNull] public string Target { get; set; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property)] public sealed class CollectionAccessAttribute : Attribute { public CollectionAccessType CollectionAccessType { get; } public CollectionAccessAttribute(CollectionAccessType collectionAccessType) { CollectionAccessType = collectionAccessType; } } [Flags] public enum CollectionAccessType { None = 0, Read = 1, ModifyExistingContent = 2, UpdatedContent = 6 } [AttributeUsage(AttributeTargets.Method)] public sealed class AssertionMethodAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] public sealed class AssertionConditionAttribute : Attribute { public AssertionConditionType ConditionType { get; } public AssertionConditionAttribute(AssertionConditionType conditionType) { ConditionType = conditionType; } } public enum AssertionConditionType { IS_TRUE, IS_FALSE, IS_NULL, IS_NOT_NULL } [Obsolete("Use [ContractAnnotation('=> halt')] instead")] [AttributeUsage(AttributeTargets.Method)] public sealed class TerminatesProgramAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] public sealed class LinqTunnelAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] public sealed class NoEnumerationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] public sealed class RegexPatternAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface)] public sealed class NoReorderAttribute : Attribute { } } namespace UnityEngine { public enum SendMessageOptions { RequireReceiver, DontRequireReceiver } public enum PrimitiveType { Sphere, Capsule, Cylinder, Cube, Plane, Quad } public enum Space { World, Self } public enum RuntimePlatform { OSXEditor = 0, OSXPlayer = 1, WindowsPlayer = 2, [Obsolete("WebPlayer export is no longer supported in Unity 5.4+.", true)] OSXWebPlayer = 3, [Obsolete("Dashboard widget on Mac OS X export is no longer supported in Unity 5.4+.", true)] OSXDashboardPlayer = 4, [Obsolete("WebPlayer export is no longer supported in Unity 5.4+.", true)] WindowsWebPlayer = 5, WindowsEditor = 7, IPhonePlayer = 8, [Obsolete("Xbox360 export is no longer supported in Unity 5.5+.")] XBOX360 = 10, [Obsolete("PS3 export is no longer supported in Unity >=5.5.")] PS3 = 9, Android = 11, [Obsolete("NaCl export is no longer supported in Unity 5.0+.")] NaCl = 12, [Obsolete("FlashPlayer export is no longer supported in Unity 5.0+.")] FlashPlayer = 15, LinuxPlayer = 13, LinuxEditor = 16, WebGLPlayer = 17, [Obsolete("Use WSAPlayerX86 instead")] MetroPlayerX86 = 18, WSAPlayerX86 = 18, [Obsolete("Use WSAPlayerX64 instead")] MetroPlayerX64 = 19, WSAPlayerX64 = 19, [Obsolete("Use WSAPlayerARM instead")] MetroPlayerARM = 20, WSAPlayerARM = 20, [Obsolete("Windows Phone 8 was removed in 5.3")] WP8Player = 21, [Obsolete("BlackBerryPlayer export is no longer supported in Unity 5.4+.")] BlackBerryPlayer = 22, [Obsolete("TizenPlayer export is no longer supported in Unity 2017.3+.")] TizenPlayer = 23, [Obsolete("PSP2 is no longer supported as of Unity 2018.3")] PSP2 = 24, PS4 = 25, [Obsolete("PSM export is no longer supported in Unity >= 5.3")] PSM = 26, XboxOne = 27, [Obsolete("SamsungTVPlayer export is no longer supported in Unity 2017.3+.")] SamsungTVPlayer = 28, [Obsolete("Wii U is no longer supported in Unity 2018.1+.")] WiiU = 30, tvOS = 31, Switch = 32, Lumin = 33, Stadia = 34, CloudRendering = 35, [Obsolete("GameCoreScarlett is deprecated, please use GameCoreXboxSeries (UnityUpgradable) -> GameCoreXboxSeries", false)] GameCoreScarlett = -1, GameCoreXboxSeries = 36, GameCoreXboxOne = 37, PS5 = 38, EmbeddedLinuxArm64 = 39, EmbeddedLinuxArm32 = 40, EmbeddedLinuxX64 = 41, EmbeddedLinuxX86 = 42, LinuxServer = 43, WindowsServer = 44, OSXServer = 45 } public enum SystemLanguage { Afrikaans = 0, Arabic = 1, Basque = 2, Belarusian = 3, Bulgarian = 4, Catalan = 5, Chinese = 6, Czech = 7, Danish = 8, Dutch = 9, English = 10, Estonian = 11, Faroese = 12, Finnish = 13, French = 14, German = 15, Greek = 16, Hebrew = 17, Icelandic = 19, Indonesian = 20, Italian = 21, Japanese = 22, Korean = 23, Latvian = 24, Lithuanian = 25, Norwegian = 26, Polish = 27, Portuguese = 28, Romanian = 29, Russian = 30, SerboCroatian = 31, Slovak = 32, Slovenian = 33, Spanish = 34, Swedish = 35, Thai = 36, Turkish = 37, Ukrainian = 38, Vietnamese = 39, ChineseSimplified = 40, ChineseTraditional = 41, Unknown = 42, Hungarian = 18 } public enum LogType { Error, Assert, Warning, Log, Exception } public enum LogOption { None, NoStacktrace } public enum ThreadPriority { Low = 0, BelowNormal = 1, Normal = 2, High = 4 } [NativeHeader("Runtime/BaseClasses/TagManager.h")] public struct SortingLayer { private int m_Id; public int id => m_Id; public string name => IDToName(m_Id); public int value => GetLayerValueFromID(m_Id); public static SortingLayer[] layers { get { int[] sortingLayerIDsInternal = GetSortingLayerIDsInternal(); SortingLayer[] array = new SortingLayer[sortingLayerIDsInternal.Length]; for (int i = 0; i < sortingLayerIDsInternal.Length; i++) { array[i].m_Id = sortingLayerIDsInternal[i]; } return array; } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTagManager().GetSortingLayerIDs")] private static extern int[] GetSortingLayerIDsInternal(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTagManager().GetSortingLayerValueFromUniqueID")] public static extern int GetLayerValueFromID(int id); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTagManager().GetSortingLayerValueFromName")] public static extern int GetLayerValueFromName(string name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTagManager().GetSortingLayerUniqueIDFromName")] public static extern int NameToID(string name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTagManager().GetSortingLayerNameFromUniqueID")] public static extern string IDToName(int id); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTagManager().IsSortingLayerUniqueIDValid")] public static extern bool IsValid(int id); } public enum WeightedMode { None, In, Out, Both } [RequiredByNativeCode] public struct Keyframe { private float m_Time; private float m_Value; private float m_InTangent; private float m_OutTangent; private int m_WeightedMode; private float m_InWeight; private float m_OutWeight; public float time { get { return m_Time; } set { m_Time = value; } } public float value { get { return m_Value; } set { m_Value = value; } } public float inTangent { get { return m_InTangent; } set { m_InTangent = value; } } public float outTangent { get { return m_OutTangent; } set { m_OutTangent = value; } } public float inWeight { get { return m_InWeight; } set { m_InWeight = value; } } public float outWeight { get { return m_OutWeight; } set { m_OutWeight = value; } } public WeightedMode weightedMode { get { return (WeightedMode)m_WeightedMode; } set { m_WeightedMode = (int)value; } } [Obsolete("Use AnimationUtility.SetKeyLeftTangentMode, AnimationUtility.SetKeyRightTangentMode, AnimationUtility.GetKeyLeftTangentMode or AnimationUtility.GetKeyRightTangentMode instead.")] public int tangentMode { get { return tangentModeInternal; } set { tangentModeInternal = value; } } internal int tangentModeInternal { get { return 0; } set { } } public Keyframe(float time, float value) { m_Time = time; m_Value = value; m_InTangent = 0f; m_OutTangent = 0f; m_WeightedMode = 0; m_InWeight = 0f; m_OutWeight = 0f; } public Keyframe(float time, float value, float inTangent, float outTangent) { m_Time = time; m_Value = value; m_InTangent = inTangent; m_OutTangent = outTangent; m_WeightedMode = 0; m_InWeight = 0f; m_OutWeight = 0f; } public Keyframe(float time, float value, float inTangent, float outTangent, float inWeight, float outWeight) { m_Time = time; m_Value = value; m_InTangent = inTangent; m_OutTangent = outTangent; m_WeightedMode = 3; m_InWeight = inWeight; m_OutWeight = outWeight; } } public enum WrapMode { Once = 1, Loop = 2, PingPong = 4, Default = 0, ClampForever = 8, Clamp = 1 } [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] [NativeHeader("Runtime/Math/AnimationCurve.bindings.h")] public class AnimationCurve : IEquatable { internal IntPtr m_Ptr; public Keyframe[] keys { get { return GetKeys(); } set { SetKeys(value); } } public Keyframe this[int index] => GetKey(index); public extern int length { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetKeyCount", IsThreadSafe = true)] get; } public extern WrapMode preWrapMode { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetPreInfinity", IsThreadSafe = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("SetPreInfinity", IsThreadSafe = true)] set; } public extern WrapMode postWrapMode { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetPostInfinity", IsThreadSafe = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("SetPostInfinity", IsThreadSafe = true)] set; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("AnimationCurveBindings::Internal_Destroy", IsThreadSafe = true)] private static extern void Internal_Destroy(IntPtr ptr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("AnimationCurveBindings::Internal_Create", IsThreadSafe = true)] private static extern IntPtr Internal_Create(Keyframe[] keys); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("AnimationCurveBindings::Internal_Equals", HasExplicitThis = true, IsThreadSafe = true)] private extern bool Internal_Equals(IntPtr other); ~AnimationCurve() { Internal_Destroy(m_Ptr); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public extern float Evaluate(float time); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("AnimationCurveBindings::AddKeySmoothTangents", HasExplicitThis = true, IsThreadSafe = true)] public extern int AddKey(float time, float value); public int AddKey(Keyframe key) { return AddKey_Internal(key); } [NativeMethod("AddKey", IsThreadSafe = true)] private int AddKey_Internal(Keyframe key) { return AddKey_Internal_Injected(ref key); } [FreeFunction("AnimationCurveBindings::MoveKey", HasExplicitThis = true, IsThreadSafe = true)] [NativeThrows] public int MoveKey(int index, Keyframe key) { return MoveKey_Injected(index, ref key); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("AnimationCurveBindings::RemoveKey", HasExplicitThis = true, IsThreadSafe = true)] [NativeThrows] public extern void RemoveKey(int index); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("AnimationCurveBindings::SetKeys", HasExplicitThis = true, IsThreadSafe = true)] private extern void SetKeys(Keyframe[] keys); [FreeFunction("AnimationCurveBindings::GetKey", HasExplicitThis = true, IsThreadSafe = true)] [NativeThrows] private Keyframe GetKey(int index) { GetKey_Injected(index, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("AnimationCurveBindings::GetKeys", HasExplicitThis = true, IsThreadSafe = true)] private extern Keyframe[] GetKeys(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] [FreeFunction("AnimationCurveBindings::SmoothTangents", HasExplicitThis = true, IsThreadSafe = true)] public extern void SmoothTangents(int index, float weight); public static AnimationCurve Constant(float timeStart, float timeEnd, float value) { return Linear(timeStart, value, timeEnd, value); } public static AnimationCurve Linear(float timeStart, float valueStart, float timeEnd, float valueEnd) { if (timeStart == timeEnd) { Keyframe keyframe = new Keyframe(timeStart, valueStart); return new AnimationCurve(keyframe); } float num = (valueEnd - valueStart) / (timeEnd - timeStart); Keyframe[] array = new Keyframe[2] { new Keyframe(timeStart, valueStart, 0f, num), new Keyframe(timeEnd, valueEnd, num, 0f) }; return new AnimationCurve(array); } public static AnimationCurve EaseInOut(float timeStart, float valueStart, float timeEnd, float valueEnd) { if (timeStart == timeEnd) { Keyframe keyframe = new Keyframe(timeStart, valueStart); return new AnimationCurve(keyframe); } Keyframe[] array = new Keyframe[2] { new Keyframe(timeStart, valueStart, 0f, 0f), new Keyframe(timeEnd, valueEnd, 0f, 0f) }; return new AnimationCurve(array); } public AnimationCurve(params Keyframe[] keys) { m_Ptr = Internal_Create(keys); } [RequiredByNativeCode] public AnimationCurve() { m_Ptr = Internal_Create(null); } public override bool Equals(object o) { if (o == null) { return false; } if (this == o) { return true; } if ((object)o.GetType() != GetType()) { return false; } return Equals((AnimationCurve)o); } public bool Equals(AnimationCurve other) { if (other == null) { return false; } if (this == other) { return true; } if (m_Ptr.Equals((object?)(nint)other.m_Ptr)) { return true; } return Internal_Equals(other.m_Ptr); } public override int GetHashCode() { return m_Ptr.GetHashCode(); } [MethodImpl(MethodImplOptions.InternalCall)] private extern int AddKey_Internal_Injected(ref Keyframe key); [MethodImpl(MethodImplOptions.InternalCall)] private extern int MoveKey_Injected(int index, ref Keyframe key); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetKey_Injected(int index, out Keyframe ret); } [NativeHeader("Runtime/Application/ApplicationInfo.h")] [NativeHeader("Runtime/Misc/BuildSettings.h")] [NativeHeader("Runtime/Logging/LogSystem.h")] [NativeHeader("Runtime/Misc/PlayerSettings.h")] [NativeHeader("Runtime/Misc/Player.h")] [NativeHeader("Runtime/PreloadManager/LoadSceneOperation.h")] [NativeHeader("Runtime/PreloadManager/PreloadManager.h")] [NativeHeader("Runtime/Utilities/Argv.h")] [NativeHeader("Runtime/Utilities/URLUtility.h")] [NativeHeader("Runtime/File/ApplicationSpecificPersistentDataPath.h")] [NativeHeader("Runtime/Network/NetworkUtility.h")] [NativeHeader("Runtime/Application/AdsIdHandler.h")] [NativeHeader("Runtime/Misc/SystemInfo.h")] [NativeHeader("Runtime/Input/TargetFrameRate.h")] [NativeHeader("Runtime/Export/Application/Application.bindings.h")] [NativeHeader("Runtime/Input/InputManager.h")] [NativeHeader("Runtime/Input/GetInput.h")] [NativeHeader("Runtime/BaseClasses/IsPlaying.h")] public class Application { public delegate void AdvertisingIdentifierCallback(string advertisingId, bool trackingEnabled, string errorMsg); public delegate void LowMemoryCallback(); public delegate void LogCallback(string condition, string stackTrace, LogType type); private static LogCallback s_LogCallbackHandler; private static LogCallback s_LogCallbackHandlerThreaded; internal static AdvertisingIdentifierCallback OnAdvertisingIdentifierCallback; private static volatile LogCallback s_RegisterLogCallbackDeprecated; [Obsolete("This property is deprecated, please use LoadLevelAsync to detect if a specific scene is currently loading.")] public static extern bool isLoadingLevel { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetPreloadManager().IsLoadingOrQueued")] get; } [Obsolete("Streaming was a Unity Web Player feature, and is removed. This property is deprecated and always returns 0.")] public static int streamedBytes => 0; [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Application.webSecurityEnabled is no longer supported, since the Unity Web Player is no longer supported by Unity", true)] public static bool webSecurityEnabled => false; public static extern bool isPlaying { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("IsWorldPlaying")] get; } public static extern bool isFocused { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("IsPlayerFocused")] get; } public static extern string buildGUID { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Application_Bindings::GetBuildGUID")] get; } public static extern bool runInBackground { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetPlayerSettingsRunInBackground")] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SetPlayerSettingsRunInBackground")] set; } public static extern bool isBatchMode { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("::IsBatchmode")] get; } internal static extern bool isTestRun { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("::IsTestRun")] get; } internal static extern bool isHumanControllingUs { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("::IsHumanControllingUs")] get; } public static extern string dataPath { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetAppDataPath")] get; } public static extern string streamingAssetsPath { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetStreamingAssetsPath", IsThreadSafe = true)] get; } public static extern string persistentDataPath { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetPersistentDataPathApplicationSpecific")] get; } public static extern string temporaryCachePath { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTemporaryCachePathApplicationSpecific")] get; } public static extern string absoluteURL { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetPlayerSettings().GetAbsoluteURL")] get; } public static extern string unityVersion { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Application_Bindings::GetUnityVersion", IsThreadSafe = true)] get; } internal static extern int unityVersionVer { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Application_Bindings::GetUnityVersionVer", IsThreadSafe = true)] get; } internal static extern int unityVersionMaj { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Application_Bindings::GetUnityVersionMaj", IsThreadSafe = true)] get; } internal static extern int unityVersionMin { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Application_Bindings::GetUnityVersionMin", IsThreadSafe = true)] get; } public static extern string version { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetApplicationInfo().GetVersion")] get; } public static extern string installerName { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetApplicationInfo().GetInstallerName")] get; } public static extern string identifier { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetApplicationInfo().GetApplicationIdentifier")] get; } public static extern ApplicationInstallMode installMode { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetApplicationInfo().GetInstallMode")] get; } public static extern ApplicationSandboxType sandboxType { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetApplicationInfo().GetSandboxType")] get; } public static extern string productName { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetPlayerSettings().GetProductName")] get; } public static extern string companyName { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetPlayerSettings().GetCompanyName")] get; } public static extern string cloudProjectId { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetPlayerSettings().GetCloudProjectId")] get; } public static extern int targetFrameRate { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTargetFrameRate")] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SetTargetFrameRate")] set; } [Obsolete("Use SetStackTraceLogType/GetStackTraceLogType instead")] public static extern StackTraceLogType stackTraceLogType { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Application_Bindings::GetStackTraceLogType")] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Application_Bindings::SetStackTraceLogType")] set; } public static extern string consoleLogPath { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetConsoleLogPath")] get; } public static extern ThreadPriority backgroundLoadingPriority { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetPreloadManager().GetThreadPriority")] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetPreloadManager().SetThreadPriority")] set; } public static extern bool genuine { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("IsApplicationGenuine")] get; } public static extern bool genuineCheckAvailable { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("IsApplicationGenuineAvailable")] get; } internal static extern bool submitAnalytics { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetPlayerSettings().GetSubmitAnalytics")] get; } [Obsolete("This property is deprecated, please use SplashScreen.isFinished instead")] public static bool isShowingSplashScreen => !SplashScreen.isFinished; public static extern RuntimePlatform platform { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::GetRuntimePlatform", IsThreadSafe = true)] get; } public static bool isMobilePlatform { get { switch (platform) { case RuntimePlatform.IPhonePlayer: case RuntimePlatform.Android: return true; case RuntimePlatform.MetroPlayerX86: case RuntimePlatform.MetroPlayerX64: case RuntimePlatform.MetroPlayerARM: return SystemInfo.deviceType == DeviceType.Handheld; default: return false; } } } public static bool isConsolePlatform { get { RuntimePlatform runtimePlatform = platform; return runtimePlatform == RuntimePlatform.GameCoreXboxOne || runtimePlatform == RuntimePlatform.GameCoreXboxSeries || runtimePlatform == RuntimePlatform.PS4 || runtimePlatform == RuntimePlatform.PS5 || runtimePlatform == RuntimePlatform.Switch || runtimePlatform == RuntimePlatform.XboxOne; } } public static extern SystemLanguage systemLanguage { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("(SystemLanguage)systeminfo::GetSystemLanguage")] get; } public static extern NetworkReachability internetReachability { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetInternetReachability")] get; } [Obsolete("use Application.isEditor instead")] public static bool isPlayer => !isEditor; [Obsolete("Use SceneManager.sceneCountInBuildSettings")] public static int levelCount => SceneManager.sceneCountInBuildSettings; [Obsolete("Use SceneManager to determine what scenes have been loaded")] public static int loadedLevel => SceneManager.GetActiveScene().buildIndex; [Obsolete("Use SceneManager to determine what scenes have been loaded")] public static string loadedLevelName => SceneManager.GetActiveScene().name; public static bool isEditor => false; public static event LowMemoryCallback lowMemory; public static event LogCallback logMessageReceived { add { s_LogCallbackHandler = (LogCallback)Delegate.Combine(s_LogCallbackHandler, value); SetLogCallbackDefined(defined: true); } remove { s_LogCallbackHandler = (LogCallback)Delegate.Remove(s_LogCallbackHandler, value); } } public static event LogCallback logMessageReceivedThreaded { add { s_LogCallbackHandlerThreaded = (LogCallback)Delegate.Combine(s_LogCallbackHandlerThreaded, value); SetLogCallbackDefined(defined: true); } remove { s_LogCallbackHandlerThreaded = (LogCallback)Delegate.Remove(s_LogCallbackHandlerThreaded, value); } } public static event UnityAction onBeforeRender { add { BeforeRenderHelper.RegisterCallback(value); } remove { BeforeRenderHelper.UnregisterCallback(value); } } public static event Action focusChanged; public static event Action deepLinkActivated; public static event Func wantsToQuit; public static event Action quitting; public static event Action unloading; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetInputManager().QuitApplication")] public static extern void Quit(int exitCode); public static void Quit() { Quit(0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetInputManager().CancelQuitApplication")] [Obsolete("CancelQuit is deprecated. Use the wantsToQuit event instead.")] public static extern void CancelQuit(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Application_Bindings::Unload")] public static extern void Unload(); [Obsolete("Streaming was a Unity Web Player feature, and is removed. This function is deprecated and always returns 1.0 for valid level indices.")] public static float GetStreamProgressForLevel(int levelIndex) { if (levelIndex >= 0 && levelIndex < SceneManager.sceneCountInBuildSettings) { return 1f; } return 0f; } [Obsolete("Streaming was a Unity Web Player feature, and is removed. This function is deprecated and always returns 1.0.")] public static float GetStreamProgressForLevel(string levelName) { return 1f; } public static bool CanStreamedLevelBeLoaded(int levelIndex) { return levelIndex >= 0 && levelIndex < SceneManager.sceneCountInBuildSettings; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Application_Bindings::CanStreamedLevelBeLoaded")] public static extern bool CanStreamedLevelBeLoaded(string levelName); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern bool IsPlaying([NotNull("NullExceptionObject")] Object obj); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetBuildSettings().GetBuildTags")] public static extern string[] GetBuildTags(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetBuildSettings().SetBuildTags")] public static extern void SetBuildTags(string[] buildTags); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetBuildSettings().GetHasPROVersion")] public static extern bool HasProLicense(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HasARGV")] internal static extern bool HasARGV(string name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetFirstValueForARGV")] internal static extern string GetValueForARGV(string name); [Obsolete("Application.ExternalEval is deprecated. See https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html for alternatives.")] public static void ExternalEval(string script) { if (script.Length > 0 && script[script.Length - 1] != ';') { script += ";"; } Internal_ExternalCall(script); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Application_Bindings::ExternalCall")] private static extern void Internal_ExternalCall(string script); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetAdsIdHandler().RequestAdsIdAsync")] public static extern bool RequestAdvertisingIdentifierAsync(AdvertisingIdentifierCallback delegateMethod); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("OpenURL")] public static extern void OpenURL(string url); [Obsolete("Use UnityEngine.Diagnostics.Utils.ForceCrash")] public static void ForceCrash(int mode) { Utils.ForceCrash((ForcedCrashCategory)mode); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Application_Bindings::SetLogCallbackDefined")] private static extern void SetLogCallbackDefined(bool defined); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetStackTraceLogType")] public static extern StackTraceLogType GetStackTraceLogType(LogType logType); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SetStackTraceLogType")] public static extern void SetStackTraceLogType(LogType logType, StackTraceLogType stackTraceType); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Application_Bindings::RequestUserAuthorization")] public static extern AsyncOperation RequestUserAuthorization(UserAuthorization mode); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Application_Bindings::HasUserAuthorization")] public static extern bool HasUserAuthorization(UserAuthorization mode); [RequiredByNativeCode] internal static void CallLowMemory() { Application.lowMemory?.Invoke(); } [RequiredByNativeCode] private static void CallLogCallback(string logString, string stackTrace, LogType type, bool invokedOnMainThread) { if (invokedOnMainThread) { s_LogCallbackHandler?.Invoke(logString, stackTrace, type); } s_LogCallbackHandlerThreaded?.Invoke(logString, stackTrace, type); } internal static void InvokeOnAdvertisingIdentifierCallback(string advertisingId, bool trackingEnabled) { if (OnAdvertisingIdentifierCallback != null) { OnAdvertisingIdentifierCallback(advertisingId, trackingEnabled, string.Empty); } } private static string ObjectToJSString(object o) { if (o == null) { return "null"; } if (o is string) { string text = o.ToString().Replace("\\", "\\\\"); text = text.Replace("\"", "\\\""); text = text.Replace("\n", "\\n"); text = text.Replace("\r", "\\r"); text = text.Replace("\0", ""); text = text.Replace("\u2028", ""); text = text.Replace("\u2029", ""); return "\"" + text + "\""; } if (o is int || o is short || o is uint || o is ushort || o is byte) { return o.ToString(); } if (o is float) { NumberFormatInfo numberFormat = CultureInfo.InvariantCulture.NumberFormat; return ((float)o).ToString(numberFormat); } if (o is double) { NumberFormatInfo numberFormat2 = CultureInfo.InvariantCulture.NumberFormat; return ((double)o).ToString(numberFormat2); } if (o is char) { if ((char)o == '"') { return "\"\\\"\""; } return "\"" + o.ToString() + "\""; } if (o is IList) { IList list = (IList)o; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("new Array("); int count = list.Count; for (int i = 0; i < count; i++) { if (i != 0) { stringBuilder.Append(", "); } stringBuilder.Append(ObjectToJSString(list[i])); } stringBuilder.Append(")"); return stringBuilder.ToString(); } return ObjectToJSString(o.ToString()); } [Obsolete("Application.ExternalCall is deprecated. See https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html for alternatives.")] public static void ExternalCall(string functionName, params object[] args) { Internal_ExternalCall(BuildInvocationForArguments(functionName, args)); } private static string BuildInvocationForArguments(string functionName, params object[] args) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(functionName); stringBuilder.Append('('); int num = args.Length; for (int i = 0; i < num; i++) { if (i != 0) { stringBuilder.Append(", "); } stringBuilder.Append(ObjectToJSString(args[i])); } stringBuilder.Append(')'); stringBuilder.Append(';'); return stringBuilder.ToString(); } [Obsolete("Use Object.DontDestroyOnLoad instead")] public static void DontDestroyOnLoad(Object o) { if (o != null) { Object.DontDestroyOnLoad(o); } } [Obsolete("Application.CaptureScreenshot is obsolete. Use ScreenCapture.CaptureScreenshot instead (UnityUpgradable) -> [UnityEngine] UnityEngine.ScreenCapture.CaptureScreenshot(*)", true)] public static void CaptureScreenshot(string filename, int superSize) { throw new NotSupportedException("Application.CaptureScreenshot is obsolete. Use ScreenCapture.CaptureScreenshot instead."); } [Obsolete("Application.CaptureScreenshot is obsolete. Use ScreenCapture.CaptureScreenshot instead (UnityUpgradable) -> [UnityEngine] UnityEngine.ScreenCapture.CaptureScreenshot(*)", true)] public static void CaptureScreenshot(string filename) { throw new NotSupportedException("Application.CaptureScreenshot is obsolete. Use ScreenCapture.CaptureScreenshot instead."); } [RequiredByNativeCode] private static bool Internal_ApplicationWantsToQuit() { if (Application.wantsToQuit != null) { Delegate[] invocationList = Application.wantsToQuit.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { Func func = (Func)invocationList[i]; try { if (!func()) { return false; } } catch (Exception exception) { Debug.LogException(exception); } } } return true; } [RequiredByNativeCode] private static void Internal_ApplicationQuit() { if (Application.quitting != null) { Application.quitting(); } } [RequiredByNativeCode] private static void Internal_ApplicationUnload() { if (Application.unloading != null) { Application.unloading(); } } [RequiredByNativeCode] internal static void InvokeOnBeforeRender() { BeforeRenderHelper.Invoke(); } [RequiredByNativeCode] internal static void InvokeFocusChanged(bool focus) { if (Application.focusChanged != null) { Application.focusChanged(focus); } } [RequiredByNativeCode] internal static void InvokeDeepLinkActivated(string url) { if (Application.deepLinkActivated != null) { Application.deepLinkActivated(url); } } [Obsolete("Application.RegisterLogCallback is deprecated. Use Application.logMessageReceived instead.")] public static void RegisterLogCallback(LogCallback handler) { RegisterLogCallback(handler, threaded: false); } [Obsolete("Application.RegisterLogCallbackThreaded is deprecated. Use Application.logMessageReceivedThreaded instead.")] public static void RegisterLogCallbackThreaded(LogCallback handler) { RegisterLogCallback(handler, threaded: true); } private static void RegisterLogCallback(LogCallback handler, bool threaded) { if (s_RegisterLogCallbackDeprecated != null) { logMessageReceived -= s_RegisterLogCallbackDeprecated; logMessageReceivedThreaded -= s_RegisterLogCallbackDeprecated; } s_RegisterLogCallbackDeprecated = handler; if (handler != null) { if (threaded) { logMessageReceivedThreaded += handler; } else { logMessageReceived += handler; } } } [Obsolete("Use SceneManager.LoadScene")] public static void LoadLevel(int index) { SceneManager.LoadScene(index, LoadSceneMode.Single); } [Obsolete("Use SceneManager.LoadScene")] public static void LoadLevel(string name) { SceneManager.LoadScene(name, LoadSceneMode.Single); } [Obsolete("Use SceneManager.LoadScene")] public static void LoadLevelAdditive(int index) { SceneManager.LoadScene(index, LoadSceneMode.Additive); } [Obsolete("Use SceneManager.LoadScene")] public static void LoadLevelAdditive(string name) { SceneManager.LoadScene(name, LoadSceneMode.Additive); } [Obsolete("Use SceneManager.LoadSceneAsync")] public static AsyncOperation LoadLevelAsync(int index) { return SceneManager.LoadSceneAsync(index, LoadSceneMode.Single); } [Obsolete("Use SceneManager.LoadSceneAsync")] public static AsyncOperation LoadLevelAsync(string levelName) { return SceneManager.LoadSceneAsync(levelName, LoadSceneMode.Single); } [Obsolete("Use SceneManager.LoadSceneAsync")] public static AsyncOperation LoadLevelAdditiveAsync(int index) { return SceneManager.LoadSceneAsync(index, LoadSceneMode.Additive); } [Obsolete("Use SceneManager.LoadSceneAsync")] public static AsyncOperation LoadLevelAdditiveAsync(string levelName) { return SceneManager.LoadSceneAsync(levelName, LoadSceneMode.Additive); } [Obsolete("Use SceneManager.UnloadScene")] public static bool UnloadLevel(int index) { return SceneManager.UnloadScene(index); } [Obsolete("Use SceneManager.UnloadScene")] public static bool UnloadLevel(string scenePath) { return SceneManager.UnloadScene(scenePath); } } public enum StackTraceLogType { None, ScriptOnly, Full } public enum NetworkReachability { NotReachable, ReachableViaCarrierDataNetwork, ReachableViaLocalAreaNetwork } public enum UserAuthorization { WebCam = 1, Microphone } public enum ApplicationInstallMode { Unknown, Store, DeveloperBuild, Adhoc, Enterprise, Editor } public enum ApplicationSandboxType { Unknown, NotSandboxed, Sandboxed, SandboxBroken } public enum AudioType { UNKNOWN = 0, ACC = 1, AIFF = 2, IT = 10, MOD = 12, MPEG = 13, OGGVORBIS = 14, S3M = 17, WAV = 20, XM = 21, XMA = 22, VAG = 23, AUDIOQUEUE = 24 } [NativeHeader("Runtime/Export/Bootstrap/BootConfig.bindings.h")] internal class BootConfigData { private IntPtr m_Ptr; public void AddKey(string key) { Append(key, null); } public string Get(string key) { return GetValue(key, 0); } public string Get(string key, int index) { return GetValue(key, index); } [MethodImpl(MethodImplOptions.InternalCall)] public extern void Append(string key, string value); [MethodImpl(MethodImplOptions.InternalCall)] public extern void Set(string key, string value); [MethodImpl(MethodImplOptions.InternalCall)] private extern string GetValue(string key, int index); [RequiredByNativeCode] private static BootConfigData WrapBootConfigData(IntPtr nativeHandle) { return new BootConfigData(nativeHandle); } private BootConfigData(IntPtr nativeHandle) { if (nativeHandle == IntPtr.Zero) { throw new ArgumentException("native handle can not be null"); } m_Ptr = nativeHandle; } } [UsedByNativeCode] public struct CachedAssetBundle { private string m_Name; private Hash128 m_Hash; public string name { get { return m_Name; } set { m_Name = value; } } public Hash128 hash { get { return m_Hash; } set { m_Hash = value; } } public CachedAssetBundle(string name, Hash128 hash) { m_Name = name; m_Hash = hash; } } [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("Runtime/Misc/Cache.h")] public struct Cache : IEquatable { private int m_Handle; internal int handle => m_Handle; public bool valid => Cache_IsValid(m_Handle); public bool ready => Cache_IsReady(m_Handle); public bool readOnly => Cache_IsReadonly(m_Handle); public string path => Cache_GetPath(m_Handle); public int index => Cache_GetIndex(m_Handle); public long spaceFree => Cache_GetSpaceFree(m_Handle); public long maximumAvailableStorageSpace { get { return Cache_GetMaximumDiskSpaceAvailable(m_Handle); } set { Cache_SetMaximumDiskSpaceAvailable(m_Handle, value); } } public long spaceOccupied => Cache_GetCachingDiskSpaceUsed(m_Handle); public int expirationDelay { get { return Cache_GetExpirationDelay(m_Handle); } set { Cache_SetExpirationDelay(m_Handle, value); } } public static bool operator ==(Cache lhs, Cache rhs) { return lhs.handle == rhs.handle; } public static bool operator !=(Cache lhs, Cache rhs) { return lhs.handle != rhs.handle; } public override int GetHashCode() { return m_Handle; } public override bool Equals(object other) { return other is Cache && Equals((Cache)other); } public bool Equals(Cache other) { return handle == other.handle; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool Cache_IsValid(int handle); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] internal static extern bool Cache_IsReady(int handle); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] internal static extern bool Cache_IsReadonly(int handle); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] internal static extern string Cache_GetPath(int handle); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int Cache_GetIndex(int handle); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] internal static extern long Cache_GetSpaceFree(int handle); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] internal static extern long Cache_GetMaximumDiskSpaceAvailable(int handle); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] internal static extern void Cache_SetMaximumDiskSpaceAvailable(int handle, long value); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] internal static extern long Cache_GetCachingDiskSpaceUsed(int handle); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] internal static extern int Cache_GetExpirationDelay(int handle); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] internal static extern void Cache_SetExpirationDelay(int handle, int value); public bool ClearCache() { return Cache_ClearCache(m_Handle); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] internal static extern bool Cache_ClearCache(int handle); public bool ClearCache(int expiration) { return Cache_ClearCache_Expiration(m_Handle, expiration); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] internal static extern bool Cache_ClearCache_Expiration(int handle, int expiration); } [Obsolete("This struct is not for public use.")] [UsedByNativeCode] public struct CacheIndex { public string name; public int bytesUsed; public int expires; } [NativeHeader("Runtime/Misc/CachingManager.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public sealed class Caching { public static extern bool compressionEnabled { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool ready { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetIsReady")] get; } [Obsolete("Please use use Cache.spaceOccupied to get used bytes per cache.")] public static int spaceUsed => (int)spaceOccupied; [Obsolete("This property is only used for the current cache, use Cache.spaceOccupied to get used bytes per cache.")] public static extern long spaceOccupied { [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeName("GetCachingDiskSpaceUsed")] get; } [Obsolete("Please use use Cache.spaceOccupied to get used bytes per cache.")] public static int spaceAvailable => (int)spaceFree; [Obsolete("This property is only used for the current cache, use Cache.spaceFree to get unused bytes per cache.")] public static extern long spaceFree { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetCachingDiskSpaceFree")] [StaticAccessor(/*Could not decode attribute arguments.*/)] get; } [Obsolete("This property is only used for the current cache, use Cache.maximumAvailableStorageSpace to access the maximum available storage space per cache.")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern long maximumAvailableDiskSpace { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetMaximumDiskSpaceAvailable")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetMaximumDiskSpaceAvailable")] set; } [StaticAccessor(/*Could not decode attribute arguments.*/)] [Obsolete("This property is only used for the current cache, use Cache.expirationDelay to access the expiration delay per cache.")] public static extern int expirationDelay { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int cacheCount { [MethodImpl(MethodImplOptions.InternalCall)] get; } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static Cache defaultCache { [NativeName("Caching_GetDefaultCacheHandle")] get { get_defaultCache_Injected(out var ret); return ret; } } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static Cache currentCacheForWriting { [NativeName("Caching_GetCurrentCacheHandle")] get { get_currentCacheForWriting_Injected(out var ret); return ret; } [NativeThrows] [NativeName("Caching_SetCurrentCacheByHandle")] set { set_currentCacheForWriting_Injected(ref value); } } [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool ClearCache(); public static bool ClearCache(int expiration) { return ClearCache_Int(expiration); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("ClearCache")] internal static extern bool ClearCache_Int(int expiration); public static bool ClearCachedVersion(string assetBundleName, Hash128 hash) { if (string.IsNullOrEmpty(assetBundleName)) { throw new ArgumentException("Input AssetBundle name cannot be null or empty."); } return ClearCachedVersionInternal(assetBundleName, hash); } [NativeName("ClearCachedVersion")] internal static bool ClearCachedVersionInternal(string assetBundleName, Hash128 hash) { return ClearCachedVersionInternal_Injected(assetBundleName, ref hash); } public static bool ClearOtherCachedVersions(string assetBundleName, Hash128 hash) { if (string.IsNullOrEmpty(assetBundleName)) { throw new ArgumentException("Input AssetBundle name cannot be null or empty."); } return ClearCachedVersions(assetBundleName, hash, keepInputVersion: true); } public static bool ClearAllCachedVersions(string assetBundleName) { if (string.IsNullOrEmpty(assetBundleName)) { throw new ArgumentException("Input AssetBundle name cannot be null or empty."); } return ClearCachedVersions(assetBundleName, default(Hash128), keepInputVersion: false); } internal static bool ClearCachedVersions(string assetBundleName, Hash128 hash, bool keepInputVersion) { return ClearCachedVersions_Injected(assetBundleName, ref hash, keepInputVersion); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Hash128[] GetCachedVersions(string assetBundleName); public static void GetCachedVersions(string assetBundleName, List outCachedVersions) { if (string.IsNullOrEmpty(assetBundleName)) { throw new ArgumentException("Input AssetBundle name cannot be null or empty."); } if (outCachedVersions == null) { throw new ArgumentNullException("Input outCachedVersions cannot be null."); } outCachedVersions.AddRange(GetCachedVersions(assetBundleName)); } [Obsolete("Please use IsVersionCached with Hash128 instead.")] public static bool IsVersionCached(string url, int version) { return IsVersionCached(url, new Hash128(0u, 0u, 0u, (uint)version)); } public static bool IsVersionCached(string url, Hash128 hash) { if (string.IsNullOrEmpty(url)) { throw new ArgumentException("Input AssetBundle url cannot be null or empty."); } return IsVersionCached(url, "", hash); } public static bool IsVersionCached(CachedAssetBundle cachedBundle) { if (string.IsNullOrEmpty(cachedBundle.name)) { throw new ArgumentException("Input AssetBundle name cannot be null or empty."); } return IsVersionCached("", cachedBundle.name, cachedBundle.hash); } [NativeName("IsCached")] internal static bool IsVersionCached(string url, string assetBundleName, Hash128 hash) { return IsVersionCached_Injected(url, assetBundleName, ref hash); } [Obsolete("Please use MarkAsUsed with Hash128 instead.")] public static bool MarkAsUsed(string url, int version) { return MarkAsUsed(url, new Hash128(0u, 0u, 0u, (uint)version)); } public static bool MarkAsUsed(string url, Hash128 hash) { if (string.IsNullOrEmpty(url)) { throw new ArgumentException("Input AssetBundle url cannot be null or empty."); } return MarkAsUsed(url, "", hash); } public static bool MarkAsUsed(CachedAssetBundle cachedBundle) { if (string.IsNullOrEmpty(cachedBundle.name)) { throw new ArgumentException("Input AssetBundle name cannot be null or empty."); } return MarkAsUsed("", cachedBundle.name, cachedBundle.hash); } internal static bool MarkAsUsed(string url, string assetBundleName, Hash128 hash) { return MarkAsUsed_Injected(url, assetBundleName, ref hash); } [Obsolete("This function is obsolete and will always return -1. Use IsVersionCached instead.")] public static int GetVersionFromCache(string url) { return -1; } public static Cache AddCache(string cachePath) { if (string.IsNullOrEmpty(cachePath)) { throw new ArgumentNullException("Cache path cannot be null or empty."); } bool isReadonly = false; if (cachePath.Replace('\\', '/').StartsWith(Application.streamingAssetsPath)) { isReadonly = true; } else { if (!Directory.Exists(cachePath)) { throw new ArgumentException("Cache path '" + cachePath + "' doesn't exist."); } if ((File.GetAttributes(cachePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { isReadonly = true; } } if (GetCacheByPath(cachePath).valid) { throw new InvalidOperationException("Cache with path '" + cachePath + "' has already been added."); } return AddCache(cachePath, isReadonly); } [NativeName("AddCachePath")] internal static Cache AddCache(string cachePath, bool isReadonly) { AddCache_Injected(cachePath, isReadonly, out var ret); return ret; } [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeName("Caching_GetCacheHandleAt")] [NativeThrows] public static Cache GetCacheAt(int cacheIndex) { GetCacheAt_Injected(cacheIndex, out var ret); return ret; } [NativeThrows] [NativeName("Caching_GetCacheHandleByPath")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static Cache GetCacheByPath(string cachePath) { GetCacheByPath_Injected(cachePath, out var ret); return ret; } public static void GetAllCachePaths(List cachePaths) { cachePaths.Clear(); for (int i = 0; i < cacheCount; i++) { cachePaths.Add(GetCacheAt(i).path); } } [NativeThrows] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeName("Caching_RemoveCacheByHandle")] public static bool RemoveCache(Cache cache) { return RemoveCache_Injected(ref cache); } [NativeName("Caching_MoveCacheBeforeByHandle")] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeThrows] public static void MoveCacheBefore(Cache src, Cache dst) { MoveCacheBefore_Injected(ref src, ref dst); } [NativeThrows] [NativeName("Caching_MoveCacheAfterByHandle")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static void MoveCacheAfter(Cache src, Cache dst) { MoveCacheAfter_Injected(ref src, ref dst); } [Obsolete("This function is obsolete. Please use ClearCache. (UnityUpgradable) -> ClearCache()")] public static bool CleanCache() { return ClearCache(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool ClearCachedVersionInternal_Injected(string assetBundleName, ref Hash128 hash); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool ClearCachedVersions_Injected(string assetBundleName, ref Hash128 hash, bool keepInputVersion); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsVersionCached_Injected(string url, string assetBundleName, ref Hash128 hash); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool MarkAsUsed_Injected(string url, string assetBundleName, ref Hash128 hash); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void AddCache_Injected(string cachePath, bool isReadonly, out Cache ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetCacheAt_Injected(int cacheIndex, out Cache ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetCacheByPath_Injected(string cachePath, out Cache ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool RemoveCache_Injected(ref Cache cache); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void MoveCacheBefore_Injected(ref Cache src, ref Cache dst); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void MoveCacheAfter_Injected(ref Cache src, ref Cache dst); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_defaultCache_Injected(out Cache ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_currentCacheForWriting_Injected(out Cache ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_currentCacheForWriting_Injected(ref Cache value); } [NativeHeader("Runtime/Camera/RenderManager.h")] [UsedByNativeCode] [NativeHeader("Runtime/Shaders/Shader.h")] [NativeHeader("Runtime/Camera/Camera.h")] [NativeHeader("Runtime/Graphics/RenderTexture.h")] [NativeHeader("Runtime/Misc/GameObjectUtility.h")] [NativeHeader("Runtime/Graphics/CommandBuffer/RenderingCommandBuffer.h")] [NativeHeader("Runtime/GfxDevice/GfxDeviceTypes.h")] [RequireComponent(typeof(Transform))] public sealed class Camera : Behaviour { internal enum ProjectionMatrixMode { Explicit, Implicit, PhysicalPropertiesBased } public enum GateFitMode { Vertical = 1, Horizontal = 2, Fill = 3, Overscan = 4, None = 0 } public enum FieldOfViewAxis { Vertical, Horizontal } public struct GateFitParameters { public GateFitMode mode { get; set; } public float aspect { get; set; } public GateFitParameters(GateFitMode mode, float aspect) { this.mode = mode; this.aspect = aspect; } } public enum StereoscopicEye { Left, Right } public enum MonoOrStereoscopicEye { Left, Right, Mono } public enum SceneViewFilterMode { Off, ShowFiltered } public enum RenderRequestMode { None, ObjectId, Depth, VertexNormal, WorldPosition, EntityId, BaseColor, SpecularColor, Metallic, Emission, Normal, Smoothness, Occlusion, DiffuseColor } public enum RenderRequestOutputSpace { ScreenSpace = -1, UV0, UV1, UV2, UV3, UV4, UV5, UV6, UV7, UV8 } public struct RenderRequest { private readonly RenderRequestMode m_CameraRenderMode; private readonly RenderTexture m_ResultRT; private readonly RenderRequestOutputSpace m_OutputSpace; public bool isValid => m_CameraRenderMode != RenderRequestMode.None && m_ResultRT != null; public RenderRequestMode mode => m_CameraRenderMode; public RenderTexture result => m_ResultRT; public RenderRequestOutputSpace outputSpace => m_OutputSpace; public RenderRequest(RenderRequestMode mode, RenderTexture rt) { m_CameraRenderMode = mode; m_ResultRT = rt; m_OutputSpace = RenderRequestOutputSpace.ScreenSpace; } public RenderRequest(RenderRequestMode mode, RenderRequestOutputSpace space, RenderTexture rt) { m_CameraRenderMode = mode; m_ResultRT = rt; m_OutputSpace = space; } } public delegate void CameraCallback(Camera cam); public static CameraCallback onPreCull; public static CameraCallback onPreRender; public static CameraCallback onPostRender; [NativeProperty("Near")] public extern float nearClipPlane { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("Far")] public extern float farClipPlane { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("VerticalFieldOfView")] public extern float fieldOfView { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern RenderingPath renderingPath { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern RenderingPath actualRenderingPath { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("CalculateRenderingPath")] get; } public extern bool allowHDR { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool allowMSAA { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool allowDynamicResolution { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("ForceIntoRT")] public extern bool forceIntoRenderTexture { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float orthographicSize { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool orthographic { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern OpaqueSortMode opaqueSortMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern TransparencySortMode transparencySortMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Vector3 transparencySortAxis { get { get_transparencySortAxis_Injected(out var ret); return ret; } set { set_transparencySortAxis_Injected(ref value); } } public extern float depth { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float aspect { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Vector3 velocity { get { get_velocity_Injected(out var ret); return ret; } } public extern int cullingMask { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int eventMask { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool layerCullSpherical { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern CameraType cameraType { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } internal extern Material skyboxMaterial { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeConditional("UNITY_EDITOR")] public extern ulong overrideSceneCullingMask { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeConditional("UNITY_EDITOR")] internal extern ulong sceneCullingMask { [MethodImpl(MethodImplOptions.InternalCall)] get; } public float[] layerCullDistances { get { return GetLayerCullDistances(); } set { if (value.Length != 32) { throw new UnityException("Array needs to contain exactly 32 floats for layerCullDistances."); } SetLayerCullDistances(value); } } [Obsolete("PreviewCullingLayer is obsolete. Use scene culling masks instead.", false)] internal static int PreviewCullingLayer => 31; public extern bool useOcclusionCulling { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Matrix4x4 cullingMatrix { get { get_cullingMatrix_Injected(out var ret); return ret; } set { set_cullingMatrix_Injected(ref value); } } public Color backgroundColor { get { get_backgroundColor_Injected(out var ret); return ret; } set { set_backgroundColor_Injected(ref value); } } public extern CameraClearFlags clearFlags { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern DepthTextureMode depthTextureMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool clearStencilAfterLightingPass { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } internal extern ProjectionMatrixMode projectionMatrixMode { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern bool usePhysicalProperties { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Vector2 sensorSize { get { get_sensorSize_Injected(out var ret); return ret; } set { set_sensorSize_Injected(ref value); } } public Vector2 lensShift { get { get_lensShift_Injected(out var ret); return ret; } set { set_lensShift_Injected(ref value); } } public extern float focalLength { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern GateFitMode gateFit { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("NormalizedViewportRect")] public Rect rect { get { get_rect_Injected(out var ret); return ret; } set { set_rect_Injected(ref value); } } [NativeProperty("ScreenViewportRect")] public Rect pixelRect { get { get_pixelRect_Injected(out var ret); return ret; } set { set_pixelRect_Injected(ref value); } } public extern int pixelWidth { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::GetPixelWidth", HasExplicitThis = true)] get; } public extern int pixelHeight { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::GetPixelHeight", HasExplicitThis = true)] get; } public extern int scaledPixelWidth { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::GetScaledPixelWidth", HasExplicitThis = true)] get; } public extern int scaledPixelHeight { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::GetScaledPixelHeight", HasExplicitThis = true)] get; } public extern RenderTexture targetTexture { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern RenderTexture activeTexture { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetCurrentTargetTexture")] get; } public extern int targetDisplay { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Matrix4x4 cameraToWorldMatrix { get { get_cameraToWorldMatrix_Injected(out var ret); return ret; } } public Matrix4x4 worldToCameraMatrix { get { get_worldToCameraMatrix_Injected(out var ret); return ret; } set { set_worldToCameraMatrix_Injected(ref value); } } public Matrix4x4 projectionMatrix { get { get_projectionMatrix_Injected(out var ret); return ret; } set { set_projectionMatrix_Injected(ref value); } } public Matrix4x4 nonJitteredProjectionMatrix { get { get_nonJitteredProjectionMatrix_Injected(out var ret); return ret; } set { set_nonJitteredProjectionMatrix_Injected(ref value); } } [NativeProperty("UseJitteredProjectionMatrixForTransparent")] public extern bool useJitteredProjectionMatrixForTransparentRendering { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Matrix4x4 previousViewProjectionMatrix { get { get_previousViewProjectionMatrix_Injected(out var ret); return ret; } } public static extern Camera main { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("FindMainCamera")] get; } public static extern Camera current { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetCurrentCameraPPtr")] get; } public Scene scene { [FreeFunction("CameraScripting::GetScene", HasExplicitThis = true)] get { get_scene_Injected(out var ret); return ret; } [FreeFunction("CameraScripting::SetScene", HasExplicitThis = true)] set { set_scene_Injected(ref value); } } public extern bool stereoEnabled { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetStereoEnabledForBuiltInOrSRP")] get; } public extern float stereoSeparation { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float stereoConvergence { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool areVRStereoViewMatricesWithinSingleCullTolerance { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("AreVRStereoViewMatricesWithinSingleCullTolerance")] get; } public extern StereoTargetEyeMask stereoTargetEye { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern MonoOrStereoscopicEye stereoActiveEye { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::GetStereoActiveEye", HasExplicitThis = true)] get; } public static int allCamerasCount => GetAllCamerasCount(); public static Camera[] allCameras { get { Camera[] array = new Camera[allCamerasCount]; GetAllCamerasImpl(array); return array; } } [NativeConditional("UNITY_EDITOR")] public SceneViewFilterMode sceneViewFilterMode => (SceneViewFilterMode)GetFilterMode(); public extern int commandBufferCount { [MethodImpl(MethodImplOptions.InternalCall)] get; } [MethodImpl(MethodImplOptions.InternalCall)] public extern void Reset(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void ResetTransparencySortSettings(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void ResetAspect(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::GetLayerCullDistances", HasExplicitThis = true)] private extern float[] GetLayerCullDistances(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::SetLayerCullDistances", HasExplicitThis = true)] private extern void SetLayerCullDistances([NotNull("ArgumentNullException")] float[] d); [MethodImpl(MethodImplOptions.InternalCall)] public extern void ResetCullingMatrix(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetReplacementShader(Shader shader, string replacementTag); [MethodImpl(MethodImplOptions.InternalCall)] public extern void ResetReplacementShader(); [MethodImpl(MethodImplOptions.InternalCall)] public extern float GetGateFittedFieldOfView(); public Vector2 GetGateFittedLensShift() { GetGateFittedLensShift_Injected(out var ret); return ret; } internal Vector3 GetLocalSpaceAim() { GetLocalSpaceAim_Injected(out var ret); return ret; } [FreeFunction("CameraScripting::SetTargetBuffers", HasExplicitThis = true)] private void SetTargetBuffersImpl(RenderBuffer color, RenderBuffer depth) { SetTargetBuffersImpl_Injected(ref color, ref depth); } public void SetTargetBuffers(RenderBuffer colorBuffer, RenderBuffer depthBuffer) { SetTargetBuffersImpl(colorBuffer, depthBuffer); } [FreeFunction("CameraScripting::SetTargetBuffers", HasExplicitThis = true)] private void SetTargetBuffersMRTImpl(RenderBuffer[] color, RenderBuffer depth) { SetTargetBuffersMRTImpl_Injected(color, ref depth); } public void SetTargetBuffers(RenderBuffer[] colorBuffer, RenderBuffer depthBuffer) { SetTargetBuffersMRTImpl(colorBuffer, depthBuffer); } [MethodImpl(MethodImplOptions.InternalCall)] internal extern string[] GetCameraBufferWarnings(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void ResetWorldToCameraMatrix(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void ResetProjectionMatrix(); [FreeFunction("CameraScripting::CalculateObliqueMatrix", HasExplicitThis = true)] public Matrix4x4 CalculateObliqueMatrix(Vector4 clipPlane) { CalculateObliqueMatrix_Injected(ref clipPlane, out var ret); return ret; } public Vector3 WorldToScreenPoint(Vector3 position, MonoOrStereoscopicEye eye) { WorldToScreenPoint_Injected(ref position, eye, out var ret); return ret; } public Vector3 WorldToViewportPoint(Vector3 position, MonoOrStereoscopicEye eye) { WorldToViewportPoint_Injected(ref position, eye, out var ret); return ret; } public Vector3 ViewportToWorldPoint(Vector3 position, MonoOrStereoscopicEye eye) { ViewportToWorldPoint_Injected(ref position, eye, out var ret); return ret; } public Vector3 ScreenToWorldPoint(Vector3 position, MonoOrStereoscopicEye eye) { ScreenToWorldPoint_Injected(ref position, eye, out var ret); return ret; } public Vector3 WorldToScreenPoint(Vector3 position) { return WorldToScreenPoint(position, MonoOrStereoscopicEye.Mono); } public Vector3 WorldToViewportPoint(Vector3 position) { return WorldToViewportPoint(position, MonoOrStereoscopicEye.Mono); } public Vector3 ViewportToWorldPoint(Vector3 position) { return ViewportToWorldPoint(position, MonoOrStereoscopicEye.Mono); } public Vector3 ScreenToWorldPoint(Vector3 position) { return ScreenToWorldPoint(position, MonoOrStereoscopicEye.Mono); } public Vector3 ScreenToViewportPoint(Vector3 position) { ScreenToViewportPoint_Injected(ref position, out var ret); return ret; } public Vector3 ViewportToScreenPoint(Vector3 position) { ViewportToScreenPoint_Injected(ref position, out var ret); return ret; } internal Vector2 GetFrustumPlaneSizeAt(float distance) { GetFrustumPlaneSizeAt_Injected(distance, out var ret); return ret; } private Ray ViewportPointToRay(Vector2 pos, MonoOrStereoscopicEye eye) { ViewportPointToRay_Injected(ref pos, eye, out var ret); return ret; } public Ray ViewportPointToRay(Vector3 pos, MonoOrStereoscopicEye eye) { return ViewportPointToRay((Vector2)pos, eye); } public Ray ViewportPointToRay(Vector3 pos) { return ViewportPointToRay(pos, MonoOrStereoscopicEye.Mono); } private Ray ScreenPointToRay(Vector2 pos, MonoOrStereoscopicEye eye) { ScreenPointToRay_Injected(ref pos, eye, out var ret); return ret; } public Ray ScreenPointToRay(Vector3 pos, MonoOrStereoscopicEye eye) { return ScreenPointToRay((Vector2)pos, eye); } public Ray ScreenPointToRay(Vector3 pos) { return ScreenPointToRay(pos, MonoOrStereoscopicEye.Mono); } [FreeFunction("CameraScripting::CalculateViewportRayVectors", HasExplicitThis = true)] private void CalculateFrustumCornersInternal(Rect viewport, float z, MonoOrStereoscopicEye eye, [Out] Vector3[] outCorners) { CalculateFrustumCornersInternal_Injected(ref viewport, z, eye, outCorners); } public void CalculateFrustumCorners(Rect viewport, float z, MonoOrStereoscopicEye eye, Vector3[] outCorners) { if (outCorners == null) { throw new ArgumentNullException("outCorners"); } if (outCorners.Length < 4) { throw new ArgumentException("outCorners minimum size is 4", "outCorners"); } CalculateFrustumCornersInternal(viewport, z, eye, outCorners); } [NativeName("CalculateProjectionMatrixFromPhysicalProperties")] private static void CalculateProjectionMatrixFromPhysicalPropertiesInternal(out Matrix4x4 output, float focalLength, Vector2 sensorSize, Vector2 lensShift, float nearClip, float farClip, float gateAspect, GateFitMode gateFitMode) { CalculateProjectionMatrixFromPhysicalPropertiesInternal_Injected(out output, focalLength, ref sensorSize, ref lensShift, nearClip, farClip, gateAspect, gateFitMode); } public static void CalculateProjectionMatrixFromPhysicalProperties(out Matrix4x4 output, float focalLength, Vector2 sensorSize, Vector2 lensShift, float nearClip, float farClip, GateFitParameters gateFitParameters = default(GateFitParameters)) { CalculateProjectionMatrixFromPhysicalPropertiesInternal(out output, focalLength, sensorSize, lensShift, nearClip, farClip, gateFitParameters.aspect, gateFitParameters.mode); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("FocalLengthToFieldOfView_Safe")] public static extern float FocalLengthToFieldOfView(float focalLength, float sensorSize); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("FieldOfViewToFocalLength_Safe")] public static extern float FieldOfViewToFocalLength(float fieldOfView, float sensorSize); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HorizontalToVerticalFieldOfView_Safe")] public static extern float HorizontalToVerticalFieldOfView(float horizontalFieldOfView, float aspectRatio); [MethodImpl(MethodImplOptions.InternalCall)] public static extern float VerticalToHorizontalFieldOfView(float verticalFieldOfView, float aspectRatio); public Matrix4x4 GetStereoNonJitteredProjectionMatrix(StereoscopicEye eye) { GetStereoNonJitteredProjectionMatrix_Injected(eye, out var ret); return ret; } [FreeFunction("CameraScripting::GetStereoViewMatrix", HasExplicitThis = true)] public Matrix4x4 GetStereoViewMatrix(StereoscopicEye eye) { GetStereoViewMatrix_Injected(eye, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] public extern void CopyStereoDeviceProjectionMatrixToNonJittered(StereoscopicEye eye); [FreeFunction("CameraScripting::GetStereoProjectionMatrix", HasExplicitThis = true)] public Matrix4x4 GetStereoProjectionMatrix(StereoscopicEye eye) { GetStereoProjectionMatrix_Injected(eye, out var ret); return ret; } public void SetStereoProjectionMatrix(StereoscopicEye eye, Matrix4x4 matrix) { SetStereoProjectionMatrix_Injected(eye, ref matrix); } [MethodImpl(MethodImplOptions.InternalCall)] public extern void ResetStereoProjectionMatrices(); public void SetStereoViewMatrix(StereoscopicEye eye, Matrix4x4 matrix) { SetStereoViewMatrix_Injected(eye, ref matrix); } [MethodImpl(MethodImplOptions.InternalCall)] public extern void ResetStereoViewMatrices(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::GetAllCamerasCount")] private static extern int GetAllCamerasCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::GetAllCameras")] private static extern int GetAllCamerasImpl([Out][NotNull("ArgumentNullException")] Camera[] cam); public static int GetAllCameras(Camera[] cameras) { if (cameras == null) { throw new NullReferenceException(); } if (cameras.Length < allCamerasCount) { throw new ArgumentException("Passed in array to fill with cameras is to small to hold the number of cameras. Use Camera.allCamerasCount to get the needed size."); } return GetAllCamerasImpl(cameras); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::RenderToCubemap", HasExplicitThis = true)] private extern bool RenderToCubemapImpl(Texture tex, [UnityEngine.Internal.DefaultValue("63")] int faceMask); public bool RenderToCubemap(Cubemap cubemap, int faceMask) { return RenderToCubemapImpl(cubemap, faceMask); } public bool RenderToCubemap(Cubemap cubemap) { return RenderToCubemapImpl(cubemap, 63); } public bool RenderToCubemap(RenderTexture cubemap, int faceMask) { return RenderToCubemapImpl(cubemap, faceMask); } public bool RenderToCubemap(RenderTexture cubemap) { return RenderToCubemapImpl(cubemap, 63); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("UNITY_EDITOR")] private extern int GetFilterMode(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("RenderToCubemap")] private extern bool RenderToCubemapEyeImpl(RenderTexture cubemap, int faceMask, MonoOrStereoscopicEye stereoEye); public bool RenderToCubemap(RenderTexture cubemap, int faceMask, MonoOrStereoscopicEye stereoEye) { return RenderToCubemapEyeImpl(cubemap, faceMask, stereoEye); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::Render", HasExplicitThis = true)] public extern void Render(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::RenderWithShader", HasExplicitThis = true)] public extern void RenderWithShader(Shader shader, string replacementTag); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::RenderDontRestore", HasExplicitThis = true)] public extern void RenderDontRestore(); public void SubmitRenderRequests(List renderRequests) { if (renderRequests == null || renderRequests.Count == 0) { throw new ArgumentException("SubmitRenderRequests has been invoked with invalid renderRequests"); } if (GraphicsSettings.currentRenderPipeline == null) { Debug.LogWarning("Trying to invoke 'SubmitRenderRequests' when no SRP is set. A scriptable render pipeline is needed for this function call"); } else { SubmitRenderRequestsInternal(renderRequests); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::SubmitRenderRequests", HasExplicitThis = true)] private extern void SubmitRenderRequestsInternal(object requests); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::SetupCurrent")] public static extern void SetupCurrent(Camera cur); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::CopyFrom", HasExplicitThis = true)] public extern void CopyFrom(Camera other); [MethodImpl(MethodImplOptions.InternalCall)] public extern void RemoveCommandBuffers(CameraEvent evt); [MethodImpl(MethodImplOptions.InternalCall)] public extern void RemoveAllCommandBuffers(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("AddCommandBuffer")] private extern void AddCommandBufferImpl(CameraEvent evt, [NotNull("ArgumentNullException")] CommandBuffer buffer); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("AddCommandBufferAsync")] private extern void AddCommandBufferAsyncImpl(CameraEvent evt, [NotNull("ArgumentNullException")] CommandBuffer buffer, ComputeQueueType queueType); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("RemoveCommandBuffer")] private extern void RemoveCommandBufferImpl(CameraEvent evt, [NotNull("ArgumentNullException")] CommandBuffer buffer); public void AddCommandBuffer(CameraEvent evt, CommandBuffer buffer) { if (!CameraEventUtils.IsValid(evt)) { throw new ArgumentException($"Invalid CameraEvent value \"{(int)evt}\".", "evt"); } if (buffer == null) { throw new NullReferenceException("buffer is null"); } AddCommandBufferImpl(evt, buffer); } public void AddCommandBufferAsync(CameraEvent evt, CommandBuffer buffer, ComputeQueueType queueType) { if (!CameraEventUtils.IsValid(evt)) { throw new ArgumentException($"Invalid CameraEvent value \"{(int)evt}\".", "evt"); } if (buffer == null) { throw new NullReferenceException("buffer is null"); } AddCommandBufferAsyncImpl(evt, buffer, queueType); } public void RemoveCommandBuffer(CameraEvent evt, CommandBuffer buffer) { if (!CameraEventUtils.IsValid(evt)) { throw new ArgumentException($"Invalid CameraEvent value \"{(int)evt}\".", "evt"); } if (buffer == null) { throw new NullReferenceException("buffer is null"); } RemoveCommandBufferImpl(evt, buffer); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CameraScripting::GetCommandBuffers", HasExplicitThis = true)] public extern CommandBuffer[] GetCommandBuffers(CameraEvent evt); [RequiredByNativeCode] private static void FireOnPreCull(Camera cam) { if (onPreCull != null) { onPreCull(cam); } } [RequiredByNativeCode] private static void FireOnPreRender(Camera cam) { if (onPreRender != null) { onPreRender(cam); } } [RequiredByNativeCode] private static void FireOnPostRender(Camera cam) { if (onPostRender != null) { onPostRender(cam); } } internal void OnlyUsedForTesting1() { } internal void OnlyUsedForTesting2() { } public unsafe bool TryGetCullingParameters(out ScriptableCullingParameters cullingParameters) { return GetCullingParameters_Internal(this, stereoAware: false, out cullingParameters, sizeof(ScriptableCullingParameters)); } public unsafe bool TryGetCullingParameters(bool stereoAware, out ScriptableCullingParameters cullingParameters) { return GetCullingParameters_Internal(this, stereoAware, out cullingParameters, sizeof(ScriptableCullingParameters)); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("Runtime/Export/RenderPipeline/ScriptableRenderPipeline.bindings.h")] [FreeFunction("ScriptableRenderPipeline_Bindings::GetCullingParameters_Internal")] private static extern bool GetCullingParameters_Internal(Camera camera, bool stereoAware, out ScriptableCullingParameters cullingParameters, int managedCullingParametersSize); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_transparencySortAxis_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_transparencySortAxis_Injected(ref Vector3 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_velocity_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_cullingMatrix_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_cullingMatrix_Injected(ref Matrix4x4 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_backgroundColor_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_backgroundColor_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_sensorSize_Injected(out Vector2 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_sensorSize_Injected(ref Vector2 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_lensShift_Injected(out Vector2 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_lensShift_Injected(ref Vector2 value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetGateFittedLensShift_Injected(out Vector2 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetLocalSpaceAim_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_rect_Injected(out Rect ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_rect_Injected(ref Rect value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_pixelRect_Injected(out Rect ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_pixelRect_Injected(ref Rect value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetTargetBuffersImpl_Injected(ref RenderBuffer color, ref RenderBuffer depth); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetTargetBuffersMRTImpl_Injected(RenderBuffer[] color, ref RenderBuffer depth); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_cameraToWorldMatrix_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_worldToCameraMatrix_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_worldToCameraMatrix_Injected(ref Matrix4x4 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_projectionMatrix_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_projectionMatrix_Injected(ref Matrix4x4 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_nonJitteredProjectionMatrix_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_nonJitteredProjectionMatrix_Injected(ref Matrix4x4 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_previousViewProjectionMatrix_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void CalculateObliqueMatrix_Injected(ref Vector4 clipPlane, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void WorldToScreenPoint_Injected(ref Vector3 position, MonoOrStereoscopicEye eye, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void WorldToViewportPoint_Injected(ref Vector3 position, MonoOrStereoscopicEye eye, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void ViewportToWorldPoint_Injected(ref Vector3 position, MonoOrStereoscopicEye eye, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void ScreenToWorldPoint_Injected(ref Vector3 position, MonoOrStereoscopicEye eye, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void ScreenToViewportPoint_Injected(ref Vector3 position, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void ViewportToScreenPoint_Injected(ref Vector3 position, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetFrustumPlaneSizeAt_Injected(float distance, out Vector2 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void ViewportPointToRay_Injected(ref Vector2 pos, MonoOrStereoscopicEye eye, out Ray ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void ScreenPointToRay_Injected(ref Vector2 pos, MonoOrStereoscopicEye eye, out Ray ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void CalculateFrustumCornersInternal_Injected(ref Rect viewport, float z, MonoOrStereoscopicEye eye, [Out] Vector3[] outCorners); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CalculateProjectionMatrixFromPhysicalPropertiesInternal_Injected(out Matrix4x4 output, float focalLength, ref Vector2 sensorSize, ref Vector2 lensShift, float nearClip, float farClip, float gateAspect, GateFitMode gateFitMode); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_scene_Injected(out Scene ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_scene_Injected(ref Scene value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetStereoNonJitteredProjectionMatrix_Injected(StereoscopicEye eye, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetStereoViewMatrix_Injected(StereoscopicEye eye, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetStereoProjectionMatrix_Injected(StereoscopicEye eye, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetStereoProjectionMatrix_Injected(StereoscopicEye eye, ref Matrix4x4 matrix); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetStereoViewMatrix_Injected(StereoscopicEye eye, ref Matrix4x4 matrix); } public struct BoundingSphere { public Vector3 position; public float radius; public BoundingSphere(Vector3 pos, float rad) { position = pos; radius = rad; } public BoundingSphere(Vector4 packedSphere) { position = new Vector3(packedSphere.x, packedSphere.y, packedSphere.z); radius = packedSphere.w; } } internal enum CullingQueryOptions { Normal, IgnoreVisibility, IgnoreDistance } public struct CullingGroupEvent { private int m_Index; private byte m_PrevState; private byte m_ThisState; private const byte kIsVisibleMask = 128; private const byte kDistanceMask = 127; public int index => m_Index; public bool isVisible => (m_ThisState & 0x80) != 0; public bool wasVisible => (m_PrevState & 0x80) != 0; public bool hasBecomeVisible => isVisible && !wasVisible; public bool hasBecomeInvisible => !isVisible && wasVisible; public int currentDistance => m_ThisState & 0x7F; public int previousDistance => m_PrevState & 0x7F; } [StructLayout(LayoutKind.Sequential)] [NativeHeader("Runtime/Export/Camera/CullingGroup.bindings.h")] public class CullingGroup : IDisposable { public delegate void StateChanged(CullingGroupEvent sphere); internal IntPtr m_Ptr; private StateChanged m_OnStateChanged = null; public StateChanged onStateChanged { get { return m_OnStateChanged; } set { m_OnStateChanged = value; } } public extern bool enabled { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Camera targetCamera { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public CullingGroup() { m_Ptr = Init(this); } ~CullingGroup() { if (m_Ptr != IntPtr.Zero) { FinalizerFailure(); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CullingGroup_Bindings::Dispose", HasExplicitThis = true)] private extern void DisposeInternal(); public void Dispose() { DisposeInternal(); m_Ptr = IntPtr.Zero; } [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetBoundingSpheres([Unmarshalled] BoundingSphere[] array); [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetBoundingSphereCount(int count); [MethodImpl(MethodImplOptions.InternalCall)] public extern void EraseSwapBack(int index); public static void EraseSwapBack(int index, T[] myArray, ref int size) { size--; myArray[index] = myArray[size]; } public int QueryIndices(bool visible, int[] result, int firstIndex) { return QueryIndices(visible, -1, CullingQueryOptions.IgnoreDistance, result, firstIndex); } public int QueryIndices(int distanceIndex, int[] result, int firstIndex) { return QueryIndices(visible: false, distanceIndex, CullingQueryOptions.IgnoreVisibility, result, firstIndex); } public int QueryIndices(bool visible, int distanceIndex, int[] result, int firstIndex) { return QueryIndices(visible, distanceIndex, CullingQueryOptions.Normal, result, firstIndex); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CullingGroup_Bindings::QueryIndices", HasExplicitThis = true)] [NativeThrows] private extern int QueryIndices(bool visible, int distanceIndex, CullingQueryOptions options, [Unmarshalled] int[] result, int firstIndex); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] [FreeFunction("CullingGroup_Bindings::IsVisible", HasExplicitThis = true)] public extern bool IsVisible(int index); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] [FreeFunction("CullingGroup_Bindings::GetDistance", HasExplicitThis = true)] public extern int GetDistance(int index); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CullingGroup_Bindings::SetBoundingDistances", HasExplicitThis = true)] public extern void SetBoundingDistances([Unmarshalled] float[] distances); [FreeFunction("CullingGroup_Bindings::SetDistanceReferencePoint", HasExplicitThis = true)] private void SetDistanceReferencePoint_InternalVector3(Vector3 point) { SetDistanceReferencePoint_InternalVector3_Injected(ref point); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("SetDistanceReferenceTransform")] private extern void SetDistanceReferencePoint_InternalTransform(Transform transform); public void SetDistanceReferencePoint(Vector3 point) { SetDistanceReferencePoint_InternalVector3(point); } public void SetDistanceReferencePoint(Transform transform) { SetDistanceReferencePoint_InternalTransform(transform); } [RequiredByNativeCode] [SecuritySafeCritical] private unsafe static void SendEvents(CullingGroup cullingGroup, IntPtr eventsPtr, int count) { CullingGroupEvent* ptr = (CullingGroupEvent*)eventsPtr.ToPointer(); if (cullingGroup.m_OnStateChanged != null) { for (int i = 0; i < count; i++) { cullingGroup.m_OnStateChanged(ptr[i]); } } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CullingGroup_Bindings::Init")] private static extern IntPtr Init(object scripting); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CullingGroup_Bindings::FinalizerFailure", HasExplicitThis = true, IsThreadSafe = true)] private extern void FinalizerFailure(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetDistanceReferencePoint_InternalVector3_Injected(ref Vector3 point); } [RequireComponent(typeof(Camera))] public class FlareLayer : Behaviour { internal FlareLayer() { } } [NativeHeader("Runtime/Camera/ReflectionProbes.h")] public sealed class ReflectionProbe : Behaviour { public enum ReflectionProbeEvent { ReflectionProbeAdded, ReflectionProbeRemoved } [NativeName("ProbeType")] [Obsolete("type property has been deprecated. Starting with Unity 5.4, the only supported reflection probe type is Cube.", true)] [EditorBrowsable(EditorBrowsableState.Never)] public extern ReflectionProbeType type { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeName("BoxSize")] public Vector3 size { get { get_size_Injected(out var ret); return ret; } set { set_size_Injected(ref value); } } [NativeName("BoxOffset")] public Vector3 center { get { get_center_Injected(out var ret); return ret; } set { set_center_Injected(ref value); } } [NativeName("Near")] public extern float nearClipPlane { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeName("Far")] public extern float farClipPlane { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeName("IntensityMultiplier")] public extern float intensity { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeName("GlobalAABB")] public Bounds bounds { get { get_bounds_Injected(out var ret); return ret; } } [NativeName("HDR")] public extern bool hdr { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeName("RenderDynamicObjects")] public extern bool renderDynamicObjects { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float shadowDistance { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int resolution { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int cullingMask { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern ReflectionProbeClearFlags clearFlags { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Color backgroundColor { get { get_backgroundColor_Injected(out var ret); return ret; } set { set_backgroundColor_Injected(ref value); } } public extern float blendDistance { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool boxProjection { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern ReflectionProbeMode mode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int importance { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern ReflectionProbeRefreshMode refreshMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern ReflectionProbeTimeSlicingMode timeSlicingMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Texture bakedTexture { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Texture customBakedTexture { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern RenderTexture realtimeTexture { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Texture texture { [MethodImpl(MethodImplOptions.InternalCall)] get; } public Vector4 textureHDRDecodeValues { [NativeName("CalculateHDRDecodeValues")] get { get_textureHDRDecodeValues_Injected(out var ret); return ret; } } [StaticAccessor("GetReflectionProbes()")] public static extern int minBakedCubemapResolution { [MethodImpl(MethodImplOptions.InternalCall)] get; } [StaticAccessor("GetReflectionProbes()")] public static extern int maxBakedCubemapResolution { [MethodImpl(MethodImplOptions.InternalCall)] get; } [StaticAccessor("GetReflectionProbes()")] public static Vector4 defaultTextureHDRDecodeValues { get { get_defaultTextureHDRDecodeValues_Injected(out var ret); return ret; } } [StaticAccessor("GetReflectionProbes()")] public static extern Texture defaultTexture { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static event Action reflectionProbeChanged; [Obsolete("ReflectionProbe.defaultReflectionSet has been deprecated. Use ReflectionProbe.defaultReflectionTexture. (UnityUpgradable) -> UnityEngine.ReflectionProbe.defaultReflectionTexture", true)] public static event Action defaultReflectionSet; public static event Action defaultReflectionTexture; [MethodImpl(MethodImplOptions.InternalCall)] public extern void Reset(); public int RenderProbe() { return RenderProbe(null); } public int RenderProbe([UnityEngine.Internal.DefaultValue("null")] RenderTexture targetTexture) { return ScheduleRender(timeSlicingMode, targetTexture); } [MethodImpl(MethodImplOptions.InternalCall)] public extern bool IsFinishedRendering(int renderId); [MethodImpl(MethodImplOptions.InternalCall)] private extern int ScheduleRender(ReflectionProbeTimeSlicingMode timeSlicingMode, RenderTexture targetTexture); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CubemapGPUBlend")] [NativeHeader("Runtime/Camera/CubemapGPUUtility.h")] public static extern bool BlendCubemap(Texture src, Texture dst, float blend, RenderTexture target); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor("GetReflectionProbes()")] [NativeMethod("UpdateSampleData")] public static extern void UpdateCachedState(); [RequiredByNativeCode] private static void CallReflectionProbeEvent(ReflectionProbe probe, ReflectionProbeEvent probeEvent) { ReflectionProbe.reflectionProbeChanged?.Invoke(probe, probeEvent); } [RequiredByNativeCode] private static void CallSetDefaultReflection(Texture defaultReflectionCubemap) { ReflectionProbe.defaultReflectionTexture?.Invoke(defaultReflectionCubemap); } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_size_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_size_Injected(ref Vector3 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_center_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_center_Injected(ref Vector3 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_bounds_Injected(out Bounds ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_backgroundColor_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_backgroundColor_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_textureHDRDecodeValues_Injected(out Vector4 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_defaultTextureHDRDecodeValues_Injected(out Vector4 ret); } [NativeHeader("Runtime/Export/CrashReport/CrashReport.bindings.h")] public sealed class CrashReport { private static List internalReports; private static object reportsLock = new object(); private readonly string id; public readonly DateTime time; public readonly string text; public static CrashReport[] reports { get { PopulateReports(); lock (reportsLock) { return internalReports.ToArray(); } } } public static CrashReport lastReport { get { PopulateReports(); lock (reportsLock) { if (internalReports.Count > 0) { return internalReports[internalReports.Count - 1]; } } return null; } } private static int Compare(CrashReport c1, CrashReport c2) { DateTime dateTime = c1.time; long ticks = dateTime.Ticks; dateTime = c2.time; long ticks2 = dateTime.Ticks; if (ticks > ticks2) { return 1; } if (ticks < ticks2) { return -1; } return 0; } private static void PopulateReports() { lock (reportsLock) { if (internalReports == null) { string[] array = GetReports(); internalReports = new List(array.Length); string[] array2 = array; foreach (string text in array2) { double secondsSinceUnixEpoch; string reportData = GetReportData(text, out secondsSinceUnixEpoch); DateTime dateTime = new DateTime(1970, 1, 1).AddSeconds(secondsSinceUnixEpoch); internalReports.Add(new CrashReport(text, dateTime, reportData)); } internalReports.Sort(Compare); } } } public static void RemoveAll() { CrashReport[] array = reports; foreach (CrashReport crashReport in array) { crashReport.Remove(); } } private CrashReport(string id, DateTime time, string text) { this.id = id; this.time = time; this.text = text; } public void Remove() { if (RemoveReport(id)) { lock (reportsLock) { internalReports.Remove(this); } } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CrashReport_Bindings::GetReports", IsThreadSafe = true)] private static extern string[] GetReports(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CrashReport_Bindings::GetReportData", IsThreadSafe = true)] private static extern string GetReportData(string id, out double secondsSinceUnixEpoch); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CrashReport_Bindings::RemoveReport", IsThreadSafe = true)] private static extern bool RemoveReport(string id); } [NativeHeader("Runtime/Export/Debug/Debug.bindings.h")] internal sealed class DebugLogHandler : ILogHandler { [MethodImpl(MethodImplOptions.InternalCall)] [ThreadAndSerializationSafe] internal static extern void Internal_Log(LogType level, LogOption options, string msg, Object obj); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadAndSerializationSafe] internal static extern void Internal_LogException(Exception ex, Object obj); public void LogFormat(LogType logType, Object context, string format, params object[] args) { Internal_Log(logType, LogOption.None, string.Format(format, args), context); } public void LogFormat(LogType logType, LogOption logOptions, Object context, string format, params object[] args) { Internal_Log(logType, logOptions, string.Format(format, args), context); } public void LogException(Exception exception, Object context) { if (exception == null) { throw new ArgumentNullException("exception"); } Internal_LogException(exception, context); } } [NativeHeader("Runtime/Export/Debug/Debug.bindings.h")] public class Debug { internal static readonly ILogger s_DefaultLogger = new Logger(new DebugLogHandler()); internal static ILogger s_Logger = new Logger(new DebugLogHandler()); public static ILogger unityLogger => s_Logger; public static extern bool developerConsoleVisible { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeProperty(/*Could not decode attribute arguments.*/)] public static extern bool isDebugBuild { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeThrows] internal static extern DiagnosticSwitch[] diagnosticSwitches { [MethodImpl(MethodImplOptions.InternalCall)] get; } [Obsolete("Debug.logger is obsolete. Please use Debug.unityLogger instead (UnityUpgradable) -> unityLogger")] [EditorBrowsable(EditorBrowsableState.Never)] public static ILogger logger => s_Logger; [ExcludeFromDocs] public static void DrawLine(Vector3 start, Vector3 end, Color color, float duration) { bool depthTest = true; DrawLine(start, end, color, duration, depthTest); } [ExcludeFromDocs] public static void DrawLine(Vector3 start, Vector3 end, Color color) { bool depthTest = true; float duration = 0f; DrawLine(start, end, color, duration, depthTest); } [ExcludeFromDocs] public static void DrawLine(Vector3 start, Vector3 end) { bool depthTest = true; float duration = 0f; Color white = Color.white; DrawLine(start, end, white, duration, depthTest); } [FreeFunction("DebugDrawLine", IsThreadSafe = true)] public static void DrawLine(Vector3 start, Vector3 end, [UnityEngine.Internal.DefaultValue("Color.white")] Color color, [UnityEngine.Internal.DefaultValue("0.0f")] float duration, [UnityEngine.Internal.DefaultValue("true")] bool depthTest) { DrawLine_Injected(ref start, ref end, ref color, duration, depthTest); } [ExcludeFromDocs] public static void DrawRay(Vector3 start, Vector3 dir, Color color, float duration) { bool depthTest = true; DrawRay(start, dir, color, duration, depthTest); } [ExcludeFromDocs] public static void DrawRay(Vector3 start, Vector3 dir, Color color) { bool depthTest = true; float duration = 0f; DrawRay(start, dir, color, duration, depthTest); } [ExcludeFromDocs] public static void DrawRay(Vector3 start, Vector3 dir) { bool depthTest = true; float duration = 0f; Color white = Color.white; DrawRay(start, dir, white, duration, depthTest); } public static void DrawRay(Vector3 start, Vector3 dir, [UnityEngine.Internal.DefaultValue("Color.white")] Color color, [UnityEngine.Internal.DefaultValue("0.0f")] float duration, [UnityEngine.Internal.DefaultValue("true")] bool depthTest) { DrawLine(start, start + dir, color, duration, depthTest); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PauseEditor")] public static extern void Break(); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void DebugBreak(); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] public unsafe static extern int ExtractStackTraceNoAlloc(byte* buffer, int bufferMax, string projectFolder); public static void Log(object message) { unityLogger.Log(LogType.Log, message); } public static void Log(object message, Object context) { unityLogger.Log(LogType.Log, message, context); } public static void LogFormat(string format, params object[] args) { unityLogger.LogFormat(LogType.Log, format, args); } public static void LogFormat(Object context, string format, params object[] args) { unityLogger.LogFormat(LogType.Log, context, format, args); } public static void LogFormat(LogType logType, LogOption logOptions, Object context, string format, params object[] args) { if (!(unityLogger.logHandler is DebugLogHandler debugLogHandler)) { unityLogger.LogFormat(logType, context, format, args); } else if (unityLogger.IsLogTypeAllowed(logType)) { debugLogHandler.LogFormat(logType, logOptions, context, format, args); } } public static void LogError(object message) { unityLogger.Log(LogType.Error, message); } public static void LogError(object message, Object context) { unityLogger.Log(LogType.Error, message, context); } public static void LogErrorFormat(string format, params object[] args) { unityLogger.LogFormat(LogType.Error, format, args); } public static void LogErrorFormat(Object context, string format, params object[] args) { unityLogger.LogFormat(LogType.Error, context, format, args); } [MethodImpl(MethodImplOptions.InternalCall)] public static extern void ClearDeveloperConsole(); public static void LogException(Exception exception) { unityLogger.LogException(exception, null); } public static void LogException(Exception exception, Object context) { unityLogger.LogException(exception, context); } public static void LogWarning(object message) { unityLogger.Log(LogType.Warning, message); } public static void LogWarning(object message, Object context) { unityLogger.Log(LogType.Warning, message, context); } public static void LogWarningFormat(string format, params object[] args) { unityLogger.LogFormat(LogType.Warning, format, args); } public static void LogWarningFormat(Object context, string format, params object[] args) { unityLogger.LogFormat(LogType.Warning, context, format, args); } [Conditional("UNITY_ASSERTIONS")] public static void Assert(bool condition) { if (!condition) { unityLogger.Log(LogType.Assert, "Assertion failed"); } } [Conditional("UNITY_ASSERTIONS")] public static void Assert(bool condition, Object context) { if (!condition) { unityLogger.Log(LogType.Assert, (object)"Assertion failed", context); } } [Conditional("UNITY_ASSERTIONS")] public static void Assert(bool condition, object message) { if (!condition) { unityLogger.Log(LogType.Assert, message); } } [Conditional("UNITY_ASSERTIONS")] public static void Assert(bool condition, string message) { if (!condition) { unityLogger.Log(LogType.Assert, message); } } [Conditional("UNITY_ASSERTIONS")] public static void Assert(bool condition, object message, Object context) { if (!condition) { unityLogger.Log(LogType.Assert, message, context); } } [Conditional("UNITY_ASSERTIONS")] public static void Assert(bool condition, string message, Object context) { if (!condition) { unityLogger.Log(LogType.Assert, (object)message, context); } } [Conditional("UNITY_ASSERTIONS")] public static void AssertFormat(bool condition, string format, params object[] args) { if (!condition) { unityLogger.LogFormat(LogType.Assert, format, args); } } [Conditional("UNITY_ASSERTIONS")] public static void AssertFormat(bool condition, Object context, string format, params object[] args) { if (!condition) { unityLogger.LogFormat(LogType.Assert, context, format, args); } } [Conditional("UNITY_ASSERTIONS")] public static void LogAssertion(object message) { unityLogger.Log(LogType.Assert, message); } [Conditional("UNITY_ASSERTIONS")] public static void LogAssertion(object message, Object context) { unityLogger.Log(LogType.Assert, message, context); } [Conditional("UNITY_ASSERTIONS")] public static void LogAssertionFormat(string format, params object[] args) { unityLogger.LogFormat(LogType.Assert, format, args); } [Conditional("UNITY_ASSERTIONS")] public static void LogAssertionFormat(Object context, string format, params object[] args) { unityLogger.LogFormat(LogType.Assert, context, format, args); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("DeveloperConsole_OpenConsoleFile")] internal static extern void OpenConsoleFile(); internal static DiagnosticSwitch GetDiagnosticSwitch(string name) { DiagnosticSwitch[] array = diagnosticSwitches; foreach (DiagnosticSwitch diagnosticSwitch in array) { if (diagnosticSwitch.name == name) { return diagnosticSwitch; } } throw new ArgumentException("Could not find DiagnosticSwitch named " + name); } [RequiredByNativeCode] internal static bool CallOverridenDebugHandler(Exception exception, Object obj) { if (unityLogger.logHandler is DebugLogHandler) { return false; } try { unityLogger.LogException(exception, obj); } catch (Exception arg) { s_DefaultLogger.LogError($"Invalid exception thrown from custom {unityLogger.logHandler.GetType()}.LogException(). Message: {arg}", obj); return false; } return true; } [RequiredByNativeCode] internal static bool IsLoggingEnabled() { if (unityLogger.logHandler is DebugLogHandler) { return unityLogger.logEnabled; } return s_DefaultLogger.logEnabled; } [Obsolete("Assert(bool, string, params object[]) is obsolete. Use AssertFormat(bool, string, params object[]) (UnityUpgradable) -> AssertFormat(*)", true)] [EditorBrowsable(EditorBrowsableState.Never)] [Conditional("UNITY_ASSERTIONS")] public static void Assert(bool condition, string format, params object[] args) { if (!condition) { unityLogger.LogFormat(LogType.Assert, format, args); } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawLine_Injected(ref Vector3 start, ref Vector3 end, [UnityEngine.Internal.DefaultValue("Color.white")] ref Color color, [UnityEngine.Internal.DefaultValue("0.0f")] float duration, [UnityEngine.Internal.DefaultValue("true")] bool depthTest); } [StructLayout(LayoutKind.Sequential)] [NativeAsStruct] [NativeHeader("Runtime/Utilities/DiagnosticSwitch.h")] [NativeClass("DiagnosticSwitch", "struct DiagnosticSwitch;")] internal class DiagnosticSwitch { [Flags] internal enum Flags { None = 0, CanChangeAfterEngineStart = 1 } private IntPtr m_Ptr; public extern string name { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern string description { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeName("OwningModuleName")] public extern string owningModule { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern Flags flags { [MethodImpl(MethodImplOptions.InternalCall)] get; } public object value { get { return GetScriptingValue(); } set { SetScriptingValue(value, setPersistent: false); } } [NativeName("ScriptingDefaultValue")] public extern object defaultValue { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeName("ScriptingMinValue")] public extern object minValue { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeName("ScriptingMaxValue")] public extern object maxValue { [MethodImpl(MethodImplOptions.InternalCall)] get; } public object persistentValue { get { return GetScriptingPersistentValue(); } set { SetScriptingValue(value, setPersistent: true); } } [NativeName("ScriptingEnumInfo")] public extern EnumInfo enumInfo { [MethodImpl(MethodImplOptions.InternalCall)] get; } public bool isSetToDefault => object.Equals(persistentValue, defaultValue); public bool needsRestart => !object.Equals(value, persistentValue); private DiagnosticSwitch() { } [MethodImpl(MethodImplOptions.InternalCall)] private extern object GetScriptingValue(); [MethodImpl(MethodImplOptions.InternalCall)] private extern object GetScriptingPersistentValue(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private extern void SetScriptingValue(object value, bool setPersistent); } [NativeHeader("Runtime/Utilities/PropertyName.h")] [NativeHeader("Runtime/Director/Core/ExposedPropertyTable.bindings.h")] public struct ExposedPropertyResolver { internal IntPtr table; internal static Object ResolveReferenceInternal(IntPtr ptr, PropertyName name, out bool isValid) { if (ptr == IntPtr.Zero) { throw new ArgumentNullException("Argument \"ptr\" can't be null."); } return ResolveReferenceBindingsInternal(ptr, name, out isValid); } [FreeFunction("ExposedPropertyTableBindings::ResolveReferenceInternal")] private static Object ResolveReferenceBindingsInternal(IntPtr ptr, PropertyName name, out bool isValid) { return ResolveReferenceBindingsInternal_Injected(ptr, ref name, out isValid); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern Object ResolveReferenceBindingsInternal_Injected(IntPtr ptr, ref PropertyName name, out bool isValid); } [Serializable] [UsedByNativeCode(Name = "ExposedReference")] public struct ExposedReference where T : Object { [SerializeField] public PropertyName exposedName; [SerializeField] public Object defaultValue; public T Resolve(IExposedPropertyTable resolver) { if (resolver != null) { bool idValid; Object referenceValue = resolver.GetReferenceValue(exposedName, out idValid); if (idValid) { return referenceValue as T; } } return defaultValue as T; } } public interface IExposedPropertyTable { void SetReferenceValue(PropertyName id, Object value); Object GetReferenceValue(PropertyName id, out bool idValid); void ClearReferenceValue(PropertyName id); } [NativeHeader("Runtime/Geometry/AABB.h")] [NativeClass("AABB")] [RequiredByNativeCode(Optional = true, GenerateProxy = true)] [NativeHeader("Runtime/Math/MathScripting.h")] [NativeHeader("Runtime/Geometry/Ray.h")] [NativeType(Header = "Runtime/Geometry/AABB.h")] [NativeHeader("Runtime/Geometry/Intersection.h")] public struct Bounds : IEquatable, IFormattable { private Vector3 m_Center; [NativeName("m_Extent")] private Vector3 m_Extents; public Vector3 center { get { return m_Center; } set { m_Center = value; } } public Vector3 size { get { return m_Extents * 2f; } set { m_Extents = value * 0.5f; } } public Vector3 extents { get { return m_Extents; } set { m_Extents = value; } } public Vector3 min { get { return center - extents; } set { SetMinMax(value, max); } } public Vector3 max { get { return center + extents; } set { SetMinMax(min, value); } } public Bounds(Vector3 center, Vector3 size) { m_Center = center; m_Extents = size * 0.5f; } public override int GetHashCode() { return center.GetHashCode() ^ (extents.GetHashCode() << 2); } public override bool Equals(object other) { if (!(other is Bounds)) { return false; } return Equals((Bounds)other); } public bool Equals(Bounds other) { return center.Equals(other.center) && extents.Equals(other.extents); } public static bool operator ==(Bounds lhs, Bounds rhs) { return lhs.center == rhs.center && lhs.extents == rhs.extents; } public static bool operator !=(Bounds lhs, Bounds rhs) { return !(lhs == rhs); } public void SetMinMax(Vector3 min, Vector3 max) { extents = (max - min) * 0.5f; center = min + extents; } public void Encapsulate(Vector3 point) { SetMinMax(Vector3.Min(min, point), Vector3.Max(max, point)); } public void Encapsulate(Bounds bounds) { Encapsulate(bounds.center - bounds.extents); Encapsulate(bounds.center + bounds.extents); } public void Expand(float amount) { amount *= 0.5f; extents += new Vector3(amount, amount, amount); } public void Expand(Vector3 amount) { extents += amount * 0.5f; } public bool Intersects(Bounds bounds) { return min.x <= bounds.max.x && max.x >= bounds.min.x && min.y <= bounds.max.y && max.y >= bounds.min.y && min.z <= bounds.max.z && max.z >= bounds.min.z; } public bool IntersectRay(Ray ray) { float dist; return IntersectRayAABB(ray, this, out dist); } public bool IntersectRay(Ray ray, out float distance) { return IntersectRayAABB(ray, this, out distance); } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) { format = "F2"; } if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("Center: {0}, Extents: {1}", new object[2] { m_Center.ToString(format, formatProvider), m_Extents.ToString(format, formatProvider) }); } [NativeMethod("IsInside", IsThreadSafe = true)] public bool Contains(Vector3 point) { return Contains_Injected(ref this, ref point); } [FreeFunction("BoundsScripting::SqrDistance", HasExplicitThis = true, IsThreadSafe = true)] public float SqrDistance(Vector3 point) { return SqrDistance_Injected(ref this, ref point); } [FreeFunction("IntersectRayAABB", IsThreadSafe = true)] private static bool IntersectRayAABB(Ray ray, Bounds bounds, out float dist) { return IntersectRayAABB_Injected(ref ray, ref bounds, out dist); } [FreeFunction("BoundsScripting::ClosestPoint", HasExplicitThis = true, IsThreadSafe = true)] public Vector3 ClosestPoint(Vector3 point) { ClosestPoint_Injected(ref this, ref point, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool Contains_Injected(ref Bounds _unity_self, ref Vector3 point); [MethodImpl(MethodImplOptions.InternalCall)] private static extern float SqrDistance_Injected(ref Bounds _unity_self, ref Vector3 point); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IntersectRayAABB_Injected(ref Ray ray, ref Bounds bounds, out float dist); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ClosestPoint_Injected(ref Bounds _unity_self, ref Vector3 point, out Vector3 ret); } [UsedByNativeCode] public struct BoundsInt : IEquatable, IFormattable { public struct PositionEnumerator : IEnumerator, IEnumerator, IDisposable { private readonly Vector3Int _min; private readonly Vector3Int _max; private Vector3Int _current; public Vector3Int Current => _current; object IEnumerator.Current => Current; public PositionEnumerator(Vector3Int min, Vector3Int max) { _min = (_current = min); _max = max; Reset(); } public PositionEnumerator GetEnumerator() { return this; } public bool MoveNext() { if (_current.z >= _max.z || _current.y >= _max.y) { return false; } _current.x++; if (_current.x >= _max.x) { _current.x = _min.x; if (_current.x >= _max.x) { return false; } _current.y++; if (_current.y >= _max.y) { _current.y = _min.y; _current.z++; if (_current.z >= _max.z) { return false; } } } return true; } public void Reset() { _current = _min; _current.x--; } void IDisposable.Dispose() { } } private Vector3Int m_Position; private Vector3Int m_Size; public int x { get { return m_Position.x; } set { m_Position.x = value; } } public int y { get { return m_Position.y; } set { m_Position.y = value; } } public int z { get { return m_Position.z; } set { m_Position.z = value; } } public Vector3 center => new Vector3((float)x + (float)m_Size.x / 2f, (float)y + (float)m_Size.y / 2f, (float)z + (float)m_Size.z / 2f); public Vector3Int min { get { return new Vector3Int(xMin, yMin, zMin); } set { xMin = value.x; yMin = value.y; zMin = value.z; } } public Vector3Int max { get { return new Vector3Int(xMax, yMax, zMax); } set { xMax = value.x; yMax = value.y; zMax = value.z; } } public int xMin { get { return Math.Min(m_Position.x, m_Position.x + m_Size.x); } set { int num = xMax; m_Position.x = value; m_Size.x = num - m_Position.x; } } public int yMin { get { return Math.Min(m_Position.y, m_Position.y + m_Size.y); } set { int num = yMax; m_Position.y = value; m_Size.y = num - m_Position.y; } } public int zMin { get { return Math.Min(m_Position.z, m_Position.z + m_Size.z); } set { int num = zMax; m_Position.z = value; m_Size.z = num - m_Position.z; } } public int xMax { get { return Math.Max(m_Position.x, m_Position.x + m_Size.x); } set { m_Size.x = value - m_Position.x; } } public int yMax { get { return Math.Max(m_Position.y, m_Position.y + m_Size.y); } set { m_Size.y = value - m_Position.y; } } public int zMax { get { return Math.Max(m_Position.z, m_Position.z + m_Size.z); } set { m_Size.z = value - m_Position.z; } } public Vector3Int position { get { return m_Position; } set { m_Position = value; } } public Vector3Int size { get { return m_Size; } set { m_Size = value; } } public PositionEnumerator allPositionsWithin => new PositionEnumerator(min, max); public BoundsInt(int xMin, int yMin, int zMin, int sizeX, int sizeY, int sizeZ) { m_Position = new Vector3Int(xMin, yMin, zMin); m_Size = new Vector3Int(sizeX, sizeY, sizeZ); } public BoundsInt(Vector3Int position, Vector3Int size) { m_Position = position; m_Size = size; } public void SetMinMax(Vector3Int minPosition, Vector3Int maxPosition) { min = minPosition; max = maxPosition; } public void ClampToBounds(BoundsInt bounds) { position = new Vector3Int(Math.Max(Math.Min(bounds.xMax, position.x), bounds.xMin), Math.Max(Math.Min(bounds.yMax, position.y), bounds.yMin), Math.Max(Math.Min(bounds.zMax, position.z), bounds.zMin)); size = new Vector3Int(Math.Min(bounds.xMax - position.x, size.x), Math.Min(bounds.yMax - position.y, size.y), Math.Min(bounds.zMax - position.z, size.z)); } public bool Contains(Vector3Int position) { return position.x >= xMin && position.y >= yMin && position.z >= zMin && position.x < xMax && position.y < yMax && position.z < zMax; } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("Position: {0}, Size: {1}", new object[2] { m_Position.ToString(format, formatProvider), m_Size.ToString(format, formatProvider) }); } public static bool operator ==(BoundsInt lhs, BoundsInt rhs) { return lhs.m_Position == rhs.m_Position && lhs.m_Size == rhs.m_Size; } public static bool operator !=(BoundsInt lhs, BoundsInt rhs) { return !(lhs == rhs); } public override bool Equals(object other) { if (!(other is BoundsInt)) { return false; } return Equals((BoundsInt)other); } public bool Equals(BoundsInt other) { return m_Position.Equals(other.m_Position) && m_Size.Equals(other.m_Size); } public override int GetHashCode() { return m_Position.GetHashCode() ^ (m_Size.GetHashCode() << 2); } } [NativeHeader("Runtime/Graphics/GraphicsScriptBindings.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public sealed class GeometryUtility { public static Plane[] CalculateFrustumPlanes(Camera camera) { Plane[] array = new Plane[6]; CalculateFrustumPlanes(camera, array); return array; } public static Plane[] CalculateFrustumPlanes(Matrix4x4 worldToProjectionMatrix) { Plane[] array = new Plane[6]; CalculateFrustumPlanes(worldToProjectionMatrix, array); return array; } public static void CalculateFrustumPlanes(Camera camera, Plane[] planes) { CalculateFrustumPlanes(camera.projectionMatrix * camera.worldToCameraMatrix, planes); } public static void CalculateFrustumPlanes(Matrix4x4 worldToProjectionMatrix, Plane[] planes) { if (planes == null) { throw new ArgumentNullException("planes"); } if (planes.Length != 6) { throw new ArgumentException("Planes array must be of length 6.", "planes"); } Internal_ExtractPlanes(planes, worldToProjectionMatrix); } public static Bounds CalculateBounds(Vector3[] positions, Matrix4x4 transform) { if (positions == null) { throw new ArgumentNullException("positions"); } if (positions.Length == 0) { throw new ArgumentException("Zero-sized array is not allowed.", "positions"); } return Internal_CalculateBounds(positions, transform); } public static bool TryCreatePlaneFromPolygon(Vector3[] vertices, out Plane plane) { if (vertices == null || vertices.Length < 3) { plane = new Plane(Vector3.up, 0f); return false; } if (vertices.Length == 3) { Vector3 a = vertices[0]; Vector3 b = vertices[1]; Vector3 c = vertices[2]; plane = new Plane(a, b, c); return plane.normal.sqrMagnitude > 0f; } Vector3 zero = Vector3.zero; int num = vertices.Length - 1; Vector3 vector = vertices[num]; for (int i = 0; i < vertices.Length; i++) { Vector3 vector2 = vertices[i]; zero.x += (vector.y - vector2.y) * (vector.z + vector2.z); zero.y += (vector.z - vector2.z) * (vector.x + vector2.x); zero.z += (vector.x - vector2.x) * (vector.y + vector2.y); vector = vector2; } zero.Normalize(); float num2 = 0f; foreach (Vector3 rhs in vertices) { num2 -= Vector3.Dot(zero, rhs); } num2 /= (float)vertices.Length; plane = new Plane(zero, num2); return plane.normal.sqrMagnitude > 0f; } public static bool TestPlanesAABB(Plane[] planes, Bounds bounds) { return TestPlanesAABB_Injected(planes, ref bounds); } [NativeName("ExtractPlanes")] private static void Internal_ExtractPlanes([Out] Plane[] planes, Matrix4x4 worldToProjectionMatrix) { Internal_ExtractPlanes_Injected(planes, ref worldToProjectionMatrix); } [NativeName("CalculateBounds")] private static Bounds Internal_CalculateBounds(Vector3[] positions, Matrix4x4 transform) { Internal_CalculateBounds_Injected(positions, ref transform, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool TestPlanesAABB_Injected(Plane[] planes, ref Bounds bounds); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_ExtractPlanes_Injected([Out] Plane[] planes, ref Matrix4x4 worldToProjectionMatrix); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_CalculateBounds_Injected(Vector3[] positions, ref Matrix4x4 transform, out Bounds ret); } [UsedByNativeCode] public struct Plane : IFormattable { internal const int size = 16; private Vector3 m_Normal; private float m_Distance; public Vector3 normal { get { return m_Normal; } set { m_Normal = value; } } public float distance { get { return m_Distance; } set { m_Distance = value; } } public Plane flipped => new Plane(-m_Normal, 0f - m_Distance); public Plane(Vector3 inNormal, Vector3 inPoint) { m_Normal = Vector3.Normalize(inNormal); m_Distance = 0f - Vector3.Dot(m_Normal, inPoint); } public Plane(Vector3 inNormal, float d) { m_Normal = Vector3.Normalize(inNormal); m_Distance = d; } public Plane(Vector3 a, Vector3 b, Vector3 c) { m_Normal = Vector3.Normalize(Vector3.Cross(b - a, c - a)); m_Distance = 0f - Vector3.Dot(m_Normal, a); } public void SetNormalAndPosition(Vector3 inNormal, Vector3 inPoint) { m_Normal = Vector3.Normalize(inNormal); m_Distance = 0f - Vector3.Dot(inNormal, inPoint); } public void Set3Points(Vector3 a, Vector3 b, Vector3 c) { m_Normal = Vector3.Normalize(Vector3.Cross(b - a, c - a)); m_Distance = 0f - Vector3.Dot(m_Normal, a); } public void Flip() { m_Normal = -m_Normal; m_Distance = 0f - m_Distance; } public void Translate(Vector3 translation) { m_Distance += Vector3.Dot(m_Normal, translation); } public static Plane Translate(Plane plane, Vector3 translation) { return new Plane(plane.m_Normal, plane.m_Distance += Vector3.Dot(plane.m_Normal, translation)); } public Vector3 ClosestPointOnPlane(Vector3 point) { float num = Vector3.Dot(m_Normal, point) + m_Distance; return point - m_Normal * num; } public float GetDistanceToPoint(Vector3 point) { return Vector3.Dot(m_Normal, point) + m_Distance; } public bool GetSide(Vector3 point) { return Vector3.Dot(m_Normal, point) + m_Distance > 0f; } public bool SameSide(Vector3 inPt0, Vector3 inPt1) { float distanceToPoint = GetDistanceToPoint(inPt0); float distanceToPoint2 = GetDistanceToPoint(inPt1); return (distanceToPoint > 0f && distanceToPoint2 > 0f) || (distanceToPoint <= 0f && distanceToPoint2 <= 0f); } public bool Raycast(Ray ray, out float enter) { float num = Vector3.Dot(ray.direction, m_Normal); float num2 = 0f - Vector3.Dot(ray.origin, m_Normal) - m_Distance; if (Mathf.Approximately(num, 0f)) { enter = 0f; return false; } enter = num2 / num; return enter > 0f; } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) { format = "F2"; } if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("(normal:{0}, distance:{1})", new object[2] { m_Normal.ToString(format, formatProvider), m_Distance.ToString(format, formatProvider) }); } } public struct Ray : IFormattable { private Vector3 m_Origin; private Vector3 m_Direction; public Vector3 origin { get { return m_Origin; } set { m_Origin = value; } } public Vector3 direction { get { return m_Direction; } set { m_Direction = value.normalized; } } public Ray(Vector3 origin, Vector3 direction) { m_Origin = origin; m_Direction = direction.normalized; } public Vector3 GetPoint(float distance) { return m_Origin + m_Direction * distance; } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) { format = "F2"; } if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("Origin: {0}, Dir: {1}", new object[2] { m_Origin.ToString(format, formatProvider), m_Direction.ToString(format, formatProvider) }); } } public struct Ray2D : IFormattable { private Vector2 m_Origin; private Vector2 m_Direction; public Vector2 origin { get { return m_Origin; } set { m_Origin = value; } } public Vector2 direction { get { return m_Direction; } set { m_Direction = value.normalized; } } public Ray2D(Vector2 origin, Vector2 direction) { m_Origin = origin; m_Direction = direction.normalized; } public Vector2 GetPoint(float distance) { return m_Origin + m_Direction * distance; } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) { format = "F2"; } if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("Origin: {0}, Dir: {1}", new object[2] { m_Origin.ToString(format, formatProvider), m_Direction.ToString(format, formatProvider) }); } } [NativeClass("Rectf", "template class RectT; typedef RectT Rectf;")] [RequiredByNativeCode(Optional = true, GenerateProxy = true)] [NativeHeader("Runtime/Math/Rect.h")] public struct Rect : IEquatable, IFormattable { [NativeName("x")] private float m_XMin; [NativeName("y")] private float m_YMin; [NativeName("width")] private float m_Width; [NativeName("height")] private float m_Height; public static Rect zero => new Rect(0f, 0f, 0f, 0f); public float x { get { return m_XMin; } set { m_XMin = value; } } public float y { get { return m_YMin; } set { m_YMin = value; } } public Vector2 position { get { return new Vector2(m_XMin, m_YMin); } set { m_XMin = value.x; m_YMin = value.y; } } public Vector2 center { get { return new Vector2(x + m_Width / 2f, y + m_Height / 2f); } set { m_XMin = value.x - m_Width / 2f; m_YMin = value.y - m_Height / 2f; } } public Vector2 min { get { return new Vector2(xMin, yMin); } set { xMin = value.x; yMin = value.y; } } public Vector2 max { get { return new Vector2(xMax, yMax); } set { xMax = value.x; yMax = value.y; } } public float width { get { return m_Width; } set { m_Width = value; } } public float height { get { return m_Height; } set { m_Height = value; } } public Vector2 size { get { return new Vector2(m_Width, m_Height); } set { m_Width = value.x; m_Height = value.y; } } public float xMin { get { return m_XMin; } set { float num = xMax; m_XMin = value; m_Width = num - m_XMin; } } public float yMin { get { return m_YMin; } set { float num = yMax; m_YMin = value; m_Height = num - m_YMin; } } public float xMax { get { return m_Width + m_XMin; } set { m_Width = value - m_XMin; } } public float yMax { get { return m_Height + m_YMin; } set { m_Height = value - m_YMin; } } [Obsolete("use xMin")] public float left => m_XMin; [Obsolete("use xMax")] public float right => m_XMin + m_Width; [Obsolete("use yMin")] public float top => m_YMin; [Obsolete("use yMax")] public float bottom => m_YMin + m_Height; public Rect(float x, float y, float width, float height) { m_XMin = x; m_YMin = y; m_Width = width; m_Height = height; } public Rect(Vector2 position, Vector2 size) { m_XMin = position.x; m_YMin = position.y; m_Width = size.x; m_Height = size.y; } public Rect(Rect source) { m_XMin = source.m_XMin; m_YMin = source.m_YMin; m_Width = source.m_Width; m_Height = source.m_Height; } public static Rect MinMaxRect(float xmin, float ymin, float xmax, float ymax) { return new Rect(xmin, ymin, xmax - xmin, ymax - ymin); } public void Set(float x, float y, float width, float height) { m_XMin = x; m_YMin = y; m_Width = width; m_Height = height; } public bool Contains(Vector2 point) { return point.x >= xMin && point.x < xMax && point.y >= yMin && point.y < yMax; } public bool Contains(Vector3 point) { return point.x >= xMin && point.x < xMax && point.y >= yMin && point.y < yMax; } public bool Contains(Vector3 point, bool allowInverse) { if (!allowInverse) { return Contains(point); } bool flag = (width < 0f && point.x <= xMin && point.x > xMax) || (width >= 0f && point.x >= xMin && point.x < xMax); bool flag2 = (height < 0f && point.y <= yMin && point.y > yMax) || (height >= 0f && point.y >= yMin && point.y < yMax); return flag && flag2; } private static Rect OrderMinMax(Rect rect) { if (rect.xMin > rect.xMax) { float num = rect.xMin; rect.xMin = rect.xMax; rect.xMax = num; } if (rect.yMin > rect.yMax) { float num2 = rect.yMin; rect.yMin = rect.yMax; rect.yMax = num2; } return rect; } public bool Overlaps(Rect other) { return other.xMax > xMin && other.xMin < xMax && other.yMax > yMin && other.yMin < yMax; } public bool Overlaps(Rect other, bool allowInverse) { Rect rect = this; if (allowInverse) { rect = OrderMinMax(rect); other = OrderMinMax(other); } return rect.Overlaps(other); } public static Vector2 NormalizedToPoint(Rect rectangle, Vector2 normalizedRectCoordinates) { return new Vector2(Mathf.Lerp(rectangle.x, rectangle.xMax, normalizedRectCoordinates.x), Mathf.Lerp(rectangle.y, rectangle.yMax, normalizedRectCoordinates.y)); } public static Vector2 PointToNormalized(Rect rectangle, Vector2 point) { return new Vector2(Mathf.InverseLerp(rectangle.x, rectangle.xMax, point.x), Mathf.InverseLerp(rectangle.y, rectangle.yMax, point.y)); } public static bool operator !=(Rect lhs, Rect rhs) { return !(lhs == rhs); } public static bool operator ==(Rect lhs, Rect rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.width == rhs.width && lhs.height == rhs.height; } public override int GetHashCode() { return x.GetHashCode() ^ (width.GetHashCode() << 2) ^ (y.GetHashCode() >> 2) ^ (height.GetHashCode() >> 1); } public override bool Equals(object other) { if (!(other is Rect)) { return false; } return Equals((Rect)other); } public bool Equals(Rect other) { return x.Equals(other.x) && y.Equals(other.y) && width.Equals(other.width) && height.Equals(other.height); } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) { format = "F2"; } if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("(x:{0}, y:{1}, width:{2}, height:{3})", new object[4] { x.ToString(format, formatProvider), y.ToString(format, formatProvider), width.ToString(format, formatProvider), height.ToString(format, formatProvider) }); } } [UsedByNativeCode] public struct RectInt : IEquatable, IFormattable { public struct PositionEnumerator : IEnumerator, IEnumerator, IDisposable { private readonly Vector2Int _min; private readonly Vector2Int _max; private Vector2Int _current; public Vector2Int Current => _current; object IEnumerator.Current => Current; public PositionEnumerator(Vector2Int min, Vector2Int max) { _min = (_current = min); _max = max; Reset(); } public PositionEnumerator GetEnumerator() { return this; } public bool MoveNext() { if (_current.y >= _max.y) { return false; } _current.x++; if (_current.x >= _max.x) { _current.x = _min.x; if (_current.x >= _max.x) { return false; } _current.y++; if (_current.y >= _max.y) { return false; } } return true; } public void Reset() { _current = _min; _current.x--; } void IDisposable.Dispose() { } } private int m_XMin; private int m_YMin; private int m_Width; private int m_Height; public int x { get { return m_XMin; } set { m_XMin = value; } } public int y { get { return m_YMin; } set { m_YMin = value; } } public Vector2 center => new Vector2((float)x + (float)m_Width / 2f, (float)y + (float)m_Height / 2f); public Vector2Int min { get { return new Vector2Int(xMin, yMin); } set { xMin = value.x; yMin = value.y; } } public Vector2Int max { get { return new Vector2Int(xMax, yMax); } set { xMax = value.x; yMax = value.y; } } public int width { get { return m_Width; } set { m_Width = value; } } public int height { get { return m_Height; } set { m_Height = value; } } public int xMin { get { return Math.Min(m_XMin, m_XMin + m_Width); } set { int num = xMax; m_XMin = value; m_Width = num - m_XMin; } } public int yMin { get { return Math.Min(m_YMin, m_YMin + m_Height); } set { int num = yMax; m_YMin = value; m_Height = num - m_YMin; } } public int xMax { get { return Math.Max(m_XMin, m_XMin + m_Width); } set { m_Width = value - m_XMin; } } public int yMax { get { return Math.Max(m_YMin, m_YMin + m_Height); } set { m_Height = value - m_YMin; } } public Vector2Int position { get { return new Vector2Int(m_XMin, m_YMin); } set { m_XMin = value.x; m_YMin = value.y; } } public Vector2Int size { get { return new Vector2Int(m_Width, m_Height); } set { m_Width = value.x; m_Height = value.y; } } public PositionEnumerator allPositionsWithin => new PositionEnumerator(min, max); public void SetMinMax(Vector2Int minPosition, Vector2Int maxPosition) { min = minPosition; max = maxPosition; } public RectInt(int xMin, int yMin, int width, int height) { m_XMin = xMin; m_YMin = yMin; m_Width = width; m_Height = height; } public RectInt(Vector2Int position, Vector2Int size) { m_XMin = position.x; m_YMin = position.y; m_Width = size.x; m_Height = size.y; } public void ClampToBounds(RectInt bounds) { position = new Vector2Int(Math.Max(Math.Min(bounds.xMax, position.x), bounds.xMin), Math.Max(Math.Min(bounds.yMax, position.y), bounds.yMin)); size = new Vector2Int(Math.Min(bounds.xMax - position.x, size.x), Math.Min(bounds.yMax - position.y, size.y)); } public bool Contains(Vector2Int position) { return position.x >= xMin && position.y >= yMin && position.x < xMax && position.y < yMax; } public bool Overlaps(RectInt other) { return other.xMin < xMax && other.xMax > xMin && other.yMin < yMax && other.yMax > yMin; } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("(x:{0}, y:{1}, width:{2}, height:{3})", new object[4] { x.ToString(format, formatProvider), y.ToString(format, formatProvider), width.ToString(format, formatProvider), height.ToString(format, formatProvider) }); } public bool Equals(RectInt other) { return m_XMin == other.m_XMin && m_YMin == other.m_YMin && m_Width == other.m_Width && m_Height == other.m_Height; } } [Serializable] [StructLayout(LayoutKind.Sequential)] [NativeHeader("Modules/IMGUI/GUIStyle.h")] [UsedByNativeCode] public class RectOffset : IFormattable { [NonSerialized] [VisibleToOtherModules(new string[] { "UnityEngine.IMGUIModule" })] internal IntPtr m_Ptr; private readonly object m_SourceStyle; [NativeProperty(/*Could not decode attribute arguments.*/)] public extern int left { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty(/*Could not decode attribute arguments.*/)] public extern int right { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty(/*Could not decode attribute arguments.*/)] public extern int top { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty(/*Could not decode attribute arguments.*/)] public extern int bottom { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int horizontal { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern int vertical { [MethodImpl(MethodImplOptions.InternalCall)] get; } public RectOffset() { m_Ptr = InternalCreate(); } [VisibleToOtherModules(new string[] { "UnityEngine.IMGUIModule" })] internal RectOffset(object sourceStyle, IntPtr source) { m_SourceStyle = sourceStyle; m_Ptr = source; } ~RectOffset() { if (m_SourceStyle == null) { Destroy(); } } public RectOffset(int left, int right, int top, int bottom) { m_Ptr = InternalCreate(); this.left = left; this.right = right; this.top = top; this.bottom = bottom; } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("RectOffset (l:{0} r:{1} t:{2} b:{3})", new object[4] { left.ToString(format, formatProvider), right.ToString(format, formatProvider), top.ToString(format, formatProvider), bottom.ToString(format, formatProvider) }); } private void Destroy() { if (m_Ptr != IntPtr.Zero) { InternalDestroy(m_Ptr); m_Ptr = IntPtr.Zero; } } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadAndSerializationSafe] private static extern IntPtr InternalCreate(); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadAndSerializationSafe] private static extern void InternalDestroy(IntPtr ptr); public Rect Add(Rect rect) { Add_Injected(ref rect, out var ret); return ret; } public Rect Remove(Rect rect) { Remove_Injected(ref rect, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] private extern void Add_Injected(ref Rect rect, out Rect ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Remove_Injected(ref Rect rect, out Rect ret); } [NativeHeader("Runtime/GI/DynamicGI.h")] public sealed class DynamicGI { public static extern float indirectScale { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern float updateThreshold { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int materialUpdateTimeSlice { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool synchronousMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool isConverged { [MethodImpl(MethodImplOptions.InternalCall)] get; } internal static extern int scheduledMaterialUpdatesCount { [MethodImpl(MethodImplOptions.InternalCall)] get; } internal static extern bool asyncMaterialUpdates { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static void SetEmissive(Renderer renderer, Color color) { SetEmissive_Injected(renderer, ref color); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] public static extern void SetEnvironmentData([NotNull("ArgumentNullException")] float[] input); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void UpdateEnvironment(); [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("DynamicGI.UpdateMaterials(Renderer) is deprecated; instead, use extension method from RendererExtensions: 'renderer.UpdateGIMaterials()' (UnityUpgradable).", true)] public static void UpdateMaterials(Renderer renderer) { } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("DynamicGI.UpdateMaterials(Terrain) is deprecated; instead, use extension method from TerrainExtensions: 'terrain.UpdateGIMaterials()' (UnityUpgradable).", true)] public static void UpdateMaterials(Object renderer) { } [Obsolete("DynamicGI.UpdateMaterials(Terrain, int, int, int, int) is deprecated; instead, use extension method from TerrainExtensions: 'terrain.UpdateGIMaterials(x, y, width, height)' (UnityUpgradable).", true)] [EditorBrowsable(EditorBrowsableState.Never)] public static void UpdateMaterials(Object renderer, int x, int y, int width, int height) { } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetEmissive_Injected(Renderer renderer, ref Color color); } [PreventReadOnlyInstanceModification] [NativeHeader("Runtime/Graphics/LightingSettings.h")] public sealed class LightingSettings : Object { [NativeName("EnableBakedLightmaps")] public extern bool bakedGI { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeName("EnableRealtimeLightmaps")] public extern bool realtimeGI { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeName("RealtimeEnvironmentLighting")] public extern bool realtimeEnvironmentLighting { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [RequiredByNativeCode] internal void LightingSettingsDontStripMe() { } public LightingSettings() { Internal_Create(this); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_Create([Writable] LightingSettings self); } [NativeHeader("Runtime/Export/Gizmos/Gizmos.bindings.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public sealed class Gizmos { public static Color color { get { get_color_Injected(out var ret); return ret; } set { set_color_Injected(ref value); } } public static Matrix4x4 matrix { get { get_matrix_Injected(out var ret); return ret; } set { set_matrix_Injected(ref value); } } public static extern Texture exposure { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern float probeSize { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeThrows] public static void DrawLine(Vector3 from, Vector3 to) { DrawLine_Injected(ref from, ref to); } [NativeThrows] public static void DrawWireSphere(Vector3 center, float radius) { DrawWireSphere_Injected(ref center, radius); } [NativeThrows] public static void DrawSphere(Vector3 center, float radius) { DrawSphere_Injected(ref center, radius); } [NativeThrows] public static void DrawWireCube(Vector3 center, Vector3 size) { DrawWireCube_Injected(ref center, ref size); } [NativeThrows] public static void DrawCube(Vector3 center, Vector3 size) { DrawCube_Injected(ref center, ref size); } [NativeThrows] public static void DrawMesh(Mesh mesh, int submeshIndex, [UnityEngine.Internal.DefaultValue("Vector3.zero")] Vector3 position, [UnityEngine.Internal.DefaultValue("Quaternion.identity")] Quaternion rotation, [UnityEngine.Internal.DefaultValue("Vector3.one")] Vector3 scale) { DrawMesh_Injected(mesh, submeshIndex, ref position, ref rotation, ref scale); } [NativeThrows] public static void DrawWireMesh(Mesh mesh, int submeshIndex, [UnityEngine.Internal.DefaultValue("Vector3.zero")] Vector3 position, [UnityEngine.Internal.DefaultValue("Quaternion.identity")] Quaternion rotation, [UnityEngine.Internal.DefaultValue("Vector3.one")] Vector3 scale) { DrawWireMesh_Injected(mesh, submeshIndex, ref position, ref rotation, ref scale); } [NativeThrows] public static void DrawIcon(Vector3 center, string name, [UnityEngine.Internal.DefaultValue("true")] bool allowScaling) { DrawIcon(center, name, allowScaling, Color.white); } [NativeThrows] public static void DrawIcon(Vector3 center, string name, [UnityEngine.Internal.DefaultValue("true")] bool allowScaling, [UnityEngine.Internal.DefaultValue("Color(255,255,255,255)")] Color tint) { DrawIcon_Injected(ref center, name, allowScaling, ref tint); } [NativeThrows] public static void DrawGUITexture(Rect screenRect, Texture texture, int leftBorder, int rightBorder, int topBorder, int bottomBorder, [UnityEngine.Internal.DefaultValue("null")] Material mat) { DrawGUITexture_Injected(ref screenRect, texture, leftBorder, rightBorder, topBorder, bottomBorder, mat); } public static void DrawFrustum(Vector3 center, float fov, float maxRange, float minRange, float aspect) { DrawFrustum_Injected(ref center, fov, maxRange, minRange, aspect); } public static void DrawRay(Ray r) { DrawLine(r.origin, r.origin + r.direction); } public static void DrawRay(Vector3 from, Vector3 direction) { DrawLine(from, from + direction); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation) { Vector3 one = Vector3.one; DrawMesh(mesh, position, rotation, one); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position) { Vector3 one = Vector3.one; Quaternion identity = Quaternion.identity; DrawMesh(mesh, position, identity, one); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh) { Vector3 one = Vector3.one; Quaternion identity = Quaternion.identity; Vector3 zero = Vector3.zero; DrawMesh(mesh, zero, identity, one); } public static void DrawMesh(Mesh mesh, [UnityEngine.Internal.DefaultValue("Vector3.zero")] Vector3 position, [UnityEngine.Internal.DefaultValue("Quaternion.identity")] Quaternion rotation, [UnityEngine.Internal.DefaultValue("Vector3.one")] Vector3 scale) { DrawMesh(mesh, -1, position, rotation, scale); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, int submeshIndex, Vector3 position, Quaternion rotation) { Vector3 one = Vector3.one; DrawMesh(mesh, submeshIndex, position, rotation, one); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, int submeshIndex, Vector3 position) { Vector3 one = Vector3.one; Quaternion identity = Quaternion.identity; DrawMesh(mesh, submeshIndex, position, identity, one); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, int submeshIndex) { Vector3 one = Vector3.one; Quaternion identity = Quaternion.identity; Vector3 zero = Vector3.zero; DrawMesh(mesh, submeshIndex, zero, identity, one); } [ExcludeFromDocs] public static void DrawWireMesh(Mesh mesh, Vector3 position, Quaternion rotation) { Vector3 one = Vector3.one; DrawWireMesh(mesh, position, rotation, one); } [ExcludeFromDocs] public static void DrawWireMesh(Mesh mesh, Vector3 position) { Vector3 one = Vector3.one; Quaternion identity = Quaternion.identity; DrawWireMesh(mesh, position, identity, one); } [ExcludeFromDocs] public static void DrawWireMesh(Mesh mesh) { Vector3 one = Vector3.one; Quaternion identity = Quaternion.identity; Vector3 zero = Vector3.zero; DrawWireMesh(mesh, zero, identity, one); } public static void DrawWireMesh(Mesh mesh, [UnityEngine.Internal.DefaultValue("Vector3.zero")] Vector3 position, [UnityEngine.Internal.DefaultValue("Quaternion.identity")] Quaternion rotation, [UnityEngine.Internal.DefaultValue("Vector3.one")] Vector3 scale) { DrawWireMesh(mesh, -1, position, rotation, scale); } [ExcludeFromDocs] public static void DrawWireMesh(Mesh mesh, int submeshIndex, Vector3 position, Quaternion rotation) { Vector3 one = Vector3.one; DrawWireMesh(mesh, submeshIndex, position, rotation, one); } [ExcludeFromDocs] public static void DrawWireMesh(Mesh mesh, int submeshIndex, Vector3 position) { Vector3 one = Vector3.one; Quaternion identity = Quaternion.identity; DrawWireMesh(mesh, submeshIndex, position, identity, one); } [ExcludeFromDocs] public static void DrawWireMesh(Mesh mesh, int submeshIndex) { Vector3 one = Vector3.one; Quaternion identity = Quaternion.identity; Vector3 zero = Vector3.zero; DrawWireMesh(mesh, submeshIndex, zero, identity, one); } [ExcludeFromDocs] public static void DrawIcon(Vector3 center, string name) { bool allowScaling = true; DrawIcon(center, name, allowScaling); } [ExcludeFromDocs] public static void DrawGUITexture(Rect screenRect, Texture texture) { Material mat = null; DrawGUITexture(screenRect, texture, mat); } public static void DrawGUITexture(Rect screenRect, Texture texture, [UnityEngine.Internal.DefaultValue("null")] Material mat) { DrawGUITexture(screenRect, texture, 0, 0, 0, 0, mat); } [ExcludeFromDocs] public static void DrawGUITexture(Rect screenRect, Texture texture, int leftBorder, int rightBorder, int topBorder, int bottomBorder) { Material mat = null; DrawGUITexture(screenRect, texture, leftBorder, rightBorder, topBorder, bottomBorder, mat); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawLine_Injected(ref Vector3 from, ref Vector3 to); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawWireSphere_Injected(ref Vector3 center, float radius); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawSphere_Injected(ref Vector3 center, float radius); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawWireCube_Injected(ref Vector3 center, ref Vector3 size); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawCube_Injected(ref Vector3 center, ref Vector3 size); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawMesh_Injected(Mesh mesh, int submeshIndex, [UnityEngine.Internal.DefaultValue("Vector3.zero")] ref Vector3 position, [UnityEngine.Internal.DefaultValue("Quaternion.identity")] ref Quaternion rotation, [UnityEngine.Internal.DefaultValue("Vector3.one")] ref Vector3 scale); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawWireMesh_Injected(Mesh mesh, int submeshIndex, [UnityEngine.Internal.DefaultValue("Vector3.zero")] ref Vector3 position, [UnityEngine.Internal.DefaultValue("Quaternion.identity")] ref Quaternion rotation, [UnityEngine.Internal.DefaultValue("Vector3.one")] ref Vector3 scale); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawIcon_Injected(ref Vector3 center, string name, [UnityEngine.Internal.DefaultValue("true")] bool allowScaling, [UnityEngine.Internal.DefaultValue("Color(255,255,255,255)")] ref Color tint); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawGUITexture_Injected(ref Rect screenRect, Texture texture, int leftBorder, int rightBorder, int topBorder, int bottomBorder, [UnityEngine.Internal.DefaultValue("null")] Material mat); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_color_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_color_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_matrix_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_matrix_Injected(ref Matrix4x4 value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawFrustum_Injected(ref Vector3 center, float fov, float maxRange, float minRange, float aspect); } [AttributeUsage(AttributeTargets.Method)] public class BeforeRenderOrderAttribute : Attribute { public int order { get; private set; } public BeforeRenderOrderAttribute(int order) { this.order = order; } } internal static class BeforeRenderHelper { private struct OrderBlock { internal int order; internal UnityAction callback; } private static List s_OrderBlocks = new List(); private static int GetUpdateOrder(UnityAction callback) { object[] customAttributes = callback.Method.GetCustomAttributes(typeof(BeforeRenderOrderAttribute), inherit: true); return ((customAttributes != null && customAttributes.Length != 0) ? (customAttributes[0] as BeforeRenderOrderAttribute) : null)?.order ?? 0; } public static void RegisterCallback(UnityAction callback) { int updateOrder = GetUpdateOrder(callback); lock (s_OrderBlocks) { int i; for (i = 0; i < s_OrderBlocks.Count && s_OrderBlocks[i].order <= updateOrder; i++) { if (s_OrderBlocks[i].order == updateOrder) { OrderBlock value = s_OrderBlocks[i]; ref UnityAction callback2 = ref value.callback; callback2 = (UnityAction)Delegate.Combine(callback2, callback); s_OrderBlocks[i] = value; return; } } OrderBlock item = new OrderBlock { order = updateOrder }; ref UnityAction callback3 = ref item.callback; callback3 = (UnityAction)Delegate.Combine(callback3, callback); s_OrderBlocks.Insert(i, item); } } public static void UnregisterCallback(UnityAction callback) { int updateOrder = GetUpdateOrder(callback); lock (s_OrderBlocks) { for (int i = 0; i < s_OrderBlocks.Count && s_OrderBlocks[i].order <= updateOrder; i++) { if (s_OrderBlocks[i].order == updateOrder) { OrderBlock value = s_OrderBlocks[i]; ref UnityAction callback2 = ref value.callback; callback2 = (UnityAction)Delegate.Remove(callback2, callback); s_OrderBlocks[i] = value; if (value.callback == null) { s_OrderBlocks.RemoveAt(i); } break; } } } } public static void Invoke() { lock (s_OrderBlocks) { for (int i = 0; i < s_OrderBlocks.Count; i++) { s_OrderBlocks[i].callback?.Invoke(); } } } } [NativeHeader("Runtime/Graphics/Billboard/BillboardAsset.h")] [NativeHeader("Runtime/Export/Graphics/BillboardRenderer.bindings.h")] public sealed class BillboardAsset : Object { public extern float width { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float height { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float bottom { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int imageCount { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetNumImages")] get; } public extern int vertexCount { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetNumVertices")] get; } public extern int indexCount { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetNumIndices")] get; } public extern Material material { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public BillboardAsset() { Internal_Create(this); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "BillboardRenderer_Bindings::Internal_Create")] private static extern void Internal_Create([Writable] BillboardAsset obj); public void GetImageTexCoords(List imageTexCoords) { if (imageTexCoords == null) { throw new ArgumentNullException("imageTexCoords"); } GetImageTexCoordsInternal(imageTexCoords); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetBillboardDataReadonly().GetImageTexCoords")] public extern Vector4[] GetImageTexCoords(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "BillboardRenderer_Bindings::GetImageTexCoordsInternal", HasExplicitThis = true)] internal extern void GetImageTexCoordsInternal(object list); public void SetImageTexCoords(List imageTexCoords) { if (imageTexCoords == null) { throw new ArgumentNullException("imageTexCoords"); } SetImageTexCoordsInternalList(imageTexCoords); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "BillboardRenderer_Bindings::SetImageTexCoords", HasExplicitThis = true)] public extern void SetImageTexCoords([Unmarshalled][NotNull("ArgumentNullException")] Vector4[] imageTexCoords); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "BillboardRenderer_Bindings::SetImageTexCoordsInternalList", HasExplicitThis = true)] internal extern void SetImageTexCoordsInternalList(object list); public void GetVertices(List vertices) { if (vertices == null) { throw new ArgumentNullException("vertices"); } GetVerticesInternal(vertices); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetBillboardDataReadonly().GetVertices")] public extern Vector2[] GetVertices(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "BillboardRenderer_Bindings::GetVerticesInternal", HasExplicitThis = true)] internal extern void GetVerticesInternal(object list); public void SetVertices(List vertices) { if (vertices == null) { throw new ArgumentNullException("vertices"); } SetVerticesInternalList(vertices); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "BillboardRenderer_Bindings::SetVertices", HasExplicitThis = true)] public extern void SetVertices([NotNull("ArgumentNullException")][Unmarshalled] Vector2[] vertices); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "BillboardRenderer_Bindings::SetVerticesInternalList", HasExplicitThis = true)] internal extern void SetVerticesInternalList(object list); public void GetIndices(List indices) { if (indices == null) { throw new ArgumentNullException("indices"); } GetIndicesInternal(indices); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetBillboardDataReadonly().GetIndices")] public extern ushort[] GetIndices(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "BillboardRenderer_Bindings::GetIndicesInternal", HasExplicitThis = true)] internal extern void GetIndicesInternal(object list); public void SetIndices(List indices) { if (indices == null) { throw new ArgumentNullException("indices"); } SetIndicesInternalList(indices); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "BillboardRenderer_Bindings::SetIndices", HasExplicitThis = true)] public extern void SetIndices([NotNull("ArgumentNullException")][Unmarshalled] ushort[] indices); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "BillboardRenderer_Bindings::SetIndicesInternalList", HasExplicitThis = true)] internal extern void SetIndicesInternalList(object list); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "BillboardRenderer_Bindings::MakeMaterialProperties", HasExplicitThis = true)] internal extern void MakeMaterialProperties(MaterialPropertyBlock properties, Camera camera); } [NativeHeader("Runtime/Graphics/Billboard/BillboardRenderer.h")] public sealed class BillboardRenderer : Renderer { public extern BillboardAsset billboard { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } } [NativeHeader("Runtime/Graphics/CustomRenderTextureManager.h")] public static class CustomRenderTextureManager { public static event Action textureLoaded; public static event Action textureUnloaded; public static event Action updateTriggered; public static event Action initializeTriggered; [RequiredByNativeCode] private static void InvokeOnTextureLoaded_Internal(CustomRenderTexture source) { CustomRenderTextureManager.textureLoaded?.Invoke(source); } [RequiredByNativeCode] private static void InvokeOnTextureUnloaded_Internal(CustomRenderTexture source) { CustomRenderTextureManager.textureUnloaded?.Invoke(source); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CustomRenderTextureManagerScripting::GetAllCustomRenderTextures", HasExplicitThis = false)] public static extern void GetAllCustomRenderTextures(List currentCustomRenderTextures); internal static void InvokeTriggerUpdate(CustomRenderTexture crt, int updateCount) { CustomRenderTextureManager.updateTriggered?.Invoke(crt, updateCount); } internal static void InvokeTriggerInitialize(CustomRenderTexture crt) { CustomRenderTextureManager.initializeTriggered?.Invoke(crt); } } [UsedByNativeCode] [NativeHeader("Runtime/Graphics/DisplayManager.h")] public class Display { public delegate void DisplaysUpdatedDelegate(); internal IntPtr nativeDisplay; public static Display[] displays = new Display[1] { new Display() }; private static Display _mainDisplay = displays[0]; private static int m_ActiveEditorGameViewTarget = -1; public int renderingWidth { get { int w = 0; int h = 0; GetRenderingExtImpl(nativeDisplay, out w, out h); return w; } } public int renderingHeight { get { int w = 0; int h = 0; GetRenderingExtImpl(nativeDisplay, out w, out h); return h; } } public int systemWidth { get { int w = 0; int h = 0; GetSystemExtImpl(nativeDisplay, out w, out h); return w; } } public int systemHeight { get { int w = 0; int h = 0; GetSystemExtImpl(nativeDisplay, out w, out h); return h; } } public RenderBuffer colorBuffer { get { GetRenderingBuffersImpl(nativeDisplay, out var color, out var _); return color; } } public RenderBuffer depthBuffer { get { GetRenderingBuffersImpl(nativeDisplay, out var _, out var depth); return depth; } } public bool active => GetActiveImpl(nativeDisplay); public bool requiresBlitToBackbuffer { get { int num = nativeDisplay.ToInt32(); if (num < HDROutputSettings.displays.Length && HDROutputSettings.displays[num].available && HDROutputSettings.displays[num].active) { return true; } return RequiresBlitToBackbufferImpl(nativeDisplay); } } public bool requiresSrgbBlitToBackbuffer => RequiresSrgbBlitToBackbufferImpl(nativeDisplay); public static Display main => _mainDisplay; public static int activeEditorGameViewTarget { get { return m_ActiveEditorGameViewTarget; } internal set { m_ActiveEditorGameViewTarget = value; } } public static event DisplaysUpdatedDelegate onDisplaysUpdated; internal Display() { nativeDisplay = new IntPtr(0); } internal Display(IntPtr nativeDisplay) { this.nativeDisplay = nativeDisplay; } public void Activate() { ActivateDisplayImpl(nativeDisplay, 0, 0, 60); } public void Activate(int width, int height, int refreshRate) { ActivateDisplayImpl(nativeDisplay, width, height, refreshRate); } public void SetParams(int width, int height, int x, int y) { SetParamsImpl(nativeDisplay, width, height, x, y); } public void SetRenderingResolution(int w, int h) { SetRenderingResolutionImpl(nativeDisplay, w, h); } [Obsolete("MultiDisplayLicense has been deprecated.", false)] public static bool MultiDisplayLicense() { return true; } public static Vector3 RelativeMouseAt(Vector3 inputMouseCoordinates) { int rx = 0; int ry = 0; int x = (int)inputMouseCoordinates.x; int y = (int)inputMouseCoordinates.y; Vector3 result = default(Vector3); result.z = RelativeMouseAtImpl(x, y, out rx, out ry); result.x = rx; result.y = ry; return result; } [RequiredByNativeCode] private static void RecreateDisplayList(IntPtr[] nativeDisplay) { if (nativeDisplay.Length != 0) { displays = new Display[nativeDisplay.Length]; for (int i = 0; i < nativeDisplay.Length; i++) { displays[i] = new Display(nativeDisplay[i]); } _mainDisplay = displays[0]; } } [RequiredByNativeCode] private static void FireDisplaysUpdated() { if (Display.onDisplaysUpdated != null) { Display.onDisplaysUpdated(); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityDisplayManager_DisplaySystemResolution")] private static extern void GetSystemExtImpl(IntPtr nativeDisplay, out int w, out int h); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityDisplayManager_DisplayRenderingResolution")] private static extern void GetRenderingExtImpl(IntPtr nativeDisplay, out int w, out int h); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityDisplayManager_GetRenderingBuffersWrapper")] private static extern void GetRenderingBuffersImpl(IntPtr nativeDisplay, out RenderBuffer color, out RenderBuffer depth); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityDisplayManager_SetRenderingResolution")] private static extern void SetRenderingResolutionImpl(IntPtr nativeDisplay, int w, int h); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityDisplayManager_ActivateDisplay")] private static extern void ActivateDisplayImpl(IntPtr nativeDisplay, int width, int height, int refreshRate); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityDisplayManager_SetDisplayParam")] private static extern void SetParamsImpl(IntPtr nativeDisplay, int width, int height, int x, int y); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityDisplayManager_RelativeMouseAt")] private static extern int RelativeMouseAtImpl(int x, int y, out int rx, out int ry); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityDisplayManager_DisplayActive")] private static extern bool GetActiveImpl(IntPtr nativeDisplay); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityDisplayManager_RequiresBlitToBackbuffer")] private static extern bool RequiresBlitToBackbufferImpl(IntPtr nativeDisplay); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityDisplayManager_RequiresSRGBBlitToBackbuffer")] private static extern bool RequiresSrgbBlitToBackbufferImpl(IntPtr nativeDisplay); static Display() { Display.onDisplaysUpdated = null; } } internal enum EnabledOrientation { kAutorotateToPortrait = 1, kAutorotateToPortraitUpsideDown = 2, kAutorotateToLandscapeLeft = 4, kAutorotateToLandscapeRight = 8 } public enum FullScreenMode { ExclusiveFullScreen, FullScreenWindow, MaximizedWindow, Windowed } [NativeType("Runtime/Graphics/RefreshRate.h")] public struct RefreshRate : IEquatable { [UnityEngine.Scripting.RequiredMember] public uint numerator; [UnityEngine.Scripting.RequiredMember] public uint denominator; public double value { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (double)numerator / (double)denominator; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(RefreshRate other) { return numerator == other.numerator && denominator == other.denominator; } } [UsedByNativeCode] [NativeType("Runtime/Graphics/DisplayInfo.h")] public struct DisplayInfo : IEquatable { [UnityEngine.Scripting.RequiredMember] internal ulong handle; [UnityEngine.Scripting.RequiredMember] public int width; [UnityEngine.Scripting.RequiredMember] public int height; [UnityEngine.Scripting.RequiredMember] public RefreshRate refreshRate; [UnityEngine.Scripting.RequiredMember] public RectInt workArea; [UnityEngine.Scripting.RequiredMember] public string name; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(DisplayInfo other) { return handle == other.handle && width == other.width && height == other.height && refreshRate.Equals(other.refreshRate) && workArea.Equals(other.workArea) && name == other.name; } } public sealed class SleepTimeout { public const int NeverSleep = -1; public const int SystemSetting = -2; } [NativeHeader("Runtime/Graphics/WindowLayout.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("Runtime/Graphics/GraphicsScriptBindings.h")] [NativeHeader("Runtime/Graphics/ScreenManager.h")] public sealed class Screen { public static extern int width { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GetWidth", IsThreadSafe = true)] get; } public static extern int height { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GetHeight", IsThreadSafe = true)] get; } public static extern float dpi { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetDPI")] get; } public static ScreenOrientation orientation { get { return GetScreenOrientation(); } set { if (value == ScreenOrientation.Unknown) { Debug.Log("ScreenOrientation.Unknown is deprecated. Please use ScreenOrientation.AutoRotation"); value = ScreenOrientation.AutoRotation; } RequestOrientation(value); } } [NativeProperty("ScreenTimeout")] public static extern int sleepTimeout { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static bool autorotateToPortrait { get { return IsOrientationEnabled(EnabledOrientation.kAutorotateToPortrait); } set { SetOrientationEnabled(EnabledOrientation.kAutorotateToPortrait, value); } } public static bool autorotateToPortraitUpsideDown { get { return IsOrientationEnabled(EnabledOrientation.kAutorotateToPortraitUpsideDown); } set { SetOrientationEnabled(EnabledOrientation.kAutorotateToPortraitUpsideDown, value); } } public static bool autorotateToLandscapeLeft { get { return IsOrientationEnabled(EnabledOrientation.kAutorotateToLandscapeLeft); } set { SetOrientationEnabled(EnabledOrientation.kAutorotateToLandscapeLeft, value); } } public static bool autorotateToLandscapeRight { get { return IsOrientationEnabled(EnabledOrientation.kAutorotateToLandscapeRight); } set { SetOrientationEnabled(EnabledOrientation.kAutorotateToLandscapeRight, value); } } public static Resolution currentResolution { get { get_currentResolution_Injected(out var ret); return ret; } } public static extern bool fullScreen { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("IsFullscreen")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("RequestSetFullscreenFromScript")] set; } public static extern FullScreenMode fullScreenMode { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetFullscreenMode")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("RequestSetFullscreenModeFromScript")] set; } public static Rect safeArea { get { get_safeArea_Injected(out var ret); return ret; } } public static extern Rect[] cutouts { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScreenScripting::GetCutouts")] get; } public static Vector2Int mainWindowPosition => GetMainWindowPosition(); public static DisplayInfo mainWindowDisplayInfo => GetMainWindowDisplayInfo(); public static extern Resolution[] resolutions { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScreenScripting::GetResolutions")] get; } public static extern float brightness { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [Obsolete("Use Cursor.lockState and Cursor.visible instead.", false)] [EditorBrowsable(EditorBrowsableState.Never)] public static bool lockCursor { get { return CursorLockMode.Locked == Cursor.lockState; } set { if (value) { Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; } else { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; } } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void RequestOrientation(ScreenOrientation orient); [MethodImpl(MethodImplOptions.InternalCall)] private static extern ScreenOrientation GetScreenOrientation(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetIsOrientationEnabled")] private static extern bool IsOrientationEnabled(EnabledOrientation orient); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetIsOrientationEnabled")] private static extern void SetOrientationEnabled(EnabledOrientation orient, bool enabled); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("RequestResolution")] public static extern void SetResolution(int width, int height, FullScreenMode fullscreenMode, [UnityEngine.Internal.DefaultValue("0")] int preferredRefreshRate); public static void SetResolution(int width, int height, FullScreenMode fullscreenMode) { SetResolution(width, height, fullscreenMode, 0); } public static void SetResolution(int width, int height, bool fullscreen, [UnityEngine.Internal.DefaultValue("0")] int preferredRefreshRate) { SetResolution(width, height, fullscreen ? FullScreenMode.FullScreenWindow : FullScreenMode.Windowed, preferredRefreshRate); } public static void SetResolution(int width, int height, bool fullscreen) { SetResolution(width, height, fullscreen, 0); } public static void GetDisplayLayout(List displayLayout) { if (displayLayout == null) { throw new ArgumentNullException(); } GetDisplayLayoutImpl(displayLayout); } public static AsyncOperation MoveMainWindowTo(in DisplayInfo display, Vector2Int position) { return MoveMainWindowImpl(in display, position); } [FreeFunction("GetMainWindowPosition")] private static Vector2Int GetMainWindowPosition() { GetMainWindowPosition_Injected(out var ret); return ret; } [FreeFunction("GetMainWindowDisplayInfo")] private static DisplayInfo GetMainWindowDisplayInfo() { GetMainWindowDisplayInfo_Injected(out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetDisplayLayout")] private static extern void GetDisplayLayoutImpl(List displayLayout); [FreeFunction("MoveMainWindow")] private static AsyncOperation MoveMainWindowImpl(in DisplayInfo display, Vector2Int position) { return MoveMainWindowImpl_Injected(in display, ref position); } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_currentResolution_Injected(out Resolution ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_safeArea_Injected(out Rect ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetMainWindowPosition_Injected(out Vector2Int ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetMainWindowDisplayInfo_Injected(out DisplayInfo ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern AsyncOperation MoveMainWindowImpl_Injected(in DisplayInfo display, ref Vector2Int position); } [NativeHeader("Runtime/Graphics/GraphicsScriptBindings.h")] public struct RenderBuffer { internal int m_RenderTextureInstanceID; internal IntPtr m_BufferPtr; internal RenderBufferLoadAction loadAction { get { return GetLoadAction(); } set { SetLoadAction(value); } } internal RenderBufferStoreAction storeAction { get { return GetStoreAction(); } set { SetStoreAction(value); } } [FreeFunction(Name = "RenderBufferScripting::SetLoadAction", HasExplicitThis = true)] internal void SetLoadAction(RenderBufferLoadAction action) { SetLoadAction_Injected(ref this, action); } [FreeFunction(Name = "RenderBufferScripting::SetStoreAction", HasExplicitThis = true)] internal void SetStoreAction(RenderBufferStoreAction action) { SetStoreAction_Injected(ref this, action); } [FreeFunction(Name = "RenderBufferScripting::GetLoadAction", HasExplicitThis = true)] internal RenderBufferLoadAction GetLoadAction() { return GetLoadAction_Injected(ref this); } [FreeFunction(Name = "RenderBufferScripting::GetStoreAction", HasExplicitThis = true)] internal RenderBufferStoreAction GetStoreAction() { return GetStoreAction_Injected(ref this); } [FreeFunction(Name = "RenderBufferScripting::GetNativeRenderBufferPtr", HasExplicitThis = true)] public IntPtr GetNativeRenderBufferPtr() { return GetNativeRenderBufferPtr_Injected(ref this); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetLoadAction_Injected(ref RenderBuffer _unity_self, RenderBufferLoadAction action); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetStoreAction_Injected(ref RenderBuffer _unity_self, RenderBufferStoreAction action); [MethodImpl(MethodImplOptions.InternalCall)] private static extern RenderBufferLoadAction GetLoadAction_Injected(ref RenderBuffer _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern RenderBufferStoreAction GetStoreAction_Injected(ref RenderBuffer _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr GetNativeRenderBufferPtr_Injected(ref RenderBuffer _unity_self); } [NativeType("Runtime/GfxDevice/GfxDeviceTypes.h")] public enum ComputeBufferMode { Immutable, Dynamic, [Obsolete("ComputeBufferMode.Circular is deprecated (legacy mode)")] Circular, [Obsolete("ComputeBufferMode.StreamOut is deprecated (internal use only)")] StreamOut, SubUpdates } [NativeHeader("Runtime/Camera/LightProbeProxyVolume.h")] [NativeHeader("Runtime/Graphics/CopyTexture.h")] [NativeHeader("Runtime/Graphics/GraphicsScriptBindings.h")] [NativeHeader("Runtime/Shaders/ComputeShader.h")] [NativeHeader("Runtime/Misc/PlayerSettings.h")] [NativeHeader("Runtime/Graphics/ColorGamut.h")] public class Graphics { internal static readonly int kMaxDrawMeshInstanceCount = Internal_GetMaxDrawMeshInstanceCount(); internal static Dictionary s_RenderInstancedDataLayouts = new Dictionary(); public static ColorGamut activeColorGamut => GetActiveColorGamut(); [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern GraphicsTier activeTier { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static bool preserveFramebufferAlpha => GetPreserveFramebufferAlpha(); public static OpenGLESVersion minOpenGLESVersion => GetMinOpenGLESVersion(); public static RenderBuffer activeColorBuffer => GetActiveColorBuffer(); public static RenderBuffer activeDepthBuffer => GetActiveDepthBuffer(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::GetMaxDrawMeshInstanceCount")] private static extern int Internal_GetMaxDrawMeshInstanceCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern ColorGamut GetActiveColorGamut(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GetPreserveFramebufferAlpha")] [StaticAccessor(/*Could not decode attribute arguments.*/)] internal static extern bool GetPreserveFramebufferAlpha(); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeMethod(Name = "GetMinOpenGLESVersion")] internal static extern OpenGLESVersion GetMinOpenGLESVersion(); [FreeFunction("GraphicsScripting::GetActiveColorBuffer")] private static RenderBuffer GetActiveColorBuffer() { GetActiveColorBuffer_Injected(out var ret); return ret; } [FreeFunction("GraphicsScripting::GetActiveDepthBuffer")] private static RenderBuffer GetActiveDepthBuffer() { GetActiveDepthBuffer_Injected(out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::SetNullRT")] private static extern void Internal_SetNullRT(); [NativeMethod(Name = "GraphicsScripting::SetRTSimple", IsFreeFunction = true, ThrowsException = true)] private static void Internal_SetRTSimple(RenderBuffer color, RenderBuffer depth, int mip, CubemapFace face, int depthSlice) { Internal_SetRTSimple_Injected(ref color, ref depth, mip, face, depthSlice); } [NativeMethod(Name = "GraphicsScripting::SetMRTSimple", IsFreeFunction = true, ThrowsException = true)] private static void Internal_SetMRTSimple([NotNull("ArgumentNullException")] RenderBuffer[] color, RenderBuffer depth, int mip, CubemapFace face, int depthSlice) { Internal_SetMRTSimple_Injected(color, ref depth, mip, face, depthSlice); } [NativeMethod(Name = "GraphicsScripting::SetMRTFull", IsFreeFunction = true, ThrowsException = true)] private static void Internal_SetMRTFullSetup([NotNull("ArgumentNullException")] RenderBuffer[] color, RenderBuffer depth, int mip, CubemapFace face, int depthSlice, [NotNull("ArgumentNullException")] RenderBufferLoadAction[] colorLA, [NotNull("ArgumentNullException")] RenderBufferStoreAction[] colorSA, RenderBufferLoadAction depthLA, RenderBufferStoreAction depthSA) { Internal_SetMRTFullSetup_Injected(color, ref depth, mip, face, depthSlice, colorLA, colorSA, depthLA, depthSA); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GraphicsScripting::SetRandomWriteTargetRT", IsFreeFunction = true, ThrowsException = true)] private static extern void Internal_SetRandomWriteTargetRT(int index, RenderTexture uav); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::SetRandomWriteTargetBuffer")] private static extern void Internal_SetRandomWriteTargetBuffer(int index, ComputeBuffer uav, bool preserveCounterValue); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::SetRandomWriteTargetBuffer")] private static extern void Internal_SetRandomWriteTargetGraphicsBuffer(int index, GraphicsBuffer uav, bool preserveCounterValue); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern void ClearRandomWriteTargets(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CopyTexture")] private static extern void CopyTexture_Full(Texture src, Texture dst); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CopyTexture")] private static extern void CopyTexture_Slice_AllMips(Texture src, int srcElement, Texture dst, int dstElement); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CopyTexture")] private static extern void CopyTexture_Slice(Texture src, int srcElement, int srcMip, Texture dst, int dstElement, int dstMip); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CopyTexture")] private static extern void CopyTexture_Region(Texture src, int srcElement, int srcMip, int srcX, int srcY, int srcWidth, int srcHeight, Texture dst, int dstElement, int dstMip, int dstX, int dstY); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ConvertTexture")] private static extern bool ConvertTexture_Full(Texture src, Texture dst); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ConvertTexture")] private static extern bool ConvertTexture_Slice(Texture src, int srcElement, Texture dst, int dstElement); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::CopyBuffer", ThrowsException = true)] private static extern void CopyBufferImpl([NotNull("ArgumentNullException")] GraphicsBuffer source, [NotNull("ArgumentNullException")] GraphicsBuffer dest); [FreeFunction("GraphicsScripting::DrawMeshNow")] private static void Internal_DrawMeshNow1([NotNull("NullExceptionObject")] Mesh mesh, int subsetIndex, Vector3 position, Quaternion rotation) { Internal_DrawMeshNow1_Injected(mesh, subsetIndex, ref position, ref rotation); } [FreeFunction("GraphicsScripting::DrawMeshNow")] private static void Internal_DrawMeshNow2([NotNull("NullExceptionObject")] Mesh mesh, int subsetIndex, Matrix4x4 matrix) { Internal_DrawMeshNow2_Injected(mesh, subsetIndex, ref matrix); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::DrawTexture")] [VisibleToOtherModules(new string[] { "UnityEngine.IMGUIModule" })] internal static extern void Internal_DrawTexture(ref Internal_DrawTextureArguments args); [FreeFunction("GraphicsScripting::RenderMesh")] private unsafe static void Internal_RenderMesh(RenderParams rparams, [NotNull("NullExceptionObject")] Mesh mesh, int submeshIndex, Matrix4x4 objectToWorld, Matrix4x4* prevObjectToWorld) { Internal_RenderMesh_Injected(ref rparams, mesh, submeshIndex, ref objectToWorld, prevObjectToWorld); } [FreeFunction("GraphicsScripting::RenderMeshInstanced")] private static void Internal_RenderMeshInstanced(RenderParams rparams, [NotNull("NullExceptionObject")] Mesh mesh, int submeshIndex, IntPtr instanceData, RenderInstancedDataLayout layout, uint instanceCount) { Internal_RenderMeshInstanced_Injected(ref rparams, mesh, submeshIndex, instanceData, ref layout, instanceCount); } [FreeFunction("GraphicsScripting::RenderMeshIndirect")] private static void Internal_RenderMeshIndirect(RenderParams rparams, [NotNull("NullExceptionObject")] Mesh mesh, [NotNull("NullExceptionObject")] GraphicsBuffer commandBuffer, int commandCount, int startCommand) { Internal_RenderMeshIndirect_Injected(ref rparams, mesh, commandBuffer, commandCount, startCommand); } [FreeFunction("GraphicsScripting::RenderMeshPrimitives")] private static void Internal_RenderMeshPrimitives(RenderParams rparams, [NotNull("NullExceptionObject")] Mesh mesh, int submeshIndex, int instanceCount) { Internal_RenderMeshPrimitives_Injected(ref rparams, mesh, submeshIndex, instanceCount); } [FreeFunction("GraphicsScripting::RenderPrimitives")] private static void Internal_RenderPrimitives(RenderParams rparams, MeshTopology topology, int vertexCount, int instanceCount) { Internal_RenderPrimitives_Injected(ref rparams, topology, vertexCount, instanceCount); } [FreeFunction("GraphicsScripting::RenderPrimitivesIndexed")] private static void Internal_RenderPrimitivesIndexed(RenderParams rparams, MeshTopology topology, [NotNull("NullExceptionObject")] GraphicsBuffer indexBuffer, int indexCount, int startIndex, int instanceCount) { Internal_RenderPrimitivesIndexed_Injected(ref rparams, topology, indexBuffer, indexCount, startIndex, instanceCount); } [FreeFunction("GraphicsScripting::RenderPrimitivesIndirect")] private static void Internal_RenderPrimitivesIndirect(RenderParams rparams, MeshTopology topology, [NotNull("NullExceptionObject")] GraphicsBuffer commandBuffer, int commandCount, int startCommand) { Internal_RenderPrimitivesIndirect_Injected(ref rparams, topology, commandBuffer, commandCount, startCommand); } [FreeFunction("GraphicsScripting::RenderPrimitivesIndexedIndirect")] private static void Internal_RenderPrimitivesIndexedIndirect(RenderParams rparams, MeshTopology topology, [NotNull("NullExceptionObject")] GraphicsBuffer indexBuffer, [NotNull("NullExceptionObject")] GraphicsBuffer commandBuffer, int commandCount, int startCommand) { Internal_RenderPrimitivesIndexedIndirect_Injected(ref rparams, topology, indexBuffer, commandBuffer, commandCount, startCommand); } [FreeFunction("GraphicsScripting::DrawMesh")] private static void Internal_DrawMesh(Mesh mesh, int submeshIndex, Matrix4x4 matrix, Material material, int layer, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, Transform probeAnchor, LightProbeUsage lightProbeUsage, LightProbeProxyVolume lightProbeProxyVolume) { Internal_DrawMesh_Injected(mesh, submeshIndex, ref matrix, material, layer, camera, properties, castShadows, receiveShadows, probeAnchor, lightProbeUsage, lightProbeProxyVolume); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::DrawMeshInstanced")] private static extern void Internal_DrawMeshInstanced([NotNull("NullExceptionObject")] Mesh mesh, int submeshIndex, [NotNull("NullExceptionObject")] Material material, Matrix4x4[] matrices, int count, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer, Camera camera, LightProbeUsage lightProbeUsage, LightProbeProxyVolume lightProbeProxyVolume); [FreeFunction("GraphicsScripting::DrawMeshInstancedProcedural")] private static void Internal_DrawMeshInstancedProcedural([NotNull("NullExceptionObject")] Mesh mesh, int submeshIndex, [NotNull("NullExceptionObject")] Material material, Bounds bounds, int count, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer, Camera camera, LightProbeUsage lightProbeUsage, LightProbeProxyVolume lightProbeProxyVolume) { Internal_DrawMeshInstancedProcedural_Injected(mesh, submeshIndex, material, ref bounds, count, properties, castShadows, receiveShadows, layer, camera, lightProbeUsage, lightProbeProxyVolume); } [FreeFunction("GraphicsScripting::DrawMeshInstancedIndirect")] private static void Internal_DrawMeshInstancedIndirect([NotNull("NullExceptionObject")] Mesh mesh, int submeshIndex, [NotNull("NullExceptionObject")] Material material, Bounds bounds, ComputeBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer, Camera camera, LightProbeUsage lightProbeUsage, LightProbeProxyVolume lightProbeProxyVolume) { Internal_DrawMeshInstancedIndirect_Injected(mesh, submeshIndex, material, ref bounds, bufferWithArgs, argsOffset, properties, castShadows, receiveShadows, layer, camera, lightProbeUsage, lightProbeProxyVolume); } [FreeFunction("GraphicsScripting::DrawMeshInstancedIndirect")] private static void Internal_DrawMeshInstancedIndirectGraphicsBuffer([NotNull("NullExceptionObject")] Mesh mesh, int submeshIndex, [NotNull("NullExceptionObject")] Material material, Bounds bounds, GraphicsBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer, Camera camera, LightProbeUsage lightProbeUsage, LightProbeProxyVolume lightProbeProxyVolume) { Internal_DrawMeshInstancedIndirectGraphicsBuffer_Injected(mesh, submeshIndex, material, ref bounds, bufferWithArgs, argsOffset, properties, castShadows, receiveShadows, layer, camera, lightProbeUsage, lightProbeProxyVolume); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::DrawProceduralNow")] private static extern void Internal_DrawProceduralNow(MeshTopology topology, int vertexCount, int instanceCount); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::DrawProceduralIndexedNow")] private static extern void Internal_DrawProceduralIndexedNow(MeshTopology topology, GraphicsBuffer indexBuffer, int indexCount, int instanceCount); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::DrawProceduralIndirectNow")] private static extern void Internal_DrawProceduralIndirectNow(MeshTopology topology, ComputeBuffer bufferWithArgs, int argsOffset); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::DrawProceduralIndexedIndirectNow")] private static extern void Internal_DrawProceduralIndexedIndirectNow(MeshTopology topology, GraphicsBuffer indexBuffer, ComputeBuffer bufferWithArgs, int argsOffset); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::DrawProceduralIndirectNow")] private static extern void Internal_DrawProceduralIndirectNowGraphicsBuffer(MeshTopology topology, GraphicsBuffer bufferWithArgs, int argsOffset); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::DrawProceduralIndexedIndirectNow")] private static extern void Internal_DrawProceduralIndexedIndirectNowGraphicsBuffer(MeshTopology topology, GraphicsBuffer indexBuffer, GraphicsBuffer bufferWithArgs, int argsOffset); [FreeFunction("GraphicsScripting::DrawProcedural")] private static void Internal_DrawProcedural(Material material, Bounds bounds, MeshTopology topology, int vertexCount, int instanceCount, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer) { Internal_DrawProcedural_Injected(material, ref bounds, topology, vertexCount, instanceCount, camera, properties, castShadows, receiveShadows, layer); } [FreeFunction("GraphicsScripting::DrawProceduralIndexed")] private static void Internal_DrawProceduralIndexed(Material material, Bounds bounds, MeshTopology topology, GraphicsBuffer indexBuffer, int indexCount, int instanceCount, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer) { Internal_DrawProceduralIndexed_Injected(material, ref bounds, topology, indexBuffer, indexCount, instanceCount, camera, properties, castShadows, receiveShadows, layer); } [FreeFunction("GraphicsScripting::DrawProceduralIndirect")] private static void Internal_DrawProceduralIndirect(Material material, Bounds bounds, MeshTopology topology, ComputeBuffer bufferWithArgs, int argsOffset, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer) { Internal_DrawProceduralIndirect_Injected(material, ref bounds, topology, bufferWithArgs, argsOffset, camera, properties, castShadows, receiveShadows, layer); } [FreeFunction("GraphicsScripting::DrawProceduralIndirect")] private static void Internal_DrawProceduralIndirectGraphicsBuffer(Material material, Bounds bounds, MeshTopology topology, GraphicsBuffer bufferWithArgs, int argsOffset, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer) { Internal_DrawProceduralIndirectGraphicsBuffer_Injected(material, ref bounds, topology, bufferWithArgs, argsOffset, camera, properties, castShadows, receiveShadows, layer); } [FreeFunction("GraphicsScripting::DrawProceduralIndexedIndirect")] private static void Internal_DrawProceduralIndexedIndirect(Material material, Bounds bounds, MeshTopology topology, GraphicsBuffer indexBuffer, ComputeBuffer bufferWithArgs, int argsOffset, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer) { Internal_DrawProceduralIndexedIndirect_Injected(material, ref bounds, topology, indexBuffer, bufferWithArgs, argsOffset, camera, properties, castShadows, receiveShadows, layer); } [FreeFunction("GraphicsScripting::DrawProceduralIndexedIndirect")] private static void Internal_DrawProceduralIndexedIndirectGraphicsBuffer(Material material, Bounds bounds, MeshTopology topology, GraphicsBuffer indexBuffer, GraphicsBuffer bufferWithArgs, int argsOffset, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer) { Internal_DrawProceduralIndexedIndirectGraphicsBuffer_Injected(material, ref bounds, topology, indexBuffer, bufferWithArgs, argsOffset, camera, properties, castShadows, receiveShadows, layer); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::BlitMaterial")] private static extern void Internal_BlitMaterial5(Texture source, RenderTexture dest, [NotNull("ArgumentNullException")] Material mat, int pass, bool setRT); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::BlitMaterial")] private static extern void Internal_BlitMaterial6(Texture source, RenderTexture dest, [NotNull("ArgumentNullException")] Material mat, int pass, bool setRT, int destDepthSlice); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::BlitMultitap")] private static extern void Internal_BlitMultiTap4(Texture source, RenderTexture dest, [NotNull("ArgumentNullException")] Material mat, [NotNull("ArgumentNullException")] Vector2[] offsets); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::BlitMultitap")] private static extern void Internal_BlitMultiTap5(Texture source, RenderTexture dest, [NotNull("ArgumentNullException")] Material mat, [NotNull("ArgumentNullException")] Vector2[] offsets, int destDepthSlice); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::Blit")] private static extern void Blit2(Texture source, RenderTexture dest); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsScripting::Blit")] private static extern void Blit3(Texture source, RenderTexture dest, int sourceDepthSlice, int destDepthSlice); [FreeFunction("GraphicsScripting::Blit")] private static void Blit4(Texture source, RenderTexture dest, Vector2 scale, Vector2 offset) { Blit4_Injected(source, dest, ref scale, ref offset); } [FreeFunction("GraphicsScripting::Blit")] private static void Blit5(Texture source, RenderTexture dest, Vector2 scale, Vector2 offset, int sourceDepthSlice, int destDepthSlice) { Blit5_Injected(source, dest, ref scale, ref offset, sourceDepthSlice, destDepthSlice); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GraphicsScripting::CreateGPUFence", IsFreeFunction = true, ThrowsException = true)] private static extern IntPtr CreateGPUFenceImpl(GraphicsFenceType fenceType, SynchronisationStageFlags stage); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GraphicsScripting::WaitOnGPUFence", IsFreeFunction = true, ThrowsException = true)] private static extern void WaitOnGPUFenceImpl(IntPtr fencePtr, SynchronisationStageFlags stage); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GraphicsScripting::ExecuteCommandBuffer", IsFreeFunction = true, ThrowsException = true)] public static extern void ExecuteCommandBuffer([NotNull("ArgumentNullException")] CommandBuffer buffer); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GraphicsScripting::ExecuteCommandBufferAsync", IsFreeFunction = true, ThrowsException = true)] public static extern void ExecuteCommandBufferAsync([NotNull("ArgumentNullException")] CommandBuffer buffer, ComputeQueueType queueType); internal static void CheckLoadActionValid(RenderBufferLoadAction load, string bufferType) { if (load != RenderBufferLoadAction.Load && load != RenderBufferLoadAction.DontCare) { throw new ArgumentException(UnityString.Format("Bad {0} LoadAction provided.", new object[1] { bufferType })); } } internal static void CheckStoreActionValid(RenderBufferStoreAction store, string bufferType) { if (store != RenderBufferStoreAction.Store && store != RenderBufferStoreAction.DontCare) { throw new ArgumentException(UnityString.Format("Bad {0} StoreAction provided.", new object[1] { bufferType })); } } internal static void SetRenderTargetImpl(RenderTargetSetup setup) { if (setup.color.Length == 0) { throw new ArgumentException("Invalid color buffer count for SetRenderTarget"); } if (setup.color.Length != setup.colorLoad.Length) { throw new ArgumentException("Color LoadAction and Buffer arrays have different sizes"); } if (setup.color.Length != setup.colorStore.Length) { throw new ArgumentException("Color StoreAction and Buffer arrays have different sizes"); } RenderBufferLoadAction[] colorLoad = setup.colorLoad; foreach (RenderBufferLoadAction load in colorLoad) { CheckLoadActionValid(load, "Color"); } RenderBufferStoreAction[] colorStore = setup.colorStore; foreach (RenderBufferStoreAction store in colorStore) { CheckStoreActionValid(store, "Color"); } CheckLoadActionValid(setup.depthLoad, "Depth"); CheckStoreActionValid(setup.depthStore, "Depth"); if (setup.cubemapFace < CubemapFace.Unknown || setup.cubemapFace > CubemapFace.NegativeZ) { throw new ArgumentException("Bad CubemapFace provided"); } Internal_SetMRTFullSetup(setup.color, setup.depth, setup.mipLevel, setup.cubemapFace, setup.depthSlice, setup.colorLoad, setup.colorStore, setup.depthLoad, setup.depthStore); } internal static void SetRenderTargetImpl(RenderBuffer colorBuffer, RenderBuffer depthBuffer, int mipLevel, CubemapFace face, int depthSlice) { Internal_SetRTSimple(colorBuffer, depthBuffer, mipLevel, face, depthSlice); } internal static void SetRenderTargetImpl(RenderTexture rt, int mipLevel, CubemapFace face, int depthSlice) { if ((bool)rt) { SetRenderTargetImpl(rt.colorBuffer, rt.depthBuffer, mipLevel, face, depthSlice); } else { Internal_SetNullRT(); } } internal static void SetRenderTargetImpl(RenderBuffer[] colorBuffers, RenderBuffer depthBuffer, int mipLevel, CubemapFace face, int depthSlice) { Internal_SetMRTSimple(colorBuffers, depthBuffer, mipLevel, face, depthSlice); } public static void SetRenderTarget(RenderTexture rt, [UnityEngine.Internal.DefaultValue("0")] int mipLevel, [UnityEngine.Internal.DefaultValue("CubemapFace.Unknown")] CubemapFace face, [UnityEngine.Internal.DefaultValue("0")] int depthSlice) { SetRenderTargetImpl(rt, mipLevel, face, depthSlice); } public static void SetRenderTarget(RenderBuffer colorBuffer, RenderBuffer depthBuffer, [UnityEngine.Internal.DefaultValue("0")] int mipLevel, [UnityEngine.Internal.DefaultValue("CubemapFace.Unknown")] CubemapFace face, [UnityEngine.Internal.DefaultValue("0")] int depthSlice) { SetRenderTargetImpl(colorBuffer, depthBuffer, mipLevel, face, depthSlice); } public static void SetRenderTarget(RenderBuffer[] colorBuffers, RenderBuffer depthBuffer) { SetRenderTargetImpl(colorBuffers, depthBuffer, 0, CubemapFace.Unknown, 0); } public static void SetRenderTarget(RenderTargetSetup setup) { SetRenderTargetImpl(setup); } public static void SetRandomWriteTarget(int index, RenderTexture uav) { if (index < 0 || index >= SystemInfo.supportedRandomWriteTargetCount) { throw new ArgumentOutOfRangeException("index", $"must be non-negative less than {SystemInfo.supportedRandomWriteTargetCount}."); } Internal_SetRandomWriteTargetRT(index, uav); } public static void SetRandomWriteTarget(int index, ComputeBuffer uav, [UnityEngine.Internal.DefaultValue("false")] bool preserveCounterValue) { if (uav == null) { throw new ArgumentNullException("uav"); } if (uav.m_Ptr == IntPtr.Zero) { throw new ObjectDisposedException("uav"); } if (index < 0 || index >= SystemInfo.supportedRandomWriteTargetCount) { throw new ArgumentOutOfRangeException("index", $"must be non-negative less than {SystemInfo.supportedRandomWriteTargetCount}."); } Internal_SetRandomWriteTargetBuffer(index, uav, preserveCounterValue); } public static void SetRandomWriteTarget(int index, GraphicsBuffer uav, [UnityEngine.Internal.DefaultValue("false")] bool preserveCounterValue) { if (uav == null) { throw new ArgumentNullException("uav"); } if (uav.m_Ptr == IntPtr.Zero) { throw new ObjectDisposedException("uav"); } if (index < 0 || index >= SystemInfo.supportedRandomWriteTargetCount) { throw new ArgumentOutOfRangeException("index", $"must be non-negative less than {SystemInfo.supportedRandomWriteTargetCount}."); } Internal_SetRandomWriteTargetGraphicsBuffer(index, uav, preserveCounterValue); } public static void CopyTexture(Texture src, Texture dst) { CopyTexture_Full(src, dst); } public static void CopyTexture(Texture src, int srcElement, Texture dst, int dstElement) { CopyTexture_Slice_AllMips(src, srcElement, dst, dstElement); } public static void CopyTexture(Texture src, int srcElement, int srcMip, Texture dst, int dstElement, int dstMip) { CopyTexture_Slice(src, srcElement, srcMip, dst, dstElement, dstMip); } public static void CopyTexture(Texture src, int srcElement, int srcMip, int srcX, int srcY, int srcWidth, int srcHeight, Texture dst, int dstElement, int dstMip, int dstX, int dstY) { CopyTexture_Region(src, srcElement, srcMip, srcX, srcY, srcWidth, srcHeight, dst, dstElement, dstMip, dstX, dstY); } public static bool ConvertTexture(Texture src, Texture dst) { return ConvertTexture_Full(src, dst); } public static bool ConvertTexture(Texture src, int srcElement, Texture dst, int dstElement) { return ConvertTexture_Slice(src, srcElement, dst, dstElement); } public static GraphicsFence CreateAsyncGraphicsFence([UnityEngine.Internal.DefaultValue("SynchronisationStage.PixelProcessing")] SynchronisationStage stage) { return CreateGraphicsFence(GraphicsFenceType.AsyncQueueSynchronisation, GraphicsFence.TranslateSynchronizationStageToFlags(stage)); } public static GraphicsFence CreateAsyncGraphicsFence() { return CreateGraphicsFence(GraphicsFenceType.AsyncQueueSynchronisation, SynchronisationStageFlags.PixelProcessing); } public static GraphicsFence CreateGraphicsFence(GraphicsFenceType fenceType, [UnityEngine.Internal.DefaultValue("SynchronisationStage.PixelProcessing")] SynchronisationStageFlags stage) { GraphicsFence result = default(GraphicsFence); result.m_FenceType = fenceType; result.m_Ptr = CreateGPUFenceImpl(fenceType, stage); result.InitPostAllocation(); result.Validate(); return result; } public static void WaitOnAsyncGraphicsFence(GraphicsFence fence) { WaitOnAsyncGraphicsFence(fence, SynchronisationStage.PixelProcessing); } public static void WaitOnAsyncGraphicsFence(GraphicsFence fence, [UnityEngine.Internal.DefaultValue("SynchronisationStage.PixelProcessing")] SynchronisationStage stage) { if (fence.m_FenceType != GraphicsFenceType.AsyncQueueSynchronisation) { throw new ArgumentException("Graphics.WaitOnGraphicsFence can only be called with fences created with GraphicsFenceType.AsyncQueueSynchronization."); } fence.Validate(); if (fence.IsFencePending()) { WaitOnGPUFenceImpl(fence.m_Ptr, GraphicsFence.TranslateSynchronizationStageToFlags(stage)); } } internal static void ValidateCopyBuffer(GraphicsBuffer source, GraphicsBuffer dest) { if (source == null) { throw new ArgumentNullException("source"); } if (dest == null) { throw new ArgumentNullException("dest"); } long num = (long)source.count * (long)source.stride; long num2 = (long)dest.count * (long)dest.stride; if (num != num2) { throw new ArgumentException($"CopyBuffer source and destination buffers must be the same size, source was {num} bytes, dest was {num2} bytes"); } if ((source.target & GraphicsBuffer.Target.CopySource) == 0) { throw new ArgumentException("CopyBuffer source must have CopySource target", "source"); } if ((dest.target & GraphicsBuffer.Target.CopyDestination) == 0) { throw new ArgumentException("CopyBuffer destination must have CopyDestination target", "dest"); } } public static void CopyBuffer(GraphicsBuffer source, GraphicsBuffer dest) { ValidateCopyBuffer(source, dest); CopyBufferImpl(source, dest); } private static void DrawTextureImpl(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder, Color color, Material mat, int pass) { Internal_DrawTextureArguments args = new Internal_DrawTextureArguments { screenRect = screenRect, sourceRect = sourceRect, leftBorder = leftBorder, rightBorder = rightBorder, topBorder = topBorder, bottomBorder = bottomBorder, color = color, leftBorderColor = Color.black, topBorderColor = Color.black, rightBorderColor = Color.black, bottomBorderColor = Color.black, pass = pass, texture = texture, smoothCorners = true, mat = mat }; Internal_DrawTexture(ref args); } public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder, Color color, [UnityEngine.Internal.DefaultValue("null")] Material mat, [UnityEngine.Internal.DefaultValue("-1")] int pass) { DrawTextureImpl(screenRect, texture, sourceRect, leftBorder, rightBorder, topBorder, bottomBorder, color, mat, pass); } public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder, [UnityEngine.Internal.DefaultValue("null")] Material mat, [UnityEngine.Internal.DefaultValue("-1")] int pass) { Color32 color = new Color32(128, 128, 128, 128); DrawTextureImpl(screenRect, texture, sourceRect, leftBorder, rightBorder, topBorder, bottomBorder, color, mat, pass); } public static void DrawTexture(Rect screenRect, Texture texture, int leftBorder, int rightBorder, int topBorder, int bottomBorder, [UnityEngine.Internal.DefaultValue("null")] Material mat, [UnityEngine.Internal.DefaultValue("-1")] int pass) { DrawTexture(screenRect, texture, new Rect(0f, 0f, 1f, 1f), leftBorder, rightBorder, topBorder, bottomBorder, mat, pass); } public static void DrawTexture(Rect screenRect, Texture texture, [UnityEngine.Internal.DefaultValue("null")] Material mat, [UnityEngine.Internal.DefaultValue("-1")] int pass) { DrawTexture(screenRect, texture, 0, 0, 0, 0, mat, pass); } public unsafe static void RenderMesh(in RenderParams rparams, Mesh mesh, int submeshIndex, Matrix4x4 objectToWorld, [UnityEngine.Internal.DefaultValue("null")] Matrix4x4? prevObjectToWorld = null) { if (prevObjectToWorld.HasValue) { Matrix4x4 value = prevObjectToWorld.Value; Internal_RenderMesh(rparams, mesh, submeshIndex, objectToWorld, &value); } else { Internal_RenderMesh(rparams, mesh, submeshIndex, objectToWorld, null); } } private static RenderInstancedDataLayout GetCachedRenderInstancedDataLayout(Type type) { int hashCode = type.GetHashCode(); if (!s_RenderInstancedDataLayouts.TryGetValue(hashCode, out var value)) { value = new RenderInstancedDataLayout(type); s_RenderInstancedDataLayouts.Add(hashCode, value); } return value; } public unsafe static void RenderMeshInstanced(in RenderParams rparams, Mesh mesh, int submeshIndex, T[] instanceData, [UnityEngine.Internal.DefaultValue("-1")] int instanceCount = -1, [UnityEngine.Internal.DefaultValue("0")] int startInstance = 0) where T : unmanaged { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } if (!rparams.material.enableInstancing) { throw new InvalidOperationException("Material needs to enable instancing for use with RenderMeshInstanced."); } if (instanceData == null) { throw new ArgumentNullException("instanceData"); } RenderInstancedDataLayout cachedRenderInstancedDataLayout = GetCachedRenderInstancedDataLayout(typeof(T)); uint instanceCount2 = Math.Min((uint)instanceCount, (uint)Math.Max(0, instanceData.Length - startInstance)); fixed (T* ptr = instanceData) { Internal_RenderMeshInstanced(rparams, mesh, submeshIndex, (IntPtr)(ptr + startInstance), cachedRenderInstancedDataLayout, instanceCount2); } } public unsafe static void RenderMeshInstanced(in RenderParams rparams, Mesh mesh, int submeshIndex, List instanceData, [UnityEngine.Internal.DefaultValue("-1")] int instanceCount = -1, [UnityEngine.Internal.DefaultValue("0")] int startInstance = 0) where T : unmanaged { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } if (!rparams.material.enableInstancing) { throw new InvalidOperationException("Material needs to enable instancing for use with RenderMeshInstanced."); } if (instanceData == null) { throw new ArgumentNullException("instanceData"); } RenderInstancedDataLayout cachedRenderInstancedDataLayout = GetCachedRenderInstancedDataLayout(typeof(T)); uint instanceCount2 = Math.Min((uint)instanceCount, (uint)Math.Max(0, instanceData.Count - startInstance)); fixed (T* ptr = NoAllocHelpers.ExtractArrayFromListT(instanceData)) { Internal_RenderMeshInstanced(rparams, mesh, submeshIndex, (IntPtr)(ptr + startInstance), cachedRenderInstancedDataLayout, instanceCount2); } } public unsafe static void RenderMeshInstanced(RenderParams rparams, Mesh mesh, int submeshIndex, NativeArray instanceData, [UnityEngine.Internal.DefaultValue("-1")] int instanceCount = -1, [UnityEngine.Internal.DefaultValue("0")] int startInstance = 0) where T : unmanaged { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } if (!rparams.material.enableInstancing) { throw new InvalidOperationException("Material needs to enable instancing for use with RenderMeshInstanced."); } bool flag = false; RenderInstancedDataLayout cachedRenderInstancedDataLayout = GetCachedRenderInstancedDataLayout(typeof(T)); uint instanceCount2 = Math.Min((uint)instanceCount, (uint)Math.Max(0, instanceData.Length - startInstance)); Internal_RenderMeshInstanced(rparams, mesh, submeshIndex, (IntPtr)((byte*)instanceData.GetUnsafePtr() + (nint)startInstance * (nint)sizeof(T)), cachedRenderInstancedDataLayout, instanceCount2); } public static void RenderMeshIndirect(in RenderParams rparams, Mesh mesh, GraphicsBuffer commandBuffer, [UnityEngine.Internal.DefaultValue("1")] int commandCount = 1, [UnityEngine.Internal.DefaultValue("0")] int startCommand = 0) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } Internal_RenderMeshIndirect(rparams, mesh, commandBuffer, commandCount, startCommand); } public static void RenderMeshPrimitives(in RenderParams rparams, Mesh mesh, int submeshIndex, [UnityEngine.Internal.DefaultValue("1")] int instanceCount = 1) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } Internal_RenderMeshPrimitives(rparams, mesh, submeshIndex, instanceCount); } public static void RenderPrimitives(in RenderParams rparams, MeshTopology topology, int vertexCount, [UnityEngine.Internal.DefaultValue("1")] int instanceCount = 1) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } Internal_RenderPrimitives(rparams, topology, vertexCount, instanceCount); } public static void RenderPrimitivesIndexed(in RenderParams rparams, MeshTopology topology, GraphicsBuffer indexBuffer, int indexCount, [UnityEngine.Internal.DefaultValue("0")] int startIndex = 0, [UnityEngine.Internal.DefaultValue("1")] int instanceCount = 1) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } Internal_RenderPrimitivesIndexed(rparams, topology, indexBuffer, indexCount, startIndex, instanceCount); } public static void RenderPrimitivesIndirect(in RenderParams rparams, MeshTopology topology, GraphicsBuffer commandBuffer, [UnityEngine.Internal.DefaultValue("1")] int commandCount = 1, [UnityEngine.Internal.DefaultValue("0")] int startCommand = 0) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } Internal_RenderPrimitivesIndirect(rparams, topology, commandBuffer, commandCount, startCommand); } public static void RenderPrimitivesIndexedIndirect(in RenderParams rparams, MeshTopology topology, GraphicsBuffer indexBuffer, GraphicsBuffer commandBuffer, [UnityEngine.Internal.DefaultValue("1")] int commandCount = 1, [UnityEngine.Internal.DefaultValue("0")] int startCommand = 0) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } Internal_RenderPrimitivesIndexedIndirect(rparams, topology, indexBuffer, commandBuffer, commandCount, startCommand); } public static void DrawMeshNow(Mesh mesh, Vector3 position, Quaternion rotation, int materialIndex) { if (mesh == null) { throw new ArgumentNullException("mesh"); } Internal_DrawMeshNow1(mesh, materialIndex, position, rotation); } public static void DrawMeshNow(Mesh mesh, Matrix4x4 matrix, int materialIndex) { if (mesh == null) { throw new ArgumentNullException("mesh"); } Internal_DrawMeshNow2(mesh, materialIndex, matrix); } public static void DrawMeshNow(Mesh mesh, Vector3 position, Quaternion rotation) { DrawMeshNow(mesh, position, rotation, -1); } public static void DrawMeshNow(Mesh mesh, Matrix4x4 matrix) { DrawMeshNow(mesh, matrix, -1); } public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, [UnityEngine.Internal.DefaultValue("null")] Camera camera, [UnityEngine.Internal.DefaultValue("0")] int submeshIndex, [UnityEngine.Internal.DefaultValue("null")] MaterialPropertyBlock properties, [UnityEngine.Internal.DefaultValue("true")] bool castShadows, [UnityEngine.Internal.DefaultValue("true")] bool receiveShadows, [UnityEngine.Internal.DefaultValue("true")] bool useLightProbes) { DrawMesh(mesh, Matrix4x4.TRS(position, rotation, Vector3.one), material, layer, camera, submeshIndex, properties, castShadows ? ShadowCastingMode.On : ShadowCastingMode.Off, receiveShadows, null, useLightProbes ? LightProbeUsage.BlendProbes : LightProbeUsage.Off, null); } public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows, [UnityEngine.Internal.DefaultValue("true")] bool receiveShadows, [UnityEngine.Internal.DefaultValue("null")] Transform probeAnchor, [UnityEngine.Internal.DefaultValue("true")] bool useLightProbes) { DrawMesh(mesh, Matrix4x4.TRS(position, rotation, Vector3.one), material, layer, camera, submeshIndex, properties, castShadows, receiveShadows, probeAnchor, useLightProbes ? LightProbeUsage.BlendProbes : LightProbeUsage.Off, null); } public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, [UnityEngine.Internal.DefaultValue("null")] Camera camera, [UnityEngine.Internal.DefaultValue("0")] int submeshIndex, [UnityEngine.Internal.DefaultValue("null")] MaterialPropertyBlock properties, [UnityEngine.Internal.DefaultValue("true")] bool castShadows, [UnityEngine.Internal.DefaultValue("true")] bool receiveShadows, [UnityEngine.Internal.DefaultValue("true")] bool useLightProbes) { DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, castShadows ? ShadowCastingMode.On : ShadowCastingMode.Off, receiveShadows, null, useLightProbes ? LightProbeUsage.BlendProbes : LightProbeUsage.Off, null); } public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, Transform probeAnchor, LightProbeUsage lightProbeUsage, [UnityEngine.Internal.DefaultValue("null")] LightProbeProxyVolume lightProbeProxyVolume) { if (lightProbeUsage == LightProbeUsage.UseProxyVolume && lightProbeProxyVolume == null) { throw new ArgumentException("Argument lightProbeProxyVolume must not be null if lightProbeUsage is set to UseProxyVolume.", "lightProbeProxyVolume"); } Internal_DrawMesh(mesh, submeshIndex, matrix, material, layer, camera, properties, castShadows, receiveShadows, probeAnchor, lightProbeUsage, lightProbeProxyVolume); } public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, Matrix4x4[] matrices, [UnityEngine.Internal.DefaultValue("matrices.Length")] int count, [UnityEngine.Internal.DefaultValue("null")] MaterialPropertyBlock properties, [UnityEngine.Internal.DefaultValue("ShadowCastingMode.On")] ShadowCastingMode castShadows, [UnityEngine.Internal.DefaultValue("true")] bool receiveShadows, [UnityEngine.Internal.DefaultValue("0")] int layer, [UnityEngine.Internal.DefaultValue("null")] Camera camera, [UnityEngine.Internal.DefaultValue("LightProbeUsage.BlendProbes")] LightProbeUsage lightProbeUsage, [UnityEngine.Internal.DefaultValue("null")] LightProbeProxyVolume lightProbeProxyVolume) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } if (mesh == null) { throw new ArgumentNullException("mesh"); } if (submeshIndex < 0 || submeshIndex >= mesh.subMeshCount) { throw new ArgumentOutOfRangeException("submeshIndex", "submeshIndex out of range."); } if (material == null) { throw new ArgumentNullException("material"); } if (!material.enableInstancing) { throw new InvalidOperationException("Material needs to enable instancing for use with DrawMeshInstanced."); } if (matrices == null) { throw new ArgumentNullException("matrices"); } if (count < 0 || count > Mathf.Min(kMaxDrawMeshInstanceCount, matrices.Length)) { throw new ArgumentOutOfRangeException("count", $"Count must be in the range of 0 to {Mathf.Min(kMaxDrawMeshInstanceCount, matrices.Length)}."); } if (lightProbeUsage == LightProbeUsage.UseProxyVolume && lightProbeProxyVolume == null) { throw new ArgumentException("Argument lightProbeProxyVolume must not be null if lightProbeUsage is set to UseProxyVolume.", "lightProbeProxyVolume"); } if (count > 0) { Internal_DrawMeshInstanced(mesh, submeshIndex, material, matrices, count, properties, castShadows, receiveShadows, layer, camera, lightProbeUsage, lightProbeProxyVolume); } } public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, List matrices, [UnityEngine.Internal.DefaultValue("null")] MaterialPropertyBlock properties, [UnityEngine.Internal.DefaultValue("ShadowCastingMode.On")] ShadowCastingMode castShadows, [UnityEngine.Internal.DefaultValue("true")] bool receiveShadows, [UnityEngine.Internal.DefaultValue("0")] int layer, [UnityEngine.Internal.DefaultValue("null")] Camera camera, [UnityEngine.Internal.DefaultValue("LightProbeUsage.BlendProbes")] LightProbeUsage lightProbeUsage, [UnityEngine.Internal.DefaultValue("null")] LightProbeProxyVolume lightProbeProxyVolume) { if (matrices == null) { throw new ArgumentNullException("matrices"); } DrawMeshInstanced(mesh, submeshIndex, material, NoAllocHelpers.ExtractArrayFromListT(matrices), matrices.Count, properties, castShadows, receiveShadows, layer, camera, lightProbeUsage, lightProbeProxyVolume); } public static void DrawMeshInstancedProcedural(Mesh mesh, int submeshIndex, Material material, Bounds bounds, int count, MaterialPropertyBlock properties = null, ShadowCastingMode castShadows = ShadowCastingMode.On, bool receiveShadows = true, int layer = 0, Camera camera = null, LightProbeUsage lightProbeUsage = LightProbeUsage.BlendProbes, LightProbeProxyVolume lightProbeProxyVolume = null) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } if (mesh == null) { throw new ArgumentNullException("mesh"); } if (submeshIndex < 0 || submeshIndex >= mesh.subMeshCount) { throw new ArgumentOutOfRangeException("submeshIndex", "submeshIndex out of range."); } if (material == null) { throw new ArgumentNullException("material"); } if (count <= 0) { throw new ArgumentOutOfRangeException("count"); } if (lightProbeUsage == LightProbeUsage.UseProxyVolume && lightProbeProxyVolume == null) { throw new ArgumentException("Argument lightProbeProxyVolume must not be null if lightProbeUsage is set to UseProxyVolume.", "lightProbeProxyVolume"); } if (count > 0) { Internal_DrawMeshInstancedProcedural(mesh, submeshIndex, material, bounds, count, properties, castShadows, receiveShadows, layer, camera, lightProbeUsage, lightProbeProxyVolume); } } public static void DrawMeshInstancedIndirect(Mesh mesh, int submeshIndex, Material material, Bounds bounds, ComputeBuffer bufferWithArgs, [UnityEngine.Internal.DefaultValue("0")] int argsOffset, [UnityEngine.Internal.DefaultValue("null")] MaterialPropertyBlock properties, [UnityEngine.Internal.DefaultValue("ShadowCastingMode.On")] ShadowCastingMode castShadows, [UnityEngine.Internal.DefaultValue("true")] bool receiveShadows, [UnityEngine.Internal.DefaultValue("0")] int layer, [UnityEngine.Internal.DefaultValue("null")] Camera camera, [UnityEngine.Internal.DefaultValue("LightProbeUsage.BlendProbes")] LightProbeUsage lightProbeUsage, [UnityEngine.Internal.DefaultValue("null")] LightProbeProxyVolume lightProbeProxyVolume) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } if (mesh == null) { throw new ArgumentNullException("mesh"); } if (submeshIndex < 0 || submeshIndex >= mesh.subMeshCount) { throw new ArgumentOutOfRangeException("submeshIndex", "submeshIndex out of range."); } if (material == null) { throw new ArgumentNullException("material"); } if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } if (lightProbeUsage == LightProbeUsage.UseProxyVolume && lightProbeProxyVolume == null) { throw new ArgumentException("Argument lightProbeProxyVolume must not be null if lightProbeUsage is set to UseProxyVolume.", "lightProbeProxyVolume"); } Internal_DrawMeshInstancedIndirect(mesh, submeshIndex, material, bounds, bufferWithArgs, argsOffset, properties, castShadows, receiveShadows, layer, camera, lightProbeUsage, lightProbeProxyVolume); } public static void DrawMeshInstancedIndirect(Mesh mesh, int submeshIndex, Material material, Bounds bounds, GraphicsBuffer bufferWithArgs, [UnityEngine.Internal.DefaultValue("0")] int argsOffset, [UnityEngine.Internal.DefaultValue("null")] MaterialPropertyBlock properties, [UnityEngine.Internal.DefaultValue("ShadowCastingMode.On")] ShadowCastingMode castShadows, [UnityEngine.Internal.DefaultValue("true")] bool receiveShadows, [UnityEngine.Internal.DefaultValue("0")] int layer, [UnityEngine.Internal.DefaultValue("null")] Camera camera, [UnityEngine.Internal.DefaultValue("LightProbeUsage.BlendProbes")] LightProbeUsage lightProbeUsage, [UnityEngine.Internal.DefaultValue("null")] LightProbeProxyVolume lightProbeProxyVolume) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } if (mesh == null) { throw new ArgumentNullException("mesh"); } if (submeshIndex < 0 || submeshIndex >= mesh.subMeshCount) { throw new ArgumentOutOfRangeException("submeshIndex", "submeshIndex out of range."); } if (material == null) { throw new ArgumentNullException("material"); } if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } if (lightProbeUsage == LightProbeUsage.UseProxyVolume && lightProbeProxyVolume == null) { throw new ArgumentException("Argument lightProbeProxyVolume must not be null if lightProbeUsage is set to UseProxyVolume.", "lightProbeProxyVolume"); } Internal_DrawMeshInstancedIndirectGraphicsBuffer(mesh, submeshIndex, material, bounds, bufferWithArgs, argsOffset, properties, castShadows, receiveShadows, layer, camera, lightProbeUsage, lightProbeProxyVolume); } public static void DrawProceduralNow(MeshTopology topology, int vertexCount, int instanceCount = 1) { Internal_DrawProceduralNow(topology, vertexCount, instanceCount); } public static void DrawProceduralNow(MeshTopology topology, GraphicsBuffer indexBuffer, int indexCount, int instanceCount = 1) { if (indexBuffer == null) { throw new ArgumentNullException("indexBuffer"); } Internal_DrawProceduralIndexedNow(topology, indexBuffer, indexCount, instanceCount); } public static void DrawProceduralIndirectNow(MeshTopology topology, ComputeBuffer bufferWithArgs, int argsOffset = 0) { if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } Internal_DrawProceduralIndirectNow(topology, bufferWithArgs, argsOffset); } public static void DrawProceduralIndirectNow(MeshTopology topology, GraphicsBuffer indexBuffer, ComputeBuffer bufferWithArgs, int argsOffset = 0) { if (indexBuffer == null) { throw new ArgumentNullException("indexBuffer"); } if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } Internal_DrawProceduralIndexedIndirectNow(topology, indexBuffer, bufferWithArgs, argsOffset); } public static void DrawProceduralIndirectNow(MeshTopology topology, GraphicsBuffer bufferWithArgs, int argsOffset = 0) { if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } Internal_DrawProceduralIndirectNowGraphicsBuffer(topology, bufferWithArgs, argsOffset); } public static void DrawProceduralIndirectNow(MeshTopology topology, GraphicsBuffer indexBuffer, GraphicsBuffer bufferWithArgs, int argsOffset = 0) { if (indexBuffer == null) { throw new ArgumentNullException("indexBuffer"); } if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } Internal_DrawProceduralIndexedIndirectNowGraphicsBuffer(topology, indexBuffer, bufferWithArgs, argsOffset); } public static void DrawProcedural(Material material, Bounds bounds, MeshTopology topology, int vertexCount, int instanceCount = 1, Camera camera = null, MaterialPropertyBlock properties = null, ShadowCastingMode castShadows = ShadowCastingMode.On, bool receiveShadows = true, int layer = 0) { Internal_DrawProcedural(material, bounds, topology, vertexCount, instanceCount, camera, properties, castShadows, receiveShadows, layer); } public static void DrawProcedural(Material material, Bounds bounds, MeshTopology topology, GraphicsBuffer indexBuffer, int indexCount, int instanceCount = 1, Camera camera = null, MaterialPropertyBlock properties = null, ShadowCastingMode castShadows = ShadowCastingMode.On, bool receiveShadows = true, int layer = 0) { if (indexBuffer == null) { throw new ArgumentNullException("indexBuffer"); } Internal_DrawProceduralIndexed(material, bounds, topology, indexBuffer, indexCount, instanceCount, camera, properties, castShadows, receiveShadows, layer); } public static void DrawProceduralIndirect(Material material, Bounds bounds, MeshTopology topology, ComputeBuffer bufferWithArgs, int argsOffset = 0, Camera camera = null, MaterialPropertyBlock properties = null, ShadowCastingMode castShadows = ShadowCastingMode.On, bool receiveShadows = true, int layer = 0) { if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } Internal_DrawProceduralIndirect(material, bounds, topology, bufferWithArgs, argsOffset, camera, properties, castShadows, receiveShadows, layer); } public static void DrawProceduralIndirect(Material material, Bounds bounds, MeshTopology topology, GraphicsBuffer bufferWithArgs, int argsOffset = 0, Camera camera = null, MaterialPropertyBlock properties = null, ShadowCastingMode castShadows = ShadowCastingMode.On, bool receiveShadows = true, int layer = 0) { if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } Internal_DrawProceduralIndirectGraphicsBuffer(material, bounds, topology, bufferWithArgs, argsOffset, camera, properties, castShadows, receiveShadows, layer); } public static void DrawProceduralIndirect(Material material, Bounds bounds, MeshTopology topology, GraphicsBuffer indexBuffer, ComputeBuffer bufferWithArgs, int argsOffset = 0, Camera camera = null, MaterialPropertyBlock properties = null, ShadowCastingMode castShadows = ShadowCastingMode.On, bool receiveShadows = true, int layer = 0) { if (indexBuffer == null) { throw new ArgumentNullException("indexBuffer"); } if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } Internal_DrawProceduralIndexedIndirect(material, bounds, topology, indexBuffer, bufferWithArgs, argsOffset, camera, properties, castShadows, receiveShadows, layer); } public static void DrawProceduralIndirect(Material material, Bounds bounds, MeshTopology topology, GraphicsBuffer indexBuffer, GraphicsBuffer bufferWithArgs, int argsOffset = 0, Camera camera = null, MaterialPropertyBlock properties = null, ShadowCastingMode castShadows = ShadowCastingMode.On, bool receiveShadows = true, int layer = 0) { if (indexBuffer == null) { throw new ArgumentNullException("indexBuffer"); } if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } Internal_DrawProceduralIndexedIndirectGraphicsBuffer(material, bounds, topology, indexBuffer, bufferWithArgs, argsOffset, camera, properties, castShadows, receiveShadows, layer); } public static void Blit(Texture source, RenderTexture dest) { Blit2(source, dest); } public static void Blit(Texture source, RenderTexture dest, int sourceDepthSlice, int destDepthSlice) { Blit3(source, dest, sourceDepthSlice, destDepthSlice); } public static void Blit(Texture source, RenderTexture dest, Vector2 scale, Vector2 offset) { Blit4(source, dest, scale, offset); } public static void Blit(Texture source, RenderTexture dest, Vector2 scale, Vector2 offset, int sourceDepthSlice, int destDepthSlice) { Blit5(source, dest, scale, offset, sourceDepthSlice, destDepthSlice); } public static void Blit(Texture source, RenderTexture dest, Material mat, [UnityEngine.Internal.DefaultValue("-1")] int pass) { Internal_BlitMaterial5(source, dest, mat, pass, setRT: true); } public static void Blit(Texture source, RenderTexture dest, Material mat, int pass, int destDepthSlice) { Internal_BlitMaterial6(source, dest, mat, pass, setRT: true, destDepthSlice); } public static void Blit(Texture source, RenderTexture dest, Material mat) { Blit(source, dest, mat, -1); } public static void Blit(Texture source, Material mat, [UnityEngine.Internal.DefaultValue("-1")] int pass) { Internal_BlitMaterial5(source, null, mat, pass, setRT: false); } public static void Blit(Texture source, Material mat, int pass, int destDepthSlice) { Internal_BlitMaterial6(source, null, mat, pass, setRT: false, destDepthSlice); } public static void Blit(Texture source, Material mat) { Blit(source, mat, -1); } public static void BlitMultiTap(Texture source, RenderTexture dest, Material mat, params Vector2[] offsets) { if (offsets.Length == 0) { throw new ArgumentException("empty offsets list passed.", "offsets"); } Internal_BlitMultiTap4(source, dest, mat, offsets); } public static void BlitMultiTap(Texture source, RenderTexture dest, Material mat, int destDepthSlice, params Vector2[] offsets) { if (offsets.Length == 0) { throw new ArgumentException("empty offsets list passed.", "offsets"); } Internal_BlitMultiTap5(source, dest, mat, offsets, destDepthSlice); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer) { DrawMesh(mesh, Matrix4x4.TRS(position, rotation, Vector3.one), material, layer, null, 0, null, ShadowCastingMode.On, receiveShadows: true, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera) { DrawMesh(mesh, Matrix4x4.TRS(position, rotation, Vector3.one), material, layer, camera, 0, null, ShadowCastingMode.On, receiveShadows: true, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex) { DrawMesh(mesh, Matrix4x4.TRS(position, rotation, Vector3.one), material, layer, camera, submeshIndex, null, ShadowCastingMode.On, receiveShadows: true, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties) { DrawMesh(mesh, Matrix4x4.TRS(position, rotation, Vector3.one), material, layer, camera, submeshIndex, properties, ShadowCastingMode.On, receiveShadows: true, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, bool castShadows) { DrawMesh(mesh, Matrix4x4.TRS(position, rotation, Vector3.one), material, layer, camera, submeshIndex, properties, castShadows ? ShadowCastingMode.On : ShadowCastingMode.Off, receiveShadows: true, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, bool castShadows, bool receiveShadows) { DrawMesh(mesh, Matrix4x4.TRS(position, rotation, Vector3.one), material, layer, camera, submeshIndex, properties, castShadows ? ShadowCastingMode.On : ShadowCastingMode.Off, receiveShadows, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows) { DrawMesh(mesh, Matrix4x4.TRS(position, rotation, Vector3.one), material, layer, camera, submeshIndex, properties, castShadows, receiveShadows: true, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows) { DrawMesh(mesh, Matrix4x4.TRS(position, rotation, Vector3.one), material, layer, camera, submeshIndex, properties, castShadows, receiveShadows, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Vector3 position, Quaternion rotation, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, Transform probeAnchor) { DrawMesh(mesh, Matrix4x4.TRS(position, rotation, Vector3.one), material, layer, camera, submeshIndex, properties, castShadows, receiveShadows, probeAnchor, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer) { DrawMesh(mesh, matrix, material, layer, null, 0, null, ShadowCastingMode.On, receiveShadows: true, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera) { DrawMesh(mesh, matrix, material, layer, camera, 0, null, ShadowCastingMode.On, receiveShadows: true, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex) { DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, null, ShadowCastingMode.On, receiveShadows: true, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties) { DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, ShadowCastingMode.On, receiveShadows: true, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, bool castShadows) { DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, castShadows ? ShadowCastingMode.On : ShadowCastingMode.Off, receiveShadows: true, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, bool castShadows, bool receiveShadows) { DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, castShadows ? ShadowCastingMode.On : ShadowCastingMode.Off, receiveShadows, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows) { DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows: true, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows) { DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, Transform probeAnchor) { DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows, probeAnchor, LightProbeUsage.BlendProbes, null); } public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows, [UnityEngine.Internal.DefaultValue("true")] bool receiveShadows, [UnityEngine.Internal.DefaultValue("null")] Transform probeAnchor, [UnityEngine.Internal.DefaultValue("true")] bool useLightProbes) { DrawMesh(mesh, matrix, material, layer, camera, submeshIndex, properties, castShadows, receiveShadows, probeAnchor, useLightProbes ? LightProbeUsage.BlendProbes : LightProbeUsage.Off, null); } [ExcludeFromDocs] public static void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int layer, Camera camera, int submeshIndex, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, Transform probeAnchor, LightProbeUsage lightProbeUsage) { Internal_DrawMesh(mesh, submeshIndex, matrix, material, layer, camera, properties, castShadows, receiveShadows, probeAnchor, lightProbeUsage, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, Matrix4x4[] matrices) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, matrices.Length, null, ShadowCastingMode.On, receiveShadows: true, 0, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, Matrix4x4[] matrices, int count) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, count, null, ShadowCastingMode.On, receiveShadows: true, 0, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, Matrix4x4[] matrices, int count, MaterialPropertyBlock properties) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, count, properties, ShadowCastingMode.On, receiveShadows: true, 0, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, Matrix4x4[] matrices, int count, MaterialPropertyBlock properties, ShadowCastingMode castShadows) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, count, properties, castShadows, receiveShadows: true, 0, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, Matrix4x4[] matrices, int count, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, count, properties, castShadows, receiveShadows, 0, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, Matrix4x4[] matrices, int count, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, count, properties, castShadows, receiveShadows, layer, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, Matrix4x4[] matrices, int count, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer, Camera camera) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, count, properties, castShadows, receiveShadows, layer, camera, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, Matrix4x4[] matrices, int count, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer, Camera camera, LightProbeUsage lightProbeUsage) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, count, properties, castShadows, receiveShadows, layer, camera, lightProbeUsage, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, List matrices) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, null, ShadowCastingMode.On, receiveShadows: true, 0, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, List matrices, MaterialPropertyBlock properties) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, properties, ShadowCastingMode.On, receiveShadows: true, 0, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, List matrices, MaterialPropertyBlock properties, ShadowCastingMode castShadows) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, properties, castShadows, receiveShadows: true, 0, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, List matrices, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, properties, castShadows, receiveShadows, 0, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, List matrices, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, properties, castShadows, receiveShadows, layer, null, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, List matrices, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer, Camera camera) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, properties, castShadows, receiveShadows, layer, camera, LightProbeUsage.BlendProbes, null); } [ExcludeFromDocs] public static void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, List matrices, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer, Camera camera, LightProbeUsage lightProbeUsage) { DrawMeshInstanced(mesh, submeshIndex, material, matrices, properties, castShadows, receiveShadows, layer, camera, lightProbeUsage, null); } [ExcludeFromDocs] public static void DrawMeshInstancedIndirect(Mesh mesh, int submeshIndex, Material material, Bounds bounds, ComputeBuffer bufferWithArgs, int argsOffset = 0, MaterialPropertyBlock properties = null, ShadowCastingMode castShadows = ShadowCastingMode.On, bool receiveShadows = true, int layer = 0, Camera camera = null, LightProbeUsage lightProbeUsage = LightProbeUsage.BlendProbes) { DrawMeshInstancedIndirect(mesh, submeshIndex, material, bounds, bufferWithArgs, argsOffset, properties, castShadows, receiveShadows, layer, camera, lightProbeUsage, null); } [ExcludeFromDocs] public static void DrawMeshInstancedIndirect(Mesh mesh, int submeshIndex, Material material, Bounds bounds, GraphicsBuffer bufferWithArgs, int argsOffset = 0, MaterialPropertyBlock properties = null, ShadowCastingMode castShadows = ShadowCastingMode.On, bool receiveShadows = true, int layer = 0, Camera camera = null, LightProbeUsage lightProbeUsage = LightProbeUsage.BlendProbes) { DrawMeshInstancedIndirect(mesh, submeshIndex, material, bounds, bufferWithArgs, argsOffset, properties, castShadows, receiveShadows, layer, camera, lightProbeUsage, null); } [ExcludeFromDocs] public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder, Color color, Material mat) { DrawTexture(screenRect, texture, sourceRect, leftBorder, rightBorder, topBorder, bottomBorder, color, mat, -1); } [ExcludeFromDocs] public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder, Color color) { DrawTexture(screenRect, texture, sourceRect, leftBorder, rightBorder, topBorder, bottomBorder, color, null, -1); } [ExcludeFromDocs] public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder, Material mat) { DrawTexture(screenRect, texture, sourceRect, leftBorder, rightBorder, topBorder, bottomBorder, mat, -1); } [ExcludeFromDocs] public static void DrawTexture(Rect screenRect, Texture texture, Rect sourceRect, int leftBorder, int rightBorder, int topBorder, int bottomBorder) { DrawTexture(screenRect, texture, sourceRect, leftBorder, rightBorder, topBorder, bottomBorder, null, -1); } [ExcludeFromDocs] public static void DrawTexture(Rect screenRect, Texture texture, int leftBorder, int rightBorder, int topBorder, int bottomBorder, Material mat) { DrawTexture(screenRect, texture, leftBorder, rightBorder, topBorder, bottomBorder, mat, -1); } [ExcludeFromDocs] public static void DrawTexture(Rect screenRect, Texture texture, int leftBorder, int rightBorder, int topBorder, int bottomBorder) { DrawTexture(screenRect, texture, leftBorder, rightBorder, topBorder, bottomBorder, null, -1); } [ExcludeFromDocs] public static void DrawTexture(Rect screenRect, Texture texture, Material mat) { DrawTexture(screenRect, texture, mat, -1); } [ExcludeFromDocs] public static void DrawTexture(Rect screenRect, Texture texture) { DrawTexture(screenRect, texture, null, -1); } [ExcludeFromDocs] public static void SetRenderTarget(RenderTexture rt) { SetRenderTarget(rt, 0, CubemapFace.Unknown, 0); } [ExcludeFromDocs] public static void SetRenderTarget(RenderTexture rt, int mipLevel) { SetRenderTarget(rt, mipLevel, CubemapFace.Unknown, 0); } [ExcludeFromDocs] public static void SetRenderTarget(RenderTexture rt, int mipLevel, CubemapFace face) { SetRenderTarget(rt, mipLevel, face, 0); } [ExcludeFromDocs] public static void SetRenderTarget(RenderBuffer colorBuffer, RenderBuffer depthBuffer) { SetRenderTarget(colorBuffer, depthBuffer, 0, CubemapFace.Unknown, 0); } [ExcludeFromDocs] public static void SetRenderTarget(RenderBuffer colorBuffer, RenderBuffer depthBuffer, int mipLevel) { SetRenderTarget(colorBuffer, depthBuffer, mipLevel, CubemapFace.Unknown, 0); } [ExcludeFromDocs] public static void SetRenderTarget(RenderBuffer colorBuffer, RenderBuffer depthBuffer, int mipLevel, CubemapFace face) { SetRenderTarget(colorBuffer, depthBuffer, mipLevel, face, 0); } [ExcludeFromDocs] public static void SetRandomWriteTarget(int index, ComputeBuffer uav) { SetRandomWriteTarget(index, uav, preserveCounterValue: false); } [ExcludeFromDocs] public static void SetRandomWriteTarget(int index, GraphicsBuffer uav) { SetRandomWriteTarget(index, uav, preserveCounterValue: false); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetActiveColorBuffer_Injected(out RenderBuffer ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetActiveDepthBuffer_Injected(out RenderBuffer ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_SetRTSimple_Injected(ref RenderBuffer color, ref RenderBuffer depth, int mip, CubemapFace face, int depthSlice); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_SetMRTSimple_Injected(RenderBuffer[] color, ref RenderBuffer depth, int mip, CubemapFace face, int depthSlice); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_SetMRTFullSetup_Injected(RenderBuffer[] color, ref RenderBuffer depth, int mip, CubemapFace face, int depthSlice, RenderBufferLoadAction[] colorLA, RenderBufferStoreAction[] colorSA, RenderBufferLoadAction depthLA, RenderBufferStoreAction depthSA); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_DrawMeshNow1_Injected(Mesh mesh, int subsetIndex, ref Vector3 position, ref Quaternion rotation); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_DrawMeshNow2_Injected(Mesh mesh, int subsetIndex, ref Matrix4x4 matrix); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Internal_RenderMesh_Injected(ref RenderParams rparams, Mesh mesh, int submeshIndex, ref Matrix4x4 objectToWorld, Matrix4x4* prevObjectToWorld); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_RenderMeshInstanced_Injected(ref RenderParams rparams, Mesh mesh, int submeshIndex, IntPtr instanceData, ref RenderInstancedDataLayout layout, uint instanceCount); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_RenderMeshIndirect_Injected(ref RenderParams rparams, Mesh mesh, GraphicsBuffer commandBuffer, int commandCount, int startCommand); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_RenderMeshPrimitives_Injected(ref RenderParams rparams, Mesh mesh, int submeshIndex, int instanceCount); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_RenderPrimitives_Injected(ref RenderParams rparams, MeshTopology topology, int vertexCount, int instanceCount); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_RenderPrimitivesIndexed_Injected(ref RenderParams rparams, MeshTopology topology, GraphicsBuffer indexBuffer, int indexCount, int startIndex, int instanceCount); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_RenderPrimitivesIndirect_Injected(ref RenderParams rparams, MeshTopology topology, GraphicsBuffer commandBuffer, int commandCount, int startCommand); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_RenderPrimitivesIndexedIndirect_Injected(ref RenderParams rparams, MeshTopology topology, GraphicsBuffer indexBuffer, GraphicsBuffer commandBuffer, int commandCount, int startCommand); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_DrawMesh_Injected(Mesh mesh, int submeshIndex, ref Matrix4x4 matrix, Material material, int layer, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, Transform probeAnchor, LightProbeUsage lightProbeUsage, LightProbeProxyVolume lightProbeProxyVolume); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_DrawMeshInstancedProcedural_Injected(Mesh mesh, int submeshIndex, Material material, ref Bounds bounds, int count, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer, Camera camera, LightProbeUsage lightProbeUsage, LightProbeProxyVolume lightProbeProxyVolume); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_DrawMeshInstancedIndirect_Injected(Mesh mesh, int submeshIndex, Material material, ref Bounds bounds, ComputeBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer, Camera camera, LightProbeUsage lightProbeUsage, LightProbeProxyVolume lightProbeProxyVolume); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_DrawMeshInstancedIndirectGraphicsBuffer_Injected(Mesh mesh, int submeshIndex, Material material, ref Bounds bounds, GraphicsBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer, Camera camera, LightProbeUsage lightProbeUsage, LightProbeProxyVolume lightProbeProxyVolume); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_DrawProcedural_Injected(Material material, ref Bounds bounds, MeshTopology topology, int vertexCount, int instanceCount, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_DrawProceduralIndexed_Injected(Material material, ref Bounds bounds, MeshTopology topology, GraphicsBuffer indexBuffer, int indexCount, int instanceCount, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_DrawProceduralIndirect_Injected(Material material, ref Bounds bounds, MeshTopology topology, ComputeBuffer bufferWithArgs, int argsOffset, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_DrawProceduralIndirectGraphicsBuffer_Injected(Material material, ref Bounds bounds, MeshTopology topology, GraphicsBuffer bufferWithArgs, int argsOffset, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_DrawProceduralIndexedIndirect_Injected(Material material, ref Bounds bounds, MeshTopology topology, GraphicsBuffer indexBuffer, ComputeBuffer bufferWithArgs, int argsOffset, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_DrawProceduralIndexedIndirectGraphicsBuffer_Injected(Material material, ref Bounds bounds, MeshTopology topology, GraphicsBuffer indexBuffer, GraphicsBuffer bufferWithArgs, int argsOffset, Camera camera, MaterialPropertyBlock properties, ShadowCastingMode castShadows, bool receiveShadows, int layer); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Blit4_Injected(Texture source, RenderTexture dest, ref Vector2 scale, ref Vector2 offset); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Blit5_Injected(Texture source, RenderTexture dest, ref Vector2 scale, ref Vector2 offset, int sourceDepthSlice, int destDepthSlice); } [NativeHeader("Runtime/GfxDevice/GfxDevice.h")] [NativeHeader("Runtime/Camera/CameraUtil.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("Runtime/Graphics/GraphicsScriptBindings.h")] [NativeHeader("Runtime/Camera/Camera.h")] public sealed class GL { public const int TRIANGLES = 4; public const int TRIANGLE_STRIP = 5; public const int QUADS = 7; public const int LINES = 1; public const int LINE_STRIP = 2; public static extern bool wireframe { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool sRGBWrite { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("UserBackfaceMode")] public static extern bool invertCulling { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static Matrix4x4 modelview { get { return GetWorldViewMatrix(); } set { SetViewMatrix(value); } } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("ImmediateVertex")] public static extern void Vertex3(float x, float y, float z); public static void Vertex(Vector3 v) { Vertex3(v.x, v.y, v.z); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("ImmediateVertices")] internal unsafe static extern void Vertices(Vector3* v, Vector3* coords, Vector4* colors, int length); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("ImmediateTexCoordAll")] public static extern void TexCoord3(float x, float y, float z); public static void TexCoord(Vector3 v) { TexCoord3(v.x, v.y, v.z); } public static void TexCoord2(float x, float y) { TexCoord3(x, y, 0f); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("ImmediateTexCoord")] public static extern void MultiTexCoord3(int unit, float x, float y, float z); public static void MultiTexCoord(int unit, Vector3 v) { MultiTexCoord3(unit, v.x, v.y, v.z); } public static void MultiTexCoord2(int unit, float x, float y) { MultiTexCoord3(unit, x, y, 0f); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("ImmediateColor")] private static extern void ImmediateColor(float r, float g, float b, float a); public static void Color(Color c) { ImmediateColor(c.r, c.g, c.b, c.a); } [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Flush(); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void RenderTargetBarrier(); private static Matrix4x4 GetWorldViewMatrix() { GetWorldViewMatrix_Injected(out var ret); return ret; } private static void SetViewMatrix(Matrix4x4 m) { SetViewMatrix_Injected(ref m); } [NativeName("SetWorldMatrix")] public static void MultMatrix(Matrix4x4 m) { MultMatrix_Injected(ref m); } [MethodImpl(MethodImplOptions.InternalCall)] [Obsolete("IssuePluginEvent(eventID) is deprecated. Use IssuePluginEvent(callback, eventID) instead.", false)] [NativeName("InsertCustomMarker")] public static extern void IssuePluginEvent(int eventID); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetUserBackfaceMode")] [Obsolete("SetRevertBackfacing(revertBackFaces) is deprecated. Use invertCulling property instead.", false)] public static extern void SetRevertBackfacing(bool revertBackFaces); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GLPushMatrixScript")] public static extern void PushMatrix(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GLPopMatrixScript")] public static extern void PopMatrix(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GLLoadIdentityScript")] public static extern void LoadIdentity(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GLLoadOrthoScript")] public static extern void LoadOrtho(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GLLoadPixelMatrixScript")] public static extern void LoadPixelMatrix(); [FreeFunction("GLLoadProjectionMatrixScript")] public static void LoadProjectionMatrix(Matrix4x4 mat) { LoadProjectionMatrix_Injected(ref mat); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GLInvalidateState")] public static extern void InvalidateState(); [FreeFunction("GLGetGPUProjectionMatrix")] public static Matrix4x4 GetGPUProjectionMatrix(Matrix4x4 proj, bool renderIntoTexture) { GetGPUProjectionMatrix_Injected(ref proj, renderIntoTexture, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern void GLLoadPixelMatrixScript(float left, float right, float bottom, float top); public static void LoadPixelMatrix(float left, float right, float bottom, float top) { GLLoadPixelMatrixScript(left, right, bottom, top); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern void GLIssuePluginEvent(IntPtr callback, int eventID); public static void IssuePluginEvent(IntPtr callback, int eventID) { if (callback == IntPtr.Zero) { throw new ArgumentException("Null callback specified.", "callback"); } GLIssuePluginEvent(callback, eventID); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GLBegin", ThrowsException = true)] public static extern void Begin(int mode); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GLEnd")] public static extern void End(); [FreeFunction] private static void GLClear(bool clearDepth, bool clearColor, Color backgroundColor, float depth) { GLClear_Injected(clearDepth, clearColor, ref backgroundColor, depth); } public static void Clear(bool clearDepth, bool clearColor, Color backgroundColor, [UnityEngine.Internal.DefaultValue("1.0f")] float depth) { GLClear(clearDepth, clearColor, backgroundColor, depth); } public static void Clear(bool clearDepth, bool clearColor, Color backgroundColor) { GLClear(clearDepth, clearColor, backgroundColor, 1f); } [FreeFunction("SetGLViewport")] public static void Viewport(Rect pixelRect) { Viewport_Injected(ref pixelRect); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ClearWithSkybox")] public static extern void ClearWithSkybox(bool clearDepth, Camera camera); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetWorldViewMatrix_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetViewMatrix_Injected(ref Matrix4x4 m); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void MultMatrix_Injected(ref Matrix4x4 m); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void LoadProjectionMatrix_Injected(ref Matrix4x4 mat); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetGPUProjectionMatrix_Injected(ref Matrix4x4 proj, bool renderIntoTexture, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GLClear_Injected(bool clearDepth, bool clearColor, ref Color backgroundColor, float depth); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Viewport_Injected(ref Rect pixelRect); } [NativeHeader("Runtime/GfxDevice/ScalableBufferManager.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static class ScalableBufferManager { public static extern float widthScaleFactor { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern float heightScaleFactor { [MethodImpl(MethodImplOptions.InternalCall)] get; } [MethodImpl(MethodImplOptions.InternalCall)] public static extern void ResizeBuffers(float widthScale, float heightScale); } [NativeHeader("Runtime/GfxDevice/FrameTiming.h")] public struct FrameTiming { [NativeName("m_CPUTimePresentCalled")] public ulong cpuTimePresentCalled; [NativeName("m_CPUFrameTime")] public double cpuFrameTime; [NativeName("m_CPUTimeFrameComplete")] public ulong cpuTimeFrameComplete; [NativeName("m_GPUFrameTime")] public double gpuFrameTime; [NativeName("m_HeightScale")] public float heightScale; [NativeName("m_WidthScale")] public float widthScale; [NativeName("m_SyncInterval")] public uint syncInterval; } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static class FrameTimingManager { [MethodImpl(MethodImplOptions.InternalCall)] public static extern void CaptureFrameTimings(); [MethodImpl(MethodImplOptions.InternalCall)] public static extern uint GetLatestTimings(uint numFrames, [Unmarshalled] FrameTiming[] timings); [MethodImpl(MethodImplOptions.InternalCall)] public static extern float GetVSyncsPerSecond(); [MethodImpl(MethodImplOptions.InternalCall)] public static extern ulong GetGpuTimerFrequency(); [MethodImpl(MethodImplOptions.InternalCall)] public static extern ulong GetCpuTimerFrequency(); } [StructLayout(LayoutKind.Sequential)] [UsedByNativeCode] [NativeHeader("Runtime/Graphics/LightmapData.h")] public sealed class LightmapData { internal Texture2D m_Light; internal Texture2D m_Dir; internal Texture2D m_ShadowMask; [Obsolete("Use lightmapColor property (UnityUpgradable) -> lightmapColor", false)] public Texture2D lightmapLight { get { return m_Light; } set { m_Light = value; } } public Texture2D lightmapColor { get { return m_Light; } set { m_Light = value; } } public Texture2D lightmapDir { get { return m_Dir; } set { m_Dir = value; } } public Texture2D shadowMask { get { return m_ShadowMask; } set { m_ShadowMask = value; } } } [StaticAccessor("GetLightmapSettings()")] [NativeHeader("Runtime/Graphics/LightmapSettings.h")] public sealed class LightmapSettings : Object { public static extern LightmapData[] lightmaps { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(ThrowsException = true)] [param: Unmarshalled] set; } public static extern LightmapsMode lightmapsMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(ThrowsException = true)] set; } public static extern LightProbes lightProbes { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetLightProbes")] [FreeFunction] set; } [Obsolete("Use lightmapsMode instead.", false)] public static LightmapsModeLegacy lightmapsModeLegacy { get { return LightmapsModeLegacy.Single; } set { } } [Obsolete("Use QualitySettings.desiredColorSpace instead.", false)] public static ColorSpace bakedColorSpace { get { return QualitySettings.desiredColorSpace; } set { } } private LightmapSettings() { } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("ResetAndAwakeFromLoad")] internal static extern void Reset(); } [StructLayout(LayoutKind.Sequential)] [NativeHeader("Runtime/Export/Graphics/Graphics.bindings.h")] public sealed class LightProbes : Object { public extern Vector3[] positions { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(HasExplicitThis = true)] [NativeName("GetLightProbePositions")] get; } public extern SphericalHarmonicsL2[] bakedProbes { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetBakedCoefficients")] [FreeFunction(HasExplicitThis = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(HasExplicitThis = true)] [NativeName("SetBakedCoefficients")] set; } public extern int count { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(HasExplicitThis = true)] [NativeName("GetLightProbeCount")] get; } public extern int cellCount { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(HasExplicitThis = true)] [NativeName("GetTetrahedraSize")] get; } [Obsolete("Use bakedProbes instead.", true)] [EditorBrowsable(EditorBrowsableState.Never)] public float[] coefficients { get { return new float[0]; } set { } } public static event Action tetrahedralizationCompleted; public static event Action needsRetetrahedralization; private LightProbes() { } [RequiredByNativeCode] private static void Internal_CallTetrahedralizationCompletedFunction() { if (LightProbes.tetrahedralizationCompleted != null) { LightProbes.tetrahedralizationCompleted(); } } [RequiredByNativeCode] private static void Internal_CallNeedsRetetrahedralizationFunction() { if (LightProbes.needsRetetrahedralization != null) { LightProbes.needsRetetrahedralization(); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void Tetrahedralize(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void TetrahedralizeAsync(); [FreeFunction] public static void GetInterpolatedProbe(Vector3 position, Renderer renderer, out SphericalHarmonicsL2 probe) { GetInterpolatedProbe_Injected(ref position, renderer, out probe); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] internal static extern bool AreLightProbesAllowed(Renderer renderer); public static void CalculateInterpolatedLightAndOcclusionProbes(Vector3[] positions, SphericalHarmonicsL2[] lightProbes, Vector4[] occlusionProbes) { if (positions == null) { throw new ArgumentNullException("positions"); } if (lightProbes == null && occlusionProbes == null) { throw new ArgumentException("Argument lightProbes and occlusionProbes cannot both be null."); } if (lightProbes != null && lightProbes.Length < positions.Length) { throw new ArgumentException("lightProbes", "Argument lightProbes has less elements than positions"); } if (occlusionProbes != null && occlusionProbes.Length < positions.Length) { throw new ArgumentException("occlusionProbes", "Argument occlusionProbes has less elements than positions"); } CalculateInterpolatedLightAndOcclusionProbes_Internal(positions, positions.Length, lightProbes, occlusionProbes); } public static void CalculateInterpolatedLightAndOcclusionProbes(List positions, List lightProbes, List occlusionProbes) { if (positions == null) { throw new ArgumentNullException("positions"); } if (lightProbes == null && occlusionProbes == null) { throw new ArgumentException("Argument lightProbes and occlusionProbes cannot both be null."); } if (lightProbes != null) { if (lightProbes.Capacity < positions.Count) { lightProbes.Capacity = positions.Count; } if (lightProbes.Count < positions.Count) { NoAllocHelpers.ResizeList(lightProbes, positions.Count); } } if (occlusionProbes != null) { if (occlusionProbes.Capacity < positions.Count) { occlusionProbes.Capacity = positions.Count; } if (occlusionProbes.Count < positions.Count) { NoAllocHelpers.ResizeList(occlusionProbes, positions.Count); } } CalculateInterpolatedLightAndOcclusionProbes_Internal(NoAllocHelpers.ExtractArrayFromListT(positions), positions.Count, NoAllocHelpers.ExtractArrayFromListT(lightProbes), NoAllocHelpers.ExtractArrayFromListT(occlusionProbes)); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("CalculateInterpolatedLightAndOcclusionProbes")] [FreeFunction] internal static extern void CalculateInterpolatedLightAndOcclusionProbes_Internal([Unmarshalled] Vector3[] positions, int positionsCount, [Unmarshalled] SphericalHarmonicsL2[] lightProbes, [Unmarshalled] Vector4[] occlusionProbes); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] [NativeName("GetLightProbeCount")] internal static extern int GetCount(); [Obsolete("Use GetInterpolatedProbe instead.", true)] [EditorBrowsable(EditorBrowsableState.Never)] public void GetInterpolatedLightProbe(Vector3 position, Renderer renderer, float[] coefficients) { } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetInterpolatedProbe_Injected(ref Vector3 position, Renderer renderer, out SphericalHarmonicsL2 probe); } public enum D3DHDRDisplayBitDepth { D3DHDRDisplayBitDepth10, D3DHDRDisplayBitDepth16 } [UsedByNativeCode] [NativeHeader("Runtime/GfxDevice/HDROutputSettings.h")] public class HDROutputSettings { private int m_DisplayIndex; public static HDROutputSettings[] displays = new HDROutputSettings[1] { new HDROutputSettings() }; private static HDROutputSettings _mainDisplay = displays[0]; public static HDROutputSettings main => _mainDisplay; public bool active => GetActive(m_DisplayIndex); public bool available => GetAvailable(m_DisplayIndex); public bool automaticHDRTonemapping { get { return GetAutomaticHDRTonemapping(m_DisplayIndex); } set { SetAutomaticHDRTonemapping(m_DisplayIndex, value); } } public ColorGamut displayColorGamut => GetDisplayColorGamut(m_DisplayIndex); public RenderTextureFormat format => GraphicsFormatUtility.GetRenderTextureFormat(GetGraphicsFormat(m_DisplayIndex)); public GraphicsFormat graphicsFormat => GetGraphicsFormat(m_DisplayIndex); public float paperWhiteNits { get { return GetPaperWhiteNits(m_DisplayIndex); } set { SetPaperWhiteNits(m_DisplayIndex, value); } } public int maxFullFrameToneMapLuminance => GetMaxFullFrameToneMapLuminance(m_DisplayIndex); public int maxToneMapLuminance => GetMaxToneMapLuminance(m_DisplayIndex); public int minToneMapLuminance => GetMinToneMapLuminance(m_DisplayIndex); public bool HDRModeChangeRequested => GetHDRModeChangeRequested(m_DisplayIndex); internal HDROutputSettings() { m_DisplayIndex = 0; } internal HDROutputSettings(int displayIndex) { m_DisplayIndex = displayIndex; } public void RequestHDRModeChange(bool enabled) { RequestHDRModeChangeInternal(m_DisplayIndex, enabled); } [Obsolete("SetPaperWhiteInNits is deprecated, please use paperWhiteNits instead.")] public static void SetPaperWhiteInNits(float paperWhite) { int displayIndex = 0; if (GetAvailable(displayIndex)) { SetPaperWhiteNits(displayIndex, paperWhite); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HDROutputSettingsBindings::GetActive", HasExplicitThis = false, ThrowsException = true)] private static extern bool GetActive(int displayIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HDROutputSettingsBindings::GetAvailable", HasExplicitThis = false, ThrowsException = true)] private static extern bool GetAvailable(int displayIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HDROutputSettingsBindings::GetAutomaticHDRTonemapping", HasExplicitThis = false, ThrowsException = true)] private static extern bool GetAutomaticHDRTonemapping(int displayIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HDROutputSettingsBindings::SetAutomaticHDRTonemapping", HasExplicitThis = false, ThrowsException = true)] private static extern void SetAutomaticHDRTonemapping(int displayIndex, bool scripted); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HDROutputSettingsBindings::GetDisplayColorGamut", HasExplicitThis = false, ThrowsException = true)] private static extern ColorGamut GetDisplayColorGamut(int displayIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HDROutputSettingsBindings::GetGraphicsFormat", HasExplicitThis = false, ThrowsException = true)] private static extern GraphicsFormat GetGraphicsFormat(int displayIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HDROutputSettingsBindings::GetPaperWhiteNits", HasExplicitThis = false, ThrowsException = true)] private static extern float GetPaperWhiteNits(int displayIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HDROutputSettingsBindings::SetPaperWhiteNits", HasExplicitThis = false, ThrowsException = true)] private static extern void SetPaperWhiteNits(int displayIndex, float paperWhite); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HDROutputSettingsBindings::GetMaxFullFrameToneMapLuminance", HasExplicitThis = false, ThrowsException = true)] private static extern int GetMaxFullFrameToneMapLuminance(int displayIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HDROutputSettingsBindings::GetMaxToneMapLuminance", HasExplicitThis = false, ThrowsException = true)] private static extern int GetMaxToneMapLuminance(int displayIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HDROutputSettingsBindings::GetMinToneMapLuminance", HasExplicitThis = false, ThrowsException = true)] private static extern int GetMinToneMapLuminance(int displayIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HDROutputSettingsBindings::GetHDRModeChangeRequested", HasExplicitThis = false, ThrowsException = true)] private static extern bool GetHDRModeChangeRequested(int displayIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HDROutputSettingsBindings::RequestHDRModeChange", HasExplicitThis = false, ThrowsException = true)] private static extern void RequestHDRModeChangeInternal(int displayIndex, bool enabled); } [RequiredByNativeCode] public struct Resolution { private int m_Width; private int m_Height; private int m_RefreshRate; public int width { get { return m_Width; } set { m_Width = value; } } public int height { get { return m_Height; } set { m_Height = value; } } public int refreshRate { get { return m_RefreshRate; } set { m_RefreshRate = value; } } public override string ToString() { return UnityString.Format("{0} x {1} @ {2}Hz", new object[3] { m_Width, m_Height, m_RefreshRate }); } } public struct RenderTargetSetup { public RenderBuffer[] color; public RenderBuffer depth; public int mipLevel; public CubemapFace cubemapFace; public int depthSlice; public RenderBufferLoadAction[] colorLoad; public RenderBufferStoreAction[] colorStore; public RenderBufferLoadAction depthLoad; public RenderBufferStoreAction depthStore; public RenderTargetSetup(RenderBuffer[] color, RenderBuffer depth, int mip, CubemapFace face, RenderBufferLoadAction[] colorLoad, RenderBufferStoreAction[] colorStore, RenderBufferLoadAction depthLoad, RenderBufferStoreAction depthStore) { this.color = color; this.depth = depth; mipLevel = mip; cubemapFace = face; depthSlice = 0; this.colorLoad = colorLoad; this.colorStore = colorStore; this.depthLoad = depthLoad; this.depthStore = depthStore; } internal static RenderBufferLoadAction[] LoadActions(RenderBuffer[] buf) { RenderBufferLoadAction[] array = new RenderBufferLoadAction[buf.Length]; for (int i = 0; i < buf.Length; i++) { array[i] = buf[i].loadAction; buf[i].loadAction = RenderBufferLoadAction.Load; } return array; } internal static RenderBufferStoreAction[] StoreActions(RenderBuffer[] buf) { RenderBufferStoreAction[] array = new RenderBufferStoreAction[buf.Length]; for (int i = 0; i < buf.Length; i++) { array[i] = buf[i].storeAction; buf[i].storeAction = RenderBufferStoreAction.Store; } return array; } public RenderTargetSetup(RenderBuffer color, RenderBuffer depth) : this(new RenderBuffer[1] { color }, depth) { } public RenderTargetSetup(RenderBuffer color, RenderBuffer depth, int mipLevel) : this(new RenderBuffer[1] { color }, depth, mipLevel) { } public RenderTargetSetup(RenderBuffer color, RenderBuffer depth, int mipLevel, CubemapFace face) : this(new RenderBuffer[1] { color }, depth, mipLevel, face) { } public RenderTargetSetup(RenderBuffer color, RenderBuffer depth, int mipLevel, CubemapFace face, int depthSlice) : this(new RenderBuffer[1] { color }, depth, mipLevel, face) { this.depthSlice = depthSlice; } public RenderTargetSetup(RenderBuffer[] color, RenderBuffer depth) : this(color, depth, 0, CubemapFace.Unknown) { } public RenderTargetSetup(RenderBuffer[] color, RenderBuffer depth, int mipLevel) : this(color, depth, mipLevel, CubemapFace.Unknown) { } public RenderTargetSetup(RenderBuffer[] color, RenderBuffer depth, int mip, CubemapFace face) : this(color, depth, mip, face, LoadActions(color), StoreActions(color), depth.loadAction, depth.storeAction) { } } public struct RenderParams { public int layer { get; set; } public uint renderingLayerMask { get; set; } public int rendererPriority { get; set; } public Bounds worldBounds { get; set; } public Camera camera { get; set; } public MotionVectorGenerationMode motionVectorMode { get; set; } public ReflectionProbeUsage reflectionProbeUsage { get; set; } public Material material { get; set; } public MaterialPropertyBlock matProps { get; set; } public ShadowCastingMode shadowCastingMode { get; set; } public bool receiveShadows { get; set; } public LightProbeUsage lightProbeUsage { get; set; } public LightProbeProxyVolume lightProbeProxyVolume { get; set; } public RenderParams(Material mat) { layer = 0; renderingLayerMask = GraphicsSettings.defaultRenderingLayerMask; rendererPriority = 0; worldBounds = new Bounds(Vector3.zero, Vector3.zero); camera = null; motionVectorMode = MotionVectorGenerationMode.Camera; reflectionProbeUsage = ReflectionProbeUsage.Off; material = mat; matProps = null; shadowCastingMode = ShadowCastingMode.Off; receiveShadows = false; lightProbeUsage = LightProbeUsage.Off; lightProbeProxyVolume = null; } } internal readonly struct RenderInstancedDataLayout { public int size { get; } public int offsetObjectToWorld { get; } public int offsetPrevObjectToWorld { get; } public int offsetRenderingLayerMask { get; } public RenderInstancedDataLayout(Type t) { size = Marshal.SizeOf(t); offsetObjectToWorld = (((object)t != typeof(Matrix4x4)) ? Marshal.OffsetOf(t, "objectToWorld").ToInt32() : 0); try { offsetPrevObjectToWorld = Marshal.OffsetOf(t, "prevObjectToWorld").ToInt32(); } catch (ArgumentException) { offsetPrevObjectToWorld = -1; } try { offsetRenderingLayerMask = Marshal.OffsetOf(t, "renderingLayerMask").ToInt32(); } catch (ArgumentException) { offsetRenderingLayerMask = -1; } } } [VisibleToOtherModules(new string[] { "UnityEngine.IMGUIModule" })] internal struct Internal_DrawTextureArguments { public Rect screenRect; public Rect sourceRect; public int leftBorder; public int rightBorder; public int topBorder; public int bottomBorder; public Color leftBorderColor; public Color rightBorderColor; public Color topBorderColor; public Color bottomBorderColor; public Color color; public Vector4 borderWidths; public Vector4 cornerRadiuses; public bool smoothCorners; public int pass; public Texture texture; public Material mat; } [NativeHeader("Runtime/Misc/PlayerSettings.h")] [NativeHeader("Runtime/Graphics/QualitySettings.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public sealed class QualitySettings : Object { [Obsolete("Use GetQualityLevel and SetQualityLevel", false)] public static QualityLevel currentLevel { get { return (QualityLevel)GetQualityLevel(); } set { SetQualityLevel((int)value, applyExpensiveChanges: true); } } public static extern int pixelLightCount { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("ShadowQuality")] public static extern ShadowQuality shadows { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern ShadowProjection shadowProjection { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int shadowCascades { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern float shadowDistance { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("ShadowResolution")] public static extern ShadowResolution shadowResolution { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("ShadowmaskMode")] public static extern ShadowmaskMode shadowmaskMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern float shadowNearPlaneOffset { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern float shadowCascade2Split { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static Vector3 shadowCascade4Split { get { get_shadowCascade4Split_Injected(out var ret); return ret; } set { set_shadowCascade4Split_Injected(ref value); } } [NativeProperty("LODBias")] public static extern float lodBias { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("AnisotropicTextures")] public static extern AnisotropicFiltering anisotropicFiltering { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int masterTextureLimit { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int maximumLODLevel { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int particleRaycastBudget { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool softParticles { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool softVegetation { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int vSyncCount { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int realtimeGICPUUsage { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int antiAliasing { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int asyncUploadTimeSlice { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int asyncUploadBufferSize { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool asyncUploadPersistentBuffer { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool realtimeReflectionProbes { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool billboardsFaceCameraPosition { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern float resolutionScalingFixedDPIFactor { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeName("RenderPipeline")] private static extern ScriptableObject INTERNAL_renderPipeline { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static RenderPipelineAsset renderPipeline { get { return INTERNAL_renderPipeline as RenderPipelineAsset; } set { INTERNAL_renderPipeline = value; } } [Obsolete("blendWeights is obsolete. Use skinWeights instead (UnityUpgradable) -> skinWeights", true)] public static extern BlendWeights blendWeights { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetSkinWeights")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetSkinWeights")] set; } public static extern SkinWeights skinWeights { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool streamingMipmapsActive { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern float streamingMipmapsMemoryBudget { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int streamingMipmapsRenderersPerFrame { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int streamingMipmapsMaxLevelReduction { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool streamingMipmapsAddAllCameras { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int streamingMipmapsMaxFileIORequests { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern int maxQueuedFrames { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("QualitySettingsNames")] public static extern string[] names { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern ColorSpace desiredColorSpace { [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeName("GetColorSpace")] get; } public static extern ColorSpace activeColorSpace { [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeName("GetColorSpace")] get; } public static void IncreaseLevel([UnityEngine.Internal.DefaultValue("false")] bool applyExpensiveChanges) { SetQualityLevel(GetQualityLevel() + 1, applyExpensiveChanges); } public static void DecreaseLevel([UnityEngine.Internal.DefaultValue("false")] bool applyExpensiveChanges) { SetQualityLevel(GetQualityLevel() - 1, applyExpensiveChanges); } public static void SetQualityLevel(int index) { SetQualityLevel(index, applyExpensiveChanges: true); } public static void IncreaseLevel() { IncreaseLevel(applyExpensiveChanges: false); } public static void DecreaseLevel() { DecreaseLevel(applyExpensiveChanges: false); } private QualitySettings() { } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetLODSettings")] public static extern void SetLODSettings(float lodBias, int maximumLODLevel, bool setDirty = true); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetRenderPipelineAssetAt")] internal static extern ScriptableObject InternalGetRenderPipelineAssetAt(int index); public static RenderPipelineAsset GetRenderPipelineAssetAt(int index) { if (index < 0 || index >= names.Length) { throw new IndexOutOfRangeException(string.Format("{0} is out of range [0..{1}[", "index", names.Length)); } return InternalGetRenderPipelineAssetAt(index) as RenderPipelineAsset; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetCurrentIndex")] public static extern int GetQualityLevel(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern Object GetQualitySettings(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetCurrentIndex")] public static extern void SetQualityLevel(int index, [UnityEngine.Internal.DefaultValue("true")] bool applyExpensiveChanges); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_shadowCascade4Split_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_shadowCascade4Split_Injected(ref Vector3 value); } [NativeHeader("Runtime/Graphics/GraphicsScriptBindings.h")] public static class RendererExtensions { public static void UpdateGIMaterials(this Renderer renderer) { UpdateGIMaterialsForRenderer(renderer); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RendererScripting::UpdateGIMaterialsForRenderer")] internal static extern void UpdateGIMaterialsForRenderer(Renderer renderer); } [UsedByNativeCode] public sealed class ImageEffectTransformsToLDR : Attribute { } public sealed class ImageEffectAllowedInSceneView : Attribute { } [UsedByNativeCode] public sealed class ImageEffectOpaque : Attribute { } [UsedByNativeCode] public sealed class ImageEffectAfterScale : Attribute { } [AttributeUsage(AttributeTargets.Method)] [UsedByNativeCode] public sealed class ImageEffectUsesCommandBuffer : Attribute { } public enum LightmapsModeLegacy { Single, Dual, Directional } [NativeHeader("Runtime/Graphics/GraphicsScriptBindings.h")] [NativeHeader("Runtime/Graphics/TrailRenderer.h")] public sealed class TrailRenderer : Renderer { [Obsolete("Use positionCount instead (UnityUpgradable) -> positionCount", false)] public int numPositions => positionCount; public extern float time { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float startWidth { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float endWidth { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float widthMultiplier { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool autodestruct { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool emitting { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int numCornerVertices { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int numCapVertices { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float minVertexDistance { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Color startColor { get { get_startColor_Injected(out var ret); return ret; } set { set_startColor_Injected(ref value); } } public Color endColor { get { get_endColor_Injected(out var ret); return ret; } set { set_endColor_Injected(ref value); } } [NativeProperty("PositionsCount")] public extern int positionCount { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern float shadowBias { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool generateLightingData { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern LineTextureMode textureMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern LineAlignment alignment { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public AnimationCurve widthCurve { get { return GetWidthCurveCopy(); } set { SetWidthCurve(value); } } public Gradient colorGradient { get { return GetColorGradientCopy(); } set { SetColorGradient(value); } } public void SetPosition(int index, Vector3 position) { SetPosition_Injected(index, ref position); } public Vector3 GetPosition(int index) { GetPosition_Injected(index, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] public extern void Clear(); public void BakeMesh(Mesh mesh, bool useTransform = false) { BakeMesh(mesh, Camera.main, useTransform); } [MethodImpl(MethodImplOptions.InternalCall)] public extern void BakeMesh([NotNull("ArgumentNullException")] Mesh mesh, [NotNull("ArgumentNullException")] Camera camera, bool useTransform = false); [MethodImpl(MethodImplOptions.InternalCall)] private extern AnimationCurve GetWidthCurveCopy(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetWidthCurve([NotNull("ArgumentNullException")] AnimationCurve curve); [MethodImpl(MethodImplOptions.InternalCall)] private extern Gradient GetColorGradientCopy(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetColorGradient([NotNull("ArgumentNullException")] Gradient curve); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "TrailRendererScripting::GetPositions", HasExplicitThis = true)] public extern int GetPositions([Out][NotNull("ArgumentNullException")] Vector3[] positions); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "TrailRendererScripting::GetVisiblePositions", HasExplicitThis = true)] public extern int GetVisiblePositions([Out][NotNull("ArgumentNullException")] Vector3[] positions); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "TrailRendererScripting::SetPositions", HasExplicitThis = true)] public extern void SetPositions([NotNull("ArgumentNullException")] Vector3[] positions); [FreeFunction(Name = "TrailRendererScripting::AddPosition", HasExplicitThis = true)] public void AddPosition(Vector3 position) { AddPosition_Injected(ref position); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "TrailRendererScripting::AddPositions", HasExplicitThis = true)] public extern void AddPositions([NotNull("ArgumentNullException")] Vector3[] positions); public unsafe void SetPositions(NativeArray positions) { SetPositionsWithNativeContainer((IntPtr)positions.GetUnsafeReadOnlyPtr(), positions.Length); } public unsafe void SetPositions(NativeSlice positions) { SetPositionsWithNativeContainer((IntPtr)positions.GetUnsafeReadOnlyPtr(), positions.Length); } public unsafe int GetPositions([Out] NativeArray positions) { return GetPositionsWithNativeContainer((IntPtr)positions.GetUnsafePtr(), positions.Length); } public unsafe int GetPositions([Out] NativeSlice positions) { return GetPositionsWithNativeContainer((IntPtr)positions.GetUnsafePtr(), positions.Length); } public unsafe int GetVisiblePositions([Out] NativeArray positions) { return GetVisiblePositionsWithNativeContainer((IntPtr)positions.GetUnsafePtr(), positions.Length); } public unsafe int GetVisiblePositions([Out] NativeSlice positions) { return GetVisiblePositionsWithNativeContainer((IntPtr)positions.GetUnsafePtr(), positions.Length); } public unsafe void AddPositions([Out] NativeArray positions) { AddPositionsWithNativeContainer((IntPtr)positions.GetUnsafePtr(), positions.Length); } public unsafe void AddPositions([Out] NativeSlice positions) { AddPositionsWithNativeContainer((IntPtr)positions.GetUnsafePtr(), positions.Length); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "TrailRendererScripting::SetPositionsWithNativeContainer", HasExplicitThis = true)] private extern void SetPositionsWithNativeContainer(IntPtr positions, int count); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "TrailRendererScripting::GetPositionsWithNativeContainer", HasExplicitThis = true)] private extern int GetPositionsWithNativeContainer(IntPtr positions, int length); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "TrailRendererScripting::GetVisiblePositionsWithNativeContainer", HasExplicitThis = true)] private extern int GetVisiblePositionsWithNativeContainer(IntPtr positions, int length); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "TrailRendererScripting::AddPositionsWithNativeContainer", HasExplicitThis = true)] private extern void AddPositionsWithNativeContainer(IntPtr positions, int length); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_startColor_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_startColor_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_endColor_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_endColor_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetPosition_Injected(int index, ref Vector3 position); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetPosition_Injected(int index, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void AddPosition_Injected(ref Vector3 position); } [NativeHeader("Runtime/Graphics/GraphicsScriptBindings.h")] [NativeHeader("Runtime/Graphics/LineRenderer.h")] public sealed class LineRenderer : Renderer { [Obsolete("Use positionCount instead (UnityUpgradable) -> positionCount", false)] public int numPositions { get { return positionCount; } set { positionCount = value; } } public extern float startWidth { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float endWidth { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float widthMultiplier { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int numCornerVertices { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int numCapVertices { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool useWorldSpace { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool loop { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Color startColor { get { get_startColor_Injected(out var ret); return ret; } set { set_startColor_Injected(ref value); } } public Color endColor { get { get_endColor_Injected(out var ret); return ret; } set { set_endColor_Injected(ref value); } } [NativeProperty("PositionsCount")] public extern int positionCount { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float shadowBias { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool generateLightingData { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern LineTextureMode textureMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern LineAlignment alignment { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public AnimationCurve widthCurve { get { return GetWidthCurveCopy(); } set { SetWidthCurve(value); } } public Gradient colorGradient { get { return GetColorGradientCopy(); } set { SetColorGradient(value); } } [Obsolete("Use startWidth, endWidth or widthCurve instead.", false)] public void SetWidth(float start, float end) { startWidth = start; endWidth = end; } [Obsolete("Use startColor, endColor or colorGradient instead.", false)] public void SetColors(Color start, Color end) { startColor = start; endColor = end; } [Obsolete("Use positionCount instead.", false)] public void SetVertexCount(int count) { positionCount = count; } public void SetPosition(int index, Vector3 position) { SetPosition_Injected(index, ref position); } public Vector3 GetPosition(int index) { GetPosition_Injected(index, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] public extern void Simplify(float tolerance); public void BakeMesh(Mesh mesh, bool useTransform = false) { BakeMesh(mesh, Camera.main, useTransform); } [MethodImpl(MethodImplOptions.InternalCall)] public extern void BakeMesh([NotNull("ArgumentNullException")] Mesh mesh, [NotNull("ArgumentNullException")] Camera camera, bool useTransform = false); [MethodImpl(MethodImplOptions.InternalCall)] private extern AnimationCurve GetWidthCurveCopy(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetWidthCurve([NotNull("ArgumentNullException")] AnimationCurve curve); [MethodImpl(MethodImplOptions.InternalCall)] private extern Gradient GetColorGradientCopy(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetColorGradient([NotNull("ArgumentNullException")] Gradient curve); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "LineRendererScripting::GetPositions", HasExplicitThis = true)] public extern int GetPositions([Out][NotNull("ArgumentNullException")] Vector3[] positions); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "LineRendererScripting::SetPositions", HasExplicitThis = true)] public extern void SetPositions([NotNull("ArgumentNullException")] Vector3[] positions); public unsafe void SetPositions(NativeArray positions) { SetPositionsWithNativeContainer((IntPtr)positions.GetUnsafeReadOnlyPtr(), positions.Length); } public unsafe void SetPositions(NativeSlice positions) { SetPositionsWithNativeContainer((IntPtr)positions.GetUnsafeReadOnlyPtr(), positions.Length); } public unsafe int GetPositions([Out] NativeArray positions) { return GetPositionsWithNativeContainer((IntPtr)positions.GetUnsafePtr(), positions.Length); } public unsafe int GetPositions([Out] NativeSlice positions) { return GetPositionsWithNativeContainer((IntPtr)positions.GetUnsafePtr(), positions.Length); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "LineRendererScripting::SetPositionsWithNativeContainer", HasExplicitThis = true)] private extern void SetPositionsWithNativeContainer(IntPtr positions, int count); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "LineRendererScripting::GetPositionsWithNativeContainer", HasExplicitThis = true)] private extern int GetPositionsWithNativeContainer(IntPtr positions, int length); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_startColor_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_startColor_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_endColor_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_endColor_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetPosition_Injected(int index, ref Vector3 position); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetPosition_Injected(int index, out Vector3 ret); } [NativeHeader("Runtime/Graphics/ShaderScriptBindings.h")] [NativeHeader("Runtime/Shaders/ComputeShader.h")] [NativeHeader("Runtime/Math/SphericalHarmonicsL2.h")] [NativeHeader("Runtime/Shaders/ShaderPropertySheet.h")] public sealed class MaterialPropertyBlock { internal IntPtr m_Ptr; public extern bool isEmpty { [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeName("IsEmpty")] get; } [Obsolete("Use SetFloat instead (UnityUpgradable) -> SetFloat(*)", false)] public void AddFloat(string name, float value) { SetFloat(Shader.PropertyToID(name), value); } [Obsolete("Use SetFloat instead (UnityUpgradable) -> SetFloat(*)", false)] public void AddFloat(int nameID, float value) { SetFloat(nameID, value); } [Obsolete("Use SetVector instead (UnityUpgradable) -> SetVector(*)", false)] public void AddVector(string name, Vector4 value) { SetVector(Shader.PropertyToID(name), value); } [Obsolete("Use SetVector instead (UnityUpgradable) -> SetVector(*)", false)] public void AddVector(int nameID, Vector4 value) { SetVector(nameID, value); } [Obsolete("Use SetColor instead (UnityUpgradable) -> SetColor(*)", false)] public void AddColor(string name, Color value) { SetColor(Shader.PropertyToID(name), value); } [Obsolete("Use SetColor instead (UnityUpgradable) -> SetColor(*)", false)] public void AddColor(int nameID, Color value) { SetColor(nameID, value); } [Obsolete("Use SetMatrix instead (UnityUpgradable) -> SetMatrix(*)", false)] public void AddMatrix(string name, Matrix4x4 value) { SetMatrix(Shader.PropertyToID(name), value); } [Obsolete("Use SetMatrix instead (UnityUpgradable) -> SetMatrix(*)", false)] public void AddMatrix(int nameID, Matrix4x4 value) { SetMatrix(nameID, value); } [Obsolete("Use SetTexture instead (UnityUpgradable) -> SetTexture(*)", false)] public void AddTexture(string name, Texture value) { SetTexture(Shader.PropertyToID(name), value); } [Obsolete("Use SetTexture instead (UnityUpgradable) -> SetTexture(*)", false)] public void AddTexture(int nameID, Texture value) { SetTexture(nameID, value); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetIntFromScript")] [ThreadSafe] private extern int GetIntImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeName("GetFloatFromScript")] private extern float GetFloatImpl(int name); [NativeName("GetVectorFromScript")] [ThreadSafe] private Vector4 GetVectorImpl(int name) { GetVectorImpl_Injected(name, out var ret); return ret; } [ThreadSafe] [NativeName("GetColorFromScript")] private Color GetColorImpl(int name) { GetColorImpl_Injected(name, out var ret); return ret; } [ThreadSafe] [NativeName("GetMatrixFromScript")] private Matrix4x4 GetMatrixImpl(int name) { GetMatrixImpl_Injected(name, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetTextureFromScript")] [ThreadSafe] private extern Texture GetTextureImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasPropertyFromScript")] private extern bool HasPropertyImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasFloatFromScript")] private extern bool HasFloatImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasIntegerFromScript")] private extern bool HasIntImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasTextureFromScript")] private extern bool HasTextureImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasMatrixFromScript")] private extern bool HasMatrixImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasVectorFromScript")] private extern bool HasVectorImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasBufferFromScript")] private extern bool HasBufferImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasConstantBufferFromScript")] private extern bool HasConstantBufferImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeName("SetIntFromScript")] private extern void SetIntImpl(int name, int value); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetFloatFromScript")] [ThreadSafe] private extern void SetFloatImpl(int name, float value); [NativeName("SetVectorFromScript")] [ThreadSafe] private void SetVectorImpl(int name, Vector4 value) { SetVectorImpl_Injected(name, ref value); } [NativeName("SetColorFromScript")] [ThreadSafe] private void SetColorImpl(int name, Color value) { SetColorImpl_Injected(name, ref value); } [NativeName("SetMatrixFromScript")] [ThreadSafe] private void SetMatrixImpl(int name, Matrix4x4 value) { SetMatrixImpl_Injected(name, ref value); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeName("SetTextureFromScript")] private extern void SetTextureImpl(int name, [NotNull("ArgumentNullException")] Texture value); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetRenderTextureFromScript")] [ThreadSafe] private extern void SetRenderTextureImpl(int name, [NotNull("ArgumentNullException")] RenderTexture value, RenderTextureSubElement element); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetBufferFromScript")] [ThreadSafe] private extern void SetBufferImpl(int name, ComputeBuffer value); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetBufferFromScript")] [ThreadSafe] private extern void SetGraphicsBufferImpl(int name, GraphicsBuffer value); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetConstantBufferFromScript")] [ThreadSafe] private extern void SetConstantBufferImpl(int name, ComputeBuffer value, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetConstantBufferFromScript")] [ThreadSafe] private extern void SetConstantGraphicsBufferImpl(int name, GraphicsBuffer value, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeName("SetFloatArrayFromScript")] private extern void SetFloatArrayImpl(int name, float[] values, int count); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeName("SetVectorArrayFromScript")] private extern void SetVectorArrayImpl(int name, Vector4[] values, int count); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetMatrixArrayFromScript")] [ThreadSafe] private extern void SetMatrixArrayImpl(int name, Matrix4x4[] values, int count); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetFloatArrayFromScript")] [ThreadSafe] private extern float[] GetFloatArrayImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeName("GetVectorArrayFromScript")] private extern Vector4[] GetVectorArrayImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeName("GetMatrixArrayFromScript")] private extern Matrix4x4[] GetMatrixArrayImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetFloatArrayCountFromScript")] [ThreadSafe] private extern int GetFloatArrayCountImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeName("GetVectorArrayCountFromScript")] private extern int GetVectorArrayCountImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetMatrixArrayCountFromScript")] [ThreadSafe] private extern int GetMatrixArrayCountImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("ExtractFloatArrayFromScript")] [ThreadSafe] private extern void ExtractFloatArrayImpl(int name, [Out] float[] val); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeName("ExtractVectorArrayFromScript")] private extern void ExtractVectorArrayImpl(int name, [Out] Vector4[] val); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeName("ExtractMatrixArrayFromScript")] private extern void ExtractMatrixArrayImpl(int name, [Out] Matrix4x4[] val); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ConvertAndCopySHCoefficientArraysToPropertySheetFromScript")] [ThreadSafe] internal static extern void Internal_CopySHCoefficientArraysFrom(MaterialPropertyBlock properties, SphericalHarmonicsL2[] lightProbes, int sourceStart, int destStart, int count); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [FreeFunction("CopyProbeOcclusionArrayToPropertySheetFromScript")] internal static extern void Internal_CopyProbeOcclusionArrayFrom(MaterialPropertyBlock properties, Vector4[] occlusionProbes, int sourceStart, int destStart, int count); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "MaterialPropertyBlockScripting::Create", IsFreeFunction = true)] private static extern IntPtr CreateImpl(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "MaterialPropertyBlockScripting::Destroy", IsFreeFunction = true, IsThreadSafe = true)] private static extern void DestroyImpl(IntPtr mpb); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] private extern void Clear(bool keepMemory); public void Clear() { Clear(keepMemory: true); } private void SetFloatArray(int name, float[] values, int count) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Length == 0) { throw new ArgumentException("Zero-sized array is not allowed."); } if (values.Length < count) { throw new ArgumentException("array has less elements than passed count."); } SetFloatArrayImpl(name, values, count); } private void SetVectorArray(int name, Vector4[] values, int count) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Length == 0) { throw new ArgumentException("Zero-sized array is not allowed."); } if (values.Length < count) { throw new ArgumentException("array has less elements than passed count."); } SetVectorArrayImpl(name, values, count); } private void SetMatrixArray(int name, Matrix4x4[] values, int count) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Length == 0) { throw new ArgumentException("Zero-sized array is not allowed."); } if (values.Length < count) { throw new ArgumentException("array has less elements than passed count."); } SetMatrixArrayImpl(name, values, count); } private void ExtractFloatArray(int name, List values) { if (values == null) { throw new ArgumentNullException("values"); } values.Clear(); int floatArrayCountImpl = GetFloatArrayCountImpl(name); if (floatArrayCountImpl > 0) { NoAllocHelpers.EnsureListElemCount(values, floatArrayCountImpl); ExtractFloatArrayImpl(name, (float[])NoAllocHelpers.ExtractArrayFromList(values)); } } private void ExtractVectorArray(int name, List values) { if (values == null) { throw new ArgumentNullException("values"); } values.Clear(); int vectorArrayCountImpl = GetVectorArrayCountImpl(name); if (vectorArrayCountImpl > 0) { NoAllocHelpers.EnsureListElemCount(values, vectorArrayCountImpl); ExtractVectorArrayImpl(name, (Vector4[])NoAllocHelpers.ExtractArrayFromList(values)); } } private void ExtractMatrixArray(int name, List values) { if (values == null) { throw new ArgumentNullException("values"); } values.Clear(); int matrixArrayCountImpl = GetMatrixArrayCountImpl(name); if (matrixArrayCountImpl > 0) { NoAllocHelpers.EnsureListElemCount(values, matrixArrayCountImpl); ExtractMatrixArrayImpl(name, (Matrix4x4[])NoAllocHelpers.ExtractArrayFromList(values)); } } public MaterialPropertyBlock() { m_Ptr = CreateImpl(); } ~MaterialPropertyBlock() { Dispose(); } private void Dispose() { if (m_Ptr != IntPtr.Zero) { DestroyImpl(m_Ptr); m_Ptr = IntPtr.Zero; } GC.SuppressFinalize(this); } public void SetInt(string name, int value) { SetFloatImpl(Shader.PropertyToID(name), value); } public void SetInt(int nameID, int value) { SetFloatImpl(nameID, value); } public void SetFloat(string name, float value) { SetFloatImpl(Shader.PropertyToID(name), value); } public void SetFloat(int nameID, float value) { SetFloatImpl(nameID, value); } public void SetInteger(string name, int value) { SetIntImpl(Shader.PropertyToID(name), value); } public void SetInteger(int nameID, int value) { SetIntImpl(nameID, value); } public void SetVector(string name, Vector4 value) { SetVectorImpl(Shader.PropertyToID(name), value); } public void SetVector(int nameID, Vector4 value) { SetVectorImpl(nameID, value); } public void SetColor(string name, Color value) { SetColorImpl(Shader.PropertyToID(name), value); } public void SetColor(int nameID, Color value) { SetColorImpl(nameID, value); } public void SetMatrix(string name, Matrix4x4 value) { SetMatrixImpl(Shader.PropertyToID(name), value); } public void SetMatrix(int nameID, Matrix4x4 value) { SetMatrixImpl(nameID, value); } public void SetBuffer(string name, ComputeBuffer value) { SetBufferImpl(Shader.PropertyToID(name), value); } public void SetBuffer(int nameID, ComputeBuffer value) { SetBufferImpl(nameID, value); } public void SetBuffer(string name, GraphicsBuffer value) { SetGraphicsBufferImpl(Shader.PropertyToID(name), value); } public void SetBuffer(int nameID, GraphicsBuffer value) { SetGraphicsBufferImpl(nameID, value); } public void SetTexture(string name, Texture value) { SetTextureImpl(Shader.PropertyToID(name), value); } public void SetTexture(int nameID, Texture value) { SetTextureImpl(nameID, value); } public void SetTexture(string name, RenderTexture value, RenderTextureSubElement element) { SetRenderTextureImpl(Shader.PropertyToID(name), value, element); } public void SetTexture(int nameID, RenderTexture value, RenderTextureSubElement element) { SetRenderTextureImpl(nameID, value, element); } public void SetConstantBuffer(string name, ComputeBuffer value, int offset, int size) { SetConstantBufferImpl(Shader.PropertyToID(name), value, offset, size); } public void SetConstantBuffer(int nameID, ComputeBuffer value, int offset, int size) { SetConstantBufferImpl(nameID, value, offset, size); } public void SetConstantBuffer(string name, GraphicsBuffer value, int offset, int size) { SetConstantGraphicsBufferImpl(Shader.PropertyToID(name), value, offset, size); } public void SetConstantBuffer(int nameID, GraphicsBuffer value, int offset, int size) { SetConstantGraphicsBufferImpl(nameID, value, offset, size); } public void SetFloatArray(string name, List values) { SetFloatArray(Shader.PropertyToID(name), NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetFloatArray(int nameID, List values) { SetFloatArray(nameID, NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetFloatArray(string name, float[] values) { SetFloatArray(Shader.PropertyToID(name), values, values.Length); } public void SetFloatArray(int nameID, float[] values) { SetFloatArray(nameID, values, values.Length); } public void SetVectorArray(string name, List values) { SetVectorArray(Shader.PropertyToID(name), NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetVectorArray(int nameID, List values) { SetVectorArray(nameID, NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetVectorArray(string name, Vector4[] values) { SetVectorArray(Shader.PropertyToID(name), values, values.Length); } public void SetVectorArray(int nameID, Vector4[] values) { SetVectorArray(nameID, values, values.Length); } public void SetMatrixArray(string name, List values) { SetMatrixArray(Shader.PropertyToID(name), NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetMatrixArray(int nameID, List values) { SetMatrixArray(nameID, NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetMatrixArray(string name, Matrix4x4[] values) { SetMatrixArray(Shader.PropertyToID(name), values, values.Length); } public void SetMatrixArray(int nameID, Matrix4x4[] values) { SetMatrixArray(nameID, values, values.Length); } public bool HasProperty(string name) { return HasPropertyImpl(Shader.PropertyToID(name)); } public bool HasProperty(int nameID) { return HasPropertyImpl(nameID); } public bool HasInt(string name) { return HasFloatImpl(Shader.PropertyToID(name)); } public bool HasInt(int nameID) { return HasFloatImpl(nameID); } public bool HasFloat(string name) { return HasFloatImpl(Shader.PropertyToID(name)); } public bool HasFloat(int nameID) { return HasFloatImpl(nameID); } public bool HasInteger(string name) { return HasIntImpl(Shader.PropertyToID(name)); } public bool HasInteger(int nameID) { return HasIntImpl(nameID); } public bool HasTexture(string name) { return HasTextureImpl(Shader.PropertyToID(name)); } public bool HasTexture(int nameID) { return HasTextureImpl(nameID); } public bool HasMatrix(string name) { return HasMatrixImpl(Shader.PropertyToID(name)); } public bool HasMatrix(int nameID) { return HasMatrixImpl(nameID); } public bool HasVector(string name) { return HasVectorImpl(Shader.PropertyToID(name)); } public bool HasVector(int nameID) { return HasVectorImpl(nameID); } public bool HasColor(string name) { return HasVectorImpl(Shader.PropertyToID(name)); } public bool HasColor(int nameID) { return HasVectorImpl(nameID); } public bool HasBuffer(string name) { return HasBufferImpl(Shader.PropertyToID(name)); } public bool HasBuffer(int nameID) { return HasBufferImpl(nameID); } public bool HasConstantBuffer(string name) { return HasConstantBufferImpl(Shader.PropertyToID(name)); } public bool HasConstantBuffer(int nameID) { return HasConstantBufferImpl(nameID); } public float GetFloat(string name) { return GetFloatImpl(Shader.PropertyToID(name)); } public float GetFloat(int nameID) { return GetFloatImpl(nameID); } public int GetInt(string name) { return (int)GetFloatImpl(Shader.PropertyToID(name)); } public int GetInt(int nameID) { return (int)GetFloatImpl(nameID); } public int GetInteger(string name) { return GetIntImpl(Shader.PropertyToID(name)); } public int GetInteger(int nameID) { return GetIntImpl(nameID); } public Vector4 GetVector(string name) { return GetVectorImpl(Shader.PropertyToID(name)); } public Vector4 GetVector(int nameID) { return GetVectorImpl(nameID); } public Color GetColor(string name) { return GetColorImpl(Shader.PropertyToID(name)); } public Color GetColor(int nameID) { return GetColorImpl(nameID); } public Matrix4x4 GetMatrix(string name) { return GetMatrixImpl(Shader.PropertyToID(name)); } public Matrix4x4 GetMatrix(int nameID) { return GetMatrixImpl(nameID); } public Texture GetTexture(string name) { return GetTextureImpl(Shader.PropertyToID(name)); } public Texture GetTexture(int nameID) { return GetTextureImpl(nameID); } public float[] GetFloatArray(string name) { return GetFloatArray(Shader.PropertyToID(name)); } public float[] GetFloatArray(int nameID) { return (GetFloatArrayCountImpl(nameID) != 0) ? GetFloatArrayImpl(nameID) : null; } public Vector4[] GetVectorArray(string name) { return GetVectorArray(Shader.PropertyToID(name)); } public Vector4[] GetVectorArray(int nameID) { return (GetVectorArrayCountImpl(nameID) != 0) ? GetVectorArrayImpl(nameID) : null; } public Matrix4x4[] GetMatrixArray(string name) { return GetMatrixArray(Shader.PropertyToID(name)); } public Matrix4x4[] GetMatrixArray(int nameID) { return (GetMatrixArrayCountImpl(nameID) != 0) ? GetMatrixArrayImpl(nameID) : null; } public void GetFloatArray(string name, List values) { ExtractFloatArray(Shader.PropertyToID(name), values); } public void GetFloatArray(int nameID, List values) { ExtractFloatArray(nameID, values); } public void GetVectorArray(string name, List values) { ExtractVectorArray(Shader.PropertyToID(name), values); } public void GetVectorArray(int nameID, List values) { ExtractVectorArray(nameID, values); } public void GetMatrixArray(string name, List values) { ExtractMatrixArray(Shader.PropertyToID(name), values); } public void GetMatrixArray(int nameID, List values) { ExtractMatrixArray(nameID, values); } public void CopySHCoefficientArraysFrom(List lightProbes) { if (lightProbes == null) { throw new ArgumentNullException("lightProbes"); } CopySHCoefficientArraysFrom(NoAllocHelpers.ExtractArrayFromListT(lightProbes), 0, 0, lightProbes.Count); } public void CopySHCoefficientArraysFrom(SphericalHarmonicsL2[] lightProbes) { if (lightProbes == null) { throw new ArgumentNullException("lightProbes"); } CopySHCoefficientArraysFrom(lightProbes, 0, 0, lightProbes.Length); } public void CopySHCoefficientArraysFrom(List lightProbes, int sourceStart, int destStart, int count) { CopySHCoefficientArraysFrom(NoAllocHelpers.ExtractArrayFromListT(lightProbes), sourceStart, destStart, count); } public void CopySHCoefficientArraysFrom(SphericalHarmonicsL2[] lightProbes, int sourceStart, int destStart, int count) { if (lightProbes == null) { throw new ArgumentNullException("lightProbes"); } if (sourceStart < 0) { throw new ArgumentOutOfRangeException("sourceStart", "Argument sourceStart must not be negative."); } if (destStart < 0) { throw new ArgumentOutOfRangeException("sourceStart", "Argument destStart must not be negative."); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "Argument count must not be negative."); } if (lightProbes.Length < sourceStart + count) { throw new ArgumentOutOfRangeException("The specified source start index or count is out of the range."); } Internal_CopySHCoefficientArraysFrom(this, lightProbes, sourceStart, destStart, count); } public void CopyProbeOcclusionArrayFrom(List occlusionProbes) { if (occlusionProbes == null) { throw new ArgumentNullException("occlusionProbes"); } CopyProbeOcclusionArrayFrom(NoAllocHelpers.ExtractArrayFromListT(occlusionProbes), 0, 0, occlusionProbes.Count); } public void CopyProbeOcclusionArrayFrom(Vector4[] occlusionProbes) { if (occlusionProbes == null) { throw new ArgumentNullException("occlusionProbes"); } CopyProbeOcclusionArrayFrom(occlusionProbes, 0, 0, occlusionProbes.Length); } public void CopyProbeOcclusionArrayFrom(List occlusionProbes, int sourceStart, int destStart, int count) { CopyProbeOcclusionArrayFrom(NoAllocHelpers.ExtractArrayFromListT(occlusionProbes), sourceStart, destStart, count); } public void CopyProbeOcclusionArrayFrom(Vector4[] occlusionProbes, int sourceStart, int destStart, int count) { if (occlusionProbes == null) { throw new ArgumentNullException("occlusionProbes"); } if (sourceStart < 0) { throw new ArgumentOutOfRangeException("sourceStart", "Argument sourceStart must not be negative."); } if (destStart < 0) { throw new ArgumentOutOfRangeException("sourceStart", "Argument destStart must not be negative."); } if (count < 0) { throw new ArgumentOutOfRangeException("count", "Argument count must not be negative."); } if (occlusionProbes.Length < sourceStart + count) { throw new ArgumentOutOfRangeException("The specified source start index or count is out of the range."); } Internal_CopyProbeOcclusionArrayFrom(this, occlusionProbes, sourceStart, destStart, count); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetVectorImpl_Injected(int name, out Vector4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetColorImpl_Injected(int name, out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetMatrixImpl_Injected(int name, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetVectorImpl_Injected(int name, ref Vector4 value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetColorImpl_Injected(int name, ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetMatrixImpl_Injected(int name, ref Matrix4x4 value); } [NativeHeader("Runtime/Graphics/GraphicsScriptBindings.h")] [NativeHeader("Runtime/Graphics/Renderer.h")] [UsedByNativeCode] [RequireComponent(typeof(Transform))] public class Renderer : Component { [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use shadowCastingMode instead.", false)] public bool castShadows { get { return shadowCastingMode != ShadowCastingMode.Off; } set { shadowCastingMode = (value ? ShadowCastingMode.On : ShadowCastingMode.Off); } } [Obsolete("Use motionVectorGenerationMode instead.", false)] public bool motionVectors { get { return motionVectorGenerationMode == MotionVectorGenerationMode.Object; } set { motionVectorGenerationMode = (value ? MotionVectorGenerationMode.Object : MotionVectorGenerationMode.Camera); } } [Obsolete("Use lightProbeUsage instead.", false)] public bool useLightProbes { get { return lightProbeUsage != LightProbeUsage.Off; } set { lightProbeUsage = (value ? LightProbeUsage.BlendProbes : LightProbeUsage.Off); } } public Bounds bounds { [FreeFunction(Name = "RendererScripting::GetWorldBounds", HasExplicitThis = true)] get { get_bounds_Injected(out var ret); return ret; } [NativeName("SetWorldAABB")] set { set_bounds_Injected(ref value); } } public Bounds localBounds { [FreeFunction(Name = "RendererScripting::GetLocalBounds", HasExplicitThis = true)] get { get_localBounds_Injected(out var ret); return ret; } [NativeName("SetLocalAABB")] set { set_localBounds_Injected(ref value); } } public extern bool enabled { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool isVisible { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("IsVisibleInScene")] get; } public extern ShadowCastingMode shadowCastingMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool receiveShadows { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool forceRenderingOff { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public bool staticShadowCaster { get { return GetIsStaticShadowCaster(); } set { SetIsStaticShadowCaster(value); } } public extern MotionVectorGenerationMode motionVectorGenerationMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern LightProbeUsage lightProbeUsage { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern ReflectionProbeUsage reflectionProbeUsage { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern uint renderingLayerMask { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int rendererPriority { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern RayTracingMode rayTracingMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern string sortingLayerName { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int sortingLayerID { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int sortingOrder { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } internal extern int sortingGroupID { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } internal extern int sortingGroupOrder { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("IsDynamicOccludee")] public extern bool allowOcclusionWhenDynamic { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("StaticBatchRoot")] internal extern Transform staticBatchRootTransform { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } internal extern int staticBatchIndex { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern bool isPartOfStaticBatch { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("IsPartOfStaticBatch")] get; } public Matrix4x4 worldToLocalMatrix { get { get_worldToLocalMatrix_Injected(out var ret); return ret; } } public Matrix4x4 localToWorldMatrix { get { get_localToWorldMatrix_Injected(out var ret); return ret; } } public extern GameObject lightProbeProxyVolumeOverride { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Transform probeAnchor { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public int lightmapIndex { get { return GetLightmapIndex(LightmapType.StaticLightmap); } set { SetLightmapIndex(value, LightmapType.StaticLightmap); } } public int realtimeLightmapIndex { get { return GetLightmapIndex(LightmapType.DynamicLightmap); } set { SetLightmapIndex(value, LightmapType.DynamicLightmap); } } public Vector4 lightmapScaleOffset { get { return GetLightmapST(LightmapType.StaticLightmap); } set { SetStaticLightmapST(value); } } public Vector4 realtimeLightmapScaleOffset { get { return GetLightmapST(LightmapType.DynamicLightmap); } set { SetLightmapST(value, LightmapType.DynamicLightmap); } } public Material[] materials { get { return GetMaterialArray(); } set { SetMaterialArray(value); } } public Material material { get { return GetMaterial(); } set { SetMaterial(value); } } public Material sharedMaterial { get { return GetSharedMaterial(); } set { SetMaterial(value); } } public Material[] sharedMaterials { get { return GetSharedMaterialArray(); } set { SetMaterialArray(value); } } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("ResetWorldAABB")] public extern void ResetBounds(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("ResetLocalAABB")] public extern void ResetLocalBounds(); [FreeFunction(Name = "RendererScripting::SetStaticLightmapST", HasExplicitThis = true)] private void SetStaticLightmapST(Vector4 st) { SetStaticLightmapST_Injected(ref st); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RendererScripting::GetMaterial", HasExplicitThis = true)] private extern Material GetMaterial(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RendererScripting::GetSharedMaterial", HasExplicitThis = true)] private extern Material GetSharedMaterial(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RendererScripting::SetMaterial", HasExplicitThis = true)] private extern void SetMaterial(Material m); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RendererScripting::GetMaterialArray", HasExplicitThis = true)] private extern Material[] GetMaterialArray(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RendererScripting::GetMaterialArray", HasExplicitThis = true)] private extern void CopyMaterialArray([Out] Material[] m); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RendererScripting::GetSharedMaterialArray", HasExplicitThis = true)] private extern void CopySharedMaterialArray([Out] Material[] m); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RendererScripting::SetMaterialArray", HasExplicitThis = true)] private extern void SetMaterialArray([NotNull("ArgumentNullException")] Material[] m); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RendererScripting::SetPropertyBlock", HasExplicitThis = true)] internal extern void Internal_SetPropertyBlock(MaterialPropertyBlock properties); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RendererScripting::GetPropertyBlock", HasExplicitThis = true)] internal extern void Internal_GetPropertyBlock([NotNull("ArgumentNullException")] MaterialPropertyBlock dest); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RendererScripting::SetPropertyBlockMaterialIndex", HasExplicitThis = true)] internal extern void Internal_SetPropertyBlockMaterialIndex(MaterialPropertyBlock properties, int materialIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RendererScripting::GetPropertyBlockMaterialIndex", HasExplicitThis = true)] internal extern void Internal_GetPropertyBlockMaterialIndex([NotNull("ArgumentNullException")] MaterialPropertyBlock dest, int materialIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RendererScripting::HasPropertyBlock", HasExplicitThis = true)] public extern bool HasPropertyBlock(); public void SetPropertyBlock(MaterialPropertyBlock properties) { Internal_SetPropertyBlock(properties); } public void SetPropertyBlock(MaterialPropertyBlock properties, int materialIndex) { Internal_SetPropertyBlockMaterialIndex(properties, materialIndex); } public void GetPropertyBlock(MaterialPropertyBlock properties) { Internal_GetPropertyBlock(properties); } public void GetPropertyBlock(MaterialPropertyBlock properties, int materialIndex) { Internal_GetPropertyBlockMaterialIndex(properties, materialIndex); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RendererScripting::GetClosestReflectionProbes", HasExplicitThis = true)] private extern void GetClosestReflectionProbesInternal(object result); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetIsStaticShadowCaster")] private extern bool GetIsStaticShadowCaster(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetIsStaticShadowCaster")] private extern void SetIsStaticShadowCaster(bool value); [MethodImpl(MethodImplOptions.InternalCall)] internal extern void SetStaticBatchInfo(int firstSubMesh, int subMeshCount); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetLightmapIndexInt")] private extern int GetLightmapIndex(LightmapType lt); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetLightmapIndexInt")] private extern void SetLightmapIndex(int index, LightmapType lt); [NativeName("GetLightmapST")] private Vector4 GetLightmapST(LightmapType lt) { GetLightmapST_Injected(lt, out var ret); return ret; } [NativeName("SetLightmapST")] private void SetLightmapST(Vector4 st, LightmapType lt) { SetLightmapST_Injected(ref st, lt); } [MethodImpl(MethodImplOptions.InternalCall)] private extern int GetMaterialCount(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetMaterialArray")] private extern Material[] GetSharedMaterialArray(); public void GetMaterials(List m) { if (m == null) { throw new ArgumentNullException("The result material list cannot be null.", "m"); } NoAllocHelpers.EnsureListElemCount(m, GetMaterialCount()); CopyMaterialArray(NoAllocHelpers.ExtractArrayFromListT(m)); } public void GetSharedMaterials(List m) { if (m == null) { throw new ArgumentNullException("The result material list cannot be null.", "m"); } NoAllocHelpers.EnsureListElemCount(m, GetMaterialCount()); CopySharedMaterialArray(NoAllocHelpers.ExtractArrayFromListT(m)); } public void GetClosestReflectionProbes(List result) { GetClosestReflectionProbesInternal(result); } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_bounds_Injected(out Bounds ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_bounds_Injected(ref Bounds value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_localBounds_Injected(out Bounds ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_localBounds_Injected(ref Bounds value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetStaticLightmapST_Injected(ref Vector4 st); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_worldToLocalMatrix_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_localToWorldMatrix_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetLightmapST_Injected(LightmapType lt, out Vector4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetLightmapST_Injected(ref Vector4 st, LightmapType lt); } [NativeHeader("Runtime/Graphics/QualitySettingsTypes.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("Runtime/Camera/RenderSettings.h")] public sealed class RenderSettings : Object { [Obsolete("Use RenderSettings.ambientIntensity instead (UnityUpgradable) -> ambientIntensity", false)] public static float ambientSkyboxAmount { get { return ambientIntensity; } set { ambientIntensity = value; } } [NativeProperty("UseFog")] public static extern bool fog { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("LinearFogStart")] public static extern float fogStartDistance { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("LinearFogEnd")] public static extern float fogEndDistance { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern FogMode fogMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static Color fogColor { get { get_fogColor_Injected(out var ret); return ret; } set { set_fogColor_Injected(ref value); } } public static extern float fogDensity { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern AmbientMode ambientMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static Color ambientSkyColor { get { get_ambientSkyColor_Injected(out var ret); return ret; } set { set_ambientSkyColor_Injected(ref value); } } public static Color ambientEquatorColor { get { get_ambientEquatorColor_Injected(out var ret); return ret; } set { set_ambientEquatorColor_Injected(ref value); } } public static Color ambientGroundColor { get { get_ambientGroundColor_Injected(out var ret); return ret; } set { set_ambientGroundColor_Injected(ref value); } } public static extern float ambientIntensity { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("AmbientSkyColor")] public static Color ambientLight { get { get_ambientLight_Injected(out var ret); return ret; } set { set_ambientLight_Injected(ref value); } } public static Color subtractiveShadowColor { get { get_subtractiveShadowColor_Injected(out var ret); return ret; } set { set_subtractiveShadowColor_Injected(ref value); } } [NativeProperty("SkyboxMaterial")] public static extern Material skybox { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern Light sun { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static SphericalHarmonicsL2 ambientProbe { [NativeMethod("GetFinalAmbientProbe")] get { get_ambientProbe_Injected(out var ret); return ret; } set { set_ambientProbe_Injected(ref value); } } public static extern Texture customReflection { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] set; } public static extern float reflectionIntensity { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int reflectionBounces { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("GeneratedSkyboxReflection")] internal static extern Cubemap defaultReflection { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern DefaultReflectionMode defaultReflectionMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int defaultReflectionResolution { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern float haloStrength { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern float flareStrength { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern float flareFadeSpeed { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } private RenderSettings() { } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetRenderSettings")] internal static extern Object GetRenderSettings(); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] internal static extern void Reset(); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_fogColor_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_fogColor_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_ambientSkyColor_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_ambientSkyColor_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_ambientEquatorColor_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_ambientEquatorColor_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_ambientGroundColor_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_ambientGroundColor_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_ambientLight_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_ambientLight_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_subtractiveShadowColor_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_subtractiveShadowColor_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_ambientProbe_Injected(out SphericalHarmonicsL2 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_ambientProbe_Injected(ref SphericalHarmonicsL2 value); } [NativeHeader("Runtime/Graphics/ShaderScriptBindings.h")] [NativeHeader("Runtime/Shaders/Shader.h")] [NativeHeader("Runtime/Shaders/Keywords/KeywordSpaceScriptBindings.h")] [NativeHeader("Runtime/Shaders/ShaderNameRegistry.h")] [NativeHeader("Runtime/Shaders/ComputeShader.h")] [NativeHeader("Runtime/Graphics/ShaderScriptBindings.h")] [NativeHeader("Runtime/Shaders/GpuPrograms/ShaderVariantCollection.h")] [NativeHeader("Runtime/Misc/ResourceManager.h")] public sealed class Shader : Object { [Obsolete("Use Graphics.activeTier instead (UnityUpgradable) -> UnityEngine.Graphics.activeTier", false)] public static ShaderHardwareTier globalShaderHardwareTier { get { return (ShaderHardwareTier)Graphics.activeTier; } set { Graphics.activeTier = (GraphicsTier)value; } } [NativeProperty("MaxChunksRuntimeOverride")] public static extern int maximumChunksOverride { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("MaximumShaderLOD")] public extern int maximumLOD { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("GlobalMaximumShaderLOD")] public static extern int globalMaximumLOD { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool isSupported { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("IsSupported")] get; } public static extern string globalRenderPipeline { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static GlobalKeyword[] enabledGlobalKeywords => GetEnabledGlobalKeywords(); public static GlobalKeyword[] globalKeywords => GetAllGlobalKeywords(); public LocalKeywordSpace keywordSpace { get { get_keywordSpace_Injected(out var ret); return ret; } } public extern int renderQueue { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetRenderQueue", HasExplicitThis = true)] get; } internal extern DisableBatchingType disableBatching { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetDisableBatchingType", HasExplicitThis = true)] get; } public extern int passCount { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ShaderScripting::GetPassCount", HasExplicitThis = true)] get; } public extern int subshaderCount { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ShaderScripting::GetSubshaderCount", HasExplicitThis = true)] get; } public static Shader Find(string name) { return ResourcesAPI.ActiveAPI.FindShaderByName(name); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetBuiltinResource")] internal static extern Shader FindBuiltin(string name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("keywords::GetEnabledGlobalKeywords")] internal static extern GlobalKeyword[] GetEnabledGlobalKeywords(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("keywords::GetAllGlobalKeywords")] internal static extern GlobalKeyword[] GetAllGlobalKeywords(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::EnableKeyword")] public static extern void EnableKeyword(string keyword); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::DisableKeyword")] public static extern void DisableKeyword(string keyword); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::IsKeywordEnabled")] public static extern bool IsKeywordEnabled(string keyword); [FreeFunction("ShaderScripting::EnableKeyword")] internal static void EnableKeywordFast(GlobalKeyword keyword) { EnableKeywordFast_Injected(ref keyword); } [FreeFunction("ShaderScripting::DisableKeyword")] internal static void DisableKeywordFast(GlobalKeyword keyword) { DisableKeywordFast_Injected(ref keyword); } [FreeFunction("ShaderScripting::SetKeyword")] internal static void SetKeywordFast(GlobalKeyword keyword, bool value) { SetKeywordFast_Injected(ref keyword, value); } [FreeFunction("ShaderScripting::IsKeywordEnabled")] internal static bool IsKeywordEnabledFast(GlobalKeyword keyword) { return IsKeywordEnabledFast_Injected(ref keyword); } public static void EnableKeyword(in GlobalKeyword keyword) { EnableKeywordFast(keyword); } public static void DisableKeyword(in GlobalKeyword keyword) { DisableKeywordFast(keyword); } public static void SetKeyword(in GlobalKeyword keyword, bool value) { SetKeywordFast(keyword, value); } public static bool IsKeywordEnabled(in GlobalKeyword keyword) { return IsKeywordEnabledFast(keyword); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void WarmupAllShaders(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::TagToID")] internal static extern int TagToID(string name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::IDToTag")] internal static extern string IDToTag(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ShaderScripting::PropertyToID", IsThreadSafe = true)] public static extern int PropertyToID(string name); [MethodImpl(MethodImplOptions.InternalCall)] public extern Shader GetDependency(string name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ShaderScripting::GetPassCountInSubshader", HasExplicitThis = true)] public extern int GetPassCountInSubshader(int subshaderIndex); public ShaderTagId FindPassTagValue(int passIndex, ShaderTagId tagName) { if (passIndex < 0 || passIndex >= passCount) { throw new ArgumentOutOfRangeException("passIndex"); } int id = Internal_FindPassTagValue(passIndex, tagName.id); return new ShaderTagId { id = id }; } public ShaderTagId FindPassTagValue(int subshaderIndex, int passIndex, ShaderTagId tagName) { if (subshaderIndex < 0 || subshaderIndex >= subshaderCount) { throw new ArgumentOutOfRangeException("subshaderIndex"); } if (passIndex < 0 || passIndex >= GetPassCountInSubshader(subshaderIndex)) { throw new ArgumentOutOfRangeException("passIndex"); } int id = Internal_FindPassTagValueInSubShader(subshaderIndex, passIndex, tagName.id); return new ShaderTagId { id = id }; } public ShaderTagId FindSubshaderTagValue(int subshaderIndex, ShaderTagId tagName) { if (subshaderIndex < 0 || subshaderIndex >= subshaderCount) { throw new ArgumentOutOfRangeException($"Invalid subshaderIndex {subshaderIndex}. Value must be in the range [0, {subshaderCount})"); } int id = Internal_FindSubshaderTagValue(subshaderIndex, tagName.id); return new ShaderTagId { id = id }; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ShaderScripting::FindPassTagValue", HasExplicitThis = true)] private extern int Internal_FindPassTagValue(int passIndex, int tagName); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ShaderScripting::FindPassTagValue", HasExplicitThis = true)] private extern int Internal_FindPassTagValueInSubShader(int subShaderIndex, int passIndex, int tagName); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ShaderScripting::FindSubshaderTagValue", HasExplicitThis = true)] private extern int Internal_FindSubshaderTagValue(int subShaderIndex, int tagName); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::SetGlobalInt")] private static extern void SetGlobalIntImpl(int name, int value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::SetGlobalFloat")] private static extern void SetGlobalFloatImpl(int name, float value); [FreeFunction("ShaderScripting::SetGlobalVector")] private static void SetGlobalVectorImpl(int name, Vector4 value) { SetGlobalVectorImpl_Injected(name, ref value); } [FreeFunction("ShaderScripting::SetGlobalMatrix")] private static void SetGlobalMatrixImpl(int name, Matrix4x4 value) { SetGlobalMatrixImpl_Injected(name, ref value); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::SetGlobalTexture")] private static extern void SetGlobalTextureImpl(int name, Texture value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::SetGlobalRenderTexture")] private static extern void SetGlobalRenderTextureImpl(int name, RenderTexture value, RenderTextureSubElement element); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::SetGlobalBuffer")] private static extern void SetGlobalBufferImpl(int name, ComputeBuffer value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::SetGlobalBuffer")] private static extern void SetGlobalGraphicsBufferImpl(int name, GraphicsBuffer value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::SetGlobalConstantBuffer")] private static extern void SetGlobalConstantBufferImpl(int name, ComputeBuffer value, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::SetGlobalConstantBuffer")] private static extern void SetGlobalConstantGraphicsBufferImpl(int name, GraphicsBuffer value, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetGlobalInt")] private static extern int GetGlobalIntImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetGlobalFloat")] private static extern float GetGlobalFloatImpl(int name); [FreeFunction("ShaderScripting::GetGlobalVector")] private static Vector4 GetGlobalVectorImpl(int name) { GetGlobalVectorImpl_Injected(name, out var ret); return ret; } [FreeFunction("ShaderScripting::GetGlobalMatrix")] private static Matrix4x4 GetGlobalMatrixImpl(int name) { GetGlobalMatrixImpl_Injected(name, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetGlobalTexture")] private static extern Texture GetGlobalTextureImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::SetGlobalFloatArray")] private static extern void SetGlobalFloatArrayImpl(int name, float[] values, int count); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::SetGlobalVectorArray")] private static extern void SetGlobalVectorArrayImpl(int name, Vector4[] values, int count); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::SetGlobalMatrixArray")] private static extern void SetGlobalMatrixArrayImpl(int name, Matrix4x4[] values, int count); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetGlobalFloatArray")] private static extern float[] GetGlobalFloatArrayImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetGlobalVectorArray")] private static extern Vector4[] GetGlobalVectorArrayImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetGlobalMatrixArray")] private static extern Matrix4x4[] GetGlobalMatrixArrayImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetGlobalFloatArrayCount")] private static extern int GetGlobalFloatArrayCountImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetGlobalVectorArrayCount")] private static extern int GetGlobalVectorArrayCountImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetGlobalMatrixArrayCount")] private static extern int GetGlobalMatrixArrayCountImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::ExtractGlobalFloatArray")] private static extern void ExtractGlobalFloatArrayImpl(int name, [Out] float[] val); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::ExtractGlobalVectorArray")] private static extern void ExtractGlobalVectorArrayImpl(int name, [Out] Vector4[] val); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::ExtractGlobalMatrixArray")] private static extern void ExtractGlobalMatrixArrayImpl(int name, [Out] Matrix4x4[] val); private static void SetGlobalFloatArray(int name, float[] values, int count) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Length == 0) { throw new ArgumentException("Zero-sized array is not allowed."); } if (values.Length < count) { throw new ArgumentException("array has less elements than passed count."); } SetGlobalFloatArrayImpl(name, values, count); } private static void SetGlobalVectorArray(int name, Vector4[] values, int count) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Length == 0) { throw new ArgumentException("Zero-sized array is not allowed."); } if (values.Length < count) { throw new ArgumentException("array has less elements than passed count."); } SetGlobalVectorArrayImpl(name, values, count); } private static void SetGlobalMatrixArray(int name, Matrix4x4[] values, int count) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Length == 0) { throw new ArgumentException("Zero-sized array is not allowed."); } if (values.Length < count) { throw new ArgumentException("array has less elements than passed count."); } SetGlobalMatrixArrayImpl(name, values, count); } private static void ExtractGlobalFloatArray(int name, List values) { if (values == null) { throw new ArgumentNullException("values"); } values.Clear(); int globalFloatArrayCountImpl = GetGlobalFloatArrayCountImpl(name); if (globalFloatArrayCountImpl > 0) { NoAllocHelpers.EnsureListElemCount(values, globalFloatArrayCountImpl); ExtractGlobalFloatArrayImpl(name, (float[])NoAllocHelpers.ExtractArrayFromList(values)); } } private static void ExtractGlobalVectorArray(int name, List values) { if (values == null) { throw new ArgumentNullException("values"); } values.Clear(); int globalVectorArrayCountImpl = GetGlobalVectorArrayCountImpl(name); if (globalVectorArrayCountImpl > 0) { NoAllocHelpers.EnsureListElemCount(values, globalVectorArrayCountImpl); ExtractGlobalVectorArrayImpl(name, (Vector4[])NoAllocHelpers.ExtractArrayFromList(values)); } } private static void ExtractGlobalMatrixArray(int name, List values) { if (values == null) { throw new ArgumentNullException("values"); } values.Clear(); int globalMatrixArrayCountImpl = GetGlobalMatrixArrayCountImpl(name); if (globalMatrixArrayCountImpl > 0) { NoAllocHelpers.EnsureListElemCount(values, globalMatrixArrayCountImpl); ExtractGlobalMatrixArrayImpl(name, (Matrix4x4[])NoAllocHelpers.ExtractArrayFromList(values)); } } public static void SetGlobalInt(string name, int value) { SetGlobalFloatImpl(PropertyToID(name), value); } public static void SetGlobalInt(int nameID, int value) { SetGlobalFloatImpl(nameID, value); } public static void SetGlobalFloat(string name, float value) { SetGlobalFloatImpl(PropertyToID(name), value); } public static void SetGlobalFloat(int nameID, float value) { SetGlobalFloatImpl(nameID, value); } public static void SetGlobalInteger(string name, int value) { SetGlobalIntImpl(PropertyToID(name), value); } public static void SetGlobalInteger(int nameID, int value) { SetGlobalIntImpl(nameID, value); } public static void SetGlobalVector(string name, Vector4 value) { SetGlobalVectorImpl(PropertyToID(name), value); } public static void SetGlobalVector(int nameID, Vector4 value) { SetGlobalVectorImpl(nameID, value); } public static void SetGlobalColor(string name, Color value) { SetGlobalVectorImpl(PropertyToID(name), value); } public static void SetGlobalColor(int nameID, Color value) { SetGlobalVectorImpl(nameID, value); } public static void SetGlobalMatrix(string name, Matrix4x4 value) { SetGlobalMatrixImpl(PropertyToID(name), value); } public static void SetGlobalMatrix(int nameID, Matrix4x4 value) { SetGlobalMatrixImpl(nameID, value); } public static void SetGlobalTexture(string name, Texture value) { SetGlobalTextureImpl(PropertyToID(name), value); } public static void SetGlobalTexture(int nameID, Texture value) { SetGlobalTextureImpl(nameID, value); } public static void SetGlobalTexture(string name, RenderTexture value, RenderTextureSubElement element) { SetGlobalRenderTextureImpl(PropertyToID(name), value, element); } public static void SetGlobalTexture(int nameID, RenderTexture value, RenderTextureSubElement element) { SetGlobalRenderTextureImpl(nameID, value, element); } public static void SetGlobalBuffer(string name, ComputeBuffer value) { SetGlobalBufferImpl(PropertyToID(name), value); } public static void SetGlobalBuffer(int nameID, ComputeBuffer value) { SetGlobalBufferImpl(nameID, value); } public static void SetGlobalBuffer(string name, GraphicsBuffer value) { SetGlobalGraphicsBufferImpl(PropertyToID(name), value); } public static void SetGlobalBuffer(int nameID, GraphicsBuffer value) { SetGlobalGraphicsBufferImpl(nameID, value); } public static void SetGlobalConstantBuffer(string name, ComputeBuffer value, int offset, int size) { SetGlobalConstantBufferImpl(PropertyToID(name), value, offset, size); } public static void SetGlobalConstantBuffer(int nameID, ComputeBuffer value, int offset, int size) { SetGlobalConstantBufferImpl(nameID, value, offset, size); } public static void SetGlobalConstantBuffer(string name, GraphicsBuffer value, int offset, int size) { SetGlobalConstantGraphicsBufferImpl(PropertyToID(name), value, offset, size); } public static void SetGlobalConstantBuffer(int nameID, GraphicsBuffer value, int offset, int size) { SetGlobalConstantGraphicsBufferImpl(nameID, value, offset, size); } public static void SetGlobalFloatArray(string name, List values) { SetGlobalFloatArray(PropertyToID(name), NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public static void SetGlobalFloatArray(int nameID, List values) { SetGlobalFloatArray(nameID, NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public static void SetGlobalFloatArray(string name, float[] values) { SetGlobalFloatArray(PropertyToID(name), values, values.Length); } public static void SetGlobalFloatArray(int nameID, float[] values) { SetGlobalFloatArray(nameID, values, values.Length); } public static void SetGlobalVectorArray(string name, List values) { SetGlobalVectorArray(PropertyToID(name), NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public static void SetGlobalVectorArray(int nameID, List values) { SetGlobalVectorArray(nameID, NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public static void SetGlobalVectorArray(string name, Vector4[] values) { SetGlobalVectorArray(PropertyToID(name), values, values.Length); } public static void SetGlobalVectorArray(int nameID, Vector4[] values) { SetGlobalVectorArray(nameID, values, values.Length); } public static void SetGlobalMatrixArray(string name, List values) { SetGlobalMatrixArray(PropertyToID(name), NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public static void SetGlobalMatrixArray(int nameID, List values) { SetGlobalMatrixArray(nameID, NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public static void SetGlobalMatrixArray(string name, Matrix4x4[] values) { SetGlobalMatrixArray(PropertyToID(name), values, values.Length); } public static void SetGlobalMatrixArray(int nameID, Matrix4x4[] values) { SetGlobalMatrixArray(nameID, values, values.Length); } public static int GetGlobalInt(string name) { return (int)GetGlobalFloatImpl(PropertyToID(name)); } public static int GetGlobalInt(int nameID) { return (int)GetGlobalFloatImpl(nameID); } public static float GetGlobalFloat(string name) { return GetGlobalFloatImpl(PropertyToID(name)); } public static float GetGlobalFloat(int nameID) { return GetGlobalFloatImpl(nameID); } public static int GetGlobalInteger(string name) { return GetGlobalIntImpl(PropertyToID(name)); } public static int GetGlobalInteger(int nameID) { return GetGlobalIntImpl(nameID); } public static Vector4 GetGlobalVector(string name) { return GetGlobalVectorImpl(PropertyToID(name)); } public static Vector4 GetGlobalVector(int nameID) { return GetGlobalVectorImpl(nameID); } public static Color GetGlobalColor(string name) { return GetGlobalVectorImpl(PropertyToID(name)); } public static Color GetGlobalColor(int nameID) { return GetGlobalVectorImpl(nameID); } public static Matrix4x4 GetGlobalMatrix(string name) { return GetGlobalMatrixImpl(PropertyToID(name)); } public static Matrix4x4 GetGlobalMatrix(int nameID) { return GetGlobalMatrixImpl(nameID); } public static Texture GetGlobalTexture(string name) { return GetGlobalTextureImpl(PropertyToID(name)); } public static Texture GetGlobalTexture(int nameID) { return GetGlobalTextureImpl(nameID); } public static float[] GetGlobalFloatArray(string name) { return GetGlobalFloatArray(PropertyToID(name)); } public static float[] GetGlobalFloatArray(int nameID) { return (GetGlobalFloatArrayCountImpl(nameID) != 0) ? GetGlobalFloatArrayImpl(nameID) : null; } public static Vector4[] GetGlobalVectorArray(string name) { return GetGlobalVectorArray(PropertyToID(name)); } public static Vector4[] GetGlobalVectorArray(int nameID) { return (GetGlobalVectorArrayCountImpl(nameID) != 0) ? GetGlobalVectorArrayImpl(nameID) : null; } public static Matrix4x4[] GetGlobalMatrixArray(string name) { return GetGlobalMatrixArray(PropertyToID(name)); } public static Matrix4x4[] GetGlobalMatrixArray(int nameID) { return (GetGlobalMatrixArrayCountImpl(nameID) != 0) ? GetGlobalMatrixArrayImpl(nameID) : null; } public static void GetGlobalFloatArray(string name, List values) { ExtractGlobalFloatArray(PropertyToID(name), values); } public static void GetGlobalFloatArray(int nameID, List values) { ExtractGlobalFloatArray(nameID, values); } public static void GetGlobalVectorArray(string name, List values) { ExtractGlobalVectorArray(PropertyToID(name), values); } public static void GetGlobalVectorArray(int nameID, List values) { ExtractGlobalVectorArray(nameID, values); } public static void GetGlobalMatrixArray(string name, List values) { ExtractGlobalMatrixArray(PropertyToID(name), values); } public static void GetGlobalMatrixArray(int nameID, List values) { ExtractGlobalMatrixArray(nameID, values); } private Shader() { } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetPropertyName")] private static extern string GetPropertyName([NotNull("ArgumentNullException")] Shader shader, int propertyIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetPropertyNameId")] private static extern int GetPropertyNameId([NotNull("ArgumentNullException")] Shader shader, int propertyIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetPropertyType")] private static extern ShaderPropertyType GetPropertyType([NotNull("ArgumentNullException")] Shader shader, int propertyIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetPropertyDescription")] private static extern string GetPropertyDescription([NotNull("ArgumentNullException")] Shader shader, int propertyIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetPropertyFlags")] private static extern ShaderPropertyFlags GetPropertyFlags([NotNull("ArgumentNullException")] Shader shader, int propertyIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetPropertyAttributes")] private static extern string[] GetPropertyAttributes([NotNull("ArgumentNullException")] Shader shader, int propertyIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetPropertyDefaultIntValue")] private static extern int GetPropertyDefaultIntValue([NotNull("ArgumentNullException")] Shader shader, int propertyIndex); [FreeFunction("ShaderScripting::GetPropertyDefaultValue")] private static Vector4 GetPropertyDefaultValue([NotNull("ArgumentNullException")] Shader shader, int propertyIndex) { GetPropertyDefaultValue_Injected(shader, propertyIndex, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetPropertyTextureDimension")] private static extern TextureDimension GetPropertyTextureDimension([NotNull("ArgumentNullException")] Shader shader, int propertyIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetPropertyTextureDefaultName")] private static extern string GetPropertyTextureDefaultName([NotNull("ArgumentNullException")] Shader shader, int propertyIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::FindTextureStack")] private static extern bool FindTextureStackImpl([NotNull("ArgumentNullException")] Shader s, int propertyIdx, out string stackName, out int layerIndex); private static void CheckPropertyIndex(Shader s, int propertyIndex) { if (propertyIndex < 0 || propertyIndex >= s.GetPropertyCount()) { throw new ArgumentOutOfRangeException("propertyIndex"); } } [MethodImpl(MethodImplOptions.InternalCall)] public extern int GetPropertyCount(); [MethodImpl(MethodImplOptions.InternalCall)] public extern int FindPropertyIndex(string propertyName); public string GetPropertyName(int propertyIndex) { CheckPropertyIndex(this, propertyIndex); return GetPropertyName(this, propertyIndex); } public int GetPropertyNameId(int propertyIndex) { CheckPropertyIndex(this, propertyIndex); return GetPropertyNameId(this, propertyIndex); } public ShaderPropertyType GetPropertyType(int propertyIndex) { CheckPropertyIndex(this, propertyIndex); return GetPropertyType(this, propertyIndex); } public string GetPropertyDescription(int propertyIndex) { CheckPropertyIndex(this, propertyIndex); return GetPropertyDescription(this, propertyIndex); } public ShaderPropertyFlags GetPropertyFlags(int propertyIndex) { CheckPropertyIndex(this, propertyIndex); return GetPropertyFlags(this, propertyIndex); } public string[] GetPropertyAttributes(int propertyIndex) { CheckPropertyIndex(this, propertyIndex); return GetPropertyAttributes(this, propertyIndex); } public float GetPropertyDefaultFloatValue(int propertyIndex) { CheckPropertyIndex(this, propertyIndex); ShaderPropertyType propertyType = GetPropertyType(propertyIndex); if (propertyType != ShaderPropertyType.Float && propertyType != ShaderPropertyType.Range) { throw new ArgumentException("Property type is not Float or Range."); } return GetPropertyDefaultValue(this, propertyIndex)[0]; } public Vector4 GetPropertyDefaultVectorValue(int propertyIndex) { CheckPropertyIndex(this, propertyIndex); ShaderPropertyType propertyType = GetPropertyType(propertyIndex); if (propertyType != ShaderPropertyType.Color && propertyType != ShaderPropertyType.Vector) { throw new ArgumentException("Property type is not Color or Vector."); } return GetPropertyDefaultValue(this, propertyIndex); } public Vector2 GetPropertyRangeLimits(int propertyIndex) { CheckPropertyIndex(this, propertyIndex); if (GetPropertyType(propertyIndex) != ShaderPropertyType.Range) { throw new ArgumentException("Property type is not Range."); } Vector4 propertyDefaultValue = GetPropertyDefaultValue(this, propertyIndex); return new Vector2(propertyDefaultValue[1], propertyDefaultValue[2]); } public TextureDimension GetPropertyTextureDimension(int propertyIndex) { CheckPropertyIndex(this, propertyIndex); if (GetPropertyType(propertyIndex) != ShaderPropertyType.Texture) { throw new ArgumentException("Property type is not TexEnv."); } return GetPropertyTextureDimension(this, propertyIndex); } public string GetPropertyTextureDefaultName(int propertyIndex) { CheckPropertyIndex(this, propertyIndex); ShaderPropertyType propertyType = GetPropertyType(propertyIndex); if (propertyType != ShaderPropertyType.Texture) { throw new ArgumentException("Property type is not Texture."); } return GetPropertyTextureDefaultName(this, propertyIndex); } public bool FindTextureStack(int propertyIndex, out string stackName, out int layerIndex) { CheckPropertyIndex(this, propertyIndex); ShaderPropertyType propertyType = GetPropertyType(propertyIndex); if (propertyType != ShaderPropertyType.Texture) { throw new ArgumentException("Property type is not Texture."); } return FindTextureStackImpl(this, propertyIndex, out stackName, out layerIndex); } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_keywordSpace_Injected(out LocalKeywordSpace ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EnableKeywordFast_Injected(ref GlobalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DisableKeywordFast_Injected(ref GlobalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetKeywordFast_Injected(ref GlobalKeyword keyword, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsKeywordEnabledFast_Injected(ref GlobalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetGlobalVectorImpl_Injected(int name, ref Vector4 value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetGlobalMatrixImpl_Injected(int name, ref Matrix4x4 value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetGlobalVectorImpl_Injected(int name, out Vector4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetGlobalMatrixImpl_Injected(int name, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetPropertyDefaultValue_Injected(Shader shader, int propertyIndex, out Vector4 ret); } [NativeHeader("Runtime/Graphics/ShaderScriptBindings.h")] [NativeHeader("Runtime/Shaders/Material.h")] public class Material : Object { public extern Shader shader { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Color color { get { int firstPropertyNameIdByAttribute = GetFirstPropertyNameIdByAttribute(ShaderPropertyFlags.MainColor); if (firstPropertyNameIdByAttribute >= 0) { return GetColor(firstPropertyNameIdByAttribute); } return GetColor("_Color"); } set { int firstPropertyNameIdByAttribute = GetFirstPropertyNameIdByAttribute(ShaderPropertyFlags.MainColor); if (firstPropertyNameIdByAttribute >= 0) { SetColor(firstPropertyNameIdByAttribute, value); } else { SetColor("_Color", value); } } } public Texture mainTexture { get { int firstPropertyNameIdByAttribute = GetFirstPropertyNameIdByAttribute(ShaderPropertyFlags.MainTexture); if (firstPropertyNameIdByAttribute >= 0) { return GetTexture(firstPropertyNameIdByAttribute); } return GetTexture("_MainTex"); } set { int firstPropertyNameIdByAttribute = GetFirstPropertyNameIdByAttribute(ShaderPropertyFlags.MainTexture); if (firstPropertyNameIdByAttribute >= 0) { SetTexture(firstPropertyNameIdByAttribute, value); } else { SetTexture("_MainTex", value); } } } public Vector2 mainTextureOffset { get { int firstPropertyNameIdByAttribute = GetFirstPropertyNameIdByAttribute(ShaderPropertyFlags.MainTexture); if (firstPropertyNameIdByAttribute >= 0) { return GetTextureOffset(firstPropertyNameIdByAttribute); } return GetTextureOffset("_MainTex"); } set { int firstPropertyNameIdByAttribute = GetFirstPropertyNameIdByAttribute(ShaderPropertyFlags.MainTexture); if (firstPropertyNameIdByAttribute >= 0) { SetTextureOffset(firstPropertyNameIdByAttribute, value); } else { SetTextureOffset("_MainTex", value); } } } public Vector2 mainTextureScale { get { int firstPropertyNameIdByAttribute = GetFirstPropertyNameIdByAttribute(ShaderPropertyFlags.MainTexture); if (firstPropertyNameIdByAttribute >= 0) { return GetTextureScale(firstPropertyNameIdByAttribute); } return GetTextureScale("_MainTex"); } set { int firstPropertyNameIdByAttribute = GetFirstPropertyNameIdByAttribute(ShaderPropertyFlags.MainTexture); if (firstPropertyNameIdByAttribute >= 0) { SetTextureScale(firstPropertyNameIdByAttribute, value); } else { SetTextureScale("_MainTex", value); } } } public extern int renderQueue { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetActualRenderQueue")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetCustomRenderQueue")] set; } internal extern int rawRenderQueue { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetCustomRenderQueue")] get; } public LocalKeyword[] enabledKeywords { get { return GetEnabledKeywords(); } set { SetEnabledKeywords(value); } } public extern MaterialGlobalIlluminationFlags globalIlluminationFlags { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool doubleSidedGI { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("EnableInstancingVariants")] public extern bool enableInstancing { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int passCount { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetShader()->GetPassCount")] get; } public string[] shaderKeywords { get { return GetShaderKeywords(); } set { SetShaderKeywords(value); } } [Obsolete("Creating materials from shader source string will be removed in the future. Use Shader assets instead.", false)] public static Material Create(string scriptContents) { return new Material(scriptContents); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::CreateWithShader")] private static extern void CreateWithShader([Writable] Material self, [NotNull("ArgumentNullException")] Shader shader); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::CreateWithMaterial")] private static extern void CreateWithMaterial([Writable] Material self, [NotNull("ArgumentNullException")] Material source); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::CreateWithString")] private static extern void CreateWithString([Writable] Material self); public Material(Shader shader) { CreateWithShader(this, shader); } [RequiredByNativeCode] public Material(Material source) { CreateWithMaterial(this, source); } [Obsolete("Creating materials from shader source string is no longer supported. Use Shader assets instead.", false)] [EditorBrowsable(EditorBrowsableState.Never)] public Material(string contents) { CreateWithString(this); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Material GetDefaultMaterial(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Material GetDefaultParticleMaterial(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Material GetDefaultLineMaterial(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetFirstPropertyNameIdByAttributeFromScript")] private extern int GetFirstPropertyNameIdByAttribute(ShaderPropertyFlags attributeFlag); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasPropertyFromScript")] public extern bool HasProperty(int nameID); public bool HasProperty(string name) { return HasProperty(Shader.PropertyToID(name)); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasFloatFromScript")] private extern bool HasFloatImpl(int name); public bool HasFloat(string name) { return HasFloatImpl(Shader.PropertyToID(name)); } public bool HasFloat(int nameID) { return HasFloatImpl(nameID); } public bool HasInt(string name) { return HasFloatImpl(Shader.PropertyToID(name)); } public bool HasInt(int nameID) { return HasFloatImpl(nameID); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasIntegerFromScript")] private extern bool HasIntImpl(int name); public bool HasInteger(string name) { return HasIntImpl(Shader.PropertyToID(name)); } public bool HasInteger(int nameID) { return HasIntImpl(nameID); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasTextureFromScript")] private extern bool HasTextureImpl(int name); public bool HasTexture(string name) { return HasTextureImpl(Shader.PropertyToID(name)); } public bool HasTexture(int nameID) { return HasTextureImpl(nameID); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasMatrixFromScript")] private extern bool HasMatrixImpl(int name); public bool HasMatrix(string name) { return HasMatrixImpl(Shader.PropertyToID(name)); } public bool HasMatrix(int nameID) { return HasMatrixImpl(nameID); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasVectorFromScript")] private extern bool HasVectorImpl(int name); public bool HasVector(string name) { return HasVectorImpl(Shader.PropertyToID(name)); } public bool HasVector(int nameID) { return HasVectorImpl(nameID); } public bool HasColor(string name) { return HasVectorImpl(Shader.PropertyToID(name)); } public bool HasColor(int nameID) { return HasVectorImpl(nameID); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasBufferFromScript")] private extern bool HasBufferImpl(int name); public bool HasBuffer(string name) { return HasBufferImpl(Shader.PropertyToID(name)); } public bool HasBuffer(int nameID) { return HasBufferImpl(nameID); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasConstantBufferFromScript")] private extern bool HasConstantBufferImpl(int name); public bool HasConstantBuffer(string name) { return HasConstantBufferImpl(Shader.PropertyToID(name)); } public bool HasConstantBuffer(int nameID) { return HasConstantBufferImpl(nameID); } [MethodImpl(MethodImplOptions.InternalCall)] public extern void EnableKeyword(string keyword); [MethodImpl(MethodImplOptions.InternalCall)] public extern void DisableKeyword(string keyword); [MethodImpl(MethodImplOptions.InternalCall)] public extern bool IsKeywordEnabled(string keyword); [FreeFunction("MaterialScripting::EnableKeyword", HasExplicitThis = true)] private void EnableLocalKeyword(LocalKeyword keyword) { EnableLocalKeyword_Injected(ref keyword); } [FreeFunction("MaterialScripting::DisableKeyword", HasExplicitThis = true)] private void DisableLocalKeyword(LocalKeyword keyword) { DisableLocalKeyword_Injected(ref keyword); } [FreeFunction("MaterialScripting::SetKeyword", HasExplicitThis = true)] private void SetLocalKeyword(LocalKeyword keyword, bool value) { SetLocalKeyword_Injected(ref keyword, value); } [FreeFunction("MaterialScripting::IsKeywordEnabled", HasExplicitThis = true)] private bool IsLocalKeywordEnabled(LocalKeyword keyword) { return IsLocalKeywordEnabled_Injected(ref keyword); } public void EnableKeyword(in LocalKeyword keyword) { EnableLocalKeyword(keyword); } public void DisableKeyword(in LocalKeyword keyword) { DisableLocalKeyword(keyword); } public void SetKeyword(in LocalKeyword keyword, bool value) { SetLocalKeyword(keyword, value); } public bool IsKeywordEnabled(in LocalKeyword keyword) { return IsLocalKeywordEnabled(keyword); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::GetEnabledKeywords", HasExplicitThis = true)] private extern LocalKeyword[] GetEnabledKeywords(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::SetEnabledKeywords", HasExplicitThis = true)] private extern void SetEnabledKeywords(LocalKeyword[] keywords); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::SetShaderPassEnabled", HasExplicitThis = true)] public extern void SetShaderPassEnabled(string passName, bool enabled); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::GetShaderPassEnabled", HasExplicitThis = true)] public extern bool GetShaderPassEnabled(string passName); [MethodImpl(MethodImplOptions.InternalCall)] public extern string GetPassName(int pass); [MethodImpl(MethodImplOptions.InternalCall)] public extern int FindPass(string passName); [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetOverrideTag(string tag, string val); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetTag")] private extern string GetTagImpl(string tag, bool currentSubShaderOnly, string defaultValue); public string GetTag(string tag, bool searchFallbacks, string defaultValue) { return GetTagImpl(tag, !searchFallbacks, defaultValue); } public string GetTag(string tag, bool searchFallbacks) { return GetTagImpl(tag, !searchFallbacks, ""); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::Lerp", HasExplicitThis = true)] [NativeThrows] public extern void Lerp(Material start, Material end, float t); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::SetPass", HasExplicitThis = true)] public extern bool SetPass(int pass); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::CopyPropertiesFrom", HasExplicitThis = true)] public extern void CopyPropertiesFromMaterial(Material mat); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::CopyMatchingPropertiesFrom", HasExplicitThis = true)] public extern void CopyMatchingPropertiesFromMaterial(Material mat); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::GetShaderKeywords", HasExplicitThis = true)] private extern string[] GetShaderKeywords(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::SetShaderKeywords", HasExplicitThis = true)] private extern void SetShaderKeywords(string[] names); [MethodImpl(MethodImplOptions.InternalCall)] public extern int ComputeCRC(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::GetTexturePropertyNames", HasExplicitThis = true)] public extern string[] GetTexturePropertyNames(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::GetTexturePropertyNameIDs", HasExplicitThis = true)] public extern int[] GetTexturePropertyNameIDs(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::GetTexturePropertyNamesInternal", HasExplicitThis = true)] private extern void GetTexturePropertyNamesInternal(object outNames); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MaterialScripting::GetTexturePropertyNameIDsInternal", HasExplicitThis = true)] private extern void GetTexturePropertyNameIDsInternal(object outNames); public void GetTexturePropertyNames(List outNames) { if (outNames == null) { throw new ArgumentNullException("outNames"); } GetTexturePropertyNamesInternal(outNames); } public void GetTexturePropertyNameIDs(List outNames) { if (outNames == null) { throw new ArgumentNullException("outNames"); } GetTexturePropertyNameIDsInternal(outNames); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetIntFromScript")] private extern void SetIntImpl(int name, int value); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetFloatFromScript")] private extern void SetFloatImpl(int name, float value); [NativeName("SetColorFromScript")] private void SetColorImpl(int name, Color value) { SetColorImpl_Injected(name, ref value); } [NativeName("SetMatrixFromScript")] private void SetMatrixImpl(int name, Matrix4x4 value) { SetMatrixImpl_Injected(name, ref value); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetTextureFromScript")] private extern void SetTextureImpl(int name, Texture value); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetRenderTextureFromScript")] private extern void SetRenderTextureImpl(int name, RenderTexture value, RenderTextureSubElement element); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetBufferFromScript")] private extern void SetBufferImpl(int name, ComputeBuffer value); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetBufferFromScript")] private extern void SetGraphicsBufferImpl(int name, GraphicsBuffer value); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetConstantBufferFromScript")] private extern void SetConstantBufferImpl(int name, ComputeBuffer value, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetConstantBufferFromScript")] private extern void SetConstantGraphicsBufferImpl(int name, GraphicsBuffer value, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetIntFromScript")] private extern int GetIntImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetFloatFromScript")] private extern float GetFloatImpl(int name); [NativeName("GetColorFromScript")] private Color GetColorImpl(int name) { GetColorImpl_Injected(name, out var ret); return ret; } [NativeName("GetMatrixFromScript")] private Matrix4x4 GetMatrixImpl(int name) { GetMatrixImpl_Injected(name, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetTextureFromScript")] private extern Texture GetTextureImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::SetFloatArray", HasExplicitThis = true)] private extern void SetFloatArrayImpl(int name, float[] values, int count); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::SetVectorArray", HasExplicitThis = true)] private extern void SetVectorArrayImpl(int name, Vector4[] values, int count); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::SetColorArray", HasExplicitThis = true)] private extern void SetColorArrayImpl(int name, Color[] values, int count); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::SetMatrixArray", HasExplicitThis = true)] private extern void SetMatrixArrayImpl(int name, Matrix4x4[] values, int count); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::GetFloatArray", HasExplicitThis = true)] private extern float[] GetFloatArrayImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::GetVectorArray", HasExplicitThis = true)] private extern Vector4[] GetVectorArrayImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::GetColorArray", HasExplicitThis = true)] private extern Color[] GetColorArrayImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::GetMatrixArray", HasExplicitThis = true)] private extern Matrix4x4[] GetMatrixArrayImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::GetFloatArrayCount", HasExplicitThis = true)] private extern int GetFloatArrayCountImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::GetVectorArrayCount", HasExplicitThis = true)] private extern int GetVectorArrayCountImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::GetColorArrayCount", HasExplicitThis = true)] private extern int GetColorArrayCountImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::GetMatrixArrayCount", HasExplicitThis = true)] private extern int GetMatrixArrayCountImpl(int name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::ExtractFloatArray", HasExplicitThis = true)] private extern void ExtractFloatArrayImpl(int name, [Out] float[] val); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::ExtractVectorArray", HasExplicitThis = true)] private extern void ExtractVectorArrayImpl(int name, [Out] Vector4[] val); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::ExtractColorArray", HasExplicitThis = true)] private extern void ExtractColorArrayImpl(int name, [Out] Color[] val); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MaterialScripting::ExtractMatrixArray", HasExplicitThis = true)] private extern void ExtractMatrixArrayImpl(int name, [Out] Matrix4x4[] val); [NativeName("GetTextureScaleAndOffsetFromScript")] private Vector4 GetTextureScaleAndOffsetImpl(int name) { GetTextureScaleAndOffsetImpl_Injected(name, out var ret); return ret; } [NativeName("SetTextureOffsetFromScript")] private void SetTextureOffsetImpl(int name, Vector2 offset) { SetTextureOffsetImpl_Injected(name, ref offset); } [NativeName("SetTextureScaleFromScript")] private void SetTextureScaleImpl(int name, Vector2 scale) { SetTextureScaleImpl_Injected(name, ref scale); } private void SetFloatArray(int name, float[] values, int count) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Length == 0) { throw new ArgumentException("Zero-sized array is not allowed."); } if (values.Length < count) { throw new ArgumentException("array has less elements than passed count."); } SetFloatArrayImpl(name, values, count); } private void SetVectorArray(int name, Vector4[] values, int count) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Length == 0) { throw new ArgumentException("Zero-sized array is not allowed."); } if (values.Length < count) { throw new ArgumentException("array has less elements than passed count."); } SetVectorArrayImpl(name, values, count); } private void SetColorArray(int name, Color[] values, int count) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Length == 0) { throw new ArgumentException("Zero-sized array is not allowed."); } if (values.Length < count) { throw new ArgumentException("array has less elements than passed count."); } SetColorArrayImpl(name, values, count); } private void SetMatrixArray(int name, Matrix4x4[] values, int count) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Length == 0) { throw new ArgumentException("Zero-sized array is not allowed."); } if (values.Length < count) { throw new ArgumentException("array has less elements than passed count."); } SetMatrixArrayImpl(name, values, count); } private void ExtractFloatArray(int name, List values) { if (values == null) { throw new ArgumentNullException("values"); } values.Clear(); int floatArrayCountImpl = GetFloatArrayCountImpl(name); if (floatArrayCountImpl > 0) { NoAllocHelpers.EnsureListElemCount(values, floatArrayCountImpl); ExtractFloatArrayImpl(name, (float[])NoAllocHelpers.ExtractArrayFromList(values)); } } private void ExtractVectorArray(int name, List values) { if (values == null) { throw new ArgumentNullException("values"); } values.Clear(); int vectorArrayCountImpl = GetVectorArrayCountImpl(name); if (vectorArrayCountImpl > 0) { NoAllocHelpers.EnsureListElemCount(values, vectorArrayCountImpl); ExtractVectorArrayImpl(name, (Vector4[])NoAllocHelpers.ExtractArrayFromList(values)); } } private void ExtractColorArray(int name, List values) { if (values == null) { throw new ArgumentNullException("values"); } values.Clear(); int colorArrayCountImpl = GetColorArrayCountImpl(name); if (colorArrayCountImpl > 0) { NoAllocHelpers.EnsureListElemCount(values, colorArrayCountImpl); ExtractColorArrayImpl(name, (Color[])NoAllocHelpers.ExtractArrayFromList(values)); } } private void ExtractMatrixArray(int name, List values) { if (values == null) { throw new ArgumentNullException("values"); } values.Clear(); int matrixArrayCountImpl = GetMatrixArrayCountImpl(name); if (matrixArrayCountImpl > 0) { NoAllocHelpers.EnsureListElemCount(values, matrixArrayCountImpl); ExtractMatrixArrayImpl(name, (Matrix4x4[])NoAllocHelpers.ExtractArrayFromList(values)); } } public void SetInt(string name, int value) { SetFloatImpl(Shader.PropertyToID(name), value); } public void SetInt(int nameID, int value) { SetFloatImpl(nameID, value); } public void SetFloat(string name, float value) { SetFloatImpl(Shader.PropertyToID(name), value); } public void SetFloat(int nameID, float value) { SetFloatImpl(nameID, value); } public void SetInteger(string name, int value) { SetIntImpl(Shader.PropertyToID(name), value); } public void SetInteger(int nameID, int value) { SetIntImpl(nameID, value); } public void SetColor(string name, Color value) { SetColorImpl(Shader.PropertyToID(name), value); } public void SetColor(int nameID, Color value) { SetColorImpl(nameID, value); } public void SetVector(string name, Vector4 value) { SetColorImpl(Shader.PropertyToID(name), value); } public void SetVector(int nameID, Vector4 value) { SetColorImpl(nameID, value); } public void SetMatrix(string name, Matrix4x4 value) { SetMatrixImpl(Shader.PropertyToID(name), value); } public void SetMatrix(int nameID, Matrix4x4 value) { SetMatrixImpl(nameID, value); } public void SetTexture(string name, Texture value) { SetTextureImpl(Shader.PropertyToID(name), value); } public void SetTexture(int nameID, Texture value) { SetTextureImpl(nameID, value); } public void SetTexture(string name, RenderTexture value, RenderTextureSubElement element) { SetRenderTextureImpl(Shader.PropertyToID(name), value, element); } public void SetTexture(int nameID, RenderTexture value, RenderTextureSubElement element) { SetRenderTextureImpl(nameID, value, element); } public void SetBuffer(string name, ComputeBuffer value) { SetBufferImpl(Shader.PropertyToID(name), value); } public void SetBuffer(int nameID, ComputeBuffer value) { SetBufferImpl(nameID, value); } public void SetBuffer(string name, GraphicsBuffer value) { SetGraphicsBufferImpl(Shader.PropertyToID(name), value); } public void SetBuffer(int nameID, GraphicsBuffer value) { SetGraphicsBufferImpl(nameID, value); } public void SetConstantBuffer(string name, ComputeBuffer value, int offset, int size) { SetConstantBufferImpl(Shader.PropertyToID(name), value, offset, size); } public void SetConstantBuffer(int nameID, ComputeBuffer value, int offset, int size) { SetConstantBufferImpl(nameID, value, offset, size); } public void SetConstantBuffer(string name, GraphicsBuffer value, int offset, int size) { SetConstantGraphicsBufferImpl(Shader.PropertyToID(name), value, offset, size); } public void SetConstantBuffer(int nameID, GraphicsBuffer value, int offset, int size) { SetConstantGraphicsBufferImpl(nameID, value, offset, size); } public void SetFloatArray(string name, List values) { SetFloatArray(Shader.PropertyToID(name), NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetFloatArray(int nameID, List values) { SetFloatArray(nameID, NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetFloatArray(string name, float[] values) { SetFloatArray(Shader.PropertyToID(name), values, values.Length); } public void SetFloatArray(int nameID, float[] values) { SetFloatArray(nameID, values, values.Length); } public void SetColorArray(string name, List values) { SetColorArray(Shader.PropertyToID(name), NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetColorArray(int nameID, List values) { SetColorArray(nameID, NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetColorArray(string name, Color[] values) { SetColorArray(Shader.PropertyToID(name), values, values.Length); } public void SetColorArray(int nameID, Color[] values) { SetColorArray(nameID, values, values.Length); } public void SetVectorArray(string name, List values) { SetVectorArray(Shader.PropertyToID(name), NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetVectorArray(int nameID, List values) { SetVectorArray(nameID, NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetVectorArray(string name, Vector4[] values) { SetVectorArray(Shader.PropertyToID(name), values, values.Length); } public void SetVectorArray(int nameID, Vector4[] values) { SetVectorArray(nameID, values, values.Length); } public void SetMatrixArray(string name, List values) { SetMatrixArray(Shader.PropertyToID(name), NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetMatrixArray(int nameID, List values) { SetMatrixArray(nameID, NoAllocHelpers.ExtractArrayFromListT(values), values.Count); } public void SetMatrixArray(string name, Matrix4x4[] values) { SetMatrixArray(Shader.PropertyToID(name), values, values.Length); } public void SetMatrixArray(int nameID, Matrix4x4[] values) { SetMatrixArray(nameID, values, values.Length); } public int GetInt(string name) { return (int)GetFloatImpl(Shader.PropertyToID(name)); } public int GetInt(int nameID) { return (int)GetFloatImpl(nameID); } public float GetFloat(string name) { return GetFloatImpl(Shader.PropertyToID(name)); } public float GetFloat(int nameID) { return GetFloatImpl(nameID); } public int GetInteger(string name) { return GetIntImpl(Shader.PropertyToID(name)); } public int GetInteger(int nameID) { return GetIntImpl(nameID); } public Color GetColor(string name) { return GetColorImpl(Shader.PropertyToID(name)); } public Color GetColor(int nameID) { return GetColorImpl(nameID); } public Vector4 GetVector(string name) { return GetColorImpl(Shader.PropertyToID(name)); } public Vector4 GetVector(int nameID) { return GetColorImpl(nameID); } public Matrix4x4 GetMatrix(string name) { return GetMatrixImpl(Shader.PropertyToID(name)); } public Matrix4x4 GetMatrix(int nameID) { return GetMatrixImpl(nameID); } public Texture GetTexture(string name) { return GetTextureImpl(Shader.PropertyToID(name)); } public Texture GetTexture(int nameID) { return GetTextureImpl(nameID); } public float[] GetFloatArray(string name) { return GetFloatArray(Shader.PropertyToID(name)); } public float[] GetFloatArray(int nameID) { return (GetFloatArrayCountImpl(nameID) != 0) ? GetFloatArrayImpl(nameID) : null; } public Color[] GetColorArray(string name) { return GetColorArray(Shader.PropertyToID(name)); } public Color[] GetColorArray(int nameID) { return (GetColorArrayCountImpl(nameID) != 0) ? GetColorArrayImpl(nameID) : null; } public Vector4[] GetVectorArray(string name) { return GetVectorArray(Shader.PropertyToID(name)); } public Vector4[] GetVectorArray(int nameID) { return (GetVectorArrayCountImpl(nameID) != 0) ? GetVectorArrayImpl(nameID) : null; } public Matrix4x4[] GetMatrixArray(string name) { return GetMatrixArray(Shader.PropertyToID(name)); } public Matrix4x4[] GetMatrixArray(int nameID) { return (GetMatrixArrayCountImpl(nameID) != 0) ? GetMatrixArrayImpl(nameID) : null; } public void GetFloatArray(string name, List values) { ExtractFloatArray(Shader.PropertyToID(name), values); } public void GetFloatArray(int nameID, List values) { ExtractFloatArray(nameID, values); } public void GetColorArray(string name, List values) { ExtractColorArray(Shader.PropertyToID(name), values); } public void GetColorArray(int nameID, List values) { ExtractColorArray(nameID, values); } public void GetVectorArray(string name, List values) { ExtractVectorArray(Shader.PropertyToID(name), values); } public void GetVectorArray(int nameID, List values) { ExtractVectorArray(nameID, values); } public void GetMatrixArray(string name, List values) { ExtractMatrixArray(Shader.PropertyToID(name), values); } public void GetMatrixArray(int nameID, List values) { ExtractMatrixArray(nameID, values); } public void SetTextureOffset(string name, Vector2 value) { SetTextureOffsetImpl(Shader.PropertyToID(name), value); } public void SetTextureOffset(int nameID, Vector2 value) { SetTextureOffsetImpl(nameID, value); } public void SetTextureScale(string name, Vector2 value) { SetTextureScaleImpl(Shader.PropertyToID(name), value); } public void SetTextureScale(int nameID, Vector2 value) { SetTextureScaleImpl(nameID, value); } public Vector2 GetTextureOffset(string name) { return GetTextureOffset(Shader.PropertyToID(name)); } public Vector2 GetTextureOffset(int nameID) { Vector4 textureScaleAndOffsetImpl = GetTextureScaleAndOffsetImpl(nameID); return new Vector2(textureScaleAndOffsetImpl.z, textureScaleAndOffsetImpl.w); } public Vector2 GetTextureScale(string name) { return GetTextureScale(Shader.PropertyToID(name)); } public Vector2 GetTextureScale(int nameID) { Vector4 textureScaleAndOffsetImpl = GetTextureScaleAndOffsetImpl(nameID); return new Vector2(textureScaleAndOffsetImpl.x, textureScaleAndOffsetImpl.y); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void EnableLocalKeyword_Injected(ref LocalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private extern void DisableLocalKeyword_Injected(ref LocalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetLocalKeyword_Injected(ref LocalKeyword keyword, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private extern bool IsLocalKeywordEnabled_Injected(ref LocalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetColorImpl_Injected(int name, ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetMatrixImpl_Injected(int name, ref Matrix4x4 value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetColorImpl_Injected(int name, out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetMatrixImpl_Injected(int name, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetTextureScaleAndOffsetImpl_Injected(int name, out Vector4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetTextureOffsetImpl_Injected(int name, ref Vector2 offset); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetTextureScaleImpl_Injected(int name, ref Vector2 scale); } [NativeHeader("Runtime/Export/Graphics/GraphicsBuffer.bindings.h")] [NativeHeader("Runtime/Shaders/GraphicsBuffer.h")] [UsedByNativeCode] public sealed class GraphicsBuffer : IDisposable { [Flags] public enum Target { Vertex = 1, Index = 2, CopySource = 4, CopyDestination = 8, Structured = 0x10, Raw = 0x20, Append = 0x40, Counter = 0x80, IndirectArguments = 0x100, Constant = 0x200 } public struct IndirectDrawArgs { public const int size = 16; public uint vertexCountPerInstance { get; set; } public uint instanceCount { get; set; } public uint startVertex { get; set; } public uint startInstance { get; set; } } public struct IndirectDrawIndexedArgs { public const int size = 20; public uint indexCountPerInstance { get; set; } public uint instanceCount { get; set; } public uint startIndex { get; set; } public uint baseVertexIndex { get; set; } public uint startInstance { get; set; } } internal IntPtr m_Ptr; public extern int count { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern int stride { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern Target target { [MethodImpl(MethodImplOptions.InternalCall)] get; } public string name { set { SetName(value); } } ~GraphicsBuffer() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposing) { DestroyBuffer(this); } else if (m_Ptr != IntPtr.Zero) { Debug.LogWarning("GarbageCollector disposing of GraphicsBuffer. Please use GraphicsBuffer.Release() or .Dispose() to manually release the buffer."); } m_Ptr = IntPtr.Zero; } private static bool RequiresCompute(Target target) { Target target2 = Target.Structured | Target.Raw | Target.Append | Target.Counter | Target.IndirectArguments; return (target & target2) != 0; } private static bool IsVertexIndexOrCopyOnly(Target target) { Target target2 = Target.Vertex | Target.Index | Target.CopySource | Target.CopyDestination; return (target & target2) == target; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsBuffer_Bindings::InitBuffer")] private static extern IntPtr InitBuffer(Target target, int count, int stride); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsBuffer_Bindings::DestroyBuffer")] private static extern void DestroyBuffer(GraphicsBuffer buf); public GraphicsBuffer(Target target, int count, int stride) { if (RequiresCompute(target) && !SystemInfo.supportsComputeShaders) { throw new ArgumentException("Attempting to create a graphics buffer that requires compute shader support, but compute shaders are not supported on this platform. Target: " + target); } if (count <= 0) { throw new ArgumentException("Attempting to create a zero length graphics buffer", "count"); } if (stride <= 0) { throw new ArgumentException("Attempting to create a graphics buffer with a negative or null stride", "stride"); } if ((target & Target.Index) != 0 && stride != 2 && stride != 4) { throw new ArgumentException("Attempting to create an index buffer with an invalid stride: " + stride, "stride"); } if (!IsVertexIndexOrCopyOnly(target) && stride % 4 != 0) { throw new ArgumentException("Stride must be a multiple of 4 unless the buffer is only used as a vertex buffer and/or index buffer ", "stride"); } long num = (long)count * (long)stride; long maxGraphicsBufferSize = SystemInfo.maxGraphicsBufferSize; if (num > maxGraphicsBufferSize) { throw new ArgumentException($"The total size of the graphics buffer ({num} bytes) exceeds the maximum buffer size. Maximum supported buffer size: {maxGraphicsBufferSize} bytes."); } m_Ptr = InitBuffer(target, count, stride); } public void Release() { Dispose(); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsBuffer_Bindings::IsValidBuffer")] private static extern bool IsValidBuffer(GraphicsBuffer buf); public bool IsValid() { return m_Ptr != IntPtr.Zero && IsValidBuffer(this); } [SecuritySafeCritical] public void SetData(Array data) { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException($"Array passed to GraphicsBuffer.SetData(array) must be blittable.\n{UnsafeUtility.GetReasonForArrayNonBlittable(data)}"); } InternalSetData(data, 0, 0, data.Length, UnsafeUtility.SizeOf(data.GetType().GetElementType())); } [SecuritySafeCritical] public void SetData(List data) where T : struct { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException($"List<{typeof(T)}> passed to GraphicsBuffer.SetData(List<>) must be blittable.\n{UnsafeUtility.GetReasonForGenericListNonBlittable()}"); } InternalSetData(NoAllocHelpers.ExtractArrayFromList(data), 0, 0, NoAllocHelpers.SafeLength(data), Marshal.SizeOf(typeof(T))); } [SecuritySafeCritical] public unsafe void SetData(NativeArray data) where T : struct { InternalSetNativeData((IntPtr)data.GetUnsafeReadOnlyPtr(), 0, 0, data.Length, UnsafeUtility.SizeOf()); } [SecuritySafeCritical] public void SetData(Array data, int managedBufferStartIndex, int graphicsBufferStartIndex, int count) { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException($"Array passed to GraphicsBuffer.SetData(array) must be blittable.\n{UnsafeUtility.GetReasonForArrayNonBlittable(data)}"); } if (managedBufferStartIndex < 0 || graphicsBufferStartIndex < 0 || count < 0 || managedBufferStartIndex + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (managedBufferStartIndex:{managedBufferStartIndex} graphicsBufferStartIndex:{graphicsBufferStartIndex} count:{count})"); } InternalSetData(data, managedBufferStartIndex, graphicsBufferStartIndex, count, Marshal.SizeOf(data.GetType().GetElementType())); } [SecuritySafeCritical] public void SetData(List data, int managedBufferStartIndex, int graphicsBufferStartIndex, int count) where T : struct { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException($"List<{typeof(T)}> passed to GraphicsBuffer.SetData(List<>) must be blittable.\n{UnsafeUtility.GetReasonForGenericListNonBlittable()}"); } if (managedBufferStartIndex < 0 || graphicsBufferStartIndex < 0 || count < 0 || managedBufferStartIndex + count > data.Count) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (managedBufferStartIndex:{managedBufferStartIndex} graphicsBufferStartIndex:{graphicsBufferStartIndex} count:{count})"); } InternalSetData(NoAllocHelpers.ExtractArrayFromList(data), managedBufferStartIndex, graphicsBufferStartIndex, count, Marshal.SizeOf(typeof(T))); } [SecuritySafeCritical] public unsafe void SetData(NativeArray data, int nativeBufferStartIndex, int graphicsBufferStartIndex, int count) where T : struct { if (nativeBufferStartIndex < 0 || graphicsBufferStartIndex < 0 || count < 0 || nativeBufferStartIndex + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (nativeBufferStartIndex:{nativeBufferStartIndex} graphicsBufferStartIndex:{graphicsBufferStartIndex} count:{count})"); } InternalSetNativeData((IntPtr)data.GetUnsafeReadOnlyPtr(), nativeBufferStartIndex, graphicsBufferStartIndex, count, UnsafeUtility.SizeOf()); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GraphicsBuffer_Bindings::InternalSetNativeData", HasExplicitThis = true, ThrowsException = true)] [SecurityCritical] private extern void InternalSetNativeData(IntPtr data, int nativeBufferStartIndex, int graphicsBufferStartIndex, int count, int elemSize); [MethodImpl(MethodImplOptions.InternalCall)] [SecurityCritical] [FreeFunction(Name = "GraphicsBuffer_Bindings::InternalSetData", HasExplicitThis = true, ThrowsException = true)] private extern void InternalSetData(Array data, int managedBufferStartIndex, int graphicsBufferStartIndex, int count, int elemSize); [SecurityCritical] public void GetData(Array data) { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException($"Array passed to GraphicsBuffer.GetData(array) must be blittable.\n{UnsafeUtility.GetReasonForArrayNonBlittable(data)}"); } InternalGetData(data, 0, 0, data.Length, Marshal.SizeOf(data.GetType().GetElementType())); } [SecurityCritical] public void GetData(Array data, int managedBufferStartIndex, int computeBufferStartIndex, int count) { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException($"Array passed to GraphicsBuffer.GetData(array) must be blittable.\n{UnsafeUtility.GetReasonForArrayNonBlittable(data)}"); } if (managedBufferStartIndex < 0 || computeBufferStartIndex < 0 || count < 0 || managedBufferStartIndex + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad indices/count argument (managedBufferStartIndex:{managedBufferStartIndex} computeBufferStartIndex:{computeBufferStartIndex} count:{count})"); } InternalGetData(data, managedBufferStartIndex, computeBufferStartIndex, count, Marshal.SizeOf(data.GetType().GetElementType())); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GraphicsBuffer_Bindings::InternalGetData", HasExplicitThis = true, ThrowsException = true)] [SecurityCritical] private extern void InternalGetData(Array data, int managedBufferStartIndex, int computeBufferStartIndex, int count, int elemSize); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GraphicsBuffer_Bindings::InternalGetNativeBufferPtr", HasExplicitThis = true)] public extern IntPtr GetNativeBufferPtr(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GraphicsBuffer_Bindings::SetName", HasExplicitThis = true)] private extern void SetName(string name); [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetCounterValue(uint counterValue); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GraphicsBuffer_Bindings::CopyCount")] private static extern void CopyCountCC(ComputeBuffer src, ComputeBuffer dst, int dstOffsetBytes); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GraphicsBuffer_Bindings::CopyCount")] private static extern void CopyCountGC(GraphicsBuffer src, ComputeBuffer dst, int dstOffsetBytes); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GraphicsBuffer_Bindings::CopyCount")] private static extern void CopyCountCG(ComputeBuffer src, GraphicsBuffer dst, int dstOffsetBytes); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GraphicsBuffer_Bindings::CopyCount")] private static extern void CopyCountGG(GraphicsBuffer src, GraphicsBuffer dst, int dstOffsetBytes); public static void CopyCount(ComputeBuffer src, ComputeBuffer dst, int dstOffsetBytes) { CopyCountCC(src, dst, dstOffsetBytes); } public static void CopyCount(GraphicsBuffer src, ComputeBuffer dst, int dstOffsetBytes) { CopyCountGC(src, dst, dstOffsetBytes); } public static void CopyCount(ComputeBuffer src, GraphicsBuffer dst, int dstOffsetBytes) { CopyCountCG(src, dst, dstOffsetBytes); } public static void CopyCount(GraphicsBuffer src, GraphicsBuffer dst, int dstOffsetBytes) { CopyCountGG(src, dst, dstOffsetBytes); } } [NativeHeader("Runtime/Camera/OcclusionPortal.h")] public sealed class OcclusionPortal : Component { [NativeProperty("IsOpen")] public extern bool open { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } } [NativeHeader("Runtime/Camera/OcclusionArea.h")] public sealed class OcclusionArea : Component { public Vector3 center { get { get_center_Injected(out var ret); return ret; } set { set_center_Injected(ref value); } } public Vector3 size { get { get_size_Injected(out var ret); return ret; } set { set_size_Injected(ref value); } } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_center_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_center_Injected(ref Vector3 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_size_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_size_Injected(ref Vector3 value); } [NativeHeader("Runtime/Camera/Flare.h")] public sealed class Flare : Object { public Flare() { Internal_Create(this); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_Create([Writable] Flare self); } [NativeHeader("Runtime/Camera/Flare.h")] public sealed class LensFlare : Behaviour { public extern float brightness { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float fadeSpeed { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Color color { get { get_color_Injected(out var ret); return ret; } set { set_color_Injected(ref value); } } public extern Flare flare { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_color_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_color_Injected(ref Color value); } [NativeHeader("Runtime/Camera/Projector.h")] public sealed class Projector : Behaviour { public extern float nearClipPlane { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float farClipPlane { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float fieldOfView { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float aspectRatio { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool orthographic { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float orthographicSize { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int ignoreLayers { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Material material { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } } [NativeHeader("Runtime/Camera/SharedLightData.h")] public struct LightBakingOutput { public int probeOcclusionLightIndex; public int occlusionMaskChannel; [NativeName("lightmapBakeMode.lightmapBakeType")] public LightmapBakeType lightmapBakeType; [NativeName("lightmapBakeMode.mixedLightingMode")] public MixedLightingMode mixedLightingMode; public bool isBaked; } [NativeHeader("Runtime/Camera/SharedLightData.h")] public enum LightShadowCasterMode { Default, NonLightmappedOnly, Everything } [NativeHeader("Runtime/Export/Graphics/Light.bindings.h")] [NativeHeader("Runtime/Camera/Light.h")] [RequireComponent(typeof(Transform))] [RequireComponent(typeof(Transform))] public sealed class Light : Behaviour { private int m_BakedIndex; [NativeProperty("LightType")] public extern LightType type { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("LightShape")] public extern LightShape shape { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float spotAngle { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float innerSpotAngle { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Color color { get { get_color_Injected(out var ret); return ret; } set { set_color_Injected(ref value); } } public extern float colorTemperature { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool useColorTemperature { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float intensity { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float bounceIntensity { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool useBoundingSphereOverride { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Vector4 boundingSphereOverride { get { get_boundingSphereOverride_Injected(out var ret); return ret; } set { set_boundingSphereOverride_Injected(ref value); } } public extern bool useViewFrustumForShadowCasterCull { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int shadowCustomResolution { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float shadowBias { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float shadowNormalBias { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float shadowNearPlane { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool useShadowMatrixOverride { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Matrix4x4 shadowMatrixOverride { get { get_shadowMatrixOverride_Injected(out var ret); return ret; } set { set_shadowMatrixOverride_Injected(ref value); } } public extern float range { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Flare flare { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public LightBakingOutput bakingOutput { get { get_bakingOutput_Injected(out var ret); return ret; } set { set_bakingOutput_Injected(ref value); } } public extern int cullingMask { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int renderingLayerMask { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern LightShadowCasterMode lightShadowCasterMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern LightShadows shadows { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetShadowType")] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Light_Bindings::SetShadowType", HasExplicitThis = true, ThrowsException = true)] set; } public extern float shadowStrength { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Light_Bindings::SetShadowStrength", HasExplicitThis = true)] set; } public extern LightShadowResolution shadowResolution { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Light_Bindings::SetShadowResolution", HasExplicitThis = true, ThrowsException = true)] set; } [Obsolete("Shadow softness is removed in Unity 5.0+", true)] [EditorBrowsable(EditorBrowsableState.Never)] public float shadowSoftness { get { return 4f; } set { } } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Shadow softness is removed in Unity 5.0+", true)] public float shadowSoftnessFade { get { return 1f; } set { } } public extern float[] layerShadowCullDistances { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Light_Bindings::GetLayerShadowCullDistances", HasExplicitThis = true, ThrowsException = false)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Light_Bindings::SetLayerShadowCullDistances", HasExplicitThis = true, ThrowsException = true)] set; } public extern float cookieSize { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Texture cookie { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern LightRenderMode renderMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Light_Bindings::SetRenderMode", HasExplicitThis = true, ThrowsException = true)] set; } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("warning bakedIndex has been removed please use bakingOutput.isBaked instead.", true)] public int bakedIndex { get { return m_BakedIndex; } set { m_BakedIndex = value; } } public extern int commandBufferCount { [MethodImpl(MethodImplOptions.InternalCall)] get; } [Obsolete("Use QualitySettings.pixelLightCount instead.")] public static int pixelLightCount { get { return QualitySettings.pixelLightCount; } set { QualitySettings.pixelLightCount = value; } } [Obsolete("light.shadowConstantBias was removed, use light.shadowBias", true)] public float shadowConstantBias { get { return 0f; } set { } } [Obsolete("light.shadowObjectSizeBias was removed, use light.shadowBias", true)] public float shadowObjectSizeBias { get { return 0f; } set { } } [Obsolete("light.attenuate was removed; all lights always attenuate now", true)] public bool attenuate { get { return true; } set { } } [MethodImpl(MethodImplOptions.InternalCall)] public extern void Reset(); public void AddCommandBuffer(LightEvent evt, CommandBuffer buffer) { AddCommandBuffer(evt, buffer, ShadowMapPass.All); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Light_Bindings::AddCommandBuffer", HasExplicitThis = true)] public extern void AddCommandBuffer(LightEvent evt, CommandBuffer buffer, ShadowMapPass shadowPassMask); public void AddCommandBufferAsync(LightEvent evt, CommandBuffer buffer, ComputeQueueType queueType) { AddCommandBufferAsync(evt, buffer, ShadowMapPass.All, queueType); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Light_Bindings::AddCommandBufferAsync", HasExplicitThis = true)] public extern void AddCommandBufferAsync(LightEvent evt, CommandBuffer buffer, ShadowMapPass shadowPassMask, ComputeQueueType queueType); [MethodImpl(MethodImplOptions.InternalCall)] public extern void RemoveCommandBuffer(LightEvent evt, CommandBuffer buffer); [MethodImpl(MethodImplOptions.InternalCall)] public extern void RemoveCommandBuffers(LightEvent evt); [MethodImpl(MethodImplOptions.InternalCall)] public extern void RemoveAllCommandBuffers(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Light_Bindings::GetCommandBuffers", HasExplicitThis = true)] public extern CommandBuffer[] GetCommandBuffers(LightEvent evt); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Light_Bindings::GetLights")] public static extern Light[] GetLights(LightType type, int layer); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_color_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_color_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_boundingSphereOverride_Injected(out Vector4 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_boundingSphereOverride_Injected(ref Vector4 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_shadowMatrixOverride_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_shadowMatrixOverride_Injected(ref Matrix4x4 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_bakingOutput_Injected(out LightBakingOutput ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_bakingOutput_Injected(ref LightBakingOutput value); } [NativeHeader("Runtime/Camera/Skybox.h")] public sealed class Skybox : Behaviour { public extern Material material { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } } [RequireComponent(typeof(Transform))] [NativeHeader("Runtime/Graphics/Mesh/MeshFilter.h")] public sealed class MeshFilter : Component { public extern Mesh sharedMesh { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Mesh mesh { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetInstantiatedMeshFromScript")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetInstantiatedMesh")] set; } [RequiredByNativeCode] private void DontStripMeshFilter() { } } [NativeHeader("Runtime/Camera/HaloManager.h")] [RequireComponent(typeof(Transform))] internal sealed class Halo : Behaviour { } public enum RenderingPath { UsePlayerSettings = -1, VertexLit, Forward, DeferredLighting, DeferredShading } public enum TransparencySortMode { Default, Perspective, Orthographic, CustomAxis } public enum StereoTargetEyeMask { None, Left, Right, Both } [Flags] public enum CameraType { Game = 1, SceneView = 2, Preview = 4, VR = 8, Reflection = 0x10 } [Flags] public enum ComputeBufferType { Default = 0, Raw = 1, Append = 2, Counter = 4, Constant = 8, Structured = 0x10, [Obsolete("Enum member DrawIndirect has been deprecated. Use IndirectArguments instead (UnityUpgradable) -> IndirectArguments", false)] DrawIndirect = 0x100, IndirectArguments = 0x100, [Obsolete("Enum member GPUMemory has been deprecated. All compute buffers now follow the behavior previously defined by this member.", false)] GPUMemory = 0x200 } public enum LightType { Spot = 0, Directional = 1, Point = 2, Area = 3, Rectangle = 3, Disc = 4 } public enum LightShape { Cone, Pyramid, Box } public enum LightRenderMode { Auto, ForcePixel, ForceVertex } public enum LightShadows { None, Hard, Soft } public enum FogMode { Linear = 1, Exponential, ExponentialSquared } [Flags] public enum LightmapBakeType { Realtime = 4, Baked = 2, Mixed = 1 } public enum MixedLightingMode { IndirectOnly = 0, Shadowmask = 2, Subtractive = 1 } public enum ReceiveGI { Lightmaps = 1, LightProbes } public enum LightmapCompression { None, LowQuality, NormalQuality, HighQuality } [Obsolete("See QualitySettings.names, QualitySettings.SetQualityLevel, and QualitySettings.GetQualityLevel")] public enum QualityLevel { Fastest, Fast, Simple, Good, Beautiful, Fantastic } public enum ShadowProjection { CloseFit, StableFit } public enum ShadowQuality { Disable, HardOnly, All } public enum ShadowResolution { Low, Medium, High, VeryHigh } public enum ShadowmaskMode { Shadowmask, DistanceShadowmask } public enum ShadowObjectsFilter { AllObjects, DynamicOnly, StaticOnly } public enum CameraClearFlags { Skybox = 1, Color = 2, SolidColor = 2, Depth = 3, Nothing = 4 } [Flags] public enum DepthTextureMode { None = 0, Depth = 1, DepthNormals = 2, MotionVectors = 4 } public enum TexGenMode { None, SphereMap, Object, EyeLinear, CubeReflect, CubeNormal } public enum AnisotropicFiltering { Disable, Enable, ForceEnable } [Obsolete("BlendWeights is obsolete. Use SkinWeights instead (UnityUpgradable) -> SkinWeights", true)] public enum BlendWeights { [Obsolete("BlendWeights.OneBone is obsolete. Use SkinWeights.OneBone instead (UnityUpgradable) -> SkinWeights.OneBone", true)] OneBone = 1, [Obsolete("BlendWeights.TwoBones is obsolete. Use SkinWeights.TwoBones instead (UnityUpgradable) -> SkinWeights.TwoBones", true)] TwoBones = 2, [Obsolete("BlendWeights.FourBones is obsolete. Use SkinWeights.FourBones instead (UnityUpgradable) -> SkinWeights.FourBones", true)] FourBones = 4 } public enum SkinWeights { OneBone = 1, TwoBones = 2, FourBones = 4, Unlimited = 255 } public enum MeshTopology { Triangles = 0, Quads = 2, Lines = 3, LineStrip = 4, Points = 5 } public enum SkinQuality { Auto = 0, Bone1 = 1, Bone2 = 2, Bone4 = 4 } public enum ColorSpace { Uninitialized = -1, Gamma, Linear } [NativeHeader("Runtime/Graphics/ColorGamut.h")] [UsedByNativeCode] public enum ColorGamut { sRGB, Rec709, Rec2020, DisplayP3, HDR10, DolbyHDR } public enum ScreenOrientation { [Obsolete("Enum member Unknown has been deprecated.", false)] Unknown = 0, [Obsolete("Use LandscapeLeft instead (UnityUpgradable) -> LandscapeLeft", true)] Landscape = 3, Portrait = 1, PortraitUpsideDown = 2, LandscapeLeft = 3, LandscapeRight = 4, AutoRotation = 5 } public enum FilterMode { Point, Bilinear, Trilinear } public enum TextureWrapMode { Repeat, Clamp, Mirror, MirrorOnce } public enum NPOTSupport { [Obsolete("NPOTSupport.None does not happen on any platforms")] None, Restricted, Full } public enum TextureFormat { Alpha8 = 1, ARGB4444 = 2, RGB24 = 3, RGBA32 = 4, ARGB32 = 5, RGB565 = 7, R16 = 9, DXT1 = 10, DXT5 = 12, RGBA4444 = 13, BGRA32 = 14, RHalf = 15, RGHalf = 16, RGBAHalf = 17, RFloat = 18, RGFloat = 19, RGBAFloat = 20, YUY2 = 21, RGB9e5Float = 22, BC4 = 26, BC5 = 27, BC6H = 24, BC7 = 25, DXT1Crunched = 28, DXT5Crunched = 29, PVRTC_RGB2 = 30, PVRTC_RGBA2 = 31, PVRTC_RGB4 = 32, PVRTC_RGBA4 = 33, ETC_RGB4 = 34, EAC_R = 41, EAC_R_SIGNED = 42, EAC_RG = 43, EAC_RG_SIGNED = 44, ETC2_RGB = 45, ETC2_RGBA1 = 46, ETC2_RGBA8 = 47, ASTC_4x4 = 48, ASTC_5x5 = 49, ASTC_6x6 = 50, ASTC_8x8 = 51, ASTC_10x10 = 52, ASTC_12x12 = 53, [Obsolete("Nintendo 3DS is no longer supported.")] ETC_RGB4_3DS = 60, [Obsolete("Nintendo 3DS is no longer supported.")] ETC_RGBA8_3DS = 61, RG16 = 62, R8 = 63, ETC_RGB4Crunched = 64, ETC2_RGBA8Crunched = 65, ASTC_HDR_4x4 = 66, ASTC_HDR_5x5 = 67, ASTC_HDR_6x6 = 68, ASTC_HDR_8x8 = 69, ASTC_HDR_10x10 = 70, ASTC_HDR_12x12 = 71, RG32 = 72, RGB48 = 73, RGBA64 = 74, [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Enum member TextureFormat.ASTC_RGB_4x4 has been deprecated. Use ASTC_4x4 instead (UnityUpgradable) -> ASTC_4x4")] ASTC_RGB_4x4 = 48, [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Enum member TextureFormat.ASTC_RGB_5x5 has been deprecated. Use ASTC_5x5 instead (UnityUpgradable) -> ASTC_5x5")] ASTC_RGB_5x5 = 49, [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Enum member TextureFormat.ASTC_RGB_6x6 has been deprecated. Use ASTC_6x6 instead (UnityUpgradable) -> ASTC_6x6")] ASTC_RGB_6x6 = 50, [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Enum member TextureFormat.ASTC_RGB_8x8 has been deprecated. Use ASTC_8x8 instead (UnityUpgradable) -> ASTC_8x8")] ASTC_RGB_8x8 = 51, [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Enum member TextureFormat.ASTC_RGB_10x10 has been deprecated. Use ASTC_10x10 instead (UnityUpgradable) -> ASTC_10x10")] ASTC_RGB_10x10 = 52, [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Enum member TextureFormat.ASTC_RGB_12x12 has been deprecated. Use ASTC_12x12 instead (UnityUpgradable) -> ASTC_12x12")] ASTC_RGB_12x12 = 53, [Obsolete("Enum member TextureFormat.ASTC_RGBA_4x4 has been deprecated. Use ASTC_4x4 instead (UnityUpgradable) -> ASTC_4x4")] [EditorBrowsable(EditorBrowsableState.Never)] ASTC_RGBA_4x4 = 54, [Obsolete("Enum member TextureFormat.ASTC_RGBA_5x5 has been deprecated. Use ASTC_5x5 instead (UnityUpgradable) -> ASTC_5x5")] [EditorBrowsable(EditorBrowsableState.Never)] ASTC_RGBA_5x5 = 55, [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Enum member TextureFormat.ASTC_RGBA_6x6 has been deprecated. Use ASTC_6x6 instead (UnityUpgradable) -> ASTC_6x6")] ASTC_RGBA_6x6 = 56, [Obsolete("Enum member TextureFormat.ASTC_RGBA_8x8 has been deprecated. Use ASTC_8x8 instead (UnityUpgradable) -> ASTC_8x8")] [EditorBrowsable(EditorBrowsableState.Never)] ASTC_RGBA_8x8 = 57, [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Enum member TextureFormat.ASTC_RGBA_10x10 has been deprecated. Use ASTC_10x10 instead (UnityUpgradable) -> ASTC_10x10")] ASTC_RGBA_10x10 = 58, [Obsolete("Enum member TextureFormat.ASTC_RGBA_12x12 has been deprecated. Use ASTC_12x12 instead (UnityUpgradable) -> ASTC_12x12")] [EditorBrowsable(EditorBrowsableState.Never)] ASTC_RGBA_12x12 = 59 } internal enum TextureColorSpace { Linear, sRGB } public enum CubemapFace { Unknown = -1, PositiveX, NegativeX, PositiveY, NegativeY, PositiveZ, NegativeZ } public enum RenderTextureFormat { ARGB32 = 0, Depth = 1, ARGBHalf = 2, Shadowmap = 3, RGB565 = 4, ARGB4444 = 5, ARGB1555 = 6, Default = 7, ARGB2101010 = 8, DefaultHDR = 9, ARGB64 = 10, ARGBFloat = 11, RGFloat = 12, RGHalf = 13, RFloat = 14, RHalf = 15, R8 = 16, ARGBInt = 17, RGInt = 18, RInt = 19, BGRA32 = 20, RGB111110Float = 22, RG32 = 23, RGBAUShort = 24, RG16 = 25, BGRA10101010_XR = 26, BGR101010_XR = 27, R16 = 28 } public enum VRTextureUsage { None, OneEye, TwoEyes, DeviceSpecific } [Flags] public enum RenderTextureCreationFlags { MipMap = 1, AutoGenerateMips = 2, SRGB = 4, EyeTexture = 8, EnableRandomWrite = 0x10, CreatedFromScript = 0x20, AllowVerticalFlip = 0x80, NoResolvedColorSurface = 0x100, DynamicallyScalable = 0x400, BindMS = 0x800 } public enum RenderTextureReadWrite { Default, Linear, sRGB } [Flags] public enum RenderTextureMemoryless { None = 0, Color = 1, Depth = 2, MSAA = 4 } [Flags] public enum HDRDisplaySupportFlags { None = 0, Supported = 1, RuntimeSwitchable = 2, AutomaticTonemapping = 4 } [Flags] public enum LightmapsMode { NonDirectional = 0, CombinedDirectional = 1 } [Flags] public enum MaterialGlobalIlluminationFlags { None = 0, RealtimeEmissive = 1, BakedEmissive = 2, EmissiveIsBlack = 4, AnyEmissive = 3 } [NativeHeader("Runtime/Camera/LightProbeProxyVolume.h")] public sealed class LightProbeProxyVolume : Behaviour { public enum ResolutionMode { Automatic, Custom } public enum BoundingBoxMode { AutomaticLocal, AutomaticWorld, Custom } public enum ProbePositionMode { CellCorner, CellCenter } public enum RefreshMode { Automatic, EveryFrame, ViaScripting } public enum QualityMode { Low, Normal } public enum DataFormat { HalfFloat, Float } public static extern bool isFeatureSupported { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("IsFeatureSupported")] get; } [NativeName("GlobalAABB")] public Bounds boundsGlobal { get { get_boundsGlobal_Injected(out var ret); return ret; } } [NativeName("BoundingBoxSizeCustom")] public Vector3 sizeCustom { get { get_sizeCustom_Injected(out var ret); return ret; } set { set_sizeCustom_Injected(ref value); } } [NativeName("BoundingBoxOriginCustom")] public Vector3 originCustom { get { get_originCustom_Injected(out var ret); return ret; } set { set_originCustom_Injected(ref value); } } public extern float probeDensity { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int gridResolutionX { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int gridResolutionY { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int gridResolutionZ { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern BoundingBoxMode boundingBoxMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern ResolutionMode resolutionMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern ProbePositionMode probePositionMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern RefreshMode refreshMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern QualityMode qualityMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern DataFormat dataFormat { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public void Update() { SetDirtyFlag(flag: true); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetDirtyFlag(bool flag); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_boundsGlobal_Injected(out Bounds ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_sizeCustom_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_sizeCustom_Injected(ref Vector3 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_originCustom_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_originCustom_Injected(ref Vector3 value); } public enum CustomRenderTextureInitializationSource { TextureAndColor, Material } public enum CustomRenderTextureUpdateMode { OnLoad, Realtime, OnDemand } public enum CustomRenderTextureUpdateZoneSpace { Normalized, Pixel } public enum MotionVectorGenerationMode { Camera, Object, ForceNoMotion } public enum LineTextureMode { Stretch, Tile, DistributePerSegment, RepeatPerSegment } public enum LineAlignment { View = 0, [Obsolete("Enum member Local has been deprecated. Use TransformZ instead (UnityUpgradable) -> TransformZ", false)] Local = 1, TransformZ = 1 } [RequiredByNativeCode] [NativeHeader("Runtime/Graphics/Mesh/SkinnedMeshRenderer.h")] public class SkinnedMeshRenderer : Renderer { public extern SkinQuality quality { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool updateWhenOffscreen { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool forceMatrixRecalculationPerRender { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Transform rootBone { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Transform[] bones { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("Mesh")] public extern Mesh sharedMesh { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("SkinnedMeshMotionVectors")] public extern bool skinnedMotionVectors { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern GraphicsBuffer.Target vertexBufferTarget { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [MethodImpl(MethodImplOptions.InternalCall)] public extern float GetBlendShapeWeight(int index); [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetBlendShapeWeight(int index, float value); public void BakeMesh(Mesh mesh) { BakeMesh(mesh, useScale: false); } [MethodImpl(MethodImplOptions.InternalCall)] public extern void BakeMesh([NotNull("NullExceptionObject")] Mesh mesh, bool useScale); public GraphicsBuffer GetVertexBuffer() { if (this == null) { throw new NullReferenceException(); } return GetVertexBufferImpl(); } public GraphicsBuffer GetPreviousVertexBuffer() { if (this == null) { throw new NullReferenceException(); } return GetPreviousVertexBufferImpl(); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "SkinnedMeshRendererScripting::GetVertexBufferPtr", HasExplicitThis = true)] private extern GraphicsBuffer GetVertexBufferImpl(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "SkinnedMeshRendererScripting::GetPreviousVertexBufferPtr", HasExplicitThis = true)] private extern GraphicsBuffer GetPreviousVertexBufferImpl(); } [NativeHeader("Runtime/Graphics/Mesh/MeshRenderer.h")] public class MeshRenderer : Renderer { public extern Mesh additionalVertexStreams { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Mesh enlightenVertexStream { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int subMeshStartIndex { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetSubMeshStartIndex")] get; } [RequiredByNativeCode] private void DontStripMeshRenderer() { } } [NativeHeader("Runtime/Graphics/LightProbeGroup.h")] public sealed class LightProbeGroup : Behaviour { public Vector3[] probePositions => null; } [NativeHeader("Runtime/Export/Graphics/LineUtility.bindings.h")] public sealed class LineUtility { public static void Simplify(List points, float tolerance, List pointsToKeep) { if (points == null) { throw new ArgumentNullException("points"); } if (pointsToKeep == null) { throw new ArgumentNullException("pointsToKeep"); } GeneratePointsToKeep3D(points, tolerance, pointsToKeep); } public static void Simplify(List points, float tolerance, List simplifiedPoints) { if (points == null) { throw new ArgumentNullException("points"); } if (simplifiedPoints == null) { throw new ArgumentNullException("simplifiedPoints"); } GenerateSimplifiedPoints3D(points, tolerance, simplifiedPoints); } public static void Simplify(List points, float tolerance, List pointsToKeep) { if (points == null) { throw new ArgumentNullException("points"); } if (pointsToKeep == null) { throw new ArgumentNullException("pointsToKeep"); } GeneratePointsToKeep2D(points, tolerance, pointsToKeep); } public static void Simplify(List points, float tolerance, List simplifiedPoints) { if (points == null) { throw new ArgumentNullException("points"); } if (simplifiedPoints == null) { throw new ArgumentNullException("simplifiedPoints"); } GenerateSimplifiedPoints2D(points, tolerance, simplifiedPoints); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("LineUtility_Bindings::GeneratePointsToKeep3D", IsThreadSafe = true)] internal static extern void GeneratePointsToKeep3D(object pointsList, float tolerance, object pointsToKeepList); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("LineUtility_Bindings::GeneratePointsToKeep2D", IsThreadSafe = true)] internal static extern void GeneratePointsToKeep2D(object pointsList, float tolerance, object pointsToKeepList); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("LineUtility_Bindings::GenerateSimplifiedPoints3D", IsThreadSafe = true)] internal static extern void GenerateSimplifiedPoints3D(object pointsList, float tolerance, object simplifiedPoints); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("LineUtility_Bindings::GenerateSimplifiedPoints2D", IsThreadSafe = true)] internal static extern void GenerateSimplifiedPoints2D(object pointsList, float tolerance, object simplifiedPoints); } public enum LODFadeMode { None, CrossFade, SpeedTree } [UsedByNativeCode] public struct LOD { public float screenRelativeTransitionHeight; public float fadeTransitionWidth; public Renderer[] renderers; public LOD(float screenRelativeTransitionHeight, Renderer[] renderers) { this.screenRelativeTransitionHeight = screenRelativeTransitionHeight; fadeTransitionWidth = 0f; this.renderers = renderers; } } [NativeHeader("Runtime/Graphics/LOD/LODGroup.h")] [NativeHeader("Runtime/Graphics/LOD/LODGroupManager.h")] [NativeHeader("Runtime/Graphics/LOD/LODUtility.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public class LODGroup : Component { public Vector3 localReferencePoint { get { get_localReferencePoint_Injected(out var ret); return ret; } set { set_localReferencePoint_Injected(ref value); } } public extern float size { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int lodCount { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetLODCount")] get; } public extern LODFadeMode fadeMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool animateCrossFading { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool enabled { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [StaticAccessor("GetLODGroupManager()")] public static extern float crossFadeAnimationDuration { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } internal Vector3 worldReferencePoint { get { get_worldReferencePoint_Injected(out var ret); return ret; } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UpdateLODGroupBoundingBox", HasExplicitThis = true)] public extern void RecalculateBounds(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetLODs_Binding", HasExplicitThis = true)] public extern LOD[] GetLODs(); [Obsolete("Use SetLODs instead.")] public void SetLODS(LOD[] lods) { SetLODs(lods); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SetLODs_Binding", HasExplicitThis = true)] public extern void SetLODs([Unmarshalled] LOD[] lods); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ForceLODLevel", HasExplicitThis = true)] public extern void ForceLOD(int index); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_localReferencePoint_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_localReferencePoint_Injected(ref Vector3 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_worldReferencePoint_Injected(out Vector3 ret); } [RequiredByNativeCode] [NativeHeader("Runtime/Graphics/Mesh/MeshScriptBindings.h")] public sealed class Mesh : Object { [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("Runtime/Graphics/Mesh/MeshScriptBindings.h")] public struct MeshData { [NativeDisableUnsafePtrRestriction] internal IntPtr m_Ptr; public int vertexCount => GetVertexCount(m_Ptr); public int vertexBufferCount => GetVertexBufferCount(m_Ptr); public IndexFormat indexFormat => GetIndexFormat(m_Ptr); public int subMeshCount { get { return GetSubMeshCount(m_Ptr); } set { SetSubMeshCount(m_Ptr, value); } } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern bool HasVertexAttribute(IntPtr self, VertexAttribute attr); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern int GetVertexAttributeDimension(IntPtr self, VertexAttribute attr); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern VertexAttributeFormat GetVertexAttributeFormat(IntPtr self, VertexAttribute attr); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern int GetVertexAttributeStream(IntPtr self, VertexAttribute attr); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern int GetVertexAttributeOffset(IntPtr self, VertexAttribute attr); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern int GetVertexCount(IntPtr self); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern int GetVertexBufferCount(IntPtr self); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern IntPtr GetVertexDataPtr(IntPtr self, int stream); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern ulong GetVertexDataSize(IntPtr self, int stream); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern int GetVertexBufferStride(IntPtr self, int stream); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern void CopyAttributeIntoPtr(IntPtr self, VertexAttribute attr, VertexAttributeFormat format, int dim, IntPtr dst); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern void CopyIndicesIntoPtr(IntPtr self, int submesh, bool applyBaseVertex, int dstStride, IntPtr dst); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern IndexFormat GetIndexFormat(IntPtr self); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern int GetIndexCount(IntPtr self, int submesh); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern IntPtr GetIndexDataPtr(IntPtr self); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern ulong GetIndexDataSize(IntPtr self); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern int GetSubMeshCount(IntPtr self); [NativeMethod(IsThreadSafe = true, ThrowsException = true)] private static SubMeshDescriptor GetSubMesh(IntPtr self, int index) { GetSubMesh_Injected(self, index, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true, ThrowsException = true)] private static extern void SetVertexBufferParamsFromPtr(IntPtr self, int vertexCount, IntPtr attributesPtr, int attributesCount); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true, ThrowsException = true)] private static extern void SetVertexBufferParamsFromArray(IntPtr self, int vertexCount, [Unmarshalled] params VertexAttributeDescriptor[] attributes); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true, ThrowsException = true)] private static extern void SetIndexBufferParamsImpl(IntPtr self, int indexCount, IndexFormat indexFormat); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern void SetSubMeshCount(IntPtr self, int count); [NativeMethod(IsThreadSafe = true, ThrowsException = true)] private static void SetSubMeshImpl(IntPtr self, int index, SubMeshDescriptor desc, MeshUpdateFlags flags) { SetSubMeshImpl_Injected(self, index, ref desc, flags); } public int GetVertexBufferStride(int stream) { return GetVertexBufferStride(m_Ptr, stream); } public bool HasVertexAttribute(VertexAttribute attr) { return HasVertexAttribute(m_Ptr, attr); } public int GetVertexAttributeDimension(VertexAttribute attr) { return GetVertexAttributeDimension(m_Ptr, attr); } public VertexAttributeFormat GetVertexAttributeFormat(VertexAttribute attr) { return GetVertexAttributeFormat(m_Ptr, attr); } public int GetVertexAttributeStream(VertexAttribute attr) { return GetVertexAttributeStream(m_Ptr, attr); } public int GetVertexAttributeOffset(VertexAttribute attr) { return GetVertexAttributeOffset(m_Ptr, attr); } public void GetVertices(NativeArray outVertices) { CopyAttributeInto(outVertices, VertexAttribute.Position, VertexAttributeFormat.Float32, 3); } public void GetNormals(NativeArray outNormals) { CopyAttributeInto(outNormals, VertexAttribute.Normal, VertexAttributeFormat.Float32, 3); } public void GetTangents(NativeArray outTangents) { CopyAttributeInto(outTangents, VertexAttribute.Tangent, VertexAttributeFormat.Float32, 4); } public void GetColors(NativeArray outColors) { CopyAttributeInto(outColors, VertexAttribute.Color, VertexAttributeFormat.Float32, 4); } public void GetColors(NativeArray outColors) { CopyAttributeInto(outColors, VertexAttribute.Color, VertexAttributeFormat.UNorm8, 4); } public void GetUVs(int channel, NativeArray outUVs) { if (channel < 0 || channel > 7) { throw new ArgumentOutOfRangeException("channel", channel, "The uv index is invalid. Must be in the range 0 to 7."); } CopyAttributeInto(outUVs, GetUVChannel(channel), VertexAttributeFormat.Float32, 2); } public void GetUVs(int channel, NativeArray outUVs) { if (channel < 0 || channel > 7) { throw new ArgumentOutOfRangeException("channel", channel, "The uv index is invalid. Must be in the range 0 to 7."); } CopyAttributeInto(outUVs, GetUVChannel(channel), VertexAttributeFormat.Float32, 3); } public void GetUVs(int channel, NativeArray outUVs) { if (channel < 0 || channel > 7) { throw new ArgumentOutOfRangeException("channel", channel, "The uv index is invalid. Must be in the range 0 to 7."); } CopyAttributeInto(outUVs, GetUVChannel(channel), VertexAttributeFormat.Float32, 4); } public unsafe NativeArray GetVertexData([UnityEngine.Internal.DefaultValue("0")] int stream = 0) where T : struct { if (stream < 0 || stream >= vertexBufferCount) { throw new ArgumentOutOfRangeException(string.Format("{0} out of bounds, should be below {1} but was {2}", "stream", vertexBufferCount, stream)); } ulong vertexDataSize = GetVertexDataSize(m_Ptr, stream); ulong num = (ulong)UnsafeUtility.SizeOf(); if (vertexDataSize % num != 0) { throw new ArgumentException(string.Format("Type passed to {0} can't capture the vertex buffer. Mesh vertex buffer size is {1} which is not a multiple of type size {2}", "GetVertexData", vertexDataSize, num)); } ulong num2 = vertexDataSize / num; return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)GetVertexDataPtr(m_Ptr, stream), (int)num2, Allocator.None); } private unsafe void CopyAttributeInto(NativeArray buffer, VertexAttribute channel, VertexAttributeFormat format, int dim) where T : struct { if (!HasVertexAttribute(channel)) { throw new InvalidOperationException($"Mesh data does not have {channel} vertex component"); } if (buffer.Length < vertexCount) { throw new InvalidOperationException($"Not enough space in output buffer (need {vertexCount}, has {buffer.Length})"); } CopyAttributeIntoPtr(m_Ptr, channel, format, dim, (IntPtr)buffer.GetUnsafePtr()); } public void SetVertexBufferParams(int vertexCount, params VertexAttributeDescriptor[] attributes) { SetVertexBufferParamsFromArray(m_Ptr, vertexCount, attributes); } public unsafe void SetVertexBufferParams(int vertexCount, NativeArray attributes) { SetVertexBufferParamsFromPtr(m_Ptr, vertexCount, (IntPtr)attributes.GetUnsafeReadOnlyPtr(), attributes.Length); } public void SetIndexBufferParams(int indexCount, IndexFormat format) { SetIndexBufferParamsImpl(m_Ptr, indexCount, format); } public unsafe void GetIndices(NativeArray outIndices, int submesh, [UnityEngine.Internal.DefaultValue("true")] bool applyBaseVertex = true) { if (submesh < 0 || submesh >= subMeshCount) { throw new IndexOutOfRangeException($"Specified submesh ({submesh}) is out of range. Must be greater or equal to 0 and less than subMeshCount ({subMeshCount})."); } int indexCount = GetIndexCount(m_Ptr, submesh); if (outIndices.Length < indexCount) { throw new InvalidOperationException($"Not enough space in output buffer (need {indexCount}, has {outIndices.Length})"); } CopyIndicesIntoPtr(m_Ptr, submesh, applyBaseVertex, 2, (IntPtr)outIndices.GetUnsafePtr()); } public unsafe void GetIndices(NativeArray outIndices, int submesh, [UnityEngine.Internal.DefaultValue("true")] bool applyBaseVertex = true) { if (submesh < 0 || submesh >= subMeshCount) { throw new IndexOutOfRangeException($"Specified submesh ({submesh}) is out of range. Must be greater or equal to 0 and less than subMeshCount ({subMeshCount})."); } int indexCount = GetIndexCount(m_Ptr, submesh); if (outIndices.Length < indexCount) { throw new InvalidOperationException($"Not enough space in output buffer (need {indexCount}, has {outIndices.Length})"); } CopyIndicesIntoPtr(m_Ptr, submesh, applyBaseVertex, 4, (IntPtr)outIndices.GetUnsafePtr()); } public unsafe NativeArray GetIndexData() where T : struct { ulong indexDataSize = GetIndexDataSize(m_Ptr); ulong num = (ulong)UnsafeUtility.SizeOf(); if (indexDataSize % num != 0) { throw new ArgumentException(string.Format("Type passed to {0} can't capture the index buffer. Mesh index buffer size is {1} which is not a multiple of type size {2}", "GetIndexData", indexDataSize, num)); } ulong num2 = indexDataSize / num; return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)GetIndexDataPtr(m_Ptr), (int)num2, Allocator.None); } public SubMeshDescriptor GetSubMesh(int index) { return GetSubMesh(m_Ptr, index); } public void SetSubMesh(int index, SubMeshDescriptor desc, MeshUpdateFlags flags = MeshUpdateFlags.Default) { SetSubMeshImpl(m_Ptr, index, desc, flags); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private void CheckReadAccess() { } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private void CheckWriteAccess() { } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetSubMesh_Injected(IntPtr self, int index, out SubMeshDescriptor ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetSubMeshImpl_Injected(IntPtr self, int index, ref SubMeshDescriptor desc, MeshUpdateFlags flags); } [NativeContainer] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeContainerSupportsMinMaxWriteRestriction] public struct MeshDataArray : IDisposable { [NativeDisableUnsafePtrRestriction] private unsafe IntPtr* m_Ptrs; internal int m_Length; public int Length => m_Length; public unsafe MeshData this[int index] { get { MeshData result = default(MeshData); result.m_Ptr = m_Ptrs[index]; return result; } } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void AcquireReadOnlyMeshData([NotNull("ArgumentNullException")] Mesh mesh, IntPtr* datas); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void AcquireReadOnlyMeshDatas([NotNull("ArgumentNullException")] Mesh[] meshes, IntPtr* datas, int count); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void ReleaseMeshDatas(IntPtr* datas, int count); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void CreateNewMeshDatas(IntPtr* datas, int count); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private unsafe static extern void ApplyToMeshesImpl([NotNull("ArgumentNullException")] Mesh[] meshes, IntPtr* datas, int count, MeshUpdateFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern void ApplyToMeshImpl([NotNull("ArgumentNullException")] Mesh mesh, IntPtr data, MeshUpdateFlags flags); public unsafe void Dispose() { if (m_Length != 0) { ReleaseMeshDatas(m_Ptrs, m_Length); UnsafeUtility.Free(m_Ptrs, Allocator.Persistent); } m_Ptrs = null; m_Length = 0; } internal unsafe void ApplyToMeshAndDispose(Mesh mesh, MeshUpdateFlags flags) { if (!mesh.canAccess) { throw new InvalidOperationException("Not allowed to access vertex data on mesh '" + mesh.name + "' (isReadable is false; Read/Write must be enabled in import settings)"); } ApplyToMeshImpl(mesh, *m_Ptrs, flags); Dispose(); } internal unsafe void ApplyToMeshesAndDispose(Mesh[] meshes, MeshUpdateFlags flags) { for (int i = 0; i < m_Length; i++) { Mesh mesh = meshes[i]; if (mesh == null) { throw new ArgumentNullException("meshes", $"Mesh at index {i} is null"); } if (!mesh.canAccess) { throw new InvalidOperationException($"Not allowed to access vertex data on mesh '{mesh.name}' at array index {i} (isReadable is false; Read/Write must be enabled in import settings)"); } } ApplyToMeshesImpl(meshes, m_Ptrs, m_Length, flags); Dispose(); } internal unsafe MeshDataArray(Mesh mesh, bool checkReadWrite = true) { if (mesh == null) { throw new ArgumentNullException("mesh", "Mesh is null"); } if (checkReadWrite && !mesh.canAccess) { throw new InvalidOperationException("Not allowed to access vertex data on mesh '" + mesh.name + "' (isReadable is false; Read/Write must be enabled in import settings)"); } m_Length = 1; int num = UnsafeUtility.SizeOf(); m_Ptrs = (IntPtr*)UnsafeUtility.Malloc(num, UnsafeUtility.AlignOf(), Allocator.Persistent); AcquireReadOnlyMeshData(mesh, m_Ptrs); } internal unsafe MeshDataArray(Mesh[] meshes, int meshesCount, bool checkReadWrite = true) { if (meshes.Length < meshesCount) { throw new InvalidOperationException($"Meshes array size ({meshes.Length}) is smaller than meshes count ({meshesCount})"); } for (int i = 0; i < meshesCount; i++) { Mesh mesh = meshes[i]; if (mesh == null) { throw new ArgumentNullException("meshes", $"Mesh at index {i} is null"); } if (checkReadWrite && !mesh.canAccess) { throw new InvalidOperationException($"Not allowed to access vertex data on mesh '{mesh.name}' at array index {i} (isReadable is false; Read/Write must be enabled in import settings)"); } } m_Length = meshesCount; int num = UnsafeUtility.SizeOf() * meshesCount; m_Ptrs = (IntPtr*)UnsafeUtility.Malloc(num, UnsafeUtility.AlignOf(), Allocator.Persistent); AcquireReadOnlyMeshDatas(meshes, m_Ptrs, meshesCount); } internal unsafe MeshDataArray(int meshesCount) { if (meshesCount < 0) { throw new InvalidOperationException($"Mesh count can not be negative (was {meshesCount})"); } m_Length = meshesCount; int num = UnsafeUtility.SizeOf() * meshesCount; m_Ptrs = (IntPtr*)UnsafeUtility.Malloc(num, UnsafeUtility.AlignOf(), Allocator.Persistent); CreateNewMeshDatas(m_Ptrs, meshesCount); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private void CheckElementReadAccess(int index) { } } public extern IndexFormat indexFormat { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int vertexBufferCount { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetVertexBufferCount", HasExplicitThis = true)] get; } public extern GraphicsBuffer.Target vertexBufferTarget { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern GraphicsBuffer.Target indexBufferTarget { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int blendShapeCount { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GetBlendShapeChannelCount")] get; } [NativeName("BindPosesFromScript")] public extern Matrix4x4[] bindposes { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool isReadable { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetIsReadable")] get; } internal extern bool canAccess { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("CanAccessFromScript")] get; } public extern int vertexCount { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetVertexCount")] get; } public extern int subMeshCount { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GetSubMeshCount")] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::SetSubMeshCount", HasExplicitThis = true)] set; } public Bounds bounds { get { get_bounds_Injected(out var ret); return ret; } set { set_bounds_Injected(ref value); } } public Vector3[] vertices { get { return GetAllocArrayFromChannel(VertexAttribute.Position); } set { SetArrayForChannel(VertexAttribute.Position, value); } } public Vector3[] normals { get { return GetAllocArrayFromChannel(VertexAttribute.Normal); } set { SetArrayForChannel(VertexAttribute.Normal, value); } } public Vector4[] tangents { get { return GetAllocArrayFromChannel(VertexAttribute.Tangent); } set { SetArrayForChannel(VertexAttribute.Tangent, value); } } public Vector2[] uv { get { return GetAllocArrayFromChannel(VertexAttribute.TexCoord0); } set { SetArrayForChannel(VertexAttribute.TexCoord0, value); } } public Vector2[] uv2 { get { return GetAllocArrayFromChannel(VertexAttribute.TexCoord1); } set { SetArrayForChannel(VertexAttribute.TexCoord1, value); } } public Vector2[] uv3 { get { return GetAllocArrayFromChannel(VertexAttribute.TexCoord2); } set { SetArrayForChannel(VertexAttribute.TexCoord2, value); } } public Vector2[] uv4 { get { return GetAllocArrayFromChannel(VertexAttribute.TexCoord3); } set { SetArrayForChannel(VertexAttribute.TexCoord3, value); } } public Vector2[] uv5 { get { return GetAllocArrayFromChannel(VertexAttribute.TexCoord4); } set { SetArrayForChannel(VertexAttribute.TexCoord4, value); } } public Vector2[] uv6 { get { return GetAllocArrayFromChannel(VertexAttribute.TexCoord5); } set { SetArrayForChannel(VertexAttribute.TexCoord5, value); } } public Vector2[] uv7 { get { return GetAllocArrayFromChannel(VertexAttribute.TexCoord6); } set { SetArrayForChannel(VertexAttribute.TexCoord6, value); } } public Vector2[] uv8 { get { return GetAllocArrayFromChannel(VertexAttribute.TexCoord7); } set { SetArrayForChannel(VertexAttribute.TexCoord7, value); } } public Color[] colors { get { return GetAllocArrayFromChannel(VertexAttribute.Color); } set { SetArrayForChannel(VertexAttribute.Color, value); } } public Color32[] colors32 { get { return GetAllocArrayFromChannel(VertexAttribute.Color, VertexAttributeFormat.UNorm8, 4); } set { SetArrayForChannel(VertexAttribute.Color, VertexAttributeFormat.UNorm8, 4, value); } } public int vertexAttributeCount => GetVertexAttributeCountImpl(); public int[] triangles { get { if (canAccess) { return GetTrianglesImpl(-1, applyBaseVertex: true); } PrintErrorCantAccessIndices(); return new int[0]; } set { if (canAccess) { SetTrianglesImpl(-1, IndexFormat.UInt32, value, NoAllocHelpers.SafeLength(value), 0, NoAllocHelpers.SafeLength(value), calculateBounds: true, 0); } else { PrintErrorCantAccessIndices(); } } } public BoneWeight[] boneWeights { get { return GetBoneWeightsImpl(); } set { SetBoneWeightsImpl(value); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MeshScripting::CreateMesh")] private static extern void Internal_Create([Writable] Mesh mono); [RequiredByNativeCode] public Mesh() { Internal_Create(this); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MeshScripting::MeshFromInstanceId")] internal static extern Mesh FromInstanceID(int id); [MethodImpl(MethodImplOptions.InternalCall)] internal extern uint GetTotalIndexCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::SetIndexBufferParams", HasExplicitThis = true, ThrowsException = true)] public extern void SetIndexBufferParams(int indexCount, IndexFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::InternalSetIndexBufferData", HasExplicitThis = true, ThrowsException = true)] private extern void InternalSetIndexBufferData(IntPtr data, int dataStart, int meshBufferStart, int count, int elemSize, MeshUpdateFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::InternalSetIndexBufferDataFromArray", HasExplicitThis = true, ThrowsException = true)] private extern void InternalSetIndexBufferDataFromArray(Array data, int dataStart, int meshBufferStart, int count, int elemSize, MeshUpdateFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::SetVertexBufferParamsFromPtr", HasExplicitThis = true, ThrowsException = true)] private extern void SetVertexBufferParamsFromPtr(int vertexCount, IntPtr attributesPtr, int attributesCount); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::SetVertexBufferParamsFromArray", HasExplicitThis = true, ThrowsException = true)] private extern void SetVertexBufferParamsFromArray(int vertexCount, [Unmarshalled] params VertexAttributeDescriptor[] attributes); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::InternalSetVertexBufferData", HasExplicitThis = true)] private extern void InternalSetVertexBufferData(int stream, IntPtr data, int dataStart, int meshBufferStart, int count, int elemSize, MeshUpdateFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::InternalSetVertexBufferDataFromArray", HasExplicitThis = true)] private extern void InternalSetVertexBufferDataFromArray(int stream, Array data, int dataStart, int meshBufferStart, int count, int elemSize, MeshUpdateFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetVertexAttributesAlloc", HasExplicitThis = true)] private extern Array GetVertexAttributesAlloc(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetVertexAttributesArray", HasExplicitThis = true)] private extern int GetVertexAttributesArray([Unmarshalled][NotNull("ArgumentNullException")] VertexAttributeDescriptor[] attributes); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetVertexAttributesList", HasExplicitThis = true)] private extern int GetVertexAttributesList([NotNull("ArgumentNullException")] List attributes); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetVertexAttributesCount", HasExplicitThis = true)] private extern int GetVertexAttributeCountImpl(); [FreeFunction(Name = "MeshScripting::GetVertexAttributeByIndex", HasExplicitThis = true, ThrowsException = true)] public VertexAttributeDescriptor GetVertexAttribute(int index) { GetVertexAttribute_Injected(index, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetIndexStart", HasExplicitThis = true)] private extern uint GetIndexStartImpl(int submesh); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetIndexCount", HasExplicitThis = true)] private extern uint GetIndexCountImpl(int submesh); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetTrianglesCount", HasExplicitThis = true)] private extern uint GetTrianglesCountImpl(int submesh); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetBaseVertex", HasExplicitThis = true)] private extern uint GetBaseVertexImpl(int submesh); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetTriangles", HasExplicitThis = true)] private extern int[] GetTrianglesImpl(int submesh, bool applyBaseVertex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetIndices", HasExplicitThis = true)] private extern int[] GetIndicesImpl(int submesh, bool applyBaseVertex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "SetMeshIndicesFromScript", HasExplicitThis = true, ThrowsException = true)] private extern void SetIndicesImpl(int submesh, MeshTopology topology, IndexFormat indicesFormat, Array indices, int arrayStart, int arraySize, bool calculateBounds, int baseVertex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "SetMeshIndicesFromNativeArray", HasExplicitThis = true, ThrowsException = true)] private extern void SetIndicesNativeArrayImpl(int submesh, MeshTopology topology, IndexFormat indicesFormat, IntPtr indices, int arrayStart, int arraySize, bool calculateBounds, int baseVertex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::ExtractTrianglesToArray", HasExplicitThis = true)] private extern void GetTrianglesNonAllocImpl([Out] int[] values, int submesh, bool applyBaseVertex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::ExtractTrianglesToArray16", HasExplicitThis = true)] private extern void GetTrianglesNonAllocImpl16([Out] ushort[] values, int submesh, bool applyBaseVertex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::ExtractIndicesToArray", HasExplicitThis = true)] private extern void GetIndicesNonAllocImpl([Out] int[] values, int submesh, bool applyBaseVertex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::ExtractIndicesToArray16", HasExplicitThis = true)] private extern void GetIndicesNonAllocImpl16([Out] ushort[] values, int submesh, bool applyBaseVertex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::PrintErrorCantAccessChannel", HasExplicitThis = true)] private extern void PrintErrorCantAccessChannel(VertexAttribute ch); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::HasChannel", HasExplicitThis = true)] public extern bool HasVertexAttribute(VertexAttribute attr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetChannelDimension", HasExplicitThis = true)] public extern int GetVertexAttributeDimension(VertexAttribute attr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetChannelFormat", HasExplicitThis = true)] public extern VertexAttributeFormat GetVertexAttributeFormat(VertexAttribute attr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetChannelStream", HasExplicitThis = true)] public extern int GetVertexAttributeStream(VertexAttribute attr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetChannelOffset", HasExplicitThis = true)] public extern int GetVertexAttributeOffset(VertexAttribute attr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "SetMeshComponentFromArrayFromScript", HasExplicitThis = true)] private extern void SetArrayForChannelImpl(VertexAttribute channel, VertexAttributeFormat format, int dim, Array values, int arraySize, int valuesStart, int valuesCount, MeshUpdateFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "SetMeshComponentFromNativeArrayFromScript", HasExplicitThis = true)] private extern void SetNativeArrayForChannelImpl(VertexAttribute channel, VertexAttributeFormat format, int dim, IntPtr values, int arraySize, int valuesStart, int valuesCount, MeshUpdateFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "AllocExtractMeshComponentFromScript", HasExplicitThis = true)] private extern Array GetAllocArrayFromChannelImpl(VertexAttribute channel, VertexAttributeFormat format, int dim); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ExtractMeshComponentFromScript", HasExplicitThis = true)] private extern void GetArrayFromChannelImpl(VertexAttribute channel, VertexAttributeFormat format, int dim, Array values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetVertexBufferStride", HasExplicitThis = true)] public extern int GetVertexBufferStride(int stream); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] [FreeFunction(Name = "MeshScripting::GetNativeVertexBufferPtr", HasExplicitThis = true)] public extern IntPtr GetNativeVertexBufferPtr(int index); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetNativeIndexBufferPtr", HasExplicitThis = true)] public extern IntPtr GetNativeIndexBufferPtr(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetVertexBufferPtr", HasExplicitThis = true, ThrowsException = true)] private extern GraphicsBuffer GetVertexBufferImpl(int index); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetIndexBufferPtr", HasExplicitThis = true, ThrowsException = true)] private extern GraphicsBuffer GetIndexBufferImpl(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::ClearBlendShapes", HasExplicitThis = true)] public extern void ClearBlendShapes(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetBlendShapeName", HasExplicitThis = true, ThrowsException = true)] public extern string GetBlendShapeName(int shapeIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetBlendShapeIndex", HasExplicitThis = true, ThrowsException = true)] public extern int GetBlendShapeIndex(string blendShapeName); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetBlendShapeFrameCount", HasExplicitThis = true, ThrowsException = true)] public extern int GetBlendShapeFrameCount(int shapeIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetBlendShapeFrameWeight", HasExplicitThis = true, ThrowsException = true)] public extern float GetBlendShapeFrameWeight(int shapeIndex, int frameIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetBlendShapeFrameVerticesFromScript", HasExplicitThis = true, ThrowsException = true)] public extern void GetBlendShapeFrameVertices(int shapeIndex, int frameIndex, [Unmarshalled] Vector3[] deltaVertices, [Unmarshalled] Vector3[] deltaNormals, [Unmarshalled] Vector3[] deltaTangents); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "AddBlendShapeFrameFromScript", HasExplicitThis = true, ThrowsException = true)] public extern void AddBlendShapeFrame(string shapeName, float frameWeight, [Unmarshalled] Vector3[] deltaVertices, [Unmarshalled] Vector3[] deltaNormals, [Unmarshalled] Vector3[] deltaTangents); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("HasBoneWeights")] private extern bool HasBoneWeights(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetBoneWeights", HasExplicitThis = true)] private extern BoneWeight[] GetBoneWeightsImpl(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::SetBoneWeights", HasExplicitThis = true)] private extern void SetBoneWeightsImpl(BoneWeight[] weights); public unsafe void SetBoneWeights(NativeArray bonesPerVertex, NativeArray weights) { InternalSetBoneWeights((IntPtr)bonesPerVertex.GetUnsafeReadOnlyPtr(), bonesPerVertex.Length, (IntPtr)weights.GetUnsafeReadOnlyPtr(), weights.Length); } [MethodImpl(MethodImplOptions.InternalCall)] [SecurityCritical] [FreeFunction(Name = "MeshScripting::SetBoneWeights", HasExplicitThis = true)] private extern void InternalSetBoneWeights(IntPtr bonesPerVertex, int bonesPerVertexSize, IntPtr weights, int weightsSize); public unsafe NativeArray GetAllBoneWeights() { return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)GetAllBoneWeightsArray(), GetAllBoneWeightsArraySize(), Allocator.None); } public unsafe NativeArray GetBonesPerVertex() { int length = (HasBoneWeights() ? vertexCount : 0); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)GetBonesPerVertexArray(), length, Allocator.None); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetAllBoneWeightsArraySize", HasExplicitThis = true)] private extern int GetAllBoneWeightsArraySize(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetAllBoneWeightsArray", HasExplicitThis = true)] [SecurityCritical] private extern IntPtr GetAllBoneWeightsArray(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetBonesPerVertexArray", HasExplicitThis = true)] [SecurityCritical] private extern IntPtr GetBonesPerVertexArray(); [MethodImpl(MethodImplOptions.InternalCall)] private extern int GetBindposeCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::ExtractBoneWeightsIntoArray", HasExplicitThis = true)] private extern void GetBoneWeightsNonAllocImpl([Out] BoneWeight[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::ExtractBindPosesIntoArray", HasExplicitThis = true)] private extern void GetBindposesNonAllocImpl([Out] Matrix4x4[] values); [FreeFunction("MeshScripting::SetSubMesh", HasExplicitThis = true, ThrowsException = true)] public void SetSubMesh(int index, SubMeshDescriptor desc, MeshUpdateFlags flags = MeshUpdateFlags.Default) { SetSubMesh_Injected(index, ref desc, flags); } [FreeFunction("MeshScripting::GetSubMesh", HasExplicitThis = true, ThrowsException = true)] public SubMeshDescriptor GetSubMesh(int index) { GetSubMesh_Injected(index, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MeshScripting::SetAllSubMeshesAtOnceFromArray", HasExplicitThis = true, ThrowsException = true)] private extern void SetAllSubMeshesAtOnceFromArray(SubMeshDescriptor[] desc, int start, int count, MeshUpdateFlags flags = MeshUpdateFlags.Default); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MeshScripting::SetAllSubMeshesAtOnceFromNativeArray", HasExplicitThis = true, ThrowsException = true)] private extern void SetAllSubMeshesAtOnceFromNativeArray(IntPtr desc, int start, int count, MeshUpdateFlags flags = MeshUpdateFlags.Default); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("Clear")] private extern void ClearImpl(bool keepVertexLayout); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("RecalculateBounds")] private extern void RecalculateBoundsImpl(MeshUpdateFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("RecalculateNormals")] private extern void RecalculateNormalsImpl(MeshUpdateFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("RecalculateTangents")] private extern void RecalculateTangentsImpl(MeshUpdateFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("MarkDynamic")] private extern void MarkDynamicImpl(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("MarkModified")] public extern void MarkModified(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("UploadMeshData")] private extern void UploadMeshDataImpl(bool markNoLongerReadable); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MeshScripting::GetPrimitiveType", HasExplicitThis = true)] private extern MeshTopology GetTopologyImpl(int submesh); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("RecalculateMeshMetric")] private extern void RecalculateUVDistributionMetricImpl(int uvSetIndex, float uvAreaThreshold); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("RecalculateMeshMetrics")] private extern void RecalculateUVDistributionMetricsImpl(float uvAreaThreshold); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetMeshMetric")] public extern float GetUVDistributionMetric(int uvSetIndex); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "MeshScripting::CombineMeshes", IsFreeFunction = true, ThrowsException = true, HasExplicitThis = true)] private extern void CombineMeshesImpl(CombineInstance[] combine, bool mergeSubMeshes, bool useMatrices, bool hasLightmapData); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("Optimize")] private extern void OptimizeImpl(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("OptimizeIndexBuffers")] private extern void OptimizeIndexBuffersImpl(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("OptimizeReorderVertexBuffer")] private extern void OptimizeReorderVertexBufferImpl(); internal static VertexAttribute GetUVChannel(int uvIndex) { if (uvIndex < 0 || uvIndex > 7) { throw new ArgumentException("GetUVChannel called for bad uvIndex", "uvIndex"); } return (VertexAttribute)(4 + uvIndex); } internal static int DefaultDimensionForChannel(VertexAttribute channel) { if (channel == VertexAttribute.Position || channel == VertexAttribute.Normal) { return 3; } if (channel >= VertexAttribute.TexCoord0 && channel <= VertexAttribute.TexCoord7) { return 2; } if (channel == VertexAttribute.Tangent || channel == VertexAttribute.Color) { return 4; } throw new ArgumentException("DefaultDimensionForChannel called for bad channel", "channel"); } private T[] GetAllocArrayFromChannel(VertexAttribute channel, VertexAttributeFormat format, int dim) { if (canAccess) { if (HasVertexAttribute(channel)) { return (T[])GetAllocArrayFromChannelImpl(channel, format, dim); } } else { PrintErrorCantAccessChannel(channel); } return new T[0]; } private T[] GetAllocArrayFromChannel(VertexAttribute channel) { return GetAllocArrayFromChannel(channel, VertexAttributeFormat.Float32, DefaultDimensionForChannel(channel)); } private void SetSizedArrayForChannel(VertexAttribute channel, VertexAttributeFormat format, int dim, Array values, int valuesArrayLength, int valuesStart, int valuesCount, MeshUpdateFlags flags) { if (canAccess) { if (valuesStart < 0) { throw new ArgumentOutOfRangeException("valuesStart", valuesStart, "Mesh data array start index can't be negative."); } if (valuesCount < 0) { throw new ArgumentOutOfRangeException("valuesCount", valuesCount, "Mesh data array length can't be negative."); } if (valuesStart >= valuesArrayLength && valuesCount != 0) { throw new ArgumentOutOfRangeException("valuesStart", valuesStart, "Mesh data array start is outside of array size."); } if (valuesStart + valuesCount > valuesArrayLength) { throw new ArgumentOutOfRangeException("valuesCount", valuesStart + valuesCount, "Mesh data array start+count is outside of array size."); } if (values == null) { valuesStart = 0; } SetArrayForChannelImpl(channel, format, dim, values, valuesArrayLength, valuesStart, valuesCount, flags); } else { PrintErrorCantAccessChannel(channel); } } private void SetSizedNativeArrayForChannel(VertexAttribute channel, VertexAttributeFormat format, int dim, IntPtr values, int valuesArrayLength, int valuesStart, int valuesCount, MeshUpdateFlags flags) { if (canAccess) { if (valuesStart < 0) { throw new ArgumentOutOfRangeException("valuesStart", valuesStart, "Mesh data array start index can't be negative."); } if (valuesCount < 0) { throw new ArgumentOutOfRangeException("valuesCount", valuesCount, "Mesh data array length can't be negative."); } if (valuesStart >= valuesArrayLength && valuesCount != 0) { throw new ArgumentOutOfRangeException("valuesStart", valuesStart, "Mesh data array start is outside of array size."); } if (valuesStart + valuesCount > valuesArrayLength) { throw new ArgumentOutOfRangeException("valuesCount", valuesStart + valuesCount, "Mesh data array start+count is outside of array size."); } SetNativeArrayForChannelImpl(channel, format, dim, values, valuesArrayLength, valuesStart, valuesCount, flags); } else { PrintErrorCantAccessChannel(channel); } } private void SetArrayForChannel(VertexAttribute channel, VertexAttributeFormat format, int dim, T[] values, MeshUpdateFlags flags = MeshUpdateFlags.Default) { int num = NoAllocHelpers.SafeLength(values); SetSizedArrayForChannel(channel, format, dim, values, num, 0, num, flags); } private void SetArrayForChannel(VertexAttribute channel, T[] values, MeshUpdateFlags flags = MeshUpdateFlags.Default) { int num = NoAllocHelpers.SafeLength(values); SetSizedArrayForChannel(channel, VertexAttributeFormat.Float32, DefaultDimensionForChannel(channel), values, num, 0, num, flags); } private void SetListForChannel(VertexAttribute channel, VertexAttributeFormat format, int dim, List values, int start, int length, MeshUpdateFlags flags) { SetSizedArrayForChannel(channel, format, dim, NoAllocHelpers.ExtractArrayFromList(values), NoAllocHelpers.SafeLength(values), start, length, flags); } private void SetListForChannel(VertexAttribute channel, List values, int start, int length, MeshUpdateFlags flags) { SetSizedArrayForChannel(channel, VertexAttributeFormat.Float32, DefaultDimensionForChannel(channel), NoAllocHelpers.ExtractArrayFromList(values), NoAllocHelpers.SafeLength(values), start, length, flags); } private void GetListForChannel(List buffer, int capacity, VertexAttribute channel, int dim) { GetListForChannel(buffer, capacity, channel, dim, VertexAttributeFormat.Float32); } private void GetListForChannel(List buffer, int capacity, VertexAttribute channel, int dim, VertexAttributeFormat channelType) { buffer.Clear(); if (!canAccess) { PrintErrorCantAccessChannel(channel); } else if (HasVertexAttribute(channel)) { NoAllocHelpers.EnsureListElemCount(buffer, capacity); GetArrayFromChannelImpl(channel, channelType, dim, NoAllocHelpers.ExtractArrayFromList(buffer)); } } public void GetVertices(List vertices) { if (vertices == null) { throw new ArgumentNullException("vertices", "The result vertices list cannot be null."); } GetListForChannel(vertices, vertexCount, VertexAttribute.Position, DefaultDimensionForChannel(VertexAttribute.Position)); } public void SetVertices(List inVertices) { SetVertices(inVertices, 0, NoAllocHelpers.SafeLength(inVertices)); } [ExcludeFromDocs] public void SetVertices(List inVertices, int start, int length) { SetVertices(inVertices, start, length, MeshUpdateFlags.Default); } public void SetVertices(List inVertices, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetListForChannel(VertexAttribute.Position, inVertices, start, length, flags); } public void SetVertices(Vector3[] inVertices) { SetVertices(inVertices, 0, NoAllocHelpers.SafeLength(inVertices)); } [ExcludeFromDocs] public void SetVertices(Vector3[] inVertices, int start, int length) { SetVertices(inVertices, start, length, MeshUpdateFlags.Default); } public void SetVertices(Vector3[] inVertices, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetSizedArrayForChannel(VertexAttribute.Position, VertexAttributeFormat.Float32, DefaultDimensionForChannel(VertexAttribute.Position), inVertices, NoAllocHelpers.SafeLength(inVertices), start, length, flags); } public void SetVertices(NativeArray inVertices) where T : struct { SetVertices(inVertices, 0, inVertices.Length); } [ExcludeFromDocs] public void SetVertices(NativeArray inVertices, int start, int length) where T : struct { SetVertices(inVertices, start, length, MeshUpdateFlags.Default); } public unsafe void SetVertices(NativeArray inVertices, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) where T : struct { if (UnsafeUtility.SizeOf() != 12) { throw new ArgumentException("SetVertices with NativeArray should use struct type that is 12 bytes (3x float) in size"); } SetSizedNativeArrayForChannel(VertexAttribute.Position, VertexAttributeFormat.Float32, 3, (IntPtr)inVertices.GetUnsafeReadOnlyPtr(), inVertices.Length, start, length, flags); } public void GetNormals(List normals) { if (normals == null) { throw new ArgumentNullException("normals", "The result normals list cannot be null."); } GetListForChannel(normals, vertexCount, VertexAttribute.Normal, DefaultDimensionForChannel(VertexAttribute.Normal)); } public void SetNormals(List inNormals) { SetNormals(inNormals, 0, NoAllocHelpers.SafeLength(inNormals)); } [ExcludeFromDocs] public void SetNormals(List inNormals, int start, int length) { SetNormals(inNormals, start, length, MeshUpdateFlags.Default); } public void SetNormals(List inNormals, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetListForChannel(VertexAttribute.Normal, inNormals, start, length, flags); } public void SetNormals(Vector3[] inNormals) { SetNormals(inNormals, 0, NoAllocHelpers.SafeLength(inNormals)); } [ExcludeFromDocs] public void SetNormals(Vector3[] inNormals, int start, int length) { SetNormals(inNormals, start, length, MeshUpdateFlags.Default); } public void SetNormals(Vector3[] inNormals, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetSizedArrayForChannel(VertexAttribute.Normal, VertexAttributeFormat.Float32, DefaultDimensionForChannel(VertexAttribute.Normal), inNormals, NoAllocHelpers.SafeLength(inNormals), start, length, flags); } public void SetNormals(NativeArray inNormals) where T : struct { SetNormals(inNormals, 0, inNormals.Length); } [ExcludeFromDocs] public void SetNormals(NativeArray inNormals, int start, int length) where T : struct { SetNormals(inNormals, start, length, MeshUpdateFlags.Default); } public unsafe void SetNormals(NativeArray inNormals, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) where T : struct { if (UnsafeUtility.SizeOf() != 12) { throw new ArgumentException("SetNormals with NativeArray should use struct type that is 12 bytes (3x float) in size"); } SetSizedNativeArrayForChannel(VertexAttribute.Normal, VertexAttributeFormat.Float32, 3, (IntPtr)inNormals.GetUnsafeReadOnlyPtr(), inNormals.Length, start, length, flags); } public void GetTangents(List tangents) { if (tangents == null) { throw new ArgumentNullException("tangents", "The result tangents list cannot be null."); } GetListForChannel(tangents, vertexCount, VertexAttribute.Tangent, DefaultDimensionForChannel(VertexAttribute.Tangent)); } public void SetTangents(List inTangents) { SetTangents(inTangents, 0, NoAllocHelpers.SafeLength(inTangents)); } [ExcludeFromDocs] public void SetTangents(List inTangents, int start, int length) { SetTangents(inTangents, start, length, MeshUpdateFlags.Default); } public void SetTangents(List inTangents, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetListForChannel(VertexAttribute.Tangent, inTangents, start, length, flags); } public void SetTangents(Vector4[] inTangents) { SetTangents(inTangents, 0, NoAllocHelpers.SafeLength(inTangents)); } [ExcludeFromDocs] public void SetTangents(Vector4[] inTangents, int start, int length) { SetTangents(inTangents, start, length, MeshUpdateFlags.Default); } public void SetTangents(Vector4[] inTangents, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetSizedArrayForChannel(VertexAttribute.Tangent, VertexAttributeFormat.Float32, DefaultDimensionForChannel(VertexAttribute.Tangent), inTangents, NoAllocHelpers.SafeLength(inTangents), start, length, flags); } public void SetTangents(NativeArray inTangents) where T : struct { SetTangents(inTangents, 0, inTangents.Length); } [ExcludeFromDocs] public void SetTangents(NativeArray inTangents, int start, int length) where T : struct { SetTangents(inTangents, start, length, MeshUpdateFlags.Default); } public unsafe void SetTangents(NativeArray inTangents, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) where T : struct { if (UnsafeUtility.SizeOf() != 16) { throw new ArgumentException("SetTangents with NativeArray should use struct type that is 16 bytes (4x float) in size"); } SetSizedNativeArrayForChannel(VertexAttribute.Tangent, VertexAttributeFormat.Float32, 4, (IntPtr)inTangents.GetUnsafeReadOnlyPtr(), inTangents.Length, start, length, flags); } public void GetColors(List colors) { if (colors == null) { throw new ArgumentNullException("colors", "The result colors list cannot be null."); } GetListForChannel(colors, vertexCount, VertexAttribute.Color, DefaultDimensionForChannel(VertexAttribute.Color)); } public void SetColors(List inColors) { SetColors(inColors, 0, NoAllocHelpers.SafeLength(inColors)); } [ExcludeFromDocs] public void SetColors(List inColors, int start, int length) { SetColors(inColors, start, length, MeshUpdateFlags.Default); } public void SetColors(List inColors, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetListForChannel(VertexAttribute.Color, inColors, start, length, flags); } public void SetColors(Color[] inColors) { SetColors(inColors, 0, NoAllocHelpers.SafeLength(inColors)); } [ExcludeFromDocs] public void SetColors(Color[] inColors, int start, int length) { SetColors(inColors, start, length, MeshUpdateFlags.Default); } public void SetColors(Color[] inColors, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetSizedArrayForChannel(VertexAttribute.Color, VertexAttributeFormat.Float32, DefaultDimensionForChannel(VertexAttribute.Color), inColors, NoAllocHelpers.SafeLength(inColors), start, length, flags); } public void GetColors(List colors) { if (colors == null) { throw new ArgumentNullException("colors", "The result colors list cannot be null."); } GetListForChannel(colors, vertexCount, VertexAttribute.Color, 4, VertexAttributeFormat.UNorm8); } public void SetColors(List inColors) { SetColors(inColors, 0, NoAllocHelpers.SafeLength(inColors)); } [ExcludeFromDocs] public void SetColors(List inColors, int start, int length) { SetColors(inColors, start, length, MeshUpdateFlags.Default); } public void SetColors(List inColors, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetListForChannel(VertexAttribute.Color, VertexAttributeFormat.UNorm8, 4, inColors, start, length, flags); } public void SetColors(Color32[] inColors) { SetColors(inColors, 0, NoAllocHelpers.SafeLength(inColors)); } [ExcludeFromDocs] public void SetColors(Color32[] inColors, int start, int length) { SetColors(inColors, start, length, MeshUpdateFlags.Default); } public void SetColors(Color32[] inColors, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetSizedArrayForChannel(VertexAttribute.Color, VertexAttributeFormat.UNorm8, 4, inColors, NoAllocHelpers.SafeLength(inColors), start, length, flags); } public void SetColors(NativeArray inColors) where T : struct { SetColors(inColors, 0, inColors.Length); } [ExcludeFromDocs] public void SetColors(NativeArray inColors, int start, int length) where T : struct { SetColors(inColors, start, length, MeshUpdateFlags.Default); } public unsafe void SetColors(NativeArray inColors, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) where T : struct { int num = UnsafeUtility.SizeOf(); if (num != 16 && num != 4) { throw new ArgumentException("SetColors with NativeArray should use struct type that is 16 bytes (4x float) or 4 bytes (4x unorm) in size"); } SetSizedNativeArrayForChannel(VertexAttribute.Color, (num == 4) ? VertexAttributeFormat.UNorm8 : VertexAttributeFormat.Float32, 4, (IntPtr)inColors.GetUnsafeReadOnlyPtr(), inColors.Length, start, length, flags); } private void SetUvsImpl(int uvIndex, int dim, List uvs, int start, int length, MeshUpdateFlags flags) { if (uvIndex < 0 || uvIndex > 7) { Debug.LogError("The uv index is invalid. Must be in the range 0 to 7."); } else { SetListForChannel(GetUVChannel(uvIndex), VertexAttributeFormat.Float32, dim, uvs, start, length, flags); } } public void SetUVs(int channel, List uvs) { SetUVs(channel, uvs, 0, NoAllocHelpers.SafeLength(uvs)); } public void SetUVs(int channel, List uvs) { SetUVs(channel, uvs, 0, NoAllocHelpers.SafeLength(uvs)); } public void SetUVs(int channel, List uvs) { SetUVs(channel, uvs, 0, NoAllocHelpers.SafeLength(uvs)); } [ExcludeFromDocs] public void SetUVs(int channel, List uvs, int start, int length) { SetUVs(channel, uvs, start, length, MeshUpdateFlags.Default); } public void SetUVs(int channel, List uvs, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetUvsImpl(channel, 2, uvs, start, length, flags); } [ExcludeFromDocs] public void SetUVs(int channel, List uvs, int start, int length) { SetUVs(channel, uvs, start, length, MeshUpdateFlags.Default); } public void SetUVs(int channel, List uvs, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetUvsImpl(channel, 3, uvs, start, length, flags); } [ExcludeFromDocs] public void SetUVs(int channel, List uvs, int start, int length) { SetUVs(channel, uvs, start, length, MeshUpdateFlags.Default); } public void SetUVs(int channel, List uvs, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetUvsImpl(channel, 4, uvs, start, length, flags); } private void SetUvsImpl(int uvIndex, int dim, Array uvs, int arrayStart, int arraySize, MeshUpdateFlags flags) { if (uvIndex < 0 || uvIndex > 7) { throw new ArgumentOutOfRangeException("uvIndex", uvIndex, "The uv index is invalid. Must be in the range 0 to 7."); } SetSizedArrayForChannel(GetUVChannel(uvIndex), VertexAttributeFormat.Float32, dim, uvs, NoAllocHelpers.SafeLength(uvs), arrayStart, arraySize, flags); } public void SetUVs(int channel, Vector2[] uvs) { SetUVs(channel, uvs, 0, NoAllocHelpers.SafeLength(uvs)); } public void SetUVs(int channel, Vector3[] uvs) { SetUVs(channel, uvs, 0, NoAllocHelpers.SafeLength(uvs)); } public void SetUVs(int channel, Vector4[] uvs) { SetUVs(channel, uvs, 0, NoAllocHelpers.SafeLength(uvs)); } [ExcludeFromDocs] public void SetUVs(int channel, Vector2[] uvs, int start, int length) { SetUVs(channel, uvs, start, length, MeshUpdateFlags.Default); } public void SetUVs(int channel, Vector2[] uvs, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetUvsImpl(channel, 2, uvs, start, length, flags); } [ExcludeFromDocs] public void SetUVs(int channel, Vector3[] uvs, int start, int length) { SetUVs(channel, uvs, start, length, MeshUpdateFlags.Default); } public void SetUVs(int channel, Vector3[] uvs, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetUvsImpl(channel, 3, uvs, start, length, flags); } [ExcludeFromDocs] public void SetUVs(int channel, Vector4[] uvs, int start, int length) { SetUVs(channel, uvs, start, length, MeshUpdateFlags.Default); } public void SetUVs(int channel, Vector4[] uvs, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { SetUvsImpl(channel, 4, uvs, start, length, flags); } public void SetUVs(int channel, NativeArray uvs) where T : struct { SetUVs(channel, uvs, 0, uvs.Length); } [ExcludeFromDocs] public void SetUVs(int channel, NativeArray uvs, int start, int length) where T : struct { SetUVs(channel, uvs, start, length, MeshUpdateFlags.Default); } public unsafe void SetUVs(int channel, NativeArray uvs, int start, int length, [UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) where T : struct { if (channel < 0 || channel > 7) { throw new ArgumentOutOfRangeException("channel", channel, "The uv index is invalid. Must be in the range 0 to 7."); } int num = UnsafeUtility.SizeOf(); if ((num & 3) != 0) { throw new ArgumentException("SetUVs with NativeArray should use struct type that is multiple of 4 bytes in size"); } int num2 = num / 4; if (num2 < 1 || num2 > 4) { throw new ArgumentException("SetUVs with NativeArray should use struct type that is 1..4 floats in size"); } SetSizedNativeArrayForChannel(GetUVChannel(channel), VertexAttributeFormat.Float32, num2, (IntPtr)uvs.GetUnsafeReadOnlyPtr(), uvs.Length, start, length, flags); } private void GetUVsImpl(int uvIndex, List uvs, int dim) { if (uvs == null) { throw new ArgumentNullException("uvs", "The result uvs list cannot be null."); } if (uvIndex < 0 || uvIndex > 7) { throw new IndexOutOfRangeException("The uv index is invalid. Must be in the range 0 to 7."); } GetListForChannel(uvs, vertexCount, GetUVChannel(uvIndex), dim); } public void GetUVs(int channel, List uvs) { GetUVsImpl(channel, uvs, 2); } public void GetUVs(int channel, List uvs) { GetUVsImpl(channel, uvs, 3); } public void GetUVs(int channel, List uvs) { GetUVsImpl(channel, uvs, 4); } public VertexAttributeDescriptor[] GetVertexAttributes() { return (VertexAttributeDescriptor[])GetVertexAttributesAlloc(); } public int GetVertexAttributes(VertexAttributeDescriptor[] attributes) { return GetVertexAttributesArray(attributes); } public int GetVertexAttributes(List attributes) { return GetVertexAttributesList(attributes); } public void SetVertexBufferParams(int vertexCount, params VertexAttributeDescriptor[] attributes) { SetVertexBufferParamsFromArray(vertexCount, attributes); } public unsafe void SetVertexBufferParams(int vertexCount, NativeArray attributes) { SetVertexBufferParamsFromPtr(vertexCount, (IntPtr)attributes.GetUnsafeReadOnlyPtr(), attributes.Length); } public unsafe void SetVertexBufferData(NativeArray data, int dataStart, int meshBufferStart, int count, int stream = 0, MeshUpdateFlags flags = MeshUpdateFlags.Default) where T : struct { if (!canAccess) { throw new InvalidOperationException("Not allowed to access vertex data on mesh '" + base.name + "' (isReadable is false; Read/Write must be enabled in import settings)"); } if (dataStart < 0 || meshBufferStart < 0 || count < 0 || dataStart + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (dataStart:{dataStart} meshBufferStart:{meshBufferStart} count:{count})"); } InternalSetVertexBufferData(stream, (IntPtr)data.GetUnsafeReadOnlyPtr(), dataStart, meshBufferStart, count, UnsafeUtility.SizeOf(), flags); } public void SetVertexBufferData(T[] data, int dataStart, int meshBufferStart, int count, int stream = 0, MeshUpdateFlags flags = MeshUpdateFlags.Default) where T : struct { if (!canAccess) { throw new InvalidOperationException("Not allowed to access vertex data on mesh '" + base.name + "' (isReadable is false; Read/Write must be enabled in import settings)"); } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException("Array passed to SetVertexBufferData must be blittable.\n" + UnsafeUtility.GetReasonForArrayNonBlittable(data)); } if (dataStart < 0 || meshBufferStart < 0 || count < 0 || dataStart + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (dataStart:{dataStart} meshBufferStart:{meshBufferStart} count:{count})"); } InternalSetVertexBufferDataFromArray(stream, data, dataStart, meshBufferStart, count, UnsafeUtility.SizeOf(), flags); } public void SetVertexBufferData(List data, int dataStart, int meshBufferStart, int count, int stream = 0, MeshUpdateFlags flags = MeshUpdateFlags.Default) where T : struct { if (!canAccess) { throw new InvalidOperationException("Not allowed to access vertex data on mesh '" + base.name + "' (isReadable is false; Read/Write must be enabled in import settings)"); } if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException(string.Format("List<{0}> passed to {1} must be blittable.\n{2}", typeof(T), "SetVertexBufferData", UnsafeUtility.GetReasonForGenericListNonBlittable())); } if (dataStart < 0 || meshBufferStart < 0 || count < 0 || dataStart + count > data.Count) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (dataStart:{dataStart} meshBufferStart:{meshBufferStart} count:{count})"); } InternalSetVertexBufferDataFromArray(stream, NoAllocHelpers.ExtractArrayFromList(data), dataStart, meshBufferStart, count, UnsafeUtility.SizeOf(), flags); } public static MeshDataArray AcquireReadOnlyMeshData(Mesh mesh) { return new MeshDataArray(mesh); } public static MeshDataArray AcquireReadOnlyMeshData(Mesh[] meshes) { if (meshes == null) { throw new ArgumentNullException("meshes", "Mesh array is null"); } return new MeshDataArray(meshes, meshes.Length); } public static MeshDataArray AcquireReadOnlyMeshData(List meshes) { if (meshes == null) { throw new ArgumentNullException("meshes", "Mesh list is null"); } return new MeshDataArray(NoAllocHelpers.ExtractArrayFromListT(meshes), meshes.Count); } public static MeshDataArray AllocateWritableMeshData(int meshCount) { return new MeshDataArray(meshCount); } public static void ApplyAndDisposeWritableMeshData(MeshDataArray data, Mesh mesh, MeshUpdateFlags flags = MeshUpdateFlags.Default) { if (mesh == null) { throw new ArgumentNullException("mesh", "Mesh is null"); } if (data.Length != 1) { throw new InvalidOperationException(string.Format("{0} length must be 1 to apply to one mesh, was {1}", "MeshDataArray", data.Length)); } data.ApplyToMeshAndDispose(mesh, flags); } public static void ApplyAndDisposeWritableMeshData(MeshDataArray data, Mesh[] meshes, MeshUpdateFlags flags = MeshUpdateFlags.Default) { if (meshes == null) { throw new ArgumentNullException("meshes", "Mesh array is null"); } if (data.Length != meshes.Length) { throw new InvalidOperationException(string.Format("{0} length ({1}) must match destination meshes array length ({2})", "MeshDataArray", data.Length, meshes.Length)); } data.ApplyToMeshesAndDispose(meshes, flags); } public static void ApplyAndDisposeWritableMeshData(MeshDataArray data, List meshes, MeshUpdateFlags flags = MeshUpdateFlags.Default) { if (meshes == null) { throw new ArgumentNullException("meshes", "Mesh list is null"); } if (data.Length != meshes.Count) { throw new InvalidOperationException(string.Format("{0} length ({1}) must match destination meshes list length ({2})", "MeshDataArray", data.Length, meshes.Count)); } data.ApplyToMeshesAndDispose(NoAllocHelpers.ExtractArrayFromListT(meshes), flags); } public GraphicsBuffer GetVertexBuffer(int index) { if (this == null) { throw new NullReferenceException(); } return GetVertexBufferImpl(index); } public GraphicsBuffer GetIndexBuffer() { if (this == null) { throw new NullReferenceException(); } return GetIndexBufferImpl(); } private void PrintErrorCantAccessIndices() { Debug.LogError($"Not allowed to access triangles/indices on mesh '{base.name}' (isReadable is false; Read/Write must be enabled in import settings)"); } private bool CheckCanAccessSubmesh(int submesh, bool errorAboutTriangles) { if (!canAccess) { PrintErrorCantAccessIndices(); return false; } if (submesh < 0 || submesh >= subMeshCount) { Debug.LogError(string.Format("Failed getting {0}. Submesh index is out of bounds.", errorAboutTriangles ? "triangles" : "indices"), this); return false; } return true; } private bool CheckCanAccessSubmeshTriangles(int submesh) { return CheckCanAccessSubmesh(submesh, errorAboutTriangles: true); } private bool CheckCanAccessSubmeshIndices(int submesh) { return CheckCanAccessSubmesh(submesh, errorAboutTriangles: false); } public int[] GetTriangles(int submesh) { return GetTriangles(submesh, applyBaseVertex: true); } public int[] GetTriangles(int submesh, [UnityEngine.Internal.DefaultValue("true")] bool applyBaseVertex) { return CheckCanAccessSubmeshTriangles(submesh) ? GetTrianglesImpl(submesh, applyBaseVertex) : new int[0]; } public void GetTriangles(List triangles, int submesh) { GetTriangles(triangles, submesh, applyBaseVertex: true); } public void GetTriangles(List triangles, int submesh, [UnityEngine.Internal.DefaultValue("true")] bool applyBaseVertex) { if (triangles == null) { throw new ArgumentNullException("triangles", "The result triangles list cannot be null."); } if (submesh < 0 || submesh >= subMeshCount) { throw new IndexOutOfRangeException("Specified sub mesh is out of range. Must be greater or equal to 0 and less than subMeshCount."); } NoAllocHelpers.EnsureListElemCount(triangles, (int)(3 * GetTrianglesCountImpl(submesh))); GetTrianglesNonAllocImpl(NoAllocHelpers.ExtractArrayFromListT(triangles), submesh, applyBaseVertex); } public void GetTriangles(List triangles, int submesh, bool applyBaseVertex = true) { if (triangles == null) { throw new ArgumentNullException("triangles", "The result triangles list cannot be null."); } if (submesh < 0 || submesh >= subMeshCount) { throw new IndexOutOfRangeException("Specified sub mesh is out of range. Must be greater or equal to 0 and less than subMeshCount."); } NoAllocHelpers.EnsureListElemCount(triangles, (int)(3 * GetTrianglesCountImpl(submesh))); GetTrianglesNonAllocImpl16(NoAllocHelpers.ExtractArrayFromListT(triangles), submesh, applyBaseVertex); } [ExcludeFromDocs] public int[] GetIndices(int submesh) { return GetIndices(submesh, applyBaseVertex: true); } public int[] GetIndices(int submesh, [UnityEngine.Internal.DefaultValue("true")] bool applyBaseVertex) { return CheckCanAccessSubmeshIndices(submesh) ? GetIndicesImpl(submesh, applyBaseVertex) : new int[0]; } [ExcludeFromDocs] public void GetIndices(List indices, int submesh) { GetIndices(indices, submesh, applyBaseVertex: true); } public void GetIndices(List indices, int submesh, [UnityEngine.Internal.DefaultValue("true")] bool applyBaseVertex) { if (indices == null) { throw new ArgumentNullException("indices", "The result indices list cannot be null."); } if (submesh < 0 || submesh >= subMeshCount) { throw new IndexOutOfRangeException("Specified sub mesh is out of range. Must be greater or equal to 0 and less than subMeshCount."); } NoAllocHelpers.EnsureListElemCount(indices, (int)GetIndexCount(submesh)); GetIndicesNonAllocImpl(NoAllocHelpers.ExtractArrayFromListT(indices), submesh, applyBaseVertex); } public void GetIndices(List indices, int submesh, bool applyBaseVertex = true) { if (indices == null) { throw new ArgumentNullException("indices", "The result indices list cannot be null."); } if (submesh < 0 || submesh >= subMeshCount) { throw new IndexOutOfRangeException("Specified sub mesh is out of range. Must be greater or equal to 0 and less than subMeshCount."); } NoAllocHelpers.EnsureListElemCount(indices, (int)GetIndexCount(submesh)); GetIndicesNonAllocImpl16(NoAllocHelpers.ExtractArrayFromListT(indices), submesh, applyBaseVertex); } public unsafe void SetIndexBufferData(NativeArray data, int dataStart, int meshBufferStart, int count, MeshUpdateFlags flags = MeshUpdateFlags.Default) where T : struct { if (!canAccess) { PrintErrorCantAccessIndices(); return; } if (dataStart < 0 || meshBufferStart < 0 || count < 0 || dataStart + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (dataStart:{dataStart} meshBufferStart:{meshBufferStart} count:{count})"); } InternalSetIndexBufferData((IntPtr)data.GetUnsafeReadOnlyPtr(), dataStart, meshBufferStart, count, UnsafeUtility.SizeOf(), flags); } public void SetIndexBufferData(T[] data, int dataStart, int meshBufferStart, int count, MeshUpdateFlags flags = MeshUpdateFlags.Default) where T : struct { if (!canAccess) { PrintErrorCantAccessIndices(); return; } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException("Array passed to SetIndexBufferData must be blittable.\n" + UnsafeUtility.GetReasonForArrayNonBlittable(data)); } if (dataStart < 0 || meshBufferStart < 0 || count < 0 || dataStart + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (dataStart:{dataStart} meshBufferStart:{meshBufferStart} count:{count})"); } InternalSetIndexBufferDataFromArray(data, dataStart, meshBufferStart, count, UnsafeUtility.SizeOf(), flags); } public void SetIndexBufferData(List data, int dataStart, int meshBufferStart, int count, MeshUpdateFlags flags = MeshUpdateFlags.Default) where T : struct { if (!canAccess) { PrintErrorCantAccessIndices(); return; } if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException(string.Format("List<{0}> passed to {1} must be blittable.\n{2}", typeof(T), "SetIndexBufferData", UnsafeUtility.GetReasonForGenericListNonBlittable())); } if (dataStart < 0 || meshBufferStart < 0 || count < 0 || dataStart + count > data.Count) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (dataStart:{dataStart} meshBufferStart:{meshBufferStart} count:{count})"); } InternalSetIndexBufferDataFromArray(NoAllocHelpers.ExtractArrayFromList(data), dataStart, meshBufferStart, count, UnsafeUtility.SizeOf(), flags); } public uint GetIndexStart(int submesh) { if (submesh < 0 || submesh >= subMeshCount) { throw new IndexOutOfRangeException("Specified sub mesh is out of range. Must be greater or equal to 0 and less than subMeshCount."); } return GetIndexStartImpl(submesh); } public uint GetIndexCount(int submesh) { if (submesh < 0 || submesh >= subMeshCount) { throw new IndexOutOfRangeException("Specified sub mesh is out of range. Must be greater or equal to 0 and less than subMeshCount."); } return GetIndexCountImpl(submesh); } public uint GetBaseVertex(int submesh) { if (submesh < 0 || submesh >= subMeshCount) { throw new IndexOutOfRangeException("Specified sub mesh is out of range. Must be greater or equal to 0 and less than subMeshCount."); } return GetBaseVertexImpl(submesh); } private void CheckIndicesArrayRange(int valuesLength, int start, int length) { if (start < 0) { throw new ArgumentOutOfRangeException("start", start, "Mesh indices array start can't be negative."); } if (length < 0) { throw new ArgumentOutOfRangeException("length", length, "Mesh indices array length can't be negative."); } if (start >= valuesLength && length != 0) { throw new ArgumentOutOfRangeException("start", start, "Mesh indices array start is outside of array size."); } if (start + length > valuesLength) { throw new ArgumentOutOfRangeException("length", start + length, "Mesh indices array start+count is outside of array size."); } } private void SetTrianglesImpl(int submesh, IndexFormat indicesFormat, Array triangles, int trianglesArrayLength, int start, int length, bool calculateBounds, int baseVertex) { CheckIndicesArrayRange(trianglesArrayLength, start, length); SetIndicesImpl(submesh, MeshTopology.Triangles, indicesFormat, triangles, start, length, calculateBounds, baseVertex); } [ExcludeFromDocs] public void SetTriangles(int[] triangles, int submesh) { SetTriangles(triangles, submesh, calculateBounds: true, 0); } [ExcludeFromDocs] public void SetTriangles(int[] triangles, int submesh, bool calculateBounds) { SetTriangles(triangles, submesh, calculateBounds, 0); } public void SetTriangles(int[] triangles, int submesh, [UnityEngine.Internal.DefaultValue("true")] bool calculateBounds, [UnityEngine.Internal.DefaultValue("0")] int baseVertex) { SetTriangles(triangles, 0, NoAllocHelpers.SafeLength(triangles), submesh, calculateBounds, baseVertex); } public void SetTriangles(int[] triangles, int trianglesStart, int trianglesLength, int submesh, bool calculateBounds = true, int baseVertex = 0) { if (CheckCanAccessSubmeshTriangles(submesh)) { SetTrianglesImpl(submesh, IndexFormat.UInt32, triangles, NoAllocHelpers.SafeLength(triangles), trianglesStart, trianglesLength, calculateBounds, baseVertex); } } public void SetTriangles(ushort[] triangles, int submesh, bool calculateBounds = true, int baseVertex = 0) { SetTriangles(triangles, 0, NoAllocHelpers.SafeLength(triangles), submesh, calculateBounds, baseVertex); } public void SetTriangles(ushort[] triangles, int trianglesStart, int trianglesLength, int submesh, bool calculateBounds = true, int baseVertex = 0) { if (CheckCanAccessSubmeshTriangles(submesh)) { SetTrianglesImpl(submesh, IndexFormat.UInt16, triangles, NoAllocHelpers.SafeLength(triangles), trianglesStart, trianglesLength, calculateBounds, baseVertex); } } [ExcludeFromDocs] public void SetTriangles(List triangles, int submesh) { SetTriangles(triangles, submesh, calculateBounds: true, 0); } [ExcludeFromDocs] public void SetTriangles(List triangles, int submesh, bool calculateBounds) { SetTriangles(triangles, submesh, calculateBounds, 0); } public void SetTriangles(List triangles, int submesh, [UnityEngine.Internal.DefaultValue("true")] bool calculateBounds, [UnityEngine.Internal.DefaultValue("0")] int baseVertex) { SetTriangles(triangles, 0, NoAllocHelpers.SafeLength(triangles), submesh, calculateBounds, baseVertex); } public void SetTriangles(List triangles, int trianglesStart, int trianglesLength, int submesh, bool calculateBounds = true, int baseVertex = 0) { if (CheckCanAccessSubmeshTriangles(submesh)) { SetTrianglesImpl(submesh, IndexFormat.UInt32, NoAllocHelpers.ExtractArrayFromList(triangles), NoAllocHelpers.SafeLength(triangles), trianglesStart, trianglesLength, calculateBounds, baseVertex); } } public void SetTriangles(List triangles, int submesh, bool calculateBounds = true, int baseVertex = 0) { SetTriangles(triangles, 0, NoAllocHelpers.SafeLength(triangles), submesh, calculateBounds, baseVertex); } public void SetTriangles(List triangles, int trianglesStart, int trianglesLength, int submesh, bool calculateBounds = true, int baseVertex = 0) { if (CheckCanAccessSubmeshTriangles(submesh)) { SetTrianglesImpl(submesh, IndexFormat.UInt16, NoAllocHelpers.ExtractArrayFromList(triangles), NoAllocHelpers.SafeLength(triangles), trianglesStart, trianglesLength, calculateBounds, baseVertex); } } [ExcludeFromDocs] public void SetIndices(int[] indices, MeshTopology topology, int submesh) { SetIndices(indices, topology, submesh, calculateBounds: true, 0); } [ExcludeFromDocs] public void SetIndices(int[] indices, MeshTopology topology, int submesh, bool calculateBounds) { SetIndices(indices, topology, submesh, calculateBounds, 0); } public void SetIndices(int[] indices, MeshTopology topology, int submesh, [UnityEngine.Internal.DefaultValue("true")] bool calculateBounds, [UnityEngine.Internal.DefaultValue("0")] int baseVertex) { SetIndices(indices, 0, NoAllocHelpers.SafeLength(indices), topology, submesh, calculateBounds, baseVertex); } public void SetIndices(int[] indices, int indicesStart, int indicesLength, MeshTopology topology, int submesh, bool calculateBounds = true, int baseVertex = 0) { if (CheckCanAccessSubmeshIndices(submesh)) { CheckIndicesArrayRange(NoAllocHelpers.SafeLength(indices), indicesStart, indicesLength); SetIndicesImpl(submesh, topology, IndexFormat.UInt32, indices, indicesStart, indicesLength, calculateBounds, baseVertex); } } public void SetIndices(ushort[] indices, MeshTopology topology, int submesh, bool calculateBounds = true, int baseVertex = 0) { SetIndices(indices, 0, NoAllocHelpers.SafeLength(indices), topology, submesh, calculateBounds, baseVertex); } public void SetIndices(ushort[] indices, int indicesStart, int indicesLength, MeshTopology topology, int submesh, bool calculateBounds = true, int baseVertex = 0) { if (CheckCanAccessSubmeshIndices(submesh)) { CheckIndicesArrayRange(NoAllocHelpers.SafeLength(indices), indicesStart, indicesLength); SetIndicesImpl(submesh, topology, IndexFormat.UInt16, indices, indicesStart, indicesLength, calculateBounds, baseVertex); } } public void SetIndices(NativeArray indices, MeshTopology topology, int submesh, bool calculateBounds = true, int baseVertex = 0) where T : struct { SetIndices(indices, 0, indices.Length, topology, submesh, calculateBounds, baseVertex); } public unsafe void SetIndices(NativeArray indices, int indicesStart, int indicesLength, MeshTopology topology, int submesh, bool calculateBounds = true, int baseVertex = 0) where T : struct { if (CheckCanAccessSubmeshIndices(submesh)) { int num = UnsafeUtility.SizeOf(); if (num != 2 && num != 4) { throw new ArgumentException("SetIndices with NativeArray should use type is 2 or 4 bytes in size"); } CheckIndicesArrayRange(indices.Length, indicesStart, indicesLength); SetIndicesNativeArrayImpl(submesh, topology, (num != 2) ? IndexFormat.UInt32 : IndexFormat.UInt16, (IntPtr)indices.GetUnsafeReadOnlyPtr(), indicesStart, indicesLength, calculateBounds, baseVertex); } } public void SetIndices(List indices, MeshTopology topology, int submesh, bool calculateBounds = true, int baseVertex = 0) { SetIndices(indices, 0, NoAllocHelpers.SafeLength(indices), topology, submesh, calculateBounds, baseVertex); } public void SetIndices(List indices, int indicesStart, int indicesLength, MeshTopology topology, int submesh, bool calculateBounds = true, int baseVertex = 0) { if (CheckCanAccessSubmeshIndices(submesh)) { Array indices2 = NoAllocHelpers.ExtractArrayFromList(indices); CheckIndicesArrayRange(NoAllocHelpers.SafeLength(indices), indicesStart, indicesLength); SetIndicesImpl(submesh, topology, IndexFormat.UInt32, indices2, indicesStart, indicesLength, calculateBounds, baseVertex); } } public void SetIndices(List indices, MeshTopology topology, int submesh, bool calculateBounds = true, int baseVertex = 0) { SetIndices(indices, 0, NoAllocHelpers.SafeLength(indices), topology, submesh, calculateBounds, baseVertex); } public void SetIndices(List indices, int indicesStart, int indicesLength, MeshTopology topology, int submesh, bool calculateBounds = true, int baseVertex = 0) { if (CheckCanAccessSubmeshIndices(submesh)) { Array indices2 = NoAllocHelpers.ExtractArrayFromList(indices); CheckIndicesArrayRange(NoAllocHelpers.SafeLength(indices), indicesStart, indicesLength); SetIndicesImpl(submesh, topology, IndexFormat.UInt16, indices2, indicesStart, indicesLength, calculateBounds, baseVertex); } } public void SetSubMeshes(SubMeshDescriptor[] desc, int start, int count, MeshUpdateFlags flags = MeshUpdateFlags.Default) { if (count > 0 && desc == null) { throw new ArgumentNullException("desc", "Array of submeshes cannot be null unless count is zero."); } int num = ((desc != null) ? desc.Length : 0); if (start < 0 || count < 0 || start + count > num) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (start:{start} count:{count} desc.Length:{num})"); } for (int i = start; i < start + count; i++) { MeshTopology topology = desc[i].topology; if (topology < MeshTopology.Triangles || topology > MeshTopology.Points) { throw new ArgumentException("desc", $"{i}-th submesh descriptor has invalid topology ({(int)topology})."); } if (topology == (MeshTopology)1) { throw new ArgumentException("desc", $"{i}-th submesh descriptor has triangles strip topology, which is no longer supported."); } } SetAllSubMeshesAtOnceFromArray(desc, start, count, flags); } public void SetSubMeshes(SubMeshDescriptor[] desc, MeshUpdateFlags flags = MeshUpdateFlags.Default) { SetSubMeshes(desc, 0, (desc != null) ? desc.Length : 0, flags); } public void SetSubMeshes(List desc, int start, int count, MeshUpdateFlags flags = MeshUpdateFlags.Default) { SetSubMeshes(NoAllocHelpers.ExtractArrayFromListT(desc), start, count, flags); } public void SetSubMeshes(List desc, MeshUpdateFlags flags = MeshUpdateFlags.Default) { SetSubMeshes(NoAllocHelpers.ExtractArrayFromListT(desc), 0, desc?.Count ?? 0, flags); } public unsafe void SetSubMeshes(NativeArray desc, int start, int count, MeshUpdateFlags flags = MeshUpdateFlags.Default) where T : struct { if (UnsafeUtility.SizeOf() != UnsafeUtility.SizeOf()) { throw new ArgumentException(string.Format("{0} with NativeArray should use struct type that is {1} bytes in size", "SetSubMeshes", UnsafeUtility.SizeOf())); } if (start < 0 || count < 0 || start + count > desc.Length) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (start:{start} count:{count} desc.Length:{desc.Length})"); } SetAllSubMeshesAtOnceFromNativeArray((IntPtr)desc.GetUnsafeReadOnlyPtr(), start, count, flags); } public void SetSubMeshes(NativeArray desc, MeshUpdateFlags flags = MeshUpdateFlags.Default) where T : struct { SetSubMeshes(desc, 0, desc.Length, flags); } public void GetBindposes(List bindposes) { if (bindposes == null) { throw new ArgumentNullException("bindposes", "The result bindposes list cannot be null."); } NoAllocHelpers.EnsureListElemCount(bindposes, GetBindposeCount()); GetBindposesNonAllocImpl(NoAllocHelpers.ExtractArrayFromListT(bindposes)); } public void GetBoneWeights(List boneWeights) { if (boneWeights == null) { throw new ArgumentNullException("boneWeights", "The result boneWeights list cannot be null."); } if (HasBoneWeights()) { NoAllocHelpers.EnsureListElemCount(boneWeights, vertexCount); } GetBoneWeightsNonAllocImpl(NoAllocHelpers.ExtractArrayFromListT(boneWeights)); } public void Clear([UnityEngine.Internal.DefaultValue("true")] bool keepVertexLayout) { ClearImpl(keepVertexLayout); } [ExcludeFromDocs] public void Clear() { ClearImpl(keepVertexLayout: true); } [ExcludeFromDocs] public void RecalculateBounds() { RecalculateBounds(MeshUpdateFlags.Default); } [ExcludeFromDocs] public void RecalculateNormals() { RecalculateNormals(MeshUpdateFlags.Default); } [ExcludeFromDocs] public void RecalculateTangents() { RecalculateTangents(MeshUpdateFlags.Default); } public void RecalculateBounds([UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { if (canAccess) { RecalculateBoundsImpl(flags); } else { Debug.LogError($"Not allowed to call RecalculateBounds() on mesh '{base.name}'"); } } public void RecalculateNormals([UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { if (canAccess) { RecalculateNormalsImpl(flags); } else { Debug.LogError($"Not allowed to call RecalculateNormals() on mesh '{base.name}'"); } } public void RecalculateTangents([UnityEngine.Internal.DefaultValue("MeshUpdateFlags.Default")] MeshUpdateFlags flags) { if (canAccess) { RecalculateTangentsImpl(flags); } else { Debug.LogError($"Not allowed to call RecalculateTangents() on mesh '{base.name}'"); } } public void RecalculateUVDistributionMetric(int uvSetIndex, float uvAreaThreshold = 1E-09f) { if (canAccess) { RecalculateUVDistributionMetricImpl(uvSetIndex, uvAreaThreshold); } else { Debug.LogError($"Not allowed to call RecalculateUVDistributionMetric() on mesh '{base.name}'"); } } public void RecalculateUVDistributionMetrics(float uvAreaThreshold = 1E-09f) { if (canAccess) { RecalculateUVDistributionMetricsImpl(uvAreaThreshold); } else { Debug.LogError($"Not allowed to call RecalculateUVDistributionMetrics() on mesh '{base.name}'"); } } public void MarkDynamic() { if (canAccess) { MarkDynamicImpl(); } } public void UploadMeshData(bool markNoLongerReadable) { if (canAccess) { UploadMeshDataImpl(markNoLongerReadable); } } public void Optimize() { if (canAccess) { OptimizeImpl(); } else { Debug.LogError($"Not allowed to call Optimize() on mesh '{base.name}'"); } } public void OptimizeIndexBuffers() { if (canAccess) { OptimizeIndexBuffersImpl(); } else { Debug.LogError($"Not allowed to call OptimizeIndexBuffers() on mesh '{base.name}'"); } } public void OptimizeReorderVertexBuffer() { if (canAccess) { OptimizeReorderVertexBufferImpl(); } else { Debug.LogError($"Not allowed to call OptimizeReorderVertexBuffer() on mesh '{base.name}'"); } } public MeshTopology GetTopology(int submesh) { if (submesh < 0 || submesh >= subMeshCount) { Debug.LogError("Failed getting topology. Submesh index is out of bounds.", this); return MeshTopology.Triangles; } return GetTopologyImpl(submesh); } public void CombineMeshes(CombineInstance[] combine, [UnityEngine.Internal.DefaultValue("true")] bool mergeSubMeshes, [UnityEngine.Internal.DefaultValue("true")] bool useMatrices, [UnityEngine.Internal.DefaultValue("false")] bool hasLightmapData) { CombineMeshesImpl(combine, mergeSubMeshes, useMatrices, hasLightmapData); } [ExcludeFromDocs] public void CombineMeshes(CombineInstance[] combine, bool mergeSubMeshes, bool useMatrices) { CombineMeshesImpl(combine, mergeSubMeshes, useMatrices, hasLightmapData: false); } [ExcludeFromDocs] public void CombineMeshes(CombineInstance[] combine, bool mergeSubMeshes) { CombineMeshesImpl(combine, mergeSubMeshes, useMatrices: true, hasLightmapData: false); } [ExcludeFromDocs] public void CombineMeshes(CombineInstance[] combine) { CombineMeshesImpl(combine, mergeSubMeshes: true, useMatrices: true, hasLightmapData: false); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetVertexAttribute_Injected(int index, out VertexAttributeDescriptor ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetSubMesh_Injected(int index, ref SubMeshDescriptor desc, MeshUpdateFlags flags = MeshUpdateFlags.Default); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetSubMesh_Injected(int index, out SubMeshDescriptor ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_bounds_Injected(out Bounds ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_bounds_Injected(ref Bounds value); } [StructLayout(LayoutKind.Sequential, Size = 1)] [NativeHeader("Runtime/Graphics/Mesh/MeshCombiner.h")] [NativeHeader("Runtime/Graphics/Mesh/MeshScriptBindings.h")] internal struct StaticBatchingHelper { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MeshScripting::CombineMeshVerticesForStaticBatching")] internal static extern Mesh InternalCombineVertices(MeshSubsetCombineUtility.MeshInstance[] meshes, string meshName); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("MeshScripting::CombineMeshIndicesForStaticBatching")] internal static extern void InternalCombineIndices(MeshSubsetCombineUtility.SubMeshInstance[] submeshes, Mesh combinedMesh); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("IsMeshBatchable")] internal static extern bool IsMeshBatchable(Mesh mesh); } [Serializable] [UsedByNativeCode] public struct BoneWeight : IEquatable { [SerializeField] private float m_Weight0; [SerializeField] private float m_Weight1; [SerializeField] private float m_Weight2; [SerializeField] private float m_Weight3; [SerializeField] private int m_BoneIndex0; [SerializeField] private int m_BoneIndex1; [SerializeField] private int m_BoneIndex2; [SerializeField] private int m_BoneIndex3; public float weight0 { get { return m_Weight0; } set { m_Weight0 = value; } } public float weight1 { get { return m_Weight1; } set { m_Weight1 = value; } } public float weight2 { get { return m_Weight2; } set { m_Weight2 = value; } } public float weight3 { get { return m_Weight3; } set { m_Weight3 = value; } } public int boneIndex0 { get { return m_BoneIndex0; } set { m_BoneIndex0 = value; } } public int boneIndex1 { get { return m_BoneIndex1; } set { m_BoneIndex1 = value; } } public int boneIndex2 { get { return m_BoneIndex2; } set { m_BoneIndex2 = value; } } public int boneIndex3 { get { return m_BoneIndex3; } set { m_BoneIndex3 = value; } } public override int GetHashCode() { return boneIndex0.GetHashCode() ^ (boneIndex1.GetHashCode() << 2) ^ (boneIndex2.GetHashCode() >> 2) ^ (boneIndex3.GetHashCode() >> 1) ^ (weight0.GetHashCode() << 5) ^ (weight1.GetHashCode() << 4) ^ (weight2.GetHashCode() >> 4) ^ (weight3.GetHashCode() >> 3); } public override bool Equals(object other) { return other is BoneWeight && Equals((BoneWeight)other); } public bool Equals(BoneWeight other) { return boneIndex0.Equals(other.boneIndex0) && boneIndex1.Equals(other.boneIndex1) && boneIndex2.Equals(other.boneIndex2) && boneIndex3.Equals(other.boneIndex3) && new Vector4(weight0, weight1, weight2, weight3).Equals(new Vector4(other.weight0, other.weight1, other.weight2, other.weight3)); } public static bool operator ==(BoneWeight lhs, BoneWeight rhs) { return lhs.boneIndex0 == rhs.boneIndex0 && lhs.boneIndex1 == rhs.boneIndex1 && lhs.boneIndex2 == rhs.boneIndex2 && lhs.boneIndex3 == rhs.boneIndex3 && new Vector4(lhs.weight0, lhs.weight1, lhs.weight2, lhs.weight3) == new Vector4(rhs.weight0, rhs.weight1, rhs.weight2, rhs.weight3); } public static bool operator !=(BoneWeight lhs, BoneWeight rhs) { return !(lhs == rhs); } } [Serializable] [UsedByNativeCode] public struct BoneWeight1 : IEquatable { [SerializeField] private float m_Weight; [SerializeField] private int m_BoneIndex; public float weight { get { return m_Weight; } set { m_Weight = value; } } public int boneIndex { get { return m_BoneIndex; } set { m_BoneIndex = value; } } public override bool Equals(object other) { return other is BoneWeight1 && Equals((BoneWeight1)other); } public bool Equals(BoneWeight1 other) { return boneIndex.Equals(other.boneIndex) && weight.Equals(other.weight); } public override int GetHashCode() { return boneIndex.GetHashCode() ^ weight.GetHashCode(); } public static bool operator ==(BoneWeight1 lhs, BoneWeight1 rhs) { return lhs.boneIndex == rhs.boneIndex && lhs.weight == rhs.weight; } public static bool operator !=(BoneWeight1 lhs, BoneWeight1 rhs) { return !(lhs == rhs); } } public struct CombineInstance { private int m_MeshInstanceID; private int m_SubMeshIndex; private Matrix4x4 m_Transform; private Vector4 m_LightmapScaleOffset; private Vector4 m_RealtimeLightmapScaleOffset; public Mesh mesh { get { return Mesh.FromInstanceID(m_MeshInstanceID); } set { m_MeshInstanceID = ((value != null) ? value.GetInstanceID() : 0); } } public int subMeshIndex { get { return m_SubMeshIndex; } set { m_SubMeshIndex = value; } } public Matrix4x4 transform { get { return m_Transform; } set { m_Transform = value; } } public Vector4 lightmapScaleOffset { get { return m_LightmapScaleOffset; } set { m_LightmapScaleOffset = value; } } public Vector4 realtimeLightmapScaleOffset { get { return m_RealtimeLightmapScaleOffset; } set { m_RealtimeLightmapScaleOffset = value; } } } [UsedByNativeCode] [NativeHeader("Runtime/Streaming/TextureStreamingManager.h")] [NativeHeader("Runtime/Graphics/Texture.h")] public class Texture : Object { public static readonly int GenerateAllMips = -1; [NativeProperty("GlobalMasterTextureLimit")] public static extern int masterTextureLimit { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int mipmapCount { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetMipmapCount")] get; } [NativeProperty("AnisoLimit")] public static extern AnisotropicFiltering anisotropicFiltering { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public virtual GraphicsFormat graphicsFormat => GraphicsFormatUtility.GetFormat(this); public virtual int width { get { return GetDataWidth(); } set { throw new NotImplementedException(); } } public virtual int height { get { return GetDataHeight(); } set { throw new NotImplementedException(); } } public virtual TextureDimension dimension { get { return GetDimension(); } set { throw new NotImplementedException(); } } public virtual extern bool isReadable { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern TextureWrapMode wrapMode { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetWrapModeU")] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern TextureWrapMode wrapModeU { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern TextureWrapMode wrapModeV { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern TextureWrapMode wrapModeW { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern FilterMode filterMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int anisoLevel { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float mipMapBias { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Vector2 texelSize { [NativeName("GetTexelSize")] get { get_texelSize_Injected(out var ret); return ret; } } public extern uint updateCount { [MethodImpl(MethodImplOptions.InternalCall)] get; } internal ColorSpace activeTextureColorSpace { [VisibleToOtherModules(new string[] { "UnityEngine.UIElementsModule", "Unity.UIElements" })] get { return (Internal_GetActiveTextureColorSpace() == 0) ? ColorSpace.Linear : ColorSpace.Gamma; } } public bool isDataSRGB => Internal_GetStoredColorSpace() == TextureColorSpace.sRGB; public static extern ulong totalTextureMemory { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTextureStreamingManager().GetTotalTextureMemory")] get; } public static extern ulong desiredTextureMemory { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTextureStreamingManager().GetDesiredTextureMemory")] get; } public static extern ulong targetTextureMemory { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTextureStreamingManager().GetTargetTextureMemory")] get; } public static extern ulong currentTextureMemory { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTextureStreamingManager().GetCurrentTextureMemory")] get; } public static extern ulong nonStreamingTextureMemory { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTextureStreamingManager().GetNonStreamingTextureMemory")] get; } public static extern ulong streamingMipmapUploadCount { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTextureStreamingManager().GetStreamingMipmapUploadCount")] get; } public static extern ulong streamingRendererCount { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTextureStreamingManager().GetStreamingRendererCount")] get; } public static extern ulong streamingTextureCount { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTextureStreamingManager().GetStreamingTextureCount")] get; } public static extern ulong nonStreamingTextureCount { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTextureStreamingManager().GetNonStreamingTextureCount")] get; } public static extern ulong streamingTexturePendingLoadCount { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTextureStreamingManager().GetStreamingTexturePendingLoadCount")] get; } public static extern ulong streamingTextureLoadingCount { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTextureStreamingManager().GetStreamingTextureLoadingCount")] get; } public static extern bool streamingTextureForceLoadAll { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetForceLoadAll")] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().SetForceLoadAll")] set; } public static extern bool streamingTextureDiscardUnusedMips { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetDiscardUnusedMips")] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().SetDiscardUnusedMips")] set; } public static extern bool allowThreadedTextureCreation { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DScripting::IsCreateTextureThreadedEnabled")] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DScripting::EnableCreateTextureThreaded")] set; } protected Texture() { } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetGlobalAnisoLimits")] public static extern void SetGlobalAnisotropicFilteringLimits(int forcedMin, int globalMax); [MethodImpl(MethodImplOptions.InternalCall)] private extern int GetDataWidth(); [MethodImpl(MethodImplOptions.InternalCall)] private extern int GetDataHeight(); [MethodImpl(MethodImplOptions.InternalCall)] private extern TextureDimension GetDimension(); [MethodImpl(MethodImplOptions.InternalCall)] public extern IntPtr GetNativeTexturePtr(); [Obsolete("Use GetNativeTexturePtr instead.", false)] public int GetNativeTextureID() { return (int)GetNativeTexturePtr(); } [MethodImpl(MethodImplOptions.InternalCall)] public extern void IncrementUpdateCount(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetActiveTextureColorSpace")] private extern int Internal_GetActiveTextureColorSpace(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetStoredColorSpace")] private extern TextureColorSpace Internal_GetStoredColorSpace(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTextureStreamingManager().SetStreamingTextureMaterialDebugProperties")] public static extern void SetStreamingTextureMaterialDebugProperties(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern ulong GetPixelDataSize(int mipLevel, int element = 0); [MethodImpl(MethodImplOptions.InternalCall)] internal extern ulong GetPixelDataOffset(int mipLevel, int element = 0); internal TextureColorSpace GetTextureColorSpace(bool linear) { return (!linear) ? TextureColorSpace.sRGB : TextureColorSpace.Linear; } internal TextureColorSpace GetTextureColorSpace(GraphicsFormat format) { return GetTextureColorSpace(!GraphicsFormatUtility.IsSRGBFormat(format)); } internal bool ValidateFormat(RenderTextureFormat format) { if (SystemInfo.SupportsRenderTextureFormat(format)) { return true; } Debug.LogError($"RenderTexture creation failed. '{format.ToString()}' is not supported on this platform. Use 'SystemInfo.SupportsRenderTextureFormat' C# API to check format support.", this); return false; } internal bool ValidateFormat(TextureFormat format) { if (SystemInfo.SupportsTextureFormat(format)) { return true; } if (GraphicsFormatUtility.IsCompressedTextureFormat(format) && GraphicsFormatUtility.CanDecompressFormat(GraphicsFormatUtility.GetGraphicsFormat(format, isSRGB: false))) { Debug.LogWarning($"'{format.ToString()}' is not supported on this platform. Decompressing texture. Use 'SystemInfo.SupportsTextureFormat' C# API to check format support.", this); return true; } Debug.LogError($"Texture creation failed. '{format.ToString()}' is not supported on this platform. Use 'SystemInfo.SupportsTextureFormat' C# API to check format support.", this); return false; } internal bool ValidateFormat(GraphicsFormat format, FormatUsage usage) { if (usage != FormatUsage.Render && (format == GraphicsFormat.ShadowAuto || format == GraphicsFormat.DepthAuto)) { Debug.LogWarning($"'{format.ToString()}' is not allowed because it is an auto format and not an exact format. Use GraphicsFormatUtility.GetDepthStencilFormat to get an exact depth/stencil format.", this); return false; } if (SystemInfo.IsFormatSupported(format, usage)) { return true; } Debug.LogError($"Texture creation failed. '{format.ToString()}' is not supported for {usage.ToString()} usage on this platform. Use 'SystemInfo.IsFormatSupported' C# API to check format support.", this); return false; } internal UnityException CreateNonReadableException(Texture t) { return new UnityException($"Texture '{t.name}' is not readable, the texture memory can not be accessed from scripts. You can make the texture readable in the Texture Import Settings."); } internal UnityException CreateNativeArrayLengthOverflowException() { return new UnityException("Failed to create NativeArray, length exceeds the allowed maximum of Int32.MaxValue. Use a larger type as template argument to reduce the array length."); } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_texelSize_Injected(out Vector2 ret); } [UsedByNativeCode] [NativeHeader("Runtime/Graphics/Texture2D.h")] [NativeHeader("Runtime/Graphics/GeneratedTextures.h")] public sealed class Texture2D : Texture { [Flags] public enum EXRFlags { None = 0, OutputAsFloat = 1, CompressZIP = 2, CompressRLE = 4, CompressPIZ = 8 } internal const int streamingMipmapsPriorityMin = -128; internal const int streamingMipmapsPriorityMax = 127; public extern TextureFormat format { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetTextureFormat")] get; } public extern bool ignoreMipmapLimit { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("IgnoreMasterTextureLimit")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetIgnoreMasterTextureLimitAndReload")] set; } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern Texture2D whiteTexture { [MethodImpl(MethodImplOptions.InternalCall)] get; } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern Texture2D blackTexture { [MethodImpl(MethodImplOptions.InternalCall)] get; } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern Texture2D redTexture { [MethodImpl(MethodImplOptions.InternalCall)] get; } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern Texture2D grayTexture { [MethodImpl(MethodImplOptions.InternalCall)] get; } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern Texture2D linearGrayTexture { [MethodImpl(MethodImplOptions.InternalCall)] get; } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern Texture2D normalTexture { [MethodImpl(MethodImplOptions.InternalCall)] get; } public override extern bool isReadable { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeName("VTOnly")] [NativeConditional("ENABLE_VIRTUALTEXTURING && UNITY_EDITOR")] public extern bool vtOnly { [MethodImpl(MethodImplOptions.InternalCall)] get; } internal extern bool isPreProcessed { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern bool streamingMipmaps { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern int streamingMipmapsPriority { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern int requestedMipmapLevel { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetRequestedMipmapLevel", HasExplicitThis = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().SetRequestedMipmapLevel", HasExplicitThis = true)] set; } public extern int minimumMipmapLevel { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetMinimumMipmapLevel", HasExplicitThis = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().SetMinimumMipmapLevel", HasExplicitThis = true)] set; } internal extern bool loadAllMips { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetLoadAllMips", HasExplicitThis = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().SetLoadAllMips", HasExplicitThis = true)] set; } public extern int calculatedMipmapLevel { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetCalculatedMipmapLevel", HasExplicitThis = true)] get; } public extern int desiredMipmapLevel { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetDesiredMipmapLevel", HasExplicitThis = true)] get; } public extern int loadingMipmapLevel { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetLoadingMipmapLevel", HasExplicitThis = true)] get; } public extern int loadedMipmapLevel { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetLoadedMipmapLevel", HasExplicitThis = true)] get; } [MethodImpl(MethodImplOptions.InternalCall)] public extern void Compress(bool highQuality); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Texture2DScripting::Create")] private static extern bool Internal_CreateImpl([Writable] Texture2D mono, int w, int h, int mipCount, GraphicsFormat format, TextureColorSpace colorSpace, TextureCreationFlags flags, IntPtr nativeTex); private static void Internal_Create([Writable] Texture2D mono, int w, int h, int mipCount, GraphicsFormat format, TextureColorSpace colorSpace, TextureCreationFlags flags, IntPtr nativeTex) { if (!Internal_CreateImpl(mono, w, h, mipCount, format, colorSpace, flags, nativeTex)) { throw new UnityException("Failed to create texture because of invalid parameters."); } } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("Apply")] private extern void ApplyImpl(bool updateMipmaps, bool makeNoLongerReadable); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("Reinitialize")] private extern bool ReinitializeImpl(int width, int height); [NativeName("SetPixel")] private void SetPixelImpl(int image, int mip, int x, int y, Color color) { SetPixelImpl_Injected(image, mip, x, y, ref color); } [NativeName("GetPixel")] private Color GetPixelImpl(int image, int mip, int x, int y) { GetPixelImpl_Injected(image, mip, x, y, out var ret); return ret; } [NativeName("GetPixelBilinear")] private Color GetPixelBilinearImpl(int image, int mip, float u, float v) { GetPixelBilinearImpl_Injected(image, mip, u, v, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DScripting::ReinitializeWithFormat", HasExplicitThis = true)] private extern bool ReinitializeWithFormatImpl(int width, int height, GraphicsFormat format, bool hasMipMap); [FreeFunction(Name = "Texture2DScripting::ReadPixels", HasExplicitThis = true)] private void ReadPixelsImpl(Rect source, int destX, int destY, bool recalculateMipMaps) { ReadPixelsImpl_Injected(ref source, destX, destY, recalculateMipMaps); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DScripting::SetPixels", HasExplicitThis = true, ThrowsException = true)] private extern void SetPixelsImpl(int x, int y, int w, int h, Color[] pixel, int miplevel, int frame); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DScripting::LoadRawData", HasExplicitThis = true)] private extern bool LoadRawTextureDataImpl(IntPtr data, ulong size); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DScripting::LoadRawData", HasExplicitThis = true)] private extern bool LoadRawTextureDataImplArray(byte[] data); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DScripting::SetPixelDataArray", HasExplicitThis = true, ThrowsException = true)] private extern bool SetPixelDataImplArray(Array data, int mipLevel, int elementSize, int dataArraySize, int sourceDataStartIndex = 0); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DScripting::SetPixelData", HasExplicitThis = true, ThrowsException = true)] private extern bool SetPixelDataImpl(IntPtr data, int mipLevel, int elementSize, int dataArraySize, int sourceDataStartIndex = 0); [MethodImpl(MethodImplOptions.InternalCall)] private extern IntPtr GetWritableImageData(int frame); [MethodImpl(MethodImplOptions.InternalCall)] private extern ulong GetRawImageDataSize(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Texture2DScripting::GenerateAtlas")] private static extern void GenerateAtlasImpl(Vector2[] sizes, int padding, int atlasSize, [Out] Rect[] rect); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().ClearRequestedMipmapLevel", HasExplicitThis = true)] public extern void ClearRequestedMipmapLevel(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().IsRequestedMipmapLevelLoaded", HasExplicitThis = true)] public extern bool IsRequestedMipmapLevelLoaded(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().ClearMinimumMipmapLevel", HasExplicitThis = true)] public extern void ClearMinimumMipmapLevel(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Texture2DScripting::UpdateExternalTexture", HasExplicitThis = true)] public extern void UpdateExternalTexture(IntPtr nativeTex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Texture2DScripting::SetAllPixels32", HasExplicitThis = true, ThrowsException = true)] private extern void SetAllPixels32([Unmarshalled] Color32[] colors, int miplevel); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Texture2DScripting::SetBlockOfPixels32", HasExplicitThis = true, ThrowsException = true)] private extern void SetBlockOfPixels32(int x, int y, int blockWidth, int blockHeight, [Unmarshalled] Color32[] colors, int miplevel); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Texture2DScripting::GetRawTextureData", HasExplicitThis = true, ThrowsException = true)] public extern byte[] GetRawTextureData(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Texture2DScripting::GetPixels", HasExplicitThis = true, ThrowsException = true)] public extern Color[] GetPixels(int x, int y, int blockWidth, int blockHeight, [UnityEngine.Internal.DefaultValue("0")] int miplevel); [ExcludeFromDocs] public Color[] GetPixels(int x, int y, int blockWidth, int blockHeight) { return GetPixels(x, y, blockWidth, blockHeight, 0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Texture2DScripting::GetPixels32", HasExplicitThis = true, ThrowsException = true)] public extern Color32[] GetPixels32([UnityEngine.Internal.DefaultValue("0")] int miplevel); [ExcludeFromDocs] public Color32[] GetPixels32() { return GetPixels32(0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Texture2DScripting::PackTextures", HasExplicitThis = true)] public extern Rect[] PackTextures(Texture2D[] textures, int padding, int maximumAtlasSize, bool makeNoLongerReadable); public Rect[] PackTextures(Texture2D[] textures, int padding, int maximumAtlasSize) { return PackTextures(textures, padding, maximumAtlasSize, makeNoLongerReadable: false); } public Rect[] PackTextures(Texture2D[] textures, int padding) { return PackTextures(textures, padding, 2048); } internal bool ValidateFormat(TextureFormat format, int width, int height) { bool flag = ValidateFormat(format); if (flag && TextureFormat.PVRTC_RGB2 <= format && format <= TextureFormat.PVRTC_RGBA4 && (width != height || !Mathf.IsPowerOfTwo(width))) { throw new UnityException($"'{format.ToString()}' demands texture to be square and have power-of-two dimensions"); } return flag; } internal bool ValidateFormat(GraphicsFormat format, int width, int height) { bool flag = ValidateFormat(format, FormatUsage.Sample); if (flag && GraphicsFormatUtility.IsPVRTCFormat(format) && (width != height || !Mathf.IsPowerOfTwo(width))) { throw new UnityException($"'{format.ToString()}' demands texture to be square and have power-of-two dimensions"); } return flag; } internal Texture2D(int width, int height, GraphicsFormat format, TextureCreationFlags flags, int mipCount, IntPtr nativeTex) { if (ValidateFormat(format, width, height)) { Internal_Create(this, width, height, mipCount, format, GetTextureColorSpace(format), flags, nativeTex); } } [ExcludeFromDocs] public Texture2D(int width, int height, DefaultFormat format, TextureCreationFlags flags) : this(width, height, SystemInfo.GetGraphicsFormat(format), flags) { } [ExcludeFromDocs] public Texture2D(int width, int height, GraphicsFormat format, TextureCreationFlags flags) : this(width, height, format, flags, Texture.GenerateAllMips, IntPtr.Zero) { } [ExcludeFromDocs] public Texture2D(int width, int height, GraphicsFormat format, int mipCount, TextureCreationFlags flags) : this(width, height, format, flags, mipCount, IntPtr.Zero) { } internal Texture2D(int width, int height, TextureFormat textureFormat, int mipCount, bool linear, IntPtr nativeTex) { if (ValidateFormat(textureFormat, width, height)) { GraphicsFormat graphicsFormat = GraphicsFormatUtility.GetGraphicsFormat(textureFormat, !linear); TextureCreationFlags textureCreationFlags = ((mipCount != 1) ? TextureCreationFlags.MipChain : TextureCreationFlags.None); if (GraphicsFormatUtility.IsCrunchFormat(textureFormat)) { textureCreationFlags |= TextureCreationFlags.Crunch; } Internal_Create(this, width, height, mipCount, graphicsFormat, GetTextureColorSpace(linear), textureCreationFlags, nativeTex); } } public Texture2D(int width, int height, [UnityEngine.Internal.DefaultValue("TextureFormat.RGBA32")] TextureFormat textureFormat, [UnityEngine.Internal.DefaultValue("-1")] int mipCount, [UnityEngine.Internal.DefaultValue("false")] bool linear) : this(width, height, textureFormat, mipCount, linear, IntPtr.Zero) { } public Texture2D(int width, int height, [UnityEngine.Internal.DefaultValue("TextureFormat.RGBA32")] TextureFormat textureFormat, [UnityEngine.Internal.DefaultValue("true")] bool mipChain, [UnityEngine.Internal.DefaultValue("false")] bool linear) : this(width, height, textureFormat, (!mipChain) ? 1 : (-1), linear, IntPtr.Zero) { } [ExcludeFromDocs] public Texture2D(int width, int height, TextureFormat textureFormat, bool mipChain) : this(width, height, textureFormat, (!mipChain) ? 1 : (-1), linear: false, IntPtr.Zero) { } [ExcludeFromDocs] public Texture2D(int width, int height) : this(width, height, TextureFormat.RGBA32, Texture.GenerateAllMips, linear: false, IntPtr.Zero) { } public static Texture2D CreateExternalTexture(int width, int height, TextureFormat format, bool mipChain, bool linear, IntPtr nativeTex) { if (nativeTex == IntPtr.Zero) { throw new ArgumentException("nativeTex can not be null"); } return new Texture2D(width, height, format, (!mipChain) ? 1 : (-1), linear, nativeTex); } [ExcludeFromDocs] public void SetPixel(int x, int y, Color color) { if (!isReadable) { throw CreateNonReadableException(this); } SetPixelImpl(0, 0, x, y, color); } public void SetPixel(int x, int y, Color color, [UnityEngine.Internal.DefaultValue("0")] int mipLevel) { if (!isReadable) { throw CreateNonReadableException(this); } SetPixelImpl(0, mipLevel, x, y, color); } public void SetPixels(int x, int y, int blockWidth, int blockHeight, Color[] colors, [UnityEngine.Internal.DefaultValue("0")] int miplevel) { if (!isReadable) { throw CreateNonReadableException(this); } SetPixelsImpl(x, y, blockWidth, blockHeight, colors, miplevel, 0); } [ExcludeFromDocs] public void SetPixels(int x, int y, int blockWidth, int blockHeight, Color[] colors) { SetPixels(x, y, blockWidth, blockHeight, colors, 0); } public void SetPixels(Color[] colors, [UnityEngine.Internal.DefaultValue("0")] int miplevel) { int num = width >> miplevel; if (num < 1) { num = 1; } int num2 = height >> miplevel; if (num2 < 1) { num2 = 1; } SetPixels(0, 0, num, num2, colors, miplevel); } [ExcludeFromDocs] public void SetPixels(Color[] colors) { SetPixels(0, 0, width, height, colors, 0); } [ExcludeFromDocs] public Color GetPixel(int x, int y) { if (!isReadable) { throw CreateNonReadableException(this); } return GetPixelImpl(0, 0, x, y); } public Color GetPixel(int x, int y, [UnityEngine.Internal.DefaultValue("0")] int mipLevel) { if (!isReadable) { throw CreateNonReadableException(this); } return GetPixelImpl(0, mipLevel, x, y); } [ExcludeFromDocs] public Color GetPixelBilinear(float u, float v) { if (!isReadable) { throw CreateNonReadableException(this); } return GetPixelBilinearImpl(0, 0, u, v); } public Color GetPixelBilinear(float u, float v, [UnityEngine.Internal.DefaultValue("0")] int mipLevel) { if (!isReadable) { throw CreateNonReadableException(this); } return GetPixelBilinearImpl(0, mipLevel, u, v); } public void LoadRawTextureData(IntPtr data, int size) { if (!isReadable) { throw CreateNonReadableException(this); } if (data == IntPtr.Zero || size == 0) { Debug.LogError("No texture data provided to LoadRawTextureData", this); } else if (!LoadRawTextureDataImpl(data, (ulong)size)) { throw new UnityException("LoadRawTextureData: not enough data provided (will result in overread)."); } } public void LoadRawTextureData(byte[] data) { if (!isReadable) { throw CreateNonReadableException(this); } if (data == null || data.Length == 0) { Debug.LogError("No texture data provided to LoadRawTextureData", this); } else if (!LoadRawTextureDataImplArray(data)) { throw new UnityException("LoadRawTextureData: not enough data provided (will result in overread)."); } } public unsafe void LoadRawTextureData(NativeArray data) where T : struct { if (!isReadable) { throw CreateNonReadableException(this); } if (!data.IsCreated || data.Length == 0) { throw new UnityException("No texture data provided to LoadRawTextureData"); } if (!LoadRawTextureDataImpl((IntPtr)data.GetUnsafeReadOnlyPtr(), (ulong)data.Length * (ulong)UnsafeUtility.SizeOf())) { throw new UnityException("LoadRawTextureData: not enough data provided (will result in overread)."); } } public void SetPixelData(T[] data, int mipLevel, [UnityEngine.Internal.DefaultValue("0")] int sourceDataStartIndex = 0) { if (sourceDataStartIndex < 0) { throw new UnityException("SetPixelData: sourceDataStartIndex cannot be less than 0."); } if (!isReadable) { throw CreateNonReadableException(this); } if (data == null || data.Length == 0) { throw new UnityException("No texture data provided to SetPixelData."); } SetPixelDataImplArray(data, mipLevel, Marshal.SizeOf((object)data[0]), data.Length, sourceDataStartIndex); } public unsafe void SetPixelData(NativeArray data, int mipLevel, [UnityEngine.Internal.DefaultValue("0")] int sourceDataStartIndex = 0) where T : struct { if (sourceDataStartIndex < 0) { throw new UnityException("SetPixelData: sourceDataStartIndex cannot be less than 0."); } if (!isReadable) { throw CreateNonReadableException(this); } if (!data.IsCreated || data.Length == 0) { throw new UnityException("No texture data provided to SetPixelData."); } SetPixelDataImpl((IntPtr)data.GetUnsafeReadOnlyPtr(), mipLevel, UnsafeUtility.SizeOf(), data.Length, sourceDataStartIndex); } public unsafe NativeArray GetPixelData(int mipLevel) where T : struct { if (!isReadable) { throw CreateNonReadableException(this); } if (mipLevel < 0 || mipLevel >= base.mipmapCount) { throw new ArgumentException("The passed in miplevel " + mipLevel + " is invalid. It needs to be in the range 0 and " + (base.mipmapCount - 1)); } if (GetWritableImageData(0).ToInt64() == 0) { throw new UnityException("Texture '" + base.name + "' has no data."); } ulong pixelDataOffset = GetPixelDataOffset(mipLevel); ulong pixelDataSize = GetPixelDataSize(mipLevel); int num = UnsafeUtility.SizeOf(); ulong num2 = pixelDataSize / (ulong)num; if (num2 > int.MaxValue) { throw CreateNativeArrayLengthOverflowException(); } IntPtr intPtr = new IntPtr((long)GetWritableImageData(0) + (long)pixelDataOffset); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)intPtr, (int)num2, Allocator.None); } public unsafe NativeArray GetRawTextureData() where T : struct { if (!isReadable) { throw CreateNonReadableException(this); } int num = UnsafeUtility.SizeOf(); ulong num2 = GetRawImageDataSize() / (ulong)num; if (num2 > int.MaxValue) { throw CreateNativeArrayLengthOverflowException(); } return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)GetWritableImageData(0), (int)num2, Allocator.None); } public void Apply([UnityEngine.Internal.DefaultValue("true")] bool updateMipmaps, [UnityEngine.Internal.DefaultValue("false")] bool makeNoLongerReadable) { if (!isReadable) { throw CreateNonReadableException(this); } ApplyImpl(updateMipmaps, makeNoLongerReadable); } [ExcludeFromDocs] public void Apply(bool updateMipmaps) { Apply(updateMipmaps, makeNoLongerReadable: false); } [ExcludeFromDocs] public void Apply() { Apply(updateMipmaps: true, makeNoLongerReadable: false); } public bool Reinitialize(int width, int height) { if (!isReadable) { throw CreateNonReadableException(this); } return ReinitializeImpl(width, height); } public bool Reinitialize(int width, int height, TextureFormat format, bool hasMipMap) { return ReinitializeWithFormatImpl(width, height, GraphicsFormatUtility.GetGraphicsFormat(format, base.activeTextureColorSpace == ColorSpace.Gamma), hasMipMap); } public bool Reinitialize(int width, int height, GraphicsFormat format, bool hasMipMap) { if (!isReadable) { throw CreateNonReadableException(this); } return ReinitializeWithFormatImpl(width, height, format, hasMipMap); } [Obsolete("Texture2D.Resize(int, int) has been deprecated because it actually reinitializes the texture. Use Texture2D.Reinitialize(int, int) instead (UnityUpgradable) -> Reinitialize([*] System.Int32, [*] System.Int32)", false)] public bool Resize(int width, int height) { return Reinitialize(width, height); } [Obsolete("Texture2D.Resize(int, int, TextureFormat, bool) has been deprecated because it actually reinitializes the texture. Use Texture2D.Reinitialize(int, int, TextureFormat, bool) instead (UnityUpgradable) -> Reinitialize([*] System.Int32, [*] System.Int32, UnityEngine.TextureFormat, [*] System.Boolean)", false)] public bool Resize(int width, int height, TextureFormat format, bool hasMipMap) { return Reinitialize(width, height, format, hasMipMap); } [Obsolete("Texture2D.Resize(int, int, GraphicsFormat, bool) has been deprecated because it actually reinitializes the texture. Use Texture2D.Reinitialize(int, int, GraphicsFormat, bool) instead (UnityUpgradable) -> Reinitialize([*] System.Int32, [*] System.Int32, UnityEngine.Experimental.Rendering.GraphicsFormat, [*] System.Boolean)", false)] public bool Resize(int width, int height, GraphicsFormat format, bool hasMipMap) { return Reinitialize(width, height, format, hasMipMap); } public void ReadPixels(Rect source, int destX, int destY, [UnityEngine.Internal.DefaultValue("true")] bool recalculateMipMaps) { if (!isReadable) { throw CreateNonReadableException(this); } ReadPixelsImpl(source, destX, destY, recalculateMipMaps); } [ExcludeFromDocs] public void ReadPixels(Rect source, int destX, int destY) { ReadPixels(source, destX, destY, recalculateMipMaps: true); } public static bool GenerateAtlas(Vector2[] sizes, int padding, int atlasSize, List results) { if (sizes == null) { throw new ArgumentException("sizes array can not be null"); } if (results == null) { throw new ArgumentException("results list cannot be null"); } if (padding < 0) { throw new ArgumentException("padding can not be negative"); } if (atlasSize <= 0) { throw new ArgumentException("atlas size must be positive"); } results.Clear(); if (sizes.Length == 0) { return true; } NoAllocHelpers.EnsureListElemCount(results, sizes.Length); GenerateAtlasImpl(sizes, padding, atlasSize, NoAllocHelpers.ExtractArrayFromListT(results)); return results.Count != 0; } public void SetPixels32(Color32[] colors, [UnityEngine.Internal.DefaultValue("0")] int miplevel) { SetAllPixels32(colors, miplevel); } [ExcludeFromDocs] public void SetPixels32(Color32[] colors) { SetPixels32(colors, 0); } public void SetPixels32(int x, int y, int blockWidth, int blockHeight, Color32[] colors, [UnityEngine.Internal.DefaultValue("0")] int miplevel) { SetBlockOfPixels32(x, y, blockWidth, blockHeight, colors, miplevel); } [ExcludeFromDocs] public void SetPixels32(int x, int y, int blockWidth, int blockHeight, Color32[] colors) { SetPixels32(x, y, blockWidth, blockHeight, colors, 0); } public Color[] GetPixels([UnityEngine.Internal.DefaultValue("0")] int miplevel) { int num = width >> miplevel; if (num < 1) { num = 1; } int num2 = height >> miplevel; if (num2 < 1) { num2 = 1; } return GetPixels(0, 0, num, num2, miplevel); } [ExcludeFromDocs] public Color[] GetPixels() { return GetPixels(0); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetPixelImpl_Injected(int image, int mip, int x, int y, ref Color color); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetPixelImpl_Injected(int image, int mip, int x, int y, out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetPixelBilinearImpl_Injected(int image, int mip, float u, float v, out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void ReadPixelsImpl_Injected(ref Rect source, int destX, int destY, bool recalculateMipMaps); } [NativeHeader("Runtime/Graphics/CubemapTexture.h")] [ExcludeFromPreset] public sealed class Cubemap : Texture { public extern TextureFormat format { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetTextureFormat")] get; } public override extern bool isReadable { [MethodImpl(MethodImplOptions.InternalCall)] get; } internal extern bool isPreProcessed { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern bool streamingMipmaps { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern int streamingMipmapsPriority { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern int requestedMipmapLevel { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetRequestedMipmapLevel", HasExplicitThis = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().SetRequestedMipmapLevel", HasExplicitThis = true)] set; } internal extern bool loadAllMips { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetLoadAllMips", HasExplicitThis = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().SetLoadAllMips", HasExplicitThis = true)] set; } public extern int desiredMipmapLevel { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetDesiredMipmapLevel", HasExplicitThis = true)] get; } public extern int loadingMipmapLevel { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetLoadingMipmapLevel", HasExplicitThis = true)] get; } public extern int loadedMipmapLevel { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().GetLoadedMipmapLevel", HasExplicitThis = true)] get; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CubemapScripting::Create")] private static extern bool Internal_CreateImpl([Writable] Cubemap mono, int ext, int mipCount, GraphicsFormat format, TextureColorSpace colorSpace, TextureCreationFlags flags, IntPtr nativeTex); private static void Internal_Create([Writable] Cubemap mono, int ext, int mipCount, GraphicsFormat format, TextureColorSpace colorSpace, TextureCreationFlags flags, IntPtr nativeTex) { if (!Internal_CreateImpl(mono, ext, mipCount, format, colorSpace, flags, nativeTex)) { throw new UnityException("Failed to create texture because of invalid parameters."); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CubemapScripting::Apply", HasExplicitThis = true)] private extern void ApplyImpl(bool updateMipmaps, bool makeNoLongerReadable); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CubemapScripting::UpdateExternalTexture", HasExplicitThis = true)] public extern void UpdateExternalTexture(IntPtr nativeTexture); [NativeName("SetPixel")] private void SetPixelImpl(int image, int mip, int x, int y, Color color) { SetPixelImpl_Injected(image, mip, x, y, ref color); } [NativeName("GetPixel")] private Color GetPixelImpl(int image, int mip, int x, int y) { GetPixelImpl_Injected(image, mip, x, y, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("FixupEdges")] public extern void SmoothEdges([UnityEngine.Internal.DefaultValue("1")] int smoothRegionWidthInPixels); public void SmoothEdges() { SmoothEdges(1); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CubemapScripting::GetPixels", HasExplicitThis = true, ThrowsException = true)] public extern Color[] GetPixels(CubemapFace face, int miplevel); public Color[] GetPixels(CubemapFace face) { return GetPixels(face, 0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CubemapScripting::SetPixels", HasExplicitThis = true, ThrowsException = true)] public extern void SetPixels([Unmarshalled] Color[] colors, CubemapFace face, int miplevel); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CubemapScripting::SetPixelDataArray", HasExplicitThis = true, ThrowsException = true)] private extern bool SetPixelDataImplArray(Array data, int mipLevel, int face, int elementSize, int dataArraySize, int sourceDataStartIndex = 0); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CubemapScripting::SetPixelData", HasExplicitThis = true, ThrowsException = true)] private extern bool SetPixelDataImpl(IntPtr data, int mipLevel, int face, int elementSize, int dataArraySize, int sourceDataStartIndex = 0); public void SetPixels(Color[] colors, CubemapFace face) { SetPixels(colors, face, 0); } [MethodImpl(MethodImplOptions.InternalCall)] private extern IntPtr GetWritableImageData(int frame); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().ClearRequestedMipmapLevel", HasExplicitThis = true)] public extern void ClearRequestedMipmapLevel(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GetTextureStreamingManager().IsRequestedMipmapLevelLoaded", HasExplicitThis = true)] public extern bool IsRequestedMipmapLevelLoaded(); internal bool ValidateFormat(TextureFormat format, int width) { bool flag = ValidateFormat(format); if (flag && TextureFormat.PVRTC_RGB2 <= format && format <= TextureFormat.PVRTC_RGBA4 && !Mathf.IsPowerOfTwo(width)) { throw new UnityException($"'{format.ToString()}' demands texture to have power-of-two dimensions"); } return flag; } internal bool ValidateFormat(GraphicsFormat format, int width) { bool flag = ValidateFormat(format, FormatUsage.Sample); if (flag && GraphicsFormatUtility.IsPVRTCFormat(format) && !Mathf.IsPowerOfTwo(width)) { throw new UnityException($"'{format.ToString()}' demands texture to have power-of-two dimensions"); } return flag; } [ExcludeFromDocs] public Cubemap(int width, DefaultFormat format, TextureCreationFlags flags) : this(width, SystemInfo.GetGraphicsFormat(format), flags) { } [ExcludeFromDocs] [RequiredByNativeCode] public Cubemap(int width, GraphicsFormat format, TextureCreationFlags flags) { if (ValidateFormat(format, width)) { Internal_Create(this, width, Texture.GenerateAllMips, format, GetTextureColorSpace(format), flags, IntPtr.Zero); } } public Cubemap(int width, TextureFormat format, int mipCount) : this(width, format, mipCount, IntPtr.Zero) { } [ExcludeFromDocs] public Cubemap(int width, GraphicsFormat format, TextureCreationFlags flags, int mipCount) { if (ValidateFormat(format, width)) { ValidateIsNotCrunched(flags); Internal_Create(this, width, mipCount, format, GetTextureColorSpace(format), flags, IntPtr.Zero); } } internal Cubemap(int width, TextureFormat textureFormat, int mipCount, IntPtr nativeTex) { if (ValidateFormat(textureFormat, width)) { GraphicsFormat graphicsFormat = GraphicsFormatUtility.GetGraphicsFormat(textureFormat, isSRGB: false); TextureCreationFlags textureCreationFlags = ((mipCount != 1) ? TextureCreationFlags.MipChain : TextureCreationFlags.None); if (GraphicsFormatUtility.IsCrunchFormat(textureFormat)) { textureCreationFlags |= TextureCreationFlags.Crunch; } ValidateIsNotCrunched(textureCreationFlags); Internal_Create(this, width, mipCount, graphicsFormat, GetTextureColorSpace(linear: true), textureCreationFlags, nativeTex); } } internal Cubemap(int width, TextureFormat textureFormat, bool mipChain, IntPtr nativeTex) : this(width, textureFormat, (!mipChain) ? 1 : (-1), nativeTex) { } public Cubemap(int width, TextureFormat textureFormat, bool mipChain) : this(width, textureFormat, (!mipChain) ? 1 : (-1), IntPtr.Zero) { } public static Cubemap CreateExternalTexture(int width, TextureFormat format, bool mipmap, IntPtr nativeTex) { if (nativeTex == IntPtr.Zero) { throw new ArgumentException("nativeTex can not be null"); } return new Cubemap(width, format, mipmap, nativeTex); } public void SetPixelData(T[] data, int mipLevel, CubemapFace face, [UnityEngine.Internal.DefaultValue("0")] int sourceDataStartIndex = 0) { if (sourceDataStartIndex < 0) { throw new UnityException("SetPixelData: sourceDataStartIndex cannot be less than 0."); } if (!isReadable) { throw CreateNonReadableException(this); } if (data == null || data.Length == 0) { throw new UnityException("No texture data provided to SetPixelData."); } SetPixelDataImplArray(data, mipLevel, (int)face, Marshal.SizeOf((object)data[0]), data.Length, sourceDataStartIndex); } public unsafe void SetPixelData(NativeArray data, int mipLevel, CubemapFace face, [UnityEngine.Internal.DefaultValue("0")] int sourceDataStartIndex = 0) where T : struct { if (sourceDataStartIndex < 0) { throw new UnityException("SetPixelData: sourceDataStartIndex cannot be less than 0."); } if (!isReadable) { throw CreateNonReadableException(this); } if (!data.IsCreated || data.Length == 0) { throw new UnityException("No texture data provided to SetPixelData."); } SetPixelDataImpl((IntPtr)data.GetUnsafeReadOnlyPtr(), mipLevel, (int)face, UnsafeUtility.SizeOf(), data.Length, sourceDataStartIndex); } public unsafe NativeArray GetPixelData(int mipLevel, CubemapFace face) where T : struct { if (!isReadable) { throw CreateNonReadableException(this); } if (mipLevel < 0 || mipLevel >= base.mipmapCount) { throw new ArgumentException("The passed in miplevel " + mipLevel + " is invalid. The valid range is 0 through " + (base.mipmapCount - 1)); } if (face < CubemapFace.PositiveX || face >= (CubemapFace)6) { throw new ArgumentException("The passed in face " + face.ToString() + " is invalid. The valid range is 0 through 5."); } if (GetWritableImageData(0).ToInt64() == 0) { throw new UnityException("Texture '" + base.name + "' has no data."); } ulong pixelDataOffset = GetPixelDataOffset(base.mipmapCount, (int)face); ulong pixelDataOffset2 = GetPixelDataOffset(mipLevel, (int)face); ulong pixelDataSize = GetPixelDataSize(mipLevel, (int)face); int num = UnsafeUtility.SizeOf(); ulong num2 = pixelDataSize / (ulong)num; if (num2 > int.MaxValue) { throw CreateNativeArrayLengthOverflowException(); } IntPtr intPtr = new IntPtr((long)GetWritableImageData(0) + ((long)pixelDataOffset * (long)face + (long)pixelDataOffset2)); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)intPtr, (int)num2, Allocator.None); } [ExcludeFromDocs] public void SetPixel(CubemapFace face, int x, int y, Color color) { SetPixel(face, x, y, color, 0); } public void SetPixel(CubemapFace face, int x, int y, Color color, [UnityEngine.Internal.DefaultValue("0")] int mip) { if (!isReadable) { throw CreateNonReadableException(this); } SetPixelImpl((int)face, mip, x, y, color); } [ExcludeFromDocs] public Color GetPixel(CubemapFace face, int x, int y) { return GetPixel(face, x, y, 0); } public Color GetPixel(CubemapFace face, int x, int y, [UnityEngine.Internal.DefaultValue("0")] int mip) { if (!isReadable) { throw CreateNonReadableException(this); } return GetPixelImpl((int)face, mip, x, y); } public void Apply([UnityEngine.Internal.DefaultValue("true")] bool updateMipmaps, [UnityEngine.Internal.DefaultValue("false")] bool makeNoLongerReadable) { if (!isReadable) { throw CreateNonReadableException(this); } ApplyImpl(updateMipmaps, makeNoLongerReadable); } [ExcludeFromDocs] public void Apply(bool updateMipmaps) { Apply(updateMipmaps, makeNoLongerReadable: false); } [ExcludeFromDocs] public void Apply() { Apply(updateMipmaps: true, makeNoLongerReadable: false); } private static void ValidateIsNotCrunched(TextureCreationFlags flags) { if ((flags &= TextureCreationFlags.Crunch) != TextureCreationFlags.None) { throw new ArgumentException("Crunched Cubemap is not supported for textures created from script."); } } [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetPixelImpl_Injected(int image, int mip, int x, int y, ref Color color); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetPixelImpl_Injected(int image, int mip, int x, int y, out Color ret); } [ExcludeFromPreset] [NativeHeader("Runtime/Graphics/Texture3D.h")] public sealed class Texture3D : Texture { public extern int depth { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetTextureLayerCount")] get; } public extern TextureFormat format { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetTextureFormat")] get; } public override extern bool isReadable { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeName("SetPixel")] private void SetPixelImpl(int mip, int x, int y, int z, Color color) { SetPixelImpl_Injected(mip, x, y, z, ref color); } [NativeName("GetPixel")] private Color GetPixelImpl(int mip, int x, int y, int z) { GetPixelImpl_Injected(mip, x, y, z, out var ret); return ret; } [NativeName("GetPixelBilinear")] private Color GetPixelBilinearImpl(int mip, float u, float v, float w) { GetPixelBilinearImpl_Injected(mip, u, v, w, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Texture3DScripting::Create")] private static extern bool Internal_CreateImpl([Writable] Texture3D mono, int w, int h, int d, int mipCount, GraphicsFormat format, TextureColorSpace colorSpace, TextureCreationFlags flags, IntPtr nativeTex); private static void Internal_Create([Writable] Texture3D mono, int w, int h, int d, int mipCount, GraphicsFormat format, TextureColorSpace colorSpace, TextureCreationFlags flags, IntPtr nativeTex) { if (!Internal_CreateImpl(mono, w, h, d, mipCount, format, colorSpace, flags, nativeTex)) { throw new UnityException("Failed to create texture because of invalid parameters."); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Texture3DScripting::UpdateExternalTexture", HasExplicitThis = true)] public extern void UpdateExternalTexture(IntPtr nativeTex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture3DScripting::Apply", HasExplicitThis = true)] private extern void ApplyImpl(bool updateMipmaps, bool makeNoLongerReadable); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture3DScripting::GetPixels", HasExplicitThis = true, ThrowsException = true)] public extern Color[] GetPixels(int miplevel); public Color[] GetPixels() { return GetPixels(0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture3DScripting::GetPixels32", HasExplicitThis = true, ThrowsException = true)] public extern Color32[] GetPixels32(int miplevel); public Color32[] GetPixels32() { return GetPixels32(0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture3DScripting::SetPixels", HasExplicitThis = true, ThrowsException = true)] public extern void SetPixels([Unmarshalled] Color[] colors, int miplevel); public void SetPixels(Color[] colors) { SetPixels(colors, 0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture3DScripting::SetPixels32", HasExplicitThis = true, ThrowsException = true)] public extern void SetPixels32([Unmarshalled] Color32[] colors, int miplevel); public void SetPixels32(Color32[] colors) { SetPixels32(colors, 0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture3DScripting::SetPixelDataArray", HasExplicitThis = true, ThrowsException = true)] private extern bool SetPixelDataImplArray(Array data, int mipLevel, int elementSize, int dataArraySize, int sourceDataStartIndex = 0); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture3DScripting::SetPixelData", HasExplicitThis = true, ThrowsException = true)] private extern bool SetPixelDataImpl(IntPtr data, int mipLevel, int elementSize, int dataArraySize, int sourceDataStartIndex = 0); [MethodImpl(MethodImplOptions.InternalCall)] private extern IntPtr GetImageDataPointer(); [ExcludeFromDocs] public Texture3D(int width, int height, int depth, DefaultFormat format, TextureCreationFlags flags) : this(width, height, depth, SystemInfo.GetGraphicsFormat(format), flags) { } [RequiredByNativeCode] [ExcludeFromDocs] public Texture3D(int width, int height, int depth, GraphicsFormat format, TextureCreationFlags flags) : this(width, height, depth, format, flags, Texture.GenerateAllMips) { } [ExcludeFromDocs] public Texture3D(int width, int height, int depth, GraphicsFormat format, TextureCreationFlags flags, [UnityEngine.Internal.DefaultValue("-1")] int mipCount) { if (ValidateFormat(format, FormatUsage.Sample)) { ValidateIsNotCrunched(flags); Internal_Create(this, width, height, depth, mipCount, format, GetTextureColorSpace(format), flags, IntPtr.Zero); } } [ExcludeFromDocs] public Texture3D(int width, int height, int depth, TextureFormat textureFormat, int mipCount) { if (ValidateFormat(textureFormat)) { GraphicsFormat graphicsFormat = GraphicsFormatUtility.GetGraphicsFormat(textureFormat, isSRGB: false); TextureCreationFlags textureCreationFlags = ((mipCount != 1) ? TextureCreationFlags.MipChain : TextureCreationFlags.None); if (GraphicsFormatUtility.IsCrunchFormat(textureFormat)) { textureCreationFlags |= TextureCreationFlags.Crunch; } ValidateIsNotCrunched(textureCreationFlags); Internal_Create(this, width, height, depth, mipCount, graphicsFormat, GetTextureColorSpace(linear: true), textureCreationFlags, IntPtr.Zero); } } public Texture3D(int width, int height, int depth, TextureFormat textureFormat, int mipCount, [UnityEngine.Internal.DefaultValue("IntPtr.Zero")] IntPtr nativeTex) { if (ValidateFormat(textureFormat)) { GraphicsFormat graphicsFormat = GraphicsFormatUtility.GetGraphicsFormat(textureFormat, isSRGB: false); TextureCreationFlags textureCreationFlags = ((mipCount != 1) ? TextureCreationFlags.MipChain : TextureCreationFlags.None); if (GraphicsFormatUtility.IsCrunchFormat(textureFormat)) { textureCreationFlags |= TextureCreationFlags.Crunch; } ValidateIsNotCrunched(textureCreationFlags); Internal_Create(this, width, height, depth, mipCount, graphicsFormat, GetTextureColorSpace(linear: true), textureCreationFlags, nativeTex); } } [ExcludeFromDocs] public Texture3D(int width, int height, int depth, TextureFormat textureFormat, bool mipChain) : this(width, height, depth, textureFormat, (!mipChain) ? 1 : (-1)) { } public Texture3D(int width, int height, int depth, TextureFormat textureFormat, bool mipChain, [UnityEngine.Internal.DefaultValue("IntPtr.Zero")] IntPtr nativeTex) : this(width, height, depth, textureFormat, (!mipChain) ? 1 : (-1), nativeTex) { } public static Texture3D CreateExternalTexture(int width, int height, int depth, TextureFormat format, bool mipChain, IntPtr nativeTex) { if (nativeTex == IntPtr.Zero) { throw new ArgumentException("nativeTex may not be zero"); } return new Texture3D(width, height, depth, format, (!mipChain) ? 1 : (-1), nativeTex); } public void Apply([UnityEngine.Internal.DefaultValue("true")] bool updateMipmaps, [UnityEngine.Internal.DefaultValue("false")] bool makeNoLongerReadable) { if (!isReadable) { throw CreateNonReadableException(this); } ApplyImpl(updateMipmaps, makeNoLongerReadable); } [ExcludeFromDocs] public void Apply(bool updateMipmaps) { Apply(updateMipmaps, makeNoLongerReadable: false); } [ExcludeFromDocs] public void Apply() { Apply(updateMipmaps: true, makeNoLongerReadable: false); } [ExcludeFromDocs] public void SetPixel(int x, int y, int z, Color color) { if (!isReadable) { throw CreateNonReadableException(this); } SetPixelImpl(0, x, y, z, color); } public void SetPixel(int x, int y, int z, Color color, [UnityEngine.Internal.DefaultValue("0")] int mipLevel) { if (!isReadable) { throw CreateNonReadableException(this); } SetPixelImpl(mipLevel, x, y, z, color); } [ExcludeFromDocs] public Color GetPixel(int x, int y, int z) { if (!isReadable) { throw CreateNonReadableException(this); } return GetPixelImpl(0, x, y, z); } public Color GetPixel(int x, int y, int z, [UnityEngine.Internal.DefaultValue("0")] int mipLevel) { if (!isReadable) { throw CreateNonReadableException(this); } return GetPixelImpl(mipLevel, x, y, z); } [ExcludeFromDocs] public Color GetPixelBilinear(float u, float v, float w) { if (!isReadable) { throw CreateNonReadableException(this); } return GetPixelBilinearImpl(0, u, v, w); } public Color GetPixelBilinear(float u, float v, float w, [UnityEngine.Internal.DefaultValue("0")] int mipLevel) { if (!isReadable) { throw CreateNonReadableException(this); } return GetPixelBilinearImpl(mipLevel, u, v, w); } public void SetPixelData(T[] data, int mipLevel, [UnityEngine.Internal.DefaultValue("0")] int sourceDataStartIndex = 0) { if (sourceDataStartIndex < 0) { throw new UnityException("SetPixelData: sourceDataStartIndex cannot be less than 0."); } if (!isReadable) { throw CreateNonReadableException(this); } if (data == null || data.Length == 0) { throw new UnityException("No texture data provided to SetPixelData."); } SetPixelDataImplArray(data, mipLevel, Marshal.SizeOf((object)data[0]), data.Length, sourceDataStartIndex); } public unsafe void SetPixelData(NativeArray data, int mipLevel, [UnityEngine.Internal.DefaultValue("0")] int sourceDataStartIndex = 0) where T : struct { if (sourceDataStartIndex < 0) { throw new UnityException("SetPixelData: sourceDataStartIndex cannot be less than 0."); } if (!isReadable) { throw CreateNonReadableException(this); } if (!data.IsCreated || data.Length == 0) { throw new UnityException("No texture data provided to SetPixelData."); } SetPixelDataImpl((IntPtr)data.GetUnsafeReadOnlyPtr(), mipLevel, UnsafeUtility.SizeOf(), data.Length, sourceDataStartIndex); } public unsafe NativeArray GetPixelData(int mipLevel) where T : struct { if (!isReadable) { throw CreateNonReadableException(this); } if (mipLevel < 0 || mipLevel >= base.mipmapCount) { throw new ArgumentException("The passed in miplevel " + mipLevel + " is invalid. The valid range is 0 through " + (base.mipmapCount - 1)); } if (GetImageDataPointer().ToInt64() == 0) { throw new UnityException("Texture '" + base.name + "' has no data."); } ulong pixelDataOffset = GetPixelDataOffset(mipLevel); ulong pixelDataSize = GetPixelDataSize(mipLevel); int num = UnsafeUtility.SizeOf(); ulong num2 = pixelDataSize / (ulong)num; if (num2 > int.MaxValue) { throw CreateNativeArrayLengthOverflowException(); } IntPtr intPtr = new IntPtr((long)GetImageDataPointer() + (long)pixelDataOffset); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)intPtr, (int)num2, Allocator.None); } private static void ValidateIsNotCrunched(TextureCreationFlags flags) { if ((flags &= TextureCreationFlags.Crunch) != TextureCreationFlags.None) { throw new ArgumentException("Crunched Texture3D is not supported."); } } [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetPixelImpl_Injected(int mip, int x, int y, int z, ref Color color); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetPixelImpl_Injected(int mip, int x, int y, int z, out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetPixelBilinearImpl_Injected(int mip, float u, float v, float w, out Color ret); } [NativeHeader("Runtime/Graphics/Texture2DArray.h")] public sealed class Texture2DArray : Texture { public static extern int allSlices { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetAllTextureLayersIdentifier")] get; } public extern int depth { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetTextureLayerCount")] get; } public extern TextureFormat format { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetTextureFormat")] get; } public override extern bool isReadable { [MethodImpl(MethodImplOptions.InternalCall)] get; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Texture2DArrayScripting::Create")] private static extern bool Internal_CreateImpl([Writable] Texture2DArray mono, int w, int h, int d, int mipCount, GraphicsFormat format, TextureColorSpace colorSpace, TextureCreationFlags flags); private static void Internal_Create([Writable] Texture2DArray mono, int w, int h, int d, int mipCount, GraphicsFormat format, TextureColorSpace colorSpace, TextureCreationFlags flags) { if (!Internal_CreateImpl(mono, w, h, d, mipCount, format, colorSpace, flags)) { throw new UnityException("Failed to create 2D array texture because of invalid parameters."); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DArrayScripting::Apply", HasExplicitThis = true)] private extern void ApplyImpl(bool updateMipmaps, bool makeNoLongerReadable); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DArrayScripting::GetPixels", HasExplicitThis = true, ThrowsException = true)] public extern Color[] GetPixels(int arrayElement, int miplevel); public Color[] GetPixels(int arrayElement) { return GetPixels(arrayElement, 0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DArrayScripting::SetPixelDataArray", HasExplicitThis = true, ThrowsException = true)] private extern bool SetPixelDataImplArray(Array data, int mipLevel, int element, int elementSize, int dataArraySize, int sourceDataStartIndex = 0); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DArrayScripting::SetPixelData", HasExplicitThis = true, ThrowsException = true)] private extern bool SetPixelDataImpl(IntPtr data, int mipLevel, int element, int elementSize, int dataArraySize, int sourceDataStartIndex = 0); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DArrayScripting::GetPixels32", HasExplicitThis = true, ThrowsException = true)] public extern Color32[] GetPixels32(int arrayElement, int miplevel); public Color32[] GetPixels32(int arrayElement) { return GetPixels32(arrayElement, 0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DArrayScripting::SetPixels", HasExplicitThis = true, ThrowsException = true)] public extern void SetPixels([Unmarshalled] Color[] colors, int arrayElement, int miplevel); public void SetPixels(Color[] colors, int arrayElement) { SetPixels(colors, arrayElement, 0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Texture2DArrayScripting::SetPixels32", HasExplicitThis = true, ThrowsException = true)] public extern void SetPixels32([Unmarshalled] Color32[] colors, int arrayElement, int miplevel); public void SetPixels32(Color32[] colors, int arrayElement) { SetPixels32(colors, arrayElement, 0); } [MethodImpl(MethodImplOptions.InternalCall)] private extern IntPtr GetImageDataPointer(); internal bool ValidateFormat(TextureFormat format, int width, int height) { bool flag = ValidateFormat(format); if (flag && TextureFormat.PVRTC_RGB2 <= format && format <= TextureFormat.PVRTC_RGBA4 && (width != height || !Mathf.IsPowerOfTwo(width))) { throw new UnityException($"'{format.ToString()}' demands texture to be square and have power-of-two dimensions"); } return flag; } internal bool ValidateFormat(GraphicsFormat format, int width, int height) { bool flag = ValidateFormat(format, FormatUsage.Sample); if (flag && GraphicsFormatUtility.IsPVRTCFormat(format) && (width != height || !Mathf.IsPowerOfTwo(width))) { throw new UnityException($"'{format.ToString()}' demands texture to be square and have power-of-two dimensions"); } return flag; } [ExcludeFromDocs] public Texture2DArray(int width, int height, int depth, DefaultFormat format, TextureCreationFlags flags) : this(width, height, depth, SystemInfo.GetGraphicsFormat(format), flags) { } [RequiredByNativeCode] [ExcludeFromDocs] public Texture2DArray(int width, int height, int depth, GraphicsFormat format, TextureCreationFlags flags) : this(width, height, depth, format, flags, Texture.GenerateAllMips) { } [ExcludeFromDocs] public Texture2DArray(int width, int height, int depth, GraphicsFormat format, TextureCreationFlags flags, int mipCount) { if (ValidateFormat(format, width, height)) { ValidateIsNotCrunched(flags); Internal_Create(this, width, height, depth, mipCount, format, GetTextureColorSpace(format), flags); } } public Texture2DArray(int width, int height, int depth, TextureFormat textureFormat, int mipCount, bool linear) { if (ValidateFormat(textureFormat, width, height)) { GraphicsFormat graphicsFormat = GraphicsFormatUtility.GetGraphicsFormat(textureFormat, !linear); TextureCreationFlags textureCreationFlags = ((mipCount != 1) ? TextureCreationFlags.MipChain : TextureCreationFlags.None); if (GraphicsFormatUtility.IsCrunchFormat(textureFormat)) { textureCreationFlags |= TextureCreationFlags.Crunch; } ValidateIsNotCrunched(textureCreationFlags); Internal_Create(this, width, height, depth, mipCount, graphicsFormat, GetTextureColorSpace(linear), textureCreationFlags); } } public Texture2DArray(int width, int height, int depth, TextureFormat textureFormat, bool mipChain, [UnityEngine.Internal.DefaultValue("false")] bool linear) : this(width, height, depth, textureFormat, (!mipChain) ? 1 : (-1), linear) { } [ExcludeFromDocs] public Texture2DArray(int width, int height, int depth, TextureFormat textureFormat, bool mipChain) : this(width, height, depth, textureFormat, (!mipChain) ? 1 : (-1), linear: false) { } public void Apply([UnityEngine.Internal.DefaultValue("true")] bool updateMipmaps, [UnityEngine.Internal.DefaultValue("false")] bool makeNoLongerReadable) { if (!isReadable) { throw CreateNonReadableException(this); } ApplyImpl(updateMipmaps, makeNoLongerReadable); } [ExcludeFromDocs] public void Apply(bool updateMipmaps) { Apply(updateMipmaps, makeNoLongerReadable: false); } [ExcludeFromDocs] public void Apply() { Apply(updateMipmaps: true, makeNoLongerReadable: false); } public void SetPixelData(T[] data, int mipLevel, int element, [UnityEngine.Internal.DefaultValue("0")] int sourceDataStartIndex = 0) { if (sourceDataStartIndex < 0) { throw new UnityException("SetPixelData: sourceDataStartIndex cannot be less than 0."); } if (!isReadable) { throw CreateNonReadableException(this); } if (data == null || data.Length == 0) { throw new UnityException("No texture data provided to SetPixelData."); } SetPixelDataImplArray(data, mipLevel, element, Marshal.SizeOf((object)data[0]), data.Length, sourceDataStartIndex); } public unsafe void SetPixelData(NativeArray data, int mipLevel, int element, [UnityEngine.Internal.DefaultValue("0")] int sourceDataStartIndex = 0) where T : struct { if (sourceDataStartIndex < 0) { throw new UnityException("SetPixelData: sourceDataStartIndex cannot be less than 0."); } if (!isReadable) { throw CreateNonReadableException(this); } if (!data.IsCreated || data.Length == 0) { throw new UnityException("No texture data provided to SetPixelData."); } SetPixelDataImpl((IntPtr)data.GetUnsafeReadOnlyPtr(), mipLevel, element, UnsafeUtility.SizeOf(), data.Length, sourceDataStartIndex); } public unsafe NativeArray GetPixelData(int mipLevel, int element) where T : struct { if (!isReadable) { throw CreateNonReadableException(this); } if (mipLevel < 0 || mipLevel >= base.mipmapCount) { throw new ArgumentException("The passed in miplevel " + mipLevel + " is invalid. The valid range is 0 through " + (base.mipmapCount - 1)); } if (element < 0 || element >= depth) { throw new ArgumentException("The passed in element " + element + " is invalid. The valid range is 0 through " + (depth - 1)); } ulong pixelDataOffset = GetPixelDataOffset(base.mipmapCount, element); ulong pixelDataOffset2 = GetPixelDataOffset(mipLevel, element); ulong pixelDataSize = GetPixelDataSize(mipLevel, element); int num = UnsafeUtility.SizeOf(); ulong num2 = pixelDataSize / (ulong)num; if (num2 > int.MaxValue) { throw CreateNativeArrayLengthOverflowException(); } IntPtr intPtr = new IntPtr((long)GetImageDataPointer() + ((long)pixelDataOffset * (long)element + (long)pixelDataOffset2)); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)intPtr, (int)num2, Allocator.None); } private static void ValidateIsNotCrunched(TextureCreationFlags flags) { if ((flags &= TextureCreationFlags.Crunch) != TextureCreationFlags.None) { throw new ArgumentException("Crunched Texture2DArray is not supported."); } } } [NativeHeader("Runtime/Graphics/CubemapArrayTexture.h")] [ExcludeFromPreset] public sealed class CubemapArray : Texture { public extern int cubemapCount { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern TextureFormat format { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetTextureFormat")] get; } public override extern bool isReadable { [MethodImpl(MethodImplOptions.InternalCall)] get; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CubemapArrayScripting::Create")] private static extern bool Internal_CreateImpl([Writable] CubemapArray mono, int ext, int count, int mipCount, GraphicsFormat format, TextureColorSpace colorSpace, TextureCreationFlags flags); private static void Internal_Create([Writable] CubemapArray mono, int ext, int count, int mipCount, GraphicsFormat format, TextureColorSpace colorSpace, TextureCreationFlags flags) { if (!Internal_CreateImpl(mono, ext, count, mipCount, format, colorSpace, flags)) { throw new UnityException("Failed to create cubemap array texture because of invalid parameters."); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CubemapArrayScripting::Apply", HasExplicitThis = true)] private extern void ApplyImpl(bool updateMipmaps, bool makeNoLongerReadable); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CubemapArrayScripting::GetPixels", HasExplicitThis = true, ThrowsException = true)] public extern Color[] GetPixels(CubemapFace face, int arrayElement, int miplevel); public Color[] GetPixels(CubemapFace face, int arrayElement) { return GetPixels(face, arrayElement, 0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CubemapArrayScripting::GetPixels32", HasExplicitThis = true, ThrowsException = true)] public extern Color32[] GetPixels32(CubemapFace face, int arrayElement, int miplevel); public Color32[] GetPixels32(CubemapFace face, int arrayElement) { return GetPixels32(face, arrayElement, 0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CubemapArrayScripting::SetPixels", HasExplicitThis = true, ThrowsException = true)] public extern void SetPixels([Unmarshalled] Color[] colors, CubemapFace face, int arrayElement, int miplevel); public void SetPixels(Color[] colors, CubemapFace face, int arrayElement) { SetPixels(colors, face, arrayElement, 0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CubemapArrayScripting::SetPixels32", HasExplicitThis = true, ThrowsException = true)] public extern void SetPixels32([Unmarshalled] Color32[] colors, CubemapFace face, int arrayElement, int miplevel); public void SetPixels32(Color32[] colors, CubemapFace face, int arrayElement) { SetPixels32(colors, face, arrayElement, 0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CubemapArrayScripting::SetPixelDataArray", HasExplicitThis = true, ThrowsException = true)] private extern bool SetPixelDataImplArray(Array data, int mipLevel, int face, int element, int elementSize, int dataArraySize, int sourceDataStartIndex = 0); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CubemapArrayScripting::SetPixelData", HasExplicitThis = true, ThrowsException = true)] private extern bool SetPixelDataImpl(IntPtr data, int mipLevel, int face, int element, int elementSize, int dataArraySize, int sourceDataStartIndex = 0); [MethodImpl(MethodImplOptions.InternalCall)] private extern IntPtr GetImageDataPointer(); [ExcludeFromDocs] public CubemapArray(int width, int cubemapCount, DefaultFormat format, TextureCreationFlags flags) : this(width, cubemapCount, SystemInfo.GetGraphicsFormat(format), flags) { } [ExcludeFromDocs] [RequiredByNativeCode] public CubemapArray(int width, int cubemapCount, GraphicsFormat format, TextureCreationFlags flags) : this(width, cubemapCount, format, flags, Texture.GenerateAllMips) { } [ExcludeFromDocs] public CubemapArray(int width, int cubemapCount, GraphicsFormat format, TextureCreationFlags flags, [UnityEngine.Internal.DefaultValue("-1")] int mipCount) { if (ValidateFormat(format, FormatUsage.Sample)) { ValidateIsNotCrunched(flags); Internal_Create(this, width, cubemapCount, mipCount, format, GetTextureColorSpace(format), flags); } } public CubemapArray(int width, int cubemapCount, TextureFormat textureFormat, int mipCount, bool linear) { if (ValidateFormat(textureFormat)) { GraphicsFormat graphicsFormat = GraphicsFormatUtility.GetGraphicsFormat(textureFormat, !linear); TextureCreationFlags textureCreationFlags = ((mipCount != 1) ? TextureCreationFlags.MipChain : TextureCreationFlags.None); if (GraphicsFormatUtility.IsCrunchFormat(textureFormat)) { textureCreationFlags |= TextureCreationFlags.Crunch; } ValidateIsNotCrunched(textureCreationFlags); Internal_Create(this, width, cubemapCount, mipCount, graphicsFormat, GetTextureColorSpace(linear), textureCreationFlags); } } public CubemapArray(int width, int cubemapCount, TextureFormat textureFormat, bool mipChain, [UnityEngine.Internal.DefaultValue("false")] bool linear) : this(width, cubemapCount, textureFormat, (!mipChain) ? 1 : (-1), linear) { } [ExcludeFromDocs] public CubemapArray(int width, int cubemapCount, TextureFormat textureFormat, bool mipChain) : this(width, cubemapCount, textureFormat, (!mipChain) ? 1 : (-1), linear: false) { } public void Apply([UnityEngine.Internal.DefaultValue("true")] bool updateMipmaps, [UnityEngine.Internal.DefaultValue("false")] bool makeNoLongerReadable) { if (!isReadable) { throw CreateNonReadableException(this); } ApplyImpl(updateMipmaps, makeNoLongerReadable); } [ExcludeFromDocs] public void Apply(bool updateMipmaps) { Apply(updateMipmaps, makeNoLongerReadable: false); } [ExcludeFromDocs] public void Apply() { Apply(updateMipmaps: true, makeNoLongerReadable: false); } public void SetPixelData(T[] data, int mipLevel, CubemapFace face, int element, [UnityEngine.Internal.DefaultValue("0")] int sourceDataStartIndex = 0) { if (sourceDataStartIndex < 0) { throw new UnityException("SetPixelData: sourceDataStartIndex cannot be less than 0."); } if (!isReadable) { throw CreateNonReadableException(this); } if (data == null || data.Length == 0) { throw new UnityException("No texture data provided to SetPixelData."); } SetPixelDataImplArray(data, mipLevel, (int)face, element, Marshal.SizeOf((object)data[0]), data.Length, sourceDataStartIndex); } public unsafe void SetPixelData(NativeArray data, int mipLevel, CubemapFace face, int element, [UnityEngine.Internal.DefaultValue("0")] int sourceDataStartIndex = 0) where T : struct { if (sourceDataStartIndex < 0) { throw new UnityException("SetPixelData: sourceDataStartIndex cannot be less than 0."); } if (!isReadable) { throw CreateNonReadableException(this); } if (!data.IsCreated || data.Length == 0) { throw new UnityException("No texture data provided to SetPixelData."); } SetPixelDataImpl((IntPtr)data.GetUnsafeReadOnlyPtr(), mipLevel, (int)face, element, UnsafeUtility.SizeOf(), data.Length, sourceDataStartIndex); } public unsafe NativeArray GetPixelData(int mipLevel, CubemapFace face, int element) where T : struct { if (!isReadable) { throw CreateNonReadableException(this); } if (mipLevel < 0 || mipLevel >= base.mipmapCount) { throw new ArgumentException("The passed in miplevel " + mipLevel + " is invalid. The valid range is 0 through " + (base.mipmapCount - 1)); } if (face < CubemapFace.PositiveX || face >= (CubemapFace)6) { throw new ArgumentException("The passed in face " + face.ToString() + " is invalid. The valid range is 0 through 5"); } if (element < 0 || element >= cubemapCount) { throw new ArgumentException("The passed in element " + element + " is invalid. The valid range is 0 through " + (cubemapCount - 1)); } int num = (int)(element * 6 + face); ulong pixelDataOffset = GetPixelDataOffset(base.mipmapCount, num); ulong pixelDataOffset2 = GetPixelDataOffset(mipLevel, num); ulong pixelDataSize = GetPixelDataSize(mipLevel, num); int num2 = UnsafeUtility.SizeOf(); ulong num3 = pixelDataSize / (ulong)num2; if (num3 > int.MaxValue) { throw CreateNativeArrayLengthOverflowException(); } IntPtr intPtr = new IntPtr((long)GetImageDataPointer() + ((long)pixelDataOffset * (long)num + (long)pixelDataOffset2)); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)intPtr, (int)num3, Allocator.None); } private static void ValidateIsNotCrunched(TextureCreationFlags flags) { if ((flags &= TextureCreationFlags.Crunch) != TextureCreationFlags.None) { throw new ArgumentException("Crunched TextureCubeArray is not supported."); } } } [NativeHeader("Runtime/Graphics/SparseTexture.h")] public sealed class SparseTexture : Texture { public extern int tileWidth { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern int tileHeight { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern bool isCreated { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("IsInitialized")] get; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "SparseTextureScripting::Create", ThrowsException = true)] private static extern void Internal_Create([Writable] SparseTexture mono, int width, int height, GraphicsFormat format, TextureColorSpace colorSpace, int mipCount); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "SparseTextureScripting::UpdateTile", HasExplicitThis = true)] public extern void UpdateTile(int tileX, int tileY, int miplevel, [Unmarshalled] Color32[] data); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "SparseTextureScripting::UpdateTileRaw", HasExplicitThis = true)] public extern void UpdateTileRaw(int tileX, int tileY, int miplevel, [Unmarshalled] byte[] data); public void UnloadTile(int tileX, int tileY, int miplevel) { UpdateTileRaw(tileX, tileY, miplevel, null); } internal bool ValidateFormat(TextureFormat format, int width, int height) { bool flag = ValidateFormat(format); if (flag && TextureFormat.PVRTC_RGB2 <= format && format <= TextureFormat.PVRTC_RGBA4 && (width != height || !Mathf.IsPowerOfTwo(width))) { throw new UnityException($"'{format.ToString()}' demands texture to be square and have power-of-two dimensions"); } return flag; } internal bool ValidateFormat(GraphicsFormat format, int width, int height) { bool flag = ValidateFormat(format, FormatUsage.Sparse); if (flag && GraphicsFormatUtility.IsPVRTCFormat(format) && (width != height || !Mathf.IsPowerOfTwo(width))) { throw new UnityException($"'{format.ToString()}' demands texture to be square and have power-of-two dimensions"); } return flag; } internal bool ValidateSize(int width, int height, GraphicsFormat format) { if (GraphicsFormatUtility.GetBlockSize(format) * (width / GraphicsFormatUtility.GetBlockWidth(format)) * (height / GraphicsFormatUtility.GetBlockHeight(format)) < 65536) { Debug.LogError("SparseTexture creation failed. The minimum size in bytes of a SparseTexture is 64KB.", this); return false; } return true; } private static void ValidateIsNotCrunched(TextureFormat textureFormat) { if (GraphicsFormatUtility.IsCrunchFormat(textureFormat)) { throw new ArgumentException("Crunched SparseTexture is not supported."); } } [ExcludeFromDocs] public SparseTexture(int width, int height, DefaultFormat format, int mipCount) : this(width, height, SystemInfo.GetGraphicsFormat(format), mipCount) { } [ExcludeFromDocs] public SparseTexture(int width, int height, GraphicsFormat format, int mipCount) { if (ValidateFormat(format, width, height) && ValidateSize(width, height, format)) { Internal_Create(this, width, height, format, GetTextureColorSpace(format), mipCount); } } [ExcludeFromDocs] public SparseTexture(int width, int height, TextureFormat textureFormat, int mipCount) : this(width, height, textureFormat, mipCount, linear: false) { } public SparseTexture(int width, int height, TextureFormat textureFormat, int mipCount, [UnityEngine.Internal.DefaultValue("false")] bool linear) { if (ValidateFormat(textureFormat, width, height)) { ValidateIsNotCrunched(textureFormat); GraphicsFormat format = GraphicsFormatUtility.GetGraphicsFormat(textureFormat, !linear); if (!SystemInfo.IsFormatSupported(format, FormatUsage.Sparse)) { Debug.LogError($"Creation of a SparseTexture with '{textureFormat}' is not supported on this platform."); } else if (ValidateSize(width, height, format)) { Internal_Create(this, width, height, format, GetTextureColorSpace(linear), mipCount); } } } } [UsedByNativeCode] [NativeHeader("Runtime/Graphics/RenderBufferManager.h")] [NativeHeader("Runtime/Graphics/GraphicsScriptBindings.h")] [NativeHeader("Runtime/Graphics/RenderTexture.h")] [NativeHeader("Runtime/Camera/Camera.h")] public class RenderTexture : Texture { public override extern int width { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public override extern int height { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public override extern TextureDimension dimension { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("ColorFormat")] public new extern GraphicsFormat graphicsFormat { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("MipMap")] public extern bool useMipMap { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("SRGBReadWrite")] public extern bool sRGB { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeProperty("VRUsage")] public extern VRTextureUsage vrUsage { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty("Memoryless")] public extern RenderTextureMemoryless memorylessMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public RenderTextureFormat format { get { if (graphicsFormat != GraphicsFormat.None) { return GraphicsFormatUtility.GetRenderTextureFormat(graphicsFormat); } return (GetDescriptor().shadowSamplingMode == ShadowSamplingMode.None) ? RenderTextureFormat.Depth : RenderTextureFormat.Shadowmap; } set { graphicsFormat = GraphicsFormatUtility.GetGraphicsFormat(value, sRGB); } } public extern GraphicsFormat stencilFormat { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern GraphicsFormat depthStencilFormat { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool autoGenerateMips { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int volumeDepth { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int antiAliasing { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool bindTextureMS { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool enableRandomWrite { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool useDynamicScale { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public bool isPowerOfTwo { get { return GetIsPowerOfTwo(); } set { } } public static RenderTexture active { get { return GetActive(); } set { SetActive(value); } } public RenderBuffer colorBuffer => GetColorBuffer(); public RenderBuffer depthBuffer => GetDepthBuffer(); public extern int depth { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderTextureScripting::GetDepth", HasExplicitThis = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderTextureScripting::SetDepth", HasExplicitThis = true)] set; } public RenderTextureDescriptor descriptor { get { return GetDescriptor(); } set { ValidateRenderTextureDesc(value); SetRenderTextureDescriptor(value); } } [Obsolete("Use RenderTexture.dimension instead.", false)] public bool isCubemap { get { return dimension == TextureDimension.Cube; } set { dimension = (value ? TextureDimension.Cube : TextureDimension.Tex2D); } } [Obsolete("Use RenderTexture.dimension instead.", false)] public bool isVolume { get { return dimension == TextureDimension.Tex3D; } set { dimension = (value ? TextureDimension.Tex3D : TextureDimension.Tex2D); } } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("RenderTexture.enabled is always now, no need to use it.", false)] public static bool enabled { get { return true; } set { } } [MethodImpl(MethodImplOptions.InternalCall)] private extern bool GetIsPowerOfTwo(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderTexture::GetActive")] private static extern RenderTexture GetActive(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderTextureScripting::SetActive")] private static extern void SetActive(RenderTexture rt); [FreeFunction(Name = "RenderTextureScripting::GetColorBuffer", HasExplicitThis = true)] private RenderBuffer GetColorBuffer() { GetColorBuffer_Injected(out var ret); return ret; } [FreeFunction(Name = "RenderTextureScripting::GetDepthBuffer", HasExplicitThis = true)] private RenderBuffer GetDepthBuffer() { GetDepthBuffer_Injected(out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetMipMapCount(int count); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetShadowSamplingMode(ShadowSamplingMode samplingMode); [MethodImpl(MethodImplOptions.InternalCall)] public extern IntPtr GetNativeDepthBufferPtr(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void DiscardContents(bool discardColor, bool discardDepth); [MethodImpl(MethodImplOptions.InternalCall)] [Obsolete("This function has no effect.", false)] public extern void MarkRestoreExpected(); public void DiscardContents() { DiscardContents(discardColor: true, discardDepth: true); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("ResolveAntiAliasedSurface")] private extern void ResolveAA(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("ResolveAntiAliasedSurface")] private extern void ResolveAATo(RenderTexture rt); public void ResolveAntiAliasedSurface() { ResolveAA(); } public void ResolveAntiAliasedSurface(RenderTexture target) { ResolveAATo(target); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RenderTextureScripting::SetGlobalShaderProperty", HasExplicitThis = true)] public extern void SetGlobalShaderProperty(string propertyName); [MethodImpl(MethodImplOptions.InternalCall)] public extern bool Create(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void Release(); [MethodImpl(MethodImplOptions.InternalCall)] public extern bool IsCreated(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void GenerateMips(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] public extern void ConvertToEquirect(RenderTexture equirect, Camera.MonoOrStereoscopicEye eye = Camera.MonoOrStereoscopicEye.Mono); [MethodImpl(MethodImplOptions.InternalCall)] internal extern void SetSRGBReadWrite(bool srgb); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderTextureScripting::Create")] private static extern void Internal_Create([Writable] RenderTexture rt); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderTextureSupportsStencil")] public static extern bool SupportsStencil(RenderTexture rt); [NativeName("SetRenderTextureDescFromScript")] private void SetRenderTextureDescriptor(RenderTextureDescriptor desc) { SetRenderTextureDescriptor_Injected(ref desc); } [NativeName("GetRenderTextureDesc")] private RenderTextureDescriptor GetDescriptor() { GetDescriptor_Injected(out var ret); return ret; } [FreeFunction("GetRenderBufferManager().GetTextures().GetTempBuffer")] private static RenderTexture GetTemporary_Internal(RenderTextureDescriptor desc) { return GetTemporary_Internal_Injected(ref desc); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetRenderBufferManager().GetTextures().ReleaseTempBuffer")] public static extern void ReleaseTemporary(RenderTexture temp); [RequiredByNativeCode] protected internal RenderTexture() { } public RenderTexture(RenderTextureDescriptor desc) { ValidateRenderTextureDesc(desc); Internal_Create(this); SetRenderTextureDescriptor(desc); } public RenderTexture(RenderTexture textureToCopy) { if (textureToCopy == null) { throw new ArgumentNullException("textureToCopy"); } ValidateRenderTextureDesc(textureToCopy.descriptor); Internal_Create(this); SetRenderTextureDescriptor(textureToCopy.descriptor); } [ExcludeFromDocs] public RenderTexture(int width, int height, int depth, DefaultFormat format) : this(width, height, GetDefaultColorFormat(format), GetDefaultDepthStencilFormat(format, depth), Texture.GenerateAllMips) { } [ExcludeFromDocs] public RenderTexture(int width, int height, int depth, GraphicsFormat format) : this(width, height, depth, format, Texture.GenerateAllMips) { } [ExcludeFromDocs] public RenderTexture(int width, int height, int depth, GraphicsFormat format, int mipCount) { if (format == GraphicsFormat.None || ValidateFormat(format, FormatUsage.Render)) { Internal_Create(this); depthStencilFormat = GetDepthStencilFormatLegacy(depth, format); this.width = width; this.height = height; graphicsFormat = format; SetMipMapCount(mipCount); SetSRGBReadWrite(GraphicsFormatUtility.IsSRGBFormat(format)); } } [ExcludeFromDocs] public RenderTexture(int width, int height, GraphicsFormat colorFormat, GraphicsFormat depthStencilFormat, int mipCount) { if (colorFormat == GraphicsFormat.None || ValidateFormat(colorFormat, FormatUsage.Render)) { Internal_Create(this); this.width = width; this.height = height; this.depthStencilFormat = depthStencilFormat; graphicsFormat = colorFormat; SetMipMapCount(mipCount); SetSRGBReadWrite(GraphicsFormatUtility.IsSRGBFormat(colorFormat)); } } [ExcludeFromDocs] public RenderTexture(int width, int height, GraphicsFormat colorFormat, GraphicsFormat depthStencilFormat) : this(width, height, colorFormat, depthStencilFormat, Texture.GenerateAllMips) { } public RenderTexture(int width, int height, int depth, [UnityEngine.Internal.DefaultValue("RenderTextureFormat.Default")] RenderTextureFormat format, [UnityEngine.Internal.DefaultValue("RenderTextureReadWrite.Default")] RenderTextureReadWrite readWrite) { Initialize(width, height, depth, format, readWrite, Texture.GenerateAllMips); } [ExcludeFromDocs] public RenderTexture(int width, int height, int depth, RenderTextureFormat format) : this(width, height, depth, format, Texture.GenerateAllMips) { } [ExcludeFromDocs] public RenderTexture(int width, int height, int depth) : this(width, height, depth, RenderTextureFormat.Default) { } [ExcludeFromDocs] public RenderTexture(int width, int height, int depth, RenderTextureFormat format, int mipCount) { Initialize(width, height, depth, format, RenderTextureReadWrite.Default, mipCount); } private void Initialize(int width, int height, int depth, RenderTextureFormat format, RenderTextureReadWrite readWrite, int mipCount) { GraphicsFormat compatibleFormat = GetCompatibleFormat(format, readWrite); GraphicsFormat depthStencilFormatLegacy = GetDepthStencilFormatLegacy(depth, format); if (compatibleFormat == GraphicsFormat.None || ValidateFormat(compatibleFormat, FormatUsage.Render)) { Internal_Create(this); this.width = width; this.height = height; depthStencilFormat = depthStencilFormatLegacy; graphicsFormat = compatibleFormat; SetMipMapCount(mipCount); SetSRGBReadWrite(GraphicsFormatUtility.IsSRGBFormat(compatibleFormat)); } } internal static GraphicsFormat GetDepthStencilFormatLegacy(int depthBits, GraphicsFormat colorFormat) { return (colorFormat == GraphicsFormat.ShadowAuto) ? GraphicsFormatUtility.GetDepthStencilFormat(depthBits, 0) : GraphicsFormatUtility.GetDepthStencilFormat(depthBits); } internal static GraphicsFormat GetDepthStencilFormatLegacy(int depthBits, RenderTextureFormat format) { return GetDepthStencilFormatLegacy(depthBits, format == RenderTextureFormat.Shadowmap); } internal static GraphicsFormat GetDepthStencilFormatLegacy(int depthBits, DefaultFormat format) { return GetDepthStencilFormatLegacy(depthBits, format == DefaultFormat.Shadow); } internal static GraphicsFormat GetDepthStencilFormatLegacy(int depthBits, bool requestedShadowMap) { return requestedShadowMap ? GraphicsFormatUtility.GetDepthStencilFormat(depthBits, 0) : GraphicsFormatUtility.GetDepthStencilFormat(depthBits); } private static void ValidateRenderTextureDesc(RenderTextureDescriptor desc) { if (desc.graphicsFormat == GraphicsFormat.None && desc.depthStencilFormat == GraphicsFormat.None) { throw new ArgumentException("RenderTextureDesc graphicsFormat and depthStencilFormat cannot both be None."); } if (desc.graphicsFormat != GraphicsFormat.None && !SystemInfo.IsFormatSupported(desc.graphicsFormat, FormatUsage.Render)) { throw new ArgumentException("RenderTextureDesc graphicsFormat must be a supported GraphicsFormat. " + desc.graphicsFormat.ToString() + " is not supported on this platform.", "desc.graphicsFormat"); } if (desc.depthStencilFormat != GraphicsFormat.None && !GraphicsFormatUtility.IsDepthFormat(desc.depthStencilFormat) && !GraphicsFormatUtility.IsStencilFormat(desc.depthStencilFormat)) { throw new ArgumentException("RenderTextureDesc depthStencilFormat must be a supported depth/stencil GraphicsFormat. " + desc.depthStencilFormat.ToString() + " is not supported on this platform.", "desc.depthStencilFormat"); } if (desc.width <= 0) { throw new ArgumentException("RenderTextureDesc width must be greater than zero.", "desc.width"); } if (desc.height <= 0) { throw new ArgumentException("RenderTextureDesc height must be greater than zero.", "desc.height"); } if (desc.volumeDepth <= 0) { throw new ArgumentException("RenderTextureDesc volumeDepth must be greater than zero.", "desc.volumeDepth"); } if (desc.msaaSamples != 1 && desc.msaaSamples != 2 && desc.msaaSamples != 4 && desc.msaaSamples != 8) { throw new ArgumentException("RenderTextureDesc msaaSamples must be 1, 2, 4, or 8.", "desc.msaaSamples"); } if (desc.dimension == TextureDimension.CubeArray && desc.volumeDepth % 6 != 0) { throw new ArgumentException("RenderTextureDesc volumeDepth must be a multiple of 6 when dimension is CubeArray", "desc.volumeDepth"); } if (desc.graphicsFormat != GraphicsFormat.ShadowAuto && desc.graphicsFormat != GraphicsFormat.DepthAuto && (GraphicsFormatUtility.IsDepthFormat(desc.graphicsFormat) || GraphicsFormatUtility.IsStencilFormat(desc.graphicsFormat))) { throw new ArgumentException("RenderTextureDesc graphicsFormat must not be a depth/stencil format. " + desc.graphicsFormat.ToString() + " is not supported.", "desc.graphicsFormat"); } } internal static GraphicsFormat GetDefaultColorFormat(DefaultFormat format) { return format switch { DefaultFormat.DepthStencil => GraphicsFormat.DepthAuto, DefaultFormat.Shadow => GraphicsFormat.ShadowAuto, _ => SystemInfo.GetGraphicsFormat(format), }; } internal static GraphicsFormat GetDefaultDepthStencilFormat(DefaultFormat format, int depth) { if ((uint)(format - 2) <= 1u) { return SystemInfo.GetGraphicsFormat(format); } return GetDepthStencilFormatLegacy(depth, format); } internal static GraphicsFormat GetCompatibleFormat(RenderTextureFormat renderTextureFormat, RenderTextureReadWrite readWrite) { GraphicsFormat graphicsFormat = GraphicsFormatUtility.GetGraphicsFormat(renderTextureFormat, readWrite); GraphicsFormat compatibleFormat = SystemInfo.GetCompatibleFormat(graphicsFormat, FormatUsage.Render); if (graphicsFormat == compatibleFormat) { return graphicsFormat; } Debug.LogWarning($"'{graphicsFormat.ToString()}' is not supported. RenderTexture::GetTemporary fallbacks to {compatibleFormat.ToString()} format on this platform. Use 'SystemInfo.IsFormatSupported' C# API to check format support."); return compatibleFormat; } public static RenderTexture GetTemporary(RenderTextureDescriptor desc) { ValidateRenderTextureDesc(desc); desc.createdFromScript = true; return GetTemporary_Internal(desc); } private static RenderTexture GetTemporaryImpl(int width, int height, GraphicsFormat depthStencilFormat, GraphicsFormat colorFormat, int antiAliasing = 1, RenderTextureMemoryless memorylessMode = RenderTextureMemoryless.None, VRTextureUsage vrUsage = VRTextureUsage.None, bool useDynamicScale = false) { RenderTextureDescriptor desc = new RenderTextureDescriptor(width, height, colorFormat, depthStencilFormat); desc.msaaSamples = antiAliasing; desc.memoryless = memorylessMode; desc.vrUsage = vrUsage; desc.useDynamicScale = useDynamicScale; return GetTemporary(desc); } [ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, GraphicsFormat format, [UnityEngine.Internal.DefaultValue("1")] int antiAliasing, [UnityEngine.Internal.DefaultValue("RenderTextureMemoryless.None")] RenderTextureMemoryless memorylessMode, [UnityEngine.Internal.DefaultValue("VRTextureUsage.None")] VRTextureUsage vrUsage, [UnityEngine.Internal.DefaultValue("false")] bool useDynamicScale) { return GetTemporaryImpl(width, height, GetDepthStencilFormatLegacy(depthBuffer, format), format, antiAliasing, memorylessMode, vrUsage, useDynamicScale); } [ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, GraphicsFormat format, int antiAliasing, RenderTextureMemoryless memorylessMode, VRTextureUsage vrUsage) { return GetTemporary(width, height, depthBuffer, format, antiAliasing, memorylessMode, vrUsage, useDynamicScale: false); } [ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, GraphicsFormat format, int antiAliasing, RenderTextureMemoryless memorylessMode) { return GetTemporary(width, height, depthBuffer, format, antiAliasing, memorylessMode, VRTextureUsage.None); } [ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, GraphicsFormat format, int antiAliasing) { return GetTemporary(width, height, depthBuffer, format, antiAliasing, RenderTextureMemoryless.None); } [ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, GraphicsFormat format) { return GetTemporary(width, height, depthBuffer, format, 1); } public static RenderTexture GetTemporary(int width, int height, [UnityEngine.Internal.DefaultValue("0")] int depthBuffer, [UnityEngine.Internal.DefaultValue("RenderTextureFormat.Default")] RenderTextureFormat format, [UnityEngine.Internal.DefaultValue("RenderTextureReadWrite.Default")] RenderTextureReadWrite readWrite, [UnityEngine.Internal.DefaultValue("1")] int antiAliasing, [UnityEngine.Internal.DefaultValue("RenderTextureMemoryless.None")] RenderTextureMemoryless memorylessMode, [UnityEngine.Internal.DefaultValue("VRTextureUsage.None")] VRTextureUsage vrUsage, [UnityEngine.Internal.DefaultValue("false")] bool useDynamicScale) { GraphicsFormat compatibleFormat = GetCompatibleFormat(format, readWrite); GraphicsFormat depthStencilFormatLegacy = GetDepthStencilFormatLegacy(depthBuffer, format); return GetTemporaryImpl(width, height, depthStencilFormatLegacy, compatibleFormat, antiAliasing, memorylessMode, vrUsage, useDynamicScale); } [ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, RenderTextureFormat format, RenderTextureReadWrite readWrite, int antiAliasing, RenderTextureMemoryless memorylessMode, VRTextureUsage vrUsage) { return GetTemporary(width, height, depthBuffer, format, readWrite, antiAliasing, memorylessMode, vrUsage, useDynamicScale: false); } [ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, RenderTextureFormat format, RenderTextureReadWrite readWrite, int antiAliasing, RenderTextureMemoryless memorylessMode) { return GetTemporary(width, height, depthBuffer, format, readWrite, antiAliasing, memorylessMode, VRTextureUsage.None); } [ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, RenderTextureFormat format, RenderTextureReadWrite readWrite, int antiAliasing) { return GetTemporary(width, height, depthBuffer, format, readWrite, antiAliasing, RenderTextureMemoryless.None); } [ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, RenderTextureFormat format, RenderTextureReadWrite readWrite) { return GetTemporary(width, height, depthBuffer, format, readWrite, 1); } [ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer, RenderTextureFormat format) { return GetTemporary(width, height, depthBuffer, format, RenderTextureReadWrite.Default); } [ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height, int depthBuffer) { return GetTemporary(width, height, depthBuffer, RenderTextureFormat.Default); } [ExcludeFromDocs] public static RenderTexture GetTemporary(int width, int height) { return GetTemporary(width, height, 0); } [Obsolete("GetTexelOffset always returns zero now, no point in using it.", false)] [EditorBrowsable(EditorBrowsableState.Never)] public Vector2 GetTexelOffset() { return Vector2.zero; } [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetColorBuffer_Injected(out RenderBuffer ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetDepthBuffer_Injected(out RenderBuffer ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetRenderTextureDescriptor_Injected(ref RenderTextureDescriptor desc); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetDescriptor_Injected(out RenderTextureDescriptor ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern RenderTexture GetTemporary_Internal_Injected(ref RenderTextureDescriptor desc); } [Serializable] [UsedByNativeCode] public struct CustomRenderTextureUpdateZone { public Vector3 updateZoneCenter; public Vector3 updateZoneSize; public float rotation; public int passIndex; public bool needSwap; } [NativeHeader("Runtime/Graphics/CustomRenderTexture.h")] [UsedByNativeCode] public sealed class CustomRenderTexture : RenderTexture { public extern Material material { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Material initializationMaterial { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern Texture initializationTexture { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern CustomRenderTextureInitializationSource initializationSource { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Color initializationColor { get { get_initializationColor_Injected(out var ret); return ret; } set { set_initializationColor_Injected(ref value); } } public extern CustomRenderTextureUpdateMode updateMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern CustomRenderTextureUpdateMode initializationMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern CustomRenderTextureUpdateZoneSpace updateZoneSpace { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int shaderPass { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern uint cubemapFaceMask { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool doubleBuffered { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool wrapUpdateZones { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern float updatePeriod { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CustomRenderTextureScripting::Create")] private static extern void Internal_CreateCustomRenderTexture([Writable] CustomRenderTexture rt); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("TriggerUpdate")] private extern void TriggerUpdate(int count); public void Update(int count) { CustomRenderTextureManager.InvokeTriggerUpdate(this, count); TriggerUpdate(count); } public void Update() { Update(1); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("TriggerInitialization")] private extern void TriggerInitialization(); public void Initialize() { TriggerInitialization(); CustomRenderTextureManager.InvokeTriggerInitialize(this); } [MethodImpl(MethodImplOptions.InternalCall)] public extern void ClearUpdateZones(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CustomRenderTextureScripting::GetUpdateZonesInternal", HasExplicitThis = true)] internal extern void GetUpdateZonesInternal([NotNull("ArgumentNullException")] object updateZones); public void GetUpdateZones(List updateZones) { GetUpdateZonesInternal(updateZones); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CustomRenderTextureScripting::SetUpdateZonesInternal", HasExplicitThis = true)] private extern void SetUpdateZonesInternal([Unmarshalled] CustomRenderTextureUpdateZone[] updateZones); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "CustomRenderTextureScripting::GetDoubleBufferRenderTexture", HasExplicitThis = true)] public extern RenderTexture GetDoubleBufferRenderTexture(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void EnsureDoubleBufferConsistency(); public void SetUpdateZones(CustomRenderTextureUpdateZone[] updateZones) { if (updateZones == null) { throw new ArgumentNullException("updateZones"); } SetUpdateZonesInternal(updateZones); } public CustomRenderTexture(int width, int height, RenderTextureFormat format, [UnityEngine.Internal.DefaultValue("RenderTextureReadWrite.Default")] RenderTextureReadWrite readWrite) : this(width, height, RenderTexture.GetCompatibleFormat(format, readWrite)) { } [ExcludeFromDocs] public CustomRenderTexture(int width, int height, RenderTextureFormat format) : this(width, height, format, RenderTextureReadWrite.Default) { } [ExcludeFromDocs] public CustomRenderTexture(int width, int height) : this(width, height, SystemInfo.GetGraphicsFormat(DefaultFormat.LDR)) { } [ExcludeFromDocs] public CustomRenderTexture(int width, int height, [UnityEngine.Internal.DefaultValue("DefaultFormat.LDR")] DefaultFormat defaultFormat) : this(width, height, RenderTexture.GetDefaultColorFormat(defaultFormat)) { if (defaultFormat == DefaultFormat.DepthStencil || defaultFormat == DefaultFormat.Shadow) { base.depthStencilFormat = SystemInfo.GetGraphicsFormat(defaultFormat); } } [ExcludeFromDocs] public CustomRenderTexture(int width, int height, GraphicsFormat format) { if (format == GraphicsFormat.None || ValidateFormat(format, FormatUsage.Render)) { Internal_CreateCustomRenderTexture(this); this.width = width; this.height = height; base.graphicsFormat = format; SetSRGBReadWrite(GraphicsFormatUtility.IsSRGBFormat(format)); } } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_initializationColor_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_initializationColor_Injected(ref Color value); } public struct RenderTextureDescriptor { private GraphicsFormat _graphicsFormat; private RenderTextureCreationFlags _flags; public int width { get; set; } public int height { get; set; } public int msaaSamples { get; set; } public int volumeDepth { get; set; } public int mipCount { get; set; } public GraphicsFormat graphicsFormat { get { return _graphicsFormat; } set { _graphicsFormat = value; SetOrClearRenderTextureCreationFlag(GraphicsFormatUtility.IsSRGBFormat(value), RenderTextureCreationFlags.SRGB); depthBufferBits = depthBufferBits; } } public GraphicsFormat stencilFormat { get; set; } public GraphicsFormat depthStencilFormat { get; set; } public RenderTextureFormat colorFormat { get { if (graphicsFormat != GraphicsFormat.None) { return GraphicsFormatUtility.GetRenderTextureFormat(graphicsFormat); } return (shadowSamplingMode == ShadowSamplingMode.None) ? RenderTextureFormat.Depth : RenderTextureFormat.Shadowmap; } set { GraphicsFormat format = GraphicsFormatUtility.GetGraphicsFormat(value, sRGB); graphicsFormat = SystemInfo.GetCompatibleFormat(format, FormatUsage.Render); } } public bool sRGB { get { return GraphicsFormatUtility.IsSRGBFormat(graphicsFormat); } set { graphicsFormat = ((value && QualitySettings.activeColorSpace == ColorSpace.Linear && colorFormat != RenderTextureFormat.R8 && colorFormat != RenderTextureFormat.RG16) ? GraphicsFormatUtility.GetSRGBFormat(graphicsFormat) : GraphicsFormatUtility.GetLinearFormat(graphicsFormat)); } } public int depthBufferBits { get { return GraphicsFormatUtility.GetDepthBits(depthStencilFormat); } set { depthStencilFormat = RenderTexture.GetDepthStencilFormatLegacy(value, graphicsFormat); } } public TextureDimension dimension { get; set; } public ShadowSamplingMode shadowSamplingMode { get; set; } public VRTextureUsage vrUsage { get; set; } public RenderTextureCreationFlags flags => _flags; public RenderTextureMemoryless memoryless { get; set; } public bool useMipMap { get { return (_flags & RenderTextureCreationFlags.MipMap) != 0; } set { SetOrClearRenderTextureCreationFlag(value, RenderTextureCreationFlags.MipMap); } } public bool autoGenerateMips { get { return (_flags & RenderTextureCreationFlags.AutoGenerateMips) != 0; } set { SetOrClearRenderTextureCreationFlag(value, RenderTextureCreationFlags.AutoGenerateMips); } } public bool enableRandomWrite { get { return (_flags & RenderTextureCreationFlags.EnableRandomWrite) != 0; } set { SetOrClearRenderTextureCreationFlag(value, RenderTextureCreationFlags.EnableRandomWrite); } } public bool bindMS { get { return (_flags & RenderTextureCreationFlags.BindMS) != 0; } set { SetOrClearRenderTextureCreationFlag(value, RenderTextureCreationFlags.BindMS); } } internal bool createdFromScript { get { return (_flags & RenderTextureCreationFlags.CreatedFromScript) != 0; } set { SetOrClearRenderTextureCreationFlag(value, RenderTextureCreationFlags.CreatedFromScript); } } public bool useDynamicScale { get { return (_flags & RenderTextureCreationFlags.DynamicallyScalable) != 0; } set { SetOrClearRenderTextureCreationFlag(value, RenderTextureCreationFlags.DynamicallyScalable); } } [ExcludeFromDocs] public RenderTextureDescriptor(int width, int height) : this(width, height, RenderTextureFormat.Default) { } [ExcludeFromDocs] public RenderTextureDescriptor(int width, int height, RenderTextureFormat colorFormat) : this(width, height, colorFormat, 0) { } [ExcludeFromDocs] public RenderTextureDescriptor(int width, int height, RenderTextureFormat colorFormat, int depthBufferBits) : this(width, height, colorFormat, depthBufferBits, Texture.GenerateAllMips) { } [ExcludeFromDocs] public RenderTextureDescriptor(int width, int height, GraphicsFormat colorFormat, int depthBufferBits) : this(width, height, colorFormat, depthBufferBits, Texture.GenerateAllMips) { } [ExcludeFromDocs] public RenderTextureDescriptor(int width, int height, RenderTextureFormat colorFormat, int depthBufferBits, int mipCount) : this(width, height, colorFormat, depthBufferBits, mipCount, RenderTextureReadWrite.Linear) { } public RenderTextureDescriptor(int width, int height, [UnityEngine.Internal.DefaultValue("RenderTextureFormat.Default")] RenderTextureFormat colorFormat, [UnityEngine.Internal.DefaultValue("0")] int depthBufferBits, [UnityEngine.Internal.DefaultValue("Texture.GenerateAllMips")] int mipCount, [UnityEngine.Internal.DefaultValue("RenderTextureReadWrite.Linear")] RenderTextureReadWrite readWrite) { GraphicsFormat format = GraphicsFormatUtility.GetGraphicsFormat(colorFormat, readWrite); GraphicsFormat compatibleFormat = SystemInfo.GetCompatibleFormat(format, FormatUsage.Render); this = new RenderTextureDescriptor(width, height, compatibleFormat, RenderTexture.GetDepthStencilFormatLegacy(depthBufferBits, colorFormat), mipCount); } [ExcludeFromDocs] public RenderTextureDescriptor(int width, int height, GraphicsFormat colorFormat, int depthBufferBits, int mipCount) { this = default(RenderTextureDescriptor); _flags = RenderTextureCreationFlags.AutoGenerateMips | RenderTextureCreationFlags.AllowVerticalFlip; this.width = width; this.height = height; volumeDepth = 1; msaaSamples = 1; graphicsFormat = colorFormat; depthStencilFormat = RenderTexture.GetDepthStencilFormatLegacy(depthBufferBits, colorFormat); this.mipCount = mipCount; dimension = TextureDimension.Tex2D; shadowSamplingMode = ShadowSamplingMode.None; vrUsage = VRTextureUsage.None; memoryless = RenderTextureMemoryless.None; } [ExcludeFromDocs] public RenderTextureDescriptor(int width, int height, GraphicsFormat colorFormat, GraphicsFormat depthStencilFormat) : this(width, height, colorFormat, depthStencilFormat, Texture.GenerateAllMips) { } [ExcludeFromDocs] public RenderTextureDescriptor(int width, int height, GraphicsFormat colorFormat, GraphicsFormat depthStencilFormat, int mipCount) { this = default(RenderTextureDescriptor); _flags = RenderTextureCreationFlags.AutoGenerateMips | RenderTextureCreationFlags.AllowVerticalFlip; this.width = width; this.height = height; volumeDepth = 1; msaaSamples = 1; graphicsFormat = colorFormat; this.depthStencilFormat = depthStencilFormat; this.mipCount = mipCount; dimension = TextureDimension.Tex2D; shadowSamplingMode = ShadowSamplingMode.None; vrUsage = VRTextureUsage.None; memoryless = RenderTextureMemoryless.None; } private void SetOrClearRenderTextureCreationFlag(bool value, RenderTextureCreationFlags flag) { if (value) { _flags |= flag; } else { _flags &= ~flag; } } } [Serializable] [NativeHeader("Runtime/Export/Hashing/Hash128.bindings.h")] [UsedByNativeCode] [NativeHeader("Runtime/Utilities/Hash128.h")] public struct Hash128 : IComparable, IComparable, IEquatable { internal ulong u64_0; internal ulong u64_1; private const ulong kConst = 16045690984833335023uL; public bool isValid => u64_0 != 0L || u64_1 != 0; public Hash128(uint u32_0, uint u32_1, uint u32_2, uint u32_3) { u64_0 = ((ulong)u32_1 << 32) | u32_0; u64_1 = ((ulong)u32_3 << 32) | u32_2; } public Hash128(ulong u64_0, ulong u64_1) { this.u64_0 = u64_0; this.u64_1 = u64_1; } public int CompareTo(Hash128 rhs) { if (this < rhs) { return -1; } if (this > rhs) { return 1; } return 0; } public override string ToString() { return Hash128ToStringImpl(this); } [FreeFunction("StringToHash128", IsThreadSafe = true)] public static Hash128 Parse(string hashString) { Parse_Injected(hashString, out var ret); return ret; } [FreeFunction("Hash128ToString", IsThreadSafe = true)] private static string Hash128ToStringImpl(Hash128 hash) { return Hash128ToStringImpl_Injected(ref hash); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ComputeHash128FromScriptString", IsThreadSafe = true)] private static extern void ComputeFromString(string data, ref Hash128 hash); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ComputeHash128FromScriptPointer", IsThreadSafe = true)] private static extern void ComputeFromPtr(IntPtr data, int start, int count, int elemSize, ref Hash128 hash); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ComputeHash128FromScriptArray", IsThreadSafe = true)] private static extern void ComputeFromArray(Array data, int start, int count, int elemSize, ref Hash128 hash); public static Hash128 Compute(string data) { Hash128 hash = default(Hash128); ComputeFromString(data, ref hash); return hash; } public unsafe static Hash128 Compute(NativeArray data) where T : struct { Hash128 hash = default(Hash128); ComputeFromPtr((IntPtr)data.GetUnsafeReadOnlyPtr(), 0, data.Length, UnsafeUtility.SizeOf(), ref hash); return hash; } public unsafe static Hash128 Compute(NativeArray data, int start, int count) where T : struct { if (start < 0 || count < 0 || start + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (start:{start} count:{count})"); } Hash128 hash = default(Hash128); ComputeFromPtr((IntPtr)data.GetUnsafeReadOnlyPtr(), start, count, UnsafeUtility.SizeOf(), ref hash); return hash; } public static Hash128 Compute(T[] data) where T : struct { if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException("Array passed to Compute must be blittable.\n" + UnsafeUtility.GetReasonForArrayNonBlittable(data)); } Hash128 hash = default(Hash128); ComputeFromArray(data, 0, data.Length, UnsafeUtility.SizeOf(), ref hash); return hash; } public static Hash128 Compute(T[] data, int start, int count) where T : struct { if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException("Array passed to Compute must be blittable.\n" + UnsafeUtility.GetReasonForArrayNonBlittable(data)); } if (start < 0 || count < 0 || start + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (start:{start} count:{count})"); } Hash128 hash = default(Hash128); ComputeFromArray(data, start, count, UnsafeUtility.SizeOf(), ref hash); return hash; } public static Hash128 Compute(List data) where T : struct { if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException(string.Format("List<{0}> passed to {1} must be blittable.\n{2}", typeof(T), "Compute", UnsafeUtility.GetReasonForGenericListNonBlittable())); } Hash128 hash = default(Hash128); ComputeFromArray(NoAllocHelpers.ExtractArrayFromList(data), 0, data.Count, UnsafeUtility.SizeOf(), ref hash); return hash; } public static Hash128 Compute(List data, int start, int count) where T : struct { if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException(string.Format("List<{0}> passed to {1} must be blittable.\n{2}", typeof(T), "Compute", UnsafeUtility.GetReasonForGenericListNonBlittable())); } if (start < 0 || count < 0 || start + count > data.Count) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (start:{start} count:{count})"); } Hash128 hash = default(Hash128); ComputeFromArray(NoAllocHelpers.ExtractArrayFromList(data), start, count, UnsafeUtility.SizeOf(), ref hash); return hash; } public unsafe static Hash128 Compute(ref T val) where T : unmanaged { fixed (T* ptr = &val) { void* ptr2 = ptr; Hash128 hash = default(Hash128); ComputeFromPtr((IntPtr)ptr2, 0, 1, UnsafeUtility.SizeOf(), ref hash); return hash; } } public static Hash128 Compute(int val) { Hash128 result = default(Hash128); result.Append(val); return result; } public static Hash128 Compute(float val) { Hash128 result = default(Hash128); result.Append(val); return result; } public unsafe static Hash128 Compute(void* data, ulong size) { Hash128 hash = default(Hash128); ComputeFromPtr(new IntPtr(data), 0, (int)size, 1, ref hash); return hash; } public void Append(string data) { ComputeFromString(data, ref this); } public unsafe void Append(NativeArray data) where T : struct { ComputeFromPtr((IntPtr)data.GetUnsafeReadOnlyPtr(), 0, data.Length, UnsafeUtility.SizeOf(), ref this); } public unsafe void Append(NativeArray data, int start, int count) where T : struct { if (start < 0 || count < 0 || start + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (start:{start} count:{count})"); } ComputeFromPtr((IntPtr)data.GetUnsafeReadOnlyPtr(), start, count, UnsafeUtility.SizeOf(), ref this); } public void Append(T[] data) where T : struct { if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException("Array passed to Append must be blittable.\n" + UnsafeUtility.GetReasonForArrayNonBlittable(data)); } ComputeFromArray(data, 0, data.Length, UnsafeUtility.SizeOf(), ref this); } public void Append(T[] data, int start, int count) where T : struct { if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException("Array passed to Append must be blittable.\n" + UnsafeUtility.GetReasonForArrayNonBlittable(data)); } if (start < 0 || count < 0 || start + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (start:{start} count:{count})"); } ComputeFromArray(data, start, count, UnsafeUtility.SizeOf(), ref this); } public void Append(List data) where T : struct { if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException(string.Format("List<{0}> passed to {1} must be blittable.\n{2}", typeof(T), "Append", UnsafeUtility.GetReasonForGenericListNonBlittable())); } ComputeFromArray(NoAllocHelpers.ExtractArrayFromList(data), 0, data.Count, UnsafeUtility.SizeOf(), ref this); } public void Append(List data, int start, int count) where T : struct { if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException(string.Format("List<{0}> passed to {1} must be blittable.\n{2}", typeof(T), "Append", UnsafeUtility.GetReasonForGenericListNonBlittable())); } if (start < 0 || count < 0 || start + count > data.Count) { throw new ArgumentOutOfRangeException($"Bad start/count arguments (start:{start} count:{count})"); } ComputeFromArray(NoAllocHelpers.ExtractArrayFromList(data), start, count, UnsafeUtility.SizeOf(), ref this); } public unsafe void Append(ref T val) where T : unmanaged { fixed (T* ptr = &val) { void* ptr2 = ptr; ComputeFromPtr((IntPtr)ptr2, 0, 1, UnsafeUtility.SizeOf(), ref this); } } public void Append(int val) { ShortHash4((uint)val); } public unsafe void Append(float val) { ShortHash4(*(uint*)(&val)); } public unsafe void Append(void* data, ulong size) { ComputeFromPtr(new IntPtr(data), 0, (int)size, 1, ref this); } public override bool Equals(object obj) { return obj is Hash128 && this == (Hash128)obj; } public bool Equals(Hash128 obj) { return this == obj; } public override int GetHashCode() { return u64_0.GetHashCode() ^ u64_1.GetHashCode(); } public int CompareTo(object obj) { if (obj == null || !(obj is Hash128)) { return 1; } Hash128 rhs = (Hash128)obj; return CompareTo(rhs); } public static bool operator ==(Hash128 hash1, Hash128 hash2) { return hash1.u64_0 == hash2.u64_0 && hash1.u64_1 == hash2.u64_1; } public static bool operator !=(Hash128 hash1, Hash128 hash2) { return !(hash1 == hash2); } public static bool operator <(Hash128 x, Hash128 y) { if (x.u64_0 != y.u64_0) { return x.u64_0 < y.u64_0; } return x.u64_1 < y.u64_1; } public static bool operator >(Hash128 x, Hash128 y) { if (x < y) { return false; } if (x == y) { return false; } return true; } private void ShortHash4(uint data) { ulong h = u64_0; ulong h2 = u64_1; ulong num = 16045690984833335023uL; ulong num2 = 16045690984833335023uL; num2 += 288230376151711744L; num += data; ShortEnd(ref h, ref h2, ref num, ref num2); u64_0 = h; u64_1 = h2; } private static void ShortEnd(ref ulong h0, ref ulong h1, ref ulong h2, ref ulong h3) { h3 ^= h2; Rot64(ref h2, 15); h3 += h2; h0 ^= h3; Rot64(ref h3, 52); h0 += h3; h1 ^= h0; Rot64(ref h0, 26); h1 += h0; h2 ^= h1; Rot64(ref h1, 51); h2 += h1; h3 ^= h2; Rot64(ref h2, 28); h3 += h2; h0 ^= h3; Rot64(ref h3, 9); h0 += h3; h1 ^= h0; Rot64(ref h0, 47); h1 += h0; h2 ^= h1; Rot64(ref h1, 54); h2 += h1; h3 ^= h2; Rot64(ref h2, 32); h3 += h2; h0 ^= h3; Rot64(ref h3, 25); h0 += h3; h1 ^= h0; Rot64(ref h0, 63); h1 += h0; } private static void Rot64(ref ulong x, int k) { x = (x << k) | (x >> 64 - k); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Parse_Injected(string hashString, out Hash128 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern string Hash128ToStringImpl_Injected(ref Hash128 hash); } public static class HashUtilities { public unsafe static void AppendHash(ref Hash128 inHash, ref Hash128 outHash) { fixed (Hash128* hash = &outHash) { fixed (Hash128* data = &inHash) { HashUnsafeUtilities.ComputeHash128(data, (ulong)sizeof(Hash128), hash); } } } public unsafe static void QuantisedMatrixHash(ref Matrix4x4 value, ref Hash128 hash) { fixed (Hash128* hash2 = &hash) { int* ptr = stackalloc int[16]; for (int i = 0; i < 16; i++) { ptr[i] = (int)(value[i] * 1000f + 0.5f); } HashUnsafeUtilities.ComputeHash128(ptr, 64uL, hash2); } } public unsafe static void QuantisedVectorHash(ref Vector3 value, ref Hash128 hash) { fixed (Hash128* hash2 = &hash) { int* ptr = stackalloc int[3]; for (int i = 0; i < 3; i++) { ptr[i] = (int)(value[i] * 1000f + 0.5f); } HashUnsafeUtilities.ComputeHash128(ptr, 12uL, hash2); } } public unsafe static void ComputeHash128(ref T value, ref Hash128 hash) where T : struct { void* data = UnsafeUtility.AddressOf(ref value); ulong dataSize = (ulong)UnsafeUtility.SizeOf(); Hash128* hash2 = (Hash128*)UnsafeUtility.AddressOf(ref hash); HashUnsafeUtilities.ComputeHash128(data, dataSize, hash2); } public unsafe static void ComputeHash128(byte[] value, ref Hash128 hash) { fixed (byte* data = &value[0]) { ulong dataSize = (ulong)value.Length; Hash128* hash2 = (Hash128*)UnsafeUtility.AddressOf(ref hash); HashUnsafeUtilities.ComputeHash128(data, dataSize, hash2); } } } public static class HashUnsafeUtilities { public unsafe static void ComputeHash128(void* data, ulong dataSize, ulong* hash1, ulong* hash2) { SpookyHash.Hash(data, dataSize, hash1, hash2); } public unsafe static void ComputeHash128(void* data, ulong dataSize, Hash128* hash) { ulong u64_ = hash->u64_0; ulong u64_2 = hash->u64_1; ComputeHash128(data, dataSize, &u64_, &u64_2); *hash = new Hash128(u64_, u64_2); } } internal static class SpookyHash { [StructLayout(LayoutKind.Explicit)] private struct U { [FieldOffset(0)] public unsafe byte* p8; [FieldOffset(0)] public unsafe uint* p32; [FieldOffset(0)] public unsafe ulong* p64; [FieldOffset(0)] public ulong i; public unsafe U(ushort* p8) { p32 = null; p64 = null; i = 0uL; this.p8 = (byte*)p8; } } private static readonly bool AllowUnalignedRead = AttemptDetectAllowUnalignedRead(); private const int k_NumVars = 12; private const int k_BlockSize = 96; private const int k_BufferSize = 192; private const ulong k_DeadBeefConst = 16045690984833335023uL; private static bool AttemptDetectAllowUnalignedRead() { string processorType = SystemInfo.processorType; string text = processorType; if (text == "x86" || text == "AMD64") { return true; } return false; } public unsafe static void Hash(void* message, ulong length, ulong* hash1, ulong* hash2) { if (length < 192) { Short(message, length, hash1, hash2); return; } ulong* ptr = stackalloc ulong[12]; ulong s2; ulong s3; ulong s4; ulong s = (s2 = (s3 = (s4 = *hash1))); ulong s6; ulong s7; ulong s8; ulong s5 = (s6 = (s7 = (s8 = *hash2))); ulong s10; ulong s11; ulong s12; ulong s9 = (s10 = (s11 = (s12 = 16045690984833335023uL))); U u = new U((ushort*)message); ulong* ptr2 = u.p64 + length / 96 * 12; if (AllowUnalignedRead || (u.i & 7) == 0) { while (u.p64 < ptr2) { Mix(u.p64, ref s, ref s5, ref s9, ref s2, ref s6, ref s10, ref s3, ref s7, ref s11, ref s4, ref s8, ref s12); u.p64 += 12; } } else { while (u.p64 < ptr2) { UnsafeUtility.MemCpy(ptr, u.p64, 96L); Mix(ptr, ref s, ref s5, ref s9, ref s2, ref s6, ref s10, ref s3, ref s7, ref s11, ref s4, ref s8, ref s12); u.p64 += 12; } } ulong num = length - (ulong)((byte*)ptr2 - (byte*)message); UnsafeUtility.MemCpy(ptr, ptr2, (long)num); memset((byte*)ptr + num, 0, 96 - num); ((sbyte*)ptr)[95] = (sbyte)(byte)num; End(ptr, ref s, ref s5, ref s9, ref s2, ref s6, ref s10, ref s3, ref s7, ref s11, ref s4, ref s8, ref s12); *hash1 = s; *hash2 = s5; } private unsafe static void End(ulong* data, ref ulong h0, ref ulong h1, ref ulong h2, ref ulong h3, ref ulong h4, ref ulong h5, ref ulong h6, ref ulong h7, ref ulong h8, ref ulong h9, ref ulong h10, ref ulong h11) { h0 += *data; h1 += data[1]; h2 += data[2]; h3 += data[3]; h4 += data[4]; h5 += data[5]; h6 += data[6]; h7 += data[7]; h8 += data[8]; h9 += data[9]; h10 += data[10]; h11 += data[11]; EndPartial(ref h0, ref h1, ref h2, ref h3, ref h4, ref h5, ref h6, ref h7, ref h8, ref h9, ref h10, ref h11); EndPartial(ref h0, ref h1, ref h2, ref h3, ref h4, ref h5, ref h6, ref h7, ref h8, ref h9, ref h10, ref h11); EndPartial(ref h0, ref h1, ref h2, ref h3, ref h4, ref h5, ref h6, ref h7, ref h8, ref h9, ref h10, ref h11); } private static void EndPartial(ref ulong h0, ref ulong h1, ref ulong h2, ref ulong h3, ref ulong h4, ref ulong h5, ref ulong h6, ref ulong h7, ref ulong h8, ref ulong h9, ref ulong h10, ref ulong h11) { h11 += h1; h2 ^= h11; Rot64(ref h1, 44); h0 += h2; h3 ^= h0; Rot64(ref h2, 15); h1 += h3; h4 ^= h1; Rot64(ref h3, 34); h2 += h4; h5 ^= h2; Rot64(ref h4, 21); h3 += h5; h6 ^= h3; Rot64(ref h5, 38); h4 += h6; h7 ^= h4; Rot64(ref h6, 33); h5 += h7; h8 ^= h5; Rot64(ref h7, 10); h6 += h8; h9 ^= h6; Rot64(ref h8, 13); h7 += h9; h10 ^= h7; Rot64(ref h9, 38); h8 += h10; h11 ^= h8; Rot64(ref h10, 53); h9 += h11; h0 ^= h9; Rot64(ref h11, 42); h10 += h0; h1 ^= h10; Rot64(ref h0, 54); } private static void Rot64(ref ulong x, int k) { x = (x << k) | (x >> 64 - k); } private unsafe static void Short(void* message, ulong length, ulong* hash1, ulong* hash2) { ulong* ptr = stackalloc ulong[24]; U u = new U((ushort*)message); if (!AllowUnalignedRead && (u.i & 7) != 0) { UnsafeUtility.MemCpy(ptr, message, (long)length); u.p64 = ptr; } ulong num = length % 32; ulong h = *hash1; ulong h2 = *hash2; ulong h3 = 16045690984833335023uL; ulong h4 = 16045690984833335023uL; if (length > 15) { ulong* ptr2 = u.p64 + length / 32 * 4; while (u.p64 < ptr2) { h3 += *u.p64; h4 += u.p64[1]; ShortMix(ref h, ref h2, ref h3, ref h4); h += u.p64[2]; h2 += u.p64[3]; u.p64 += 4; } if (num >= 16) { h3 += *u.p64; h4 += u.p64[1]; ShortMix(ref h, ref h2, ref h3, ref h4); u.p64 += 2; num -= 16; } } h4 += length << 56; ulong num2 = num; ulong num3 = num2; if (num3 <= 15) { switch (num3) { case 15uL: h4 += (ulong)u.p8[14] << 48; goto case 14uL; case 14uL: h4 += (ulong)u.p8[13] << 40; goto case 13uL; case 13uL: h4 += (ulong)u.p8[12] << 32; goto case 12uL; case 12uL: h4 += u.p32[2]; h3 += *u.p64; break; case 11uL: h4 += (ulong)u.p8[10] << 16; goto case 10uL; case 10uL: h4 += (ulong)u.p8[9] << 8; goto case 9uL; case 9uL: h4 += u.p8[8]; goto case 8uL; case 8uL: h3 += *u.p64; break; case 7uL: h3 += (ulong)u.p8[6] << 48; goto case 6uL; case 6uL: h3 += (ulong)u.p8[5] << 40; goto case 5uL; case 5uL: h3 += (ulong)u.p8[4] << 32; goto case 4uL; case 4uL: h3 += *u.p32; break; case 3uL: h3 += (ulong)u.p8[2] << 16; goto case 2uL; case 2uL: h3 += (ulong)u.p8[1] << 8; goto case 1uL; case 1uL: h3 += *u.p8; break; case 0uL: h3 += 16045690984833335023uL; h4 += 16045690984833335023uL; break; } } ShortEnd(ref h, ref h2, ref h3, ref h4); *hash1 = h; *hash2 = h2; } private static void ShortMix(ref ulong h0, ref ulong h1, ref ulong h2, ref ulong h3) { Rot64(ref h2, 50); h2 += h3; h0 ^= h2; Rot64(ref h3, 52); h3 += h0; h1 ^= h3; Rot64(ref h0, 30); h0 += h1; h2 ^= h0; Rot64(ref h1, 41); h1 += h2; h3 ^= h1; Rot64(ref h2, 54); h2 += h3; h0 ^= h2; Rot64(ref h3, 48); h3 += h0; h1 ^= h3; Rot64(ref h0, 38); h0 += h1; h2 ^= h0; Rot64(ref h1, 37); h1 += h2; h3 ^= h1; Rot64(ref h2, 62); h2 += h3; h0 ^= h2; Rot64(ref h3, 34); h3 += h0; h1 ^= h3; Rot64(ref h0, 5); h0 += h1; h2 ^= h0; Rot64(ref h1, 36); h1 += h2; h3 ^= h1; } private static void ShortEnd(ref ulong h0, ref ulong h1, ref ulong h2, ref ulong h3) { h3 ^= h2; Rot64(ref h2, 15); h3 += h2; h0 ^= h3; Rot64(ref h3, 52); h0 += h3; h1 ^= h0; Rot64(ref h0, 26); h1 += h0; h2 ^= h1; Rot64(ref h1, 51); h2 += h1; h3 ^= h2; Rot64(ref h2, 28); h3 += h2; h0 ^= h3; Rot64(ref h3, 9); h0 += h3; h1 ^= h0; Rot64(ref h0, 47); h1 += h0; h2 ^= h1; Rot64(ref h1, 54); h2 += h1; h3 ^= h2; Rot64(ref h2, 32); h3 += h2; h0 ^= h3; Rot64(ref h3, 25); h0 += h3; h1 ^= h0; Rot64(ref h0, 63); h1 += h0; } private unsafe static void Mix(ulong* data, ref ulong s0, ref ulong s1, ref ulong s2, ref ulong s3, ref ulong s4, ref ulong s5, ref ulong s6, ref ulong s7, ref ulong s8, ref ulong s9, ref ulong s10, ref ulong s11) { s0 += *data; s2 ^= s10; s11 ^= s0; Rot64(ref s0, 11); s11 += s1; s1 += data[1]; s3 ^= s11; s0 ^= s1; Rot64(ref s1, 32); s0 += s2; s2 += data[2]; s4 ^= s0; s1 ^= s2; Rot64(ref s2, 43); s1 += s3; s3 += data[3]; s5 ^= s1; s2 ^= s3; Rot64(ref s3, 31); s2 += s4; s4 += data[4]; s6 ^= s2; s3 ^= s4; Rot64(ref s4, 17); s3 += s5; s5 += data[5]; s7 ^= s3; s4 ^= s5; Rot64(ref s5, 28); s4 += s6; s6 += data[6]; s8 ^= s4; s5 ^= s6; Rot64(ref s6, 39); s5 += s7; s7 += data[7]; s9 ^= s5; s6 ^= s7; Rot64(ref s7, 57); s6 += s8; s8 += data[8]; s10 ^= s6; s7 ^= s8; Rot64(ref s8, 55); s7 += s9; s9 += data[9]; s11 ^= s7; s8 ^= s9; Rot64(ref s9, 54); s8 += s10; s10 += data[10]; s0 ^= s8; s9 ^= s10; Rot64(ref s10, 22); s9 += s11; s11 += data[11]; s1 ^= s9; s10 ^= s11; Rot64(ref s11, 46); s10 += s0; } private unsafe static void memset(void* dst, int value, ulong numberOfBytes) { ulong num = (uint)(value | value); ulong* ptr = (ulong*)dst; ulong num2 = numberOfBytes >> 3; for (ulong num3 = 0uL; num3 < num2; num3++) { ptr[num3] = num; } dst = ptr; numberOfBytes -= num2; byte* ptr2 = stackalloc byte[4]; *ptr2 = (byte)(value & 0xF); ptr2[1] = (byte)((value >>> 4) & 0xF); ptr2[2] = (byte)((value >>> 8) & 0xF); ptr2[3] = (byte)((value >>> 12) & 0xF); byte* ptr3 = (byte*)dst; ulong num4 = numberOfBytes; for (ulong num5 = 0uL; num5 < num4; num5++) { ptr3[num5] = ptr2[num5 % 4]; } } } [NativeType(Header = "Runtime/Export/HotReload/HotReload.bindings.h")] [NativeConditional("HOT_RELOAD_AVAILABLE")] internal static class HotReloadDeserializer { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HotReload::Prepare")] internal static extern void PrepareHotReload(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HotReload::Finish")] internal static extern void FinishHotReload(Type[] typesToReset); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HotReload::CreateEmptyAsset")] [NativeThrows] internal static extern Object CreateEmptyAsset(Type type); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HotReload::DeserializeAsset")] [NativeThrows] internal static extern void DeserializeAsset(Object asset, byte[] data); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] [FreeFunction("HotReload::RemapInstanceIds")] private static extern void RemapInstanceIds(Object editorAsset, int[] editorToPlayerInstanceIdMapKeys, int[] editorToPlayerInstanceIdMapValues); internal static void RemapInstanceIds(Object editorAsset, Dictionary editorToPlayerInstanceIdMap) { RemapInstanceIds(editorAsset, editorToPlayerInstanceIdMap.Keys.ToArray(), editorToPlayerInstanceIdMap.Values.ToArray()); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HotReload::FinalizeAssetCreation")] internal static extern void FinalizeAssetCreation(Object asset); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HotReload::GetDependencies")] internal static extern Object[] GetDependencies(Object asset); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("HotReload::GetNullDependencies")] internal static extern int[] GetNullDependencies(Object asset); } internal static class ScrollWaitDefinitions { public const int firstWait = 250; public const int regularWait = 30; } public enum CursorMode { Auto, ForceSoftware } public enum CursorLockMode { None, Locked, Confined } [NativeHeader("Runtime/Export/Input/Cursor.bindings.h")] public class Cursor { public static extern bool visible { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern CursorLockMode lockState { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } private static void SetCursor(Texture2D texture, CursorMode cursorMode) { SetCursor(texture, Vector2.zero, cursorMode); } public static void SetCursor(Texture2D texture, Vector2 hotspot, CursorMode cursorMode) { SetCursor_Injected(texture, ref hotspot, cursorMode); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetCursor_Injected(Texture2D texture, ref Vector2 hotspot, CursorMode cursorMode); } public enum KeyCode { None = 0, Backspace = 8, Delete = 127, Tab = 9, Clear = 12, Return = 13, Pause = 19, Escape = 27, Space = 32, Keypad0 = 256, Keypad1 = 257, Keypad2 = 258, Keypad3 = 259, Keypad4 = 260, Keypad5 = 261, Keypad6 = 262, Keypad7 = 263, Keypad8 = 264, Keypad9 = 265, KeypadPeriod = 266, KeypadDivide = 267, KeypadMultiply = 268, KeypadMinus = 269, KeypadPlus = 270, KeypadEnter = 271, KeypadEquals = 272, UpArrow = 273, DownArrow = 274, RightArrow = 275, LeftArrow = 276, Insert = 277, Home = 278, End = 279, PageUp = 280, PageDown = 281, F1 = 282, F2 = 283, F3 = 284, F4 = 285, F5 = 286, F6 = 287, F7 = 288, F8 = 289, F9 = 290, F10 = 291, F11 = 292, F12 = 293, F13 = 294, F14 = 295, F15 = 296, Alpha0 = 48, Alpha1 = 49, Alpha2 = 50, Alpha3 = 51, Alpha4 = 52, Alpha5 = 53, Alpha6 = 54, Alpha7 = 55, Alpha8 = 56, Alpha9 = 57, Exclaim = 33, DoubleQuote = 34, Hash = 35, Dollar = 36, Percent = 37, Ampersand = 38, Quote = 39, LeftParen = 40, RightParen = 41, Asterisk = 42, Plus = 43, Comma = 44, Minus = 45, Period = 46, Slash = 47, Colon = 58, Semicolon = 59, Less = 60, Equals = 61, Greater = 62, Question = 63, At = 64, LeftBracket = 91, Backslash = 92, RightBracket = 93, Caret = 94, Underscore = 95, BackQuote = 96, A = 97, B = 98, C = 99, D = 100, E = 101, F = 102, G = 103, H = 104, I = 105, J = 106, K = 107, L = 108, M = 109, N = 110, O = 111, P = 112, Q = 113, R = 114, S = 115, T = 116, U = 117, V = 118, W = 119, X = 120, Y = 121, Z = 122, LeftCurlyBracket = 123, Pipe = 124, RightCurlyBracket = 125, Tilde = 126, Numlock = 300, CapsLock = 301, ScrollLock = 302, RightShift = 303, LeftShift = 304, RightControl = 305, LeftControl = 306, RightAlt = 307, LeftAlt = 308, LeftMeta = 310, LeftCommand = 310, LeftApple = 310, LeftWindows = 311, RightMeta = 309, RightCommand = 309, RightApple = 309, RightWindows = 312, AltGr = 313, Help = 315, Print = 316, SysReq = 317, Break = 318, Menu = 319, Mouse0 = 323, Mouse1 = 324, Mouse2 = 325, Mouse3 = 326, Mouse4 = 327, Mouse5 = 328, Mouse6 = 329, JoystickButton0 = 330, JoystickButton1 = 331, JoystickButton2 = 332, JoystickButton3 = 333, JoystickButton4 = 334, JoystickButton5 = 335, JoystickButton6 = 336, JoystickButton7 = 337, JoystickButton8 = 338, JoystickButton9 = 339, JoystickButton10 = 340, JoystickButton11 = 341, JoystickButton12 = 342, JoystickButton13 = 343, JoystickButton14 = 344, JoystickButton15 = 345, JoystickButton16 = 346, JoystickButton17 = 347, JoystickButton18 = 348, JoystickButton19 = 349, Joystick1Button0 = 350, Joystick1Button1 = 351, Joystick1Button2 = 352, Joystick1Button3 = 353, Joystick1Button4 = 354, Joystick1Button5 = 355, Joystick1Button6 = 356, Joystick1Button7 = 357, Joystick1Button8 = 358, Joystick1Button9 = 359, Joystick1Button10 = 360, Joystick1Button11 = 361, Joystick1Button12 = 362, Joystick1Button13 = 363, Joystick1Button14 = 364, Joystick1Button15 = 365, Joystick1Button16 = 366, Joystick1Button17 = 367, Joystick1Button18 = 368, Joystick1Button19 = 369, Joystick2Button0 = 370, Joystick2Button1 = 371, Joystick2Button2 = 372, Joystick2Button3 = 373, Joystick2Button4 = 374, Joystick2Button5 = 375, Joystick2Button6 = 376, Joystick2Button7 = 377, Joystick2Button8 = 378, Joystick2Button9 = 379, Joystick2Button10 = 380, Joystick2Button11 = 381, Joystick2Button12 = 382, Joystick2Button13 = 383, Joystick2Button14 = 384, Joystick2Button15 = 385, Joystick2Button16 = 386, Joystick2Button17 = 387, Joystick2Button18 = 388, Joystick2Button19 = 389, Joystick3Button0 = 390, Joystick3Button1 = 391, Joystick3Button2 = 392, Joystick3Button3 = 393, Joystick3Button4 = 394, Joystick3Button5 = 395, Joystick3Button6 = 396, Joystick3Button7 = 397, Joystick3Button8 = 398, Joystick3Button9 = 399, Joystick3Button10 = 400, Joystick3Button11 = 401, Joystick3Button12 = 402, Joystick3Button13 = 403, Joystick3Button14 = 404, Joystick3Button15 = 405, Joystick3Button16 = 406, Joystick3Button17 = 407, Joystick3Button18 = 408, Joystick3Button19 = 409, Joystick4Button0 = 410, Joystick4Button1 = 411, Joystick4Button2 = 412, Joystick4Button3 = 413, Joystick4Button4 = 414, Joystick4Button5 = 415, Joystick4Button6 = 416, Joystick4Button7 = 417, Joystick4Button8 = 418, Joystick4Button9 = 419, Joystick4Button10 = 420, Joystick4Button11 = 421, Joystick4Button12 = 422, Joystick4Button13 = 423, Joystick4Button14 = 424, Joystick4Button15 = 425, Joystick4Button16 = 426, Joystick4Button17 = 427, Joystick4Button18 = 428, Joystick4Button19 = 429, Joystick5Button0 = 430, Joystick5Button1 = 431, Joystick5Button2 = 432, Joystick5Button3 = 433, Joystick5Button4 = 434, Joystick5Button5 = 435, Joystick5Button6 = 436, Joystick5Button7 = 437, Joystick5Button8 = 438, Joystick5Button9 = 439, Joystick5Button10 = 440, Joystick5Button11 = 441, Joystick5Button12 = 442, Joystick5Button13 = 443, Joystick5Button14 = 444, Joystick5Button15 = 445, Joystick5Button16 = 446, Joystick5Button17 = 447, Joystick5Button18 = 448, Joystick5Button19 = 449, Joystick6Button0 = 450, Joystick6Button1 = 451, Joystick6Button2 = 452, Joystick6Button3 = 453, Joystick6Button4 = 454, Joystick6Button5 = 455, Joystick6Button6 = 456, Joystick6Button7 = 457, Joystick6Button8 = 458, Joystick6Button9 = 459, Joystick6Button10 = 460, Joystick6Button11 = 461, Joystick6Button12 = 462, Joystick6Button13 = 463, Joystick6Button14 = 464, Joystick6Button15 = 465, Joystick6Button16 = 466, Joystick6Button17 = 467, Joystick6Button18 = 468, Joystick6Button19 = 469, Joystick7Button0 = 470, Joystick7Button1 = 471, Joystick7Button2 = 472, Joystick7Button3 = 473, Joystick7Button4 = 474, Joystick7Button5 = 475, Joystick7Button6 = 476, Joystick7Button7 = 477, Joystick7Button8 = 478, Joystick7Button9 = 479, Joystick7Button10 = 480, Joystick7Button11 = 481, Joystick7Button12 = 482, Joystick7Button13 = 483, Joystick7Button14 = 484, Joystick7Button15 = 485, Joystick7Button16 = 486, Joystick7Button17 = 487, Joystick7Button18 = 488, Joystick7Button19 = 489, Joystick8Button0 = 490, Joystick8Button1 = 491, Joystick8Button2 = 492, Joystick8Button3 = 493, Joystick8Button4 = 494, Joystick8Button5 = 495, Joystick8Button6 = 496, Joystick8Button7 = 497, Joystick8Button8 = 498, Joystick8Button9 = 499, Joystick8Button10 = 500, Joystick8Button11 = 501, Joystick8Button12 = 502, Joystick8Button13 = 503, Joystick8Button14 = 504, Joystick8Button15 = 505, Joystick8Button16 = 506, Joystick8Button17 = 507, Joystick8Button18 = 508, Joystick8Button19 = 509 } public interface ILogger : ILogHandler { ILogHandler logHandler { get; set; } bool logEnabled { get; set; } LogType filterLogType { get; set; } bool IsLogTypeAllowed(LogType logType); void Log(LogType logType, object message); void Log(LogType logType, object message, Object context); void Log(LogType logType, string tag, object message); void Log(LogType logType, string tag, object message, Object context); void Log(object message); void Log(string tag, object message); void Log(string tag, object message, Object context); void LogWarning(string tag, object message); void LogWarning(string tag, object message, Object context); void LogError(string tag, object message); void LogError(string tag, object message, Object context); void LogFormat(LogType logType, string format, params object[] args); void LogException(Exception exception); } public interface ILogHandler { void LogFormat(LogType logType, Object context, string format, params object[] args); void LogException(Exception exception, Object context); } public class Logger : ILogger, ILogHandler { private const string kNoTagFormat = "{0}"; private const string kTagFormat = "{0}: {1}"; public ILogHandler logHandler { get; set; } public bool logEnabled { get; set; } public LogType filterLogType { get; set; } private Logger() { } public Logger(ILogHandler logHandler) { this.logHandler = logHandler; logEnabled = true; filterLogType = LogType.Log; } public bool IsLogTypeAllowed(LogType logType) { if (logEnabled) { if (logType == LogType.Exception) { return true; } if (filterLogType != LogType.Exception) { return logType <= filterLogType; } } return false; } private static string GetString(object message) { if (message == null) { return "Null"; } if (message is IFormattable formattable) { return formattable.ToString(null, CultureInfo.InvariantCulture); } return message.ToString(); } public void Log(LogType logType, object message) { if (IsLogTypeAllowed(logType)) { logHandler.LogFormat(logType, null, "{0}", GetString(message)); } } public void Log(LogType logType, object message, Object context) { if (IsLogTypeAllowed(logType)) { logHandler.LogFormat(logType, context, "{0}", GetString(message)); } } public void Log(LogType logType, string tag, object message) { if (IsLogTypeAllowed(logType)) { logHandler.LogFormat(logType, null, "{0}: {1}", tag, GetString(message)); } } public void Log(LogType logType, string tag, object message, Object context) { if (IsLogTypeAllowed(logType)) { logHandler.LogFormat(logType, context, "{0}: {1}", tag, GetString(message)); } } public void Log(object message) { if (IsLogTypeAllowed(LogType.Log)) { logHandler.LogFormat(LogType.Log, null, "{0}", GetString(message)); } } public void Log(string tag, object message) { if (IsLogTypeAllowed(LogType.Log)) { logHandler.LogFormat(LogType.Log, null, "{0}: {1}", tag, GetString(message)); } } public void Log(string tag, object message, Object context) { if (IsLogTypeAllowed(LogType.Log)) { logHandler.LogFormat(LogType.Log, context, "{0}: {1}", tag, GetString(message)); } } public void LogWarning(string tag, object message) { if (IsLogTypeAllowed(LogType.Warning)) { logHandler.LogFormat(LogType.Warning, null, "{0}: {1}", tag, GetString(message)); } } public void LogWarning(string tag, object message, Object context) { if (IsLogTypeAllowed(LogType.Warning)) { logHandler.LogFormat(LogType.Warning, context, "{0}: {1}", tag, GetString(message)); } } public void LogError(string tag, object message) { if (IsLogTypeAllowed(LogType.Error)) { logHandler.LogFormat(LogType.Error, null, "{0}: {1}", tag, GetString(message)); } } public void LogError(string tag, object message, Object context) { if (IsLogTypeAllowed(LogType.Error)) { logHandler.LogFormat(LogType.Error, context, "{0}: {1}", tag, GetString(message)); } } public void LogException(Exception exception) { if (logEnabled) { logHandler.LogException(exception, null); } } public void LogException(Exception exception, Object context) { if (logEnabled) { logHandler.LogException(exception, context); } } public void LogFormat(LogType logType, string format, params object[] args) { if (IsLogTypeAllowed(logType)) { logHandler.LogFormat(logType, null, format, args); } } public void LogFormat(LogType logType, Object context, string format, params object[] args) { if (IsLogTypeAllowed(logType)) { logHandler.LogFormat(logType, context, format, args); } } } [NativeHeader("Runtime/Export/Logging/UnityLogWriter.bindings.h")] internal class UnityLogWriter : TextWriter { public override Encoding Encoding => Encoding.UTF8; [ThreadAndSerializationSafe] public static void WriteStringToUnityLog(string s) { if (s != null) { WriteStringToUnityLogImpl(s); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] private static extern void WriteStringToUnityLogImpl(string s); public static void Init() { Console.SetOut(new UnityLogWriter()); } public override void Write(char value) { WriteStringToUnityLog(value.ToString()); } public override void Write(string s) { WriteStringToUnityLog(s); } public override void Write(char[] buffer, int index, int count) { WriteStringToUnityLogImpl(new string(buffer, index, count)); } } [NativeClass("ColorRGBAf")] [RequiredByNativeCode(Optional = true, GenerateProxy = true)] [NativeHeader("Runtime/Math/Color.h")] public struct Color : IEquatable, IFormattable { public float r; public float g; public float b; public float a; public static Color red { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new Color(1f, 0f, 0f, 1f); } } public static Color green { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new Color(0f, 1f, 0f, 1f); } } public static Color blue { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new Color(0f, 0f, 1f, 1f); } } public static Color white { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new Color(1f, 1f, 1f, 1f); } } public static Color black { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new Color(0f, 0f, 0f, 1f); } } public static Color yellow { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new Color(1f, 47f / 51f, 0.015686275f, 1f); } } public static Color cyan { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new Color(0f, 1f, 1f, 1f); } } public static Color magenta { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new Color(1f, 0f, 1f, 1f); } } public static Color gray { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new Color(0.5f, 0.5f, 0.5f, 1f); } } public static Color grey { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new Color(0.5f, 0.5f, 0.5f, 1f); } } public static Color clear { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new Color(0f, 0f, 0f, 0f); } } public float grayscale { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return 0.299f * r + 0.587f * g + 0.114f * b; } } public Color linear => new Color(Mathf.GammaToLinearSpace(r), Mathf.GammaToLinearSpace(g), Mathf.GammaToLinearSpace(b), a); public Color gamma => new Color(Mathf.LinearToGammaSpace(r), Mathf.LinearToGammaSpace(g), Mathf.LinearToGammaSpace(b), a); public float maxColorComponent => Mathf.Max(Mathf.Max(r, g), b); public float this[int index] { get { return index switch { 0 => r, 1 => g, 2 => b, 3 => a, _ => throw new IndexOutOfRangeException("Invalid Color index(" + index + ")!"), }; } set { switch (index) { case 0: r = value; break; case 1: g = value; break; case 2: b = value; break; case 3: a = value; break; default: throw new IndexOutOfRangeException("Invalid Color index(" + index + ")!"); } } } public Color(float r, float g, float b, float a) { this.r = r; this.g = g; this.b = b; this.a = a; } public Color(float r, float g, float b) { this.r = r; this.g = g; this.b = b; a = 1f; } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) { format = "F3"; } if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("RGBA({0}, {1}, {2}, {3})", new object[4] { r.ToString(format, formatProvider), g.ToString(format, formatProvider), b.ToString(format, formatProvider), a.ToString(format, formatProvider) }); } public override int GetHashCode() { return ((Vector4)this/*cast due to .constrained prefix*/).GetHashCode(); } public override bool Equals(object other) { if (!(other is Color)) { return false; } return Equals((Color)other); } public bool Equals(Color other) { return r.Equals(other.r) && g.Equals(other.g) && b.Equals(other.b) && a.Equals(other.a); } public static Color operator +(Color a, Color b) { return new Color(a.r + b.r, a.g + b.g, a.b + b.b, a.a + b.a); } public static Color operator -(Color a, Color b) { return new Color(a.r - b.r, a.g - b.g, a.b - b.b, a.a - b.a); } public static Color operator *(Color a, Color b) { return new Color(a.r * b.r, a.g * b.g, a.b * b.b, a.a * b.a); } public static Color operator *(Color a, float b) { return new Color(a.r * b, a.g * b, a.b * b, a.a * b); } public static Color operator *(float b, Color a) { return new Color(a.r * b, a.g * b, a.b * b, a.a * b); } public static Color operator /(Color a, float b) { return new Color(a.r / b, a.g / b, a.b / b, a.a / b); } public static bool operator ==(Color lhs, Color rhs) { return (Vector4)lhs == (Vector4)rhs; } public static bool operator !=(Color lhs, Color rhs) { return !(lhs == rhs); } public static Color Lerp(Color a, Color b, float t) { t = Mathf.Clamp01(t); return new Color(a.r + (b.r - a.r) * t, a.g + (b.g - a.g) * t, a.b + (b.b - a.b) * t, a.a + (b.a - a.a) * t); } public static Color LerpUnclamped(Color a, Color b, float t) { return new Color(a.r + (b.r - a.r) * t, a.g + (b.g - a.g) * t, a.b + (b.b - a.b) * t, a.a + (b.a - a.a) * t); } internal Color RGBMultiplied(float multiplier) { return new Color(r * multiplier, g * multiplier, b * multiplier, a); } internal Color AlphaMultiplied(float multiplier) { return new Color(r, g, b, a * multiplier); } internal Color RGBMultiplied(Color multiplier) { return new Color(r * multiplier.r, g * multiplier.g, b * multiplier.b, a); } public static implicit operator Vector4(Color c) { return new Vector4(c.r, c.g, c.b, c.a); } public static implicit operator Color(Vector4 v) { return new Color(v.x, v.y, v.z, v.w); } public static void RGBToHSV(Color rgbColor, out float H, out float S, out float V) { if (rgbColor.b > rgbColor.g && rgbColor.b > rgbColor.r) { RGBToHSVHelper(4f, rgbColor.b, rgbColor.r, rgbColor.g, out H, out S, out V); } else if (rgbColor.g > rgbColor.r) { RGBToHSVHelper(2f, rgbColor.g, rgbColor.b, rgbColor.r, out H, out S, out V); } else { RGBToHSVHelper(0f, rgbColor.r, rgbColor.g, rgbColor.b, out H, out S, out V); } } private static void RGBToHSVHelper(float offset, float dominantcolor, float colorone, float colortwo, out float H, out float S, out float V) { V = dominantcolor; if (V != 0f) { float num = 0f; num = ((!(colorone > colortwo)) ? colorone : colortwo); float num2 = V - num; if (num2 != 0f) { S = num2 / V; H = offset + (colorone - colortwo) / num2; } else { S = 0f; H = offset + (colorone - colortwo); } H /= 6f; if (H < 0f) { H += 1f; } } else { S = 0f; H = 0f; } } public static Color HSVToRGB(float H, float S, float V) { return HSVToRGB(H, S, V, hdr: true); } public static Color HSVToRGB(float H, float S, float V, bool hdr) { Color result = white; if (S == 0f) { result.r = V; result.g = V; result.b = V; } else if (V == 0f) { result.r = 0f; result.g = 0f; result.b = 0f; } else { result.r = 0f; result.g = 0f; result.b = 0f; float num = H * 6f; int num2 = (int)Mathf.Floor(num); float num3 = num - (float)num2; float num4 = V * (1f - S); float num5 = V * (1f - S * num3); float num6 = V * (1f - S * (1f - num3)); switch (num2) { case 0: result.r = V; result.g = num6; result.b = num4; break; case 1: result.r = num5; result.g = V; result.b = num4; break; case 2: result.r = num4; result.g = V; result.b = num6; break; case 3: result.r = num4; result.g = num5; result.b = V; break; case 4: result.r = num6; result.g = num4; result.b = V; break; case 5: result.r = V; result.g = num4; result.b = num5; break; case 6: result.r = V; result.g = num6; result.b = num4; break; case -1: result.r = V; result.g = num4; result.b = num5; break; } if (!hdr) { result.r = Mathf.Clamp(result.r, 0f, 1f); result.g = Mathf.Clamp(result.g, 0f, 1f); result.b = Mathf.Clamp(result.b, 0f, 1f); } } return result; } } [StructLayout(LayoutKind.Explicit)] [UsedByNativeCode] public struct Color32 : IFormattable { [FieldOffset(0)] [Ignore(DoesNotContributeToSize = true)] private int rgba; [FieldOffset(0)] public byte r; [FieldOffset(1)] public byte g; [FieldOffset(2)] public byte b; [FieldOffset(3)] public byte a; public byte this[int index] { get { return index switch { 0 => r, 1 => g, 2 => b, 3 => a, _ => throw new IndexOutOfRangeException("Invalid Color32 index(" + index + ")!"), }; } set { switch (index) { case 0: r = value; break; case 1: g = value; break; case 2: b = value; break; case 3: a = value; break; default: throw new IndexOutOfRangeException("Invalid Color32 index(" + index + ")!"); } } } public Color32(byte r, byte g, byte b, byte a) { rgba = 0; this.r = r; this.g = g; this.b = b; this.a = a; } public static implicit operator Color32(Color c) { return new Color32((byte)Mathf.Round(Mathf.Clamp01(c.r) * 255f), (byte)Mathf.Round(Mathf.Clamp01(c.g) * 255f), (byte)Mathf.Round(Mathf.Clamp01(c.b) * 255f), (byte)Mathf.Round(Mathf.Clamp01(c.a) * 255f)); } public static implicit operator Color(Color32 c) { return new Color((float)(int)c.r / 255f, (float)(int)c.g / 255f, (float)(int)c.b / 255f, (float)(int)c.a / 255f); } public static Color32 Lerp(Color32 a, Color32 b, float t) { t = Mathf.Clamp01(t); return new Color32((byte)((float)(int)a.r + (float)(b.r - a.r) * t), (byte)((float)(int)a.g + (float)(b.g - a.g) * t), (byte)((float)(int)a.b + (float)(b.b - a.b) * t), (byte)((float)(int)a.a + (float)(b.a - a.a) * t)); } public static Color32 LerpUnclamped(Color32 a, Color32 b, float t) { return new Color32((byte)((float)(int)a.r + (float)(b.r - a.r) * t), (byte)((float)(int)a.g + (float)(b.g - a.g) * t), (byte)((float)(int)a.b + (float)(b.b - a.b) * t), (byte)((float)(int)a.a + (float)(b.a - a.a) * t)); } [VisibleToOtherModules] internal bool InternalEquals(Color32 other) { return rgba == other.rgba; } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("RGBA({0}, {1}, {2}, {3})", new object[4] { r.ToString(format, formatProvider), g.ToString(format, formatProvider), b.ToString(format, formatProvider), a.ToString(format, formatProvider) }); } } [NativeHeader("Runtime/Export/Math/ColorUtility.bindings.h")] public class ColorUtility { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] internal static extern bool DoTryParseHtmlColor(string htmlString, out Color32 color); public static bool TryParseHtmlString(string htmlString, out Color color) { Color32 color2; bool result = DoTryParseHtmlColor(htmlString, out color2); color = color2; return result; } public static string ToHtmlStringRGB(Color color) { Color32 color2 = new Color32((byte)Mathf.Clamp(Mathf.RoundToInt(color.r * 255f), 0, 255), (byte)Mathf.Clamp(Mathf.RoundToInt(color.g * 255f), 0, 255), (byte)Mathf.Clamp(Mathf.RoundToInt(color.b * 255f), 0, 255), 1); return UnityString.Format("{0:X2}{1:X2}{2:X2}", new object[3] { color2.r, color2.g, color2.b }); } public static string ToHtmlStringRGBA(Color color) { Color32 color2 = new Color32((byte)Mathf.Clamp(Mathf.RoundToInt(color.r * 255f), 0, 255), (byte)Mathf.Clamp(Mathf.RoundToInt(color.g * 255f), 0, 255), (byte)Mathf.Clamp(Mathf.RoundToInt(color.b * 255f), 0, 255), (byte)Mathf.Clamp(Mathf.RoundToInt(color.a * 255f), 0, 255)); return UnityString.Format("{0:X2}{1:X2}{2:X2}{3:X2}", new object[4] { color2.r, color2.g, color2.b, color2.a }); } } [UsedByNativeCode] public struct GradientColorKey { public Color color; public float time; public GradientColorKey(Color col, float time) { color = col; this.time = time; } } [UsedByNativeCode] public struct GradientAlphaKey { public float alpha; public float time; public GradientAlphaKey(float alpha, float time) { this.alpha = alpha; this.time = time; } } public enum GradientMode { Blend, Fixed } [StructLayout(LayoutKind.Sequential)] [NativeHeader("Runtime/Export/Math/Gradient.bindings.h")] [RequiredByNativeCode] public class Gradient : IEquatable { internal IntPtr m_Ptr; public extern GradientColorKey[] colorKeys { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Gradient_Bindings::GetColorKeys", IsThreadSafe = true, HasExplicitThis = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Gradient_Bindings::SetColorKeys", IsThreadSafe = true, HasExplicitThis = true)] [param: Unmarshalled] set; } public extern GradientAlphaKey[] alphaKeys { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Gradient_Bindings::GetAlphaKeys", IsThreadSafe = true, HasExplicitThis = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Gradient_Bindings::SetAlphaKeys", IsThreadSafe = true, HasExplicitThis = true)] [param: Unmarshalled] set; } [NativeProperty(IsThreadSafe = true)] public extern GradientMode mode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Gradient_Bindings::Init", IsThreadSafe = true)] private static extern IntPtr Init(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Gradient_Bindings::Cleanup", IsThreadSafe = true, HasExplicitThis = true)] private extern void Cleanup(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Gradient_Bindings::Internal_Equals", IsThreadSafe = true, HasExplicitThis = true)] private extern bool Internal_Equals(IntPtr other); [RequiredByNativeCode] public Gradient() { m_Ptr = Init(); } ~Gradient() { Cleanup(); } [FreeFunction(Name = "Gradient_Bindings::Evaluate", IsThreadSafe = true, HasExplicitThis = true)] public Color Evaluate(float time) { Evaluate_Injected(time, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Gradient_Bindings::SetKeys", IsThreadSafe = true, HasExplicitThis = true)] public extern void SetKeys([Unmarshalled] GradientColorKey[] colorKeys, [Unmarshalled] GradientAlphaKey[] alphaKeys); public override bool Equals(object o) { if (o == null) { return false; } if (this == o) { return true; } if ((object)o.GetType() != GetType()) { return false; } return Equals((Gradient)o); } public bool Equals(Gradient other) { if (other == null) { return false; } if (this == other) { return true; } if (m_Ptr.Equals((object?)(nint)other.m_Ptr)) { return true; } return Internal_Equals(other.m_Ptr); } public override int GetHashCode() { return m_Ptr.GetHashCode(); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void Evaluate_Injected(float time, out Color ret); } [Serializable] public struct FrustumPlanes { public float left; public float right; public float bottom; public float top; public float zNear; public float zFar; } [NativeType(Header = "Runtime/Math/Matrix4x4.h")] [NativeHeader("Runtime/Math/MathScripting.h")] [NativeClass("Matrix4x4f")] [RequiredByNativeCode(Optional = true, GenerateProxy = true)] [Il2CppEagerStaticClassConstruction] public struct Matrix4x4 : IEquatable, IFormattable { [NativeName("m_Data[0]")] public float m00; [NativeName("m_Data[1]")] public float m10; [NativeName("m_Data[2]")] public float m20; [NativeName("m_Data[3]")] public float m30; [NativeName("m_Data[4]")] public float m01; [NativeName("m_Data[5]")] public float m11; [NativeName("m_Data[6]")] public float m21; [NativeName("m_Data[7]")] public float m31; [NativeName("m_Data[8]")] public float m02; [NativeName("m_Data[9]")] public float m12; [NativeName("m_Data[10]")] public float m22; [NativeName("m_Data[11]")] public float m32; [NativeName("m_Data[12]")] public float m03; [NativeName("m_Data[13]")] public float m13; [NativeName("m_Data[14]")] public float m23; [NativeName("m_Data[15]")] public float m33; private static readonly Matrix4x4 zeroMatrix = new Matrix4x4(new Vector4(0f, 0f, 0f, 0f), new Vector4(0f, 0f, 0f, 0f), new Vector4(0f, 0f, 0f, 0f), new Vector4(0f, 0f, 0f, 0f)); private static readonly Matrix4x4 identityMatrix = new Matrix4x4(new Vector4(1f, 0f, 0f, 0f), new Vector4(0f, 1f, 0f, 0f), new Vector4(0f, 0f, 1f, 0f), new Vector4(0f, 0f, 0f, 1f)); public Quaternion rotation => GetRotation(); public Vector3 lossyScale => GetLossyScale(); public bool isIdentity => IsIdentity(); public float determinant => GetDeterminant(); public FrustumPlanes decomposeProjection => DecomposeProjection(); public Matrix4x4 inverse => Inverse(this); public Matrix4x4 transpose => Transpose(this); public float this[int row, int column] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return this[row + column * 4]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { this[row + column * 4] = value; } } public float this[int index] { get { return index switch { 0 => m00, 1 => m10, 2 => m20, 3 => m30, 4 => m01, 5 => m11, 6 => m21, 7 => m31, 8 => m02, 9 => m12, 10 => m22, 11 => m32, 12 => m03, 13 => m13, 14 => m23, 15 => m33, _ => throw new IndexOutOfRangeException("Invalid matrix index!"), }; } set { switch (index) { case 0: m00 = value; break; case 1: m10 = value; break; case 2: m20 = value; break; case 3: m30 = value; break; case 4: m01 = value; break; case 5: m11 = value; break; case 6: m21 = value; break; case 7: m31 = value; break; case 8: m02 = value; break; case 9: m12 = value; break; case 10: m22 = value; break; case 11: m32 = value; break; case 12: m03 = value; break; case 13: m13 = value; break; case 14: m23 = value; break; case 15: m33 = value; break; default: throw new IndexOutOfRangeException("Invalid matrix index!"); } } } public static Matrix4x4 zero => zeroMatrix; public static Matrix4x4 identity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return identityMatrix; } } [ThreadSafe] private Quaternion GetRotation() { GetRotation_Injected(ref this, out var ret); return ret; } [ThreadSafe] private Vector3 GetLossyScale() { GetLossyScale_Injected(ref this, out var ret); return ret; } [ThreadSafe] private bool IsIdentity() { return IsIdentity_Injected(ref this); } [ThreadSafe] private float GetDeterminant() { return GetDeterminant_Injected(ref this); } [ThreadSafe] private FrustumPlanes DecomposeProjection() { DecomposeProjection_Injected(ref this, out var ret); return ret; } [ThreadSafe] public bool ValidTRS() { return ValidTRS_Injected(ref this); } public static float Determinant(Matrix4x4 m) { return m.determinant; } [FreeFunction("MatrixScripting::TRS", IsThreadSafe = true)] public static Matrix4x4 TRS(Vector3 pos, Quaternion q, Vector3 s) { TRS_Injected(ref pos, ref q, ref s, out var ret); return ret; } public void SetTRS(Vector3 pos, Quaternion q, Vector3 s) { this = TRS(pos, q, s); } [FreeFunction("MatrixScripting::Inverse3DAffine", IsThreadSafe = true)] public static bool Inverse3DAffine(Matrix4x4 input, ref Matrix4x4 result) { return Inverse3DAffine_Injected(ref input, ref result); } [FreeFunction("MatrixScripting::Inverse", IsThreadSafe = true)] public static Matrix4x4 Inverse(Matrix4x4 m) { Inverse_Injected(ref m, out var ret); return ret; } [FreeFunction("MatrixScripting::Transpose", IsThreadSafe = true)] public static Matrix4x4 Transpose(Matrix4x4 m) { Transpose_Injected(ref m, out var ret); return ret; } [FreeFunction("MatrixScripting::Ortho", IsThreadSafe = true)] public static Matrix4x4 Ortho(float left, float right, float bottom, float top, float zNear, float zFar) { Ortho_Injected(left, right, bottom, top, zNear, zFar, out var ret); return ret; } [FreeFunction("MatrixScripting::Perspective", IsThreadSafe = true)] public static Matrix4x4 Perspective(float fov, float aspect, float zNear, float zFar) { Perspective_Injected(fov, aspect, zNear, zFar, out var ret); return ret; } [FreeFunction("MatrixScripting::LookAt", IsThreadSafe = true)] public static Matrix4x4 LookAt(Vector3 from, Vector3 to, Vector3 up) { LookAt_Injected(ref from, ref to, ref up, out var ret); return ret; } [FreeFunction("MatrixScripting::Frustum", IsThreadSafe = true)] public static Matrix4x4 Frustum(float left, float right, float bottom, float top, float zNear, float zFar) { Frustum_Injected(left, right, bottom, top, zNear, zFar, out var ret); return ret; } public static Matrix4x4 Frustum(FrustumPlanes fp) { return Frustum(fp.left, fp.right, fp.bottom, fp.top, fp.zNear, fp.zFar); } public Matrix4x4(Vector4 column0, Vector4 column1, Vector4 column2, Vector4 column3) { m00 = column0.x; m01 = column1.x; m02 = column2.x; m03 = column3.x; m10 = column0.y; m11 = column1.y; m12 = column2.y; m13 = column3.y; m20 = column0.z; m21 = column1.z; m22 = column2.z; m23 = column3.z; m30 = column0.w; m31 = column1.w; m32 = column2.w; m33 = column3.w; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return GetColumn(0).GetHashCode() ^ (GetColumn(1).GetHashCode() << 2) ^ (GetColumn(2).GetHashCode() >> 2) ^ (GetColumn(3).GetHashCode() >> 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object other) { if (!(other is Matrix4x4)) { return false; } return Equals((Matrix4x4)other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Matrix4x4 other) { return GetColumn(0).Equals(other.GetColumn(0)) && GetColumn(1).Equals(other.GetColumn(1)) && GetColumn(2).Equals(other.GetColumn(2)) && GetColumn(3).Equals(other.GetColumn(3)); } public static Matrix4x4 operator *(Matrix4x4 lhs, Matrix4x4 rhs) { Matrix4x4 result = default(Matrix4x4); result.m00 = lhs.m00 * rhs.m00 + lhs.m01 * rhs.m10 + lhs.m02 * rhs.m20 + lhs.m03 * rhs.m30; result.m01 = lhs.m00 * rhs.m01 + lhs.m01 * rhs.m11 + lhs.m02 * rhs.m21 + lhs.m03 * rhs.m31; result.m02 = lhs.m00 * rhs.m02 + lhs.m01 * rhs.m12 + lhs.m02 * rhs.m22 + lhs.m03 * rhs.m32; result.m03 = lhs.m00 * rhs.m03 + lhs.m01 * rhs.m13 + lhs.m02 * rhs.m23 + lhs.m03 * rhs.m33; result.m10 = lhs.m10 * rhs.m00 + lhs.m11 * rhs.m10 + lhs.m12 * rhs.m20 + lhs.m13 * rhs.m30; result.m11 = lhs.m10 * rhs.m01 + lhs.m11 * rhs.m11 + lhs.m12 * rhs.m21 + lhs.m13 * rhs.m31; result.m12 = lhs.m10 * rhs.m02 + lhs.m11 * rhs.m12 + lhs.m12 * rhs.m22 + lhs.m13 * rhs.m32; result.m13 = lhs.m10 * rhs.m03 + lhs.m11 * rhs.m13 + lhs.m12 * rhs.m23 + lhs.m13 * rhs.m33; result.m20 = lhs.m20 * rhs.m00 + lhs.m21 * rhs.m10 + lhs.m22 * rhs.m20 + lhs.m23 * rhs.m30; result.m21 = lhs.m20 * rhs.m01 + lhs.m21 * rhs.m11 + lhs.m22 * rhs.m21 + lhs.m23 * rhs.m31; result.m22 = lhs.m20 * rhs.m02 + lhs.m21 * rhs.m12 + lhs.m22 * rhs.m22 + lhs.m23 * rhs.m32; result.m23 = lhs.m20 * rhs.m03 + lhs.m21 * rhs.m13 + lhs.m22 * rhs.m23 + lhs.m23 * rhs.m33; result.m30 = lhs.m30 * rhs.m00 + lhs.m31 * rhs.m10 + lhs.m32 * rhs.m20 + lhs.m33 * rhs.m30; result.m31 = lhs.m30 * rhs.m01 + lhs.m31 * rhs.m11 + lhs.m32 * rhs.m21 + lhs.m33 * rhs.m31; result.m32 = lhs.m30 * rhs.m02 + lhs.m31 * rhs.m12 + lhs.m32 * rhs.m22 + lhs.m33 * rhs.m32; result.m33 = lhs.m30 * rhs.m03 + lhs.m31 * rhs.m13 + lhs.m32 * rhs.m23 + lhs.m33 * rhs.m33; return result; } public static Vector4 operator *(Matrix4x4 lhs, Vector4 vector) { Vector4 result = default(Vector4); result.x = lhs.m00 * vector.x + lhs.m01 * vector.y + lhs.m02 * vector.z + lhs.m03 * vector.w; result.y = lhs.m10 * vector.x + lhs.m11 * vector.y + lhs.m12 * vector.z + lhs.m13 * vector.w; result.z = lhs.m20 * vector.x + lhs.m21 * vector.y + lhs.m22 * vector.z + lhs.m23 * vector.w; result.w = lhs.m30 * vector.x + lhs.m31 * vector.y + lhs.m32 * vector.z + lhs.m33 * vector.w; return result; } public static bool operator ==(Matrix4x4 lhs, Matrix4x4 rhs) { return lhs.GetColumn(0) == rhs.GetColumn(0) && lhs.GetColumn(1) == rhs.GetColumn(1) && lhs.GetColumn(2) == rhs.GetColumn(2) && lhs.GetColumn(3) == rhs.GetColumn(3); } public static bool operator !=(Matrix4x4 lhs, Matrix4x4 rhs) { return !(lhs == rhs); } public Vector4 GetColumn(int index) { return index switch { 0 => new Vector4(m00, m10, m20, m30), 1 => new Vector4(m01, m11, m21, m31), 2 => new Vector4(m02, m12, m22, m32), 3 => new Vector4(m03, m13, m23, m33), _ => throw new IndexOutOfRangeException("Invalid column index!"), }; } public Vector4 GetRow(int index) { return index switch { 0 => new Vector4(m00, m01, m02, m03), 1 => new Vector4(m10, m11, m12, m13), 2 => new Vector4(m20, m21, m22, m23), 3 => new Vector4(m30, m31, m32, m33), _ => throw new IndexOutOfRangeException("Invalid row index!"), }; } public Vector3 GetPosition() { return new Vector3(m03, m13, m23); } public void SetColumn(int index, Vector4 column) { this[0, index] = column.x; this[1, index] = column.y; this[2, index] = column.z; this[3, index] = column.w; } public void SetRow(int index, Vector4 row) { this[index, 0] = row.x; this[index, 1] = row.y; this[index, 2] = row.z; this[index, 3] = row.w; } public Vector3 MultiplyPoint(Vector3 point) { Vector3 result = default(Vector3); result.x = m00 * point.x + m01 * point.y + m02 * point.z + m03; result.y = m10 * point.x + m11 * point.y + m12 * point.z + m13; result.z = m20 * point.x + m21 * point.y + m22 * point.z + m23; float num = m30 * point.x + m31 * point.y + m32 * point.z + m33; num = 1f / num; result.x *= num; result.y *= num; result.z *= num; return result; } public Vector3 MultiplyPoint3x4(Vector3 point) { Vector3 result = default(Vector3); result.x = m00 * point.x + m01 * point.y + m02 * point.z + m03; result.y = m10 * point.x + m11 * point.y + m12 * point.z + m13; result.z = m20 * point.x + m21 * point.y + m22 * point.z + m23; return result; } public Vector3 MultiplyVector(Vector3 vector) { Vector3 result = default(Vector3); result.x = m00 * vector.x + m01 * vector.y + m02 * vector.z; result.y = m10 * vector.x + m11 * vector.y + m12 * vector.z; result.z = m20 * vector.x + m21 * vector.y + m22 * vector.z; return result; } public Plane TransformPlane(Plane plane) { Matrix4x4 matrix4x = inverse; float x = plane.normal.x; float y = plane.normal.y; float z = plane.normal.z; float distance = plane.distance; float x2 = matrix4x.m00 * x + matrix4x.m10 * y + matrix4x.m20 * z + matrix4x.m30 * distance; float y2 = matrix4x.m01 * x + matrix4x.m11 * y + matrix4x.m21 * z + matrix4x.m31 * distance; float z2 = matrix4x.m02 * x + matrix4x.m12 * y + matrix4x.m22 * z + matrix4x.m32 * distance; float d = matrix4x.m03 * x + matrix4x.m13 * y + matrix4x.m23 * z + matrix4x.m33 * distance; return new Plane(new Vector3(x2, y2, z2), d); } public static Matrix4x4 Scale(Vector3 vector) { Matrix4x4 result = default(Matrix4x4); result.m00 = vector.x; result.m01 = 0f; result.m02 = 0f; result.m03 = 0f; result.m10 = 0f; result.m11 = vector.y; result.m12 = 0f; result.m13 = 0f; result.m20 = 0f; result.m21 = 0f; result.m22 = vector.z; result.m23 = 0f; result.m30 = 0f; result.m31 = 0f; result.m32 = 0f; result.m33 = 1f; return result; } public static Matrix4x4 Translate(Vector3 vector) { Matrix4x4 result = default(Matrix4x4); result.m00 = 1f; result.m01 = 0f; result.m02 = 0f; result.m03 = vector.x; result.m10 = 0f; result.m11 = 1f; result.m12 = 0f; result.m13 = vector.y; result.m20 = 0f; result.m21 = 0f; result.m22 = 1f; result.m23 = vector.z; result.m30 = 0f; result.m31 = 0f; result.m32 = 0f; result.m33 = 1f; return result; } public static Matrix4x4 Rotate(Quaternion q) { float num = q.x * 2f; float num2 = q.y * 2f; float num3 = q.z * 2f; float num4 = q.x * num; float num5 = q.y * num2; float num6 = q.z * num3; float num7 = q.x * num2; float num8 = q.x * num3; float num9 = q.y * num3; float num10 = q.w * num; float num11 = q.w * num2; float num12 = q.w * num3; Matrix4x4 result = default(Matrix4x4); result.m00 = 1f - (num5 + num6); result.m10 = num7 + num12; result.m20 = num8 - num11; result.m30 = 0f; result.m01 = num7 - num12; result.m11 = 1f - (num4 + num6); result.m21 = num9 + num10; result.m31 = 0f; result.m02 = num8 + num11; result.m12 = num9 - num10; result.m22 = 1f - (num4 + num5); result.m32 = 0f; result.m03 = 0f; result.m13 = 0f; result.m23 = 0f; result.m33 = 1f; return result; } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) { format = "F5"; } if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("{0}\t{1}\t{2}\t{3}\n{4}\t{5}\t{6}\t{7}\n{8}\t{9}\t{10}\t{11}\n{12}\t{13}\t{14}\t{15}\n", new object[16] { m00.ToString(format, formatProvider), m01.ToString(format, formatProvider), m02.ToString(format, formatProvider), m03.ToString(format, formatProvider), m10.ToString(format, formatProvider), m11.ToString(format, formatProvider), m12.ToString(format, formatProvider), m13.ToString(format, formatProvider), m20.ToString(format, formatProvider), m21.ToString(format, formatProvider), m22.ToString(format, formatProvider), m23.ToString(format, formatProvider), m30.ToString(format, formatProvider), m31.ToString(format, formatProvider), m32.ToString(format, formatProvider), m33.ToString(format, formatProvider) }); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetRotation_Injected(ref Matrix4x4 _unity_self, out Quaternion ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetLossyScale_Injected(ref Matrix4x4 _unity_self, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsIdentity_Injected(ref Matrix4x4 _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern float GetDeterminant_Injected(ref Matrix4x4 _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DecomposeProjection_Injected(ref Matrix4x4 _unity_self, out FrustumPlanes ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool ValidTRS_Injected(ref Matrix4x4 _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void TRS_Injected(ref Vector3 pos, ref Quaternion q, ref Vector3 s, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool Inverse3DAffine_Injected(ref Matrix4x4 input, ref Matrix4x4 result); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Inverse_Injected(ref Matrix4x4 m, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Transpose_Injected(ref Matrix4x4 m, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Ortho_Injected(float left, float right, float bottom, float top, float zNear, float zFar, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Perspective_Injected(float fov, float aspect, float zNear, float zFar, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void LookAt_Injected(ref Vector3 from, ref Vector3 to, ref Vector3 up, out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Frustum_Injected(float left, float right, float bottom, float top, float zNear, float zFar, out Matrix4x4 ret); } [NativeType(Header = "Runtime/Math/Vector3.h")] [NativeHeader("Runtime/Math/MathScripting.h")] [RequiredByNativeCode(Optional = true, GenerateProxy = true)] [Il2CppEagerStaticClassConstruction] [NativeHeader("Runtime/Math/Vector3.h")] [NativeClass("Vector3f")] public struct Vector3 : IEquatable, IFormattable { public const float kEpsilon = 1E-05f; public const float kEpsilonNormalSqrt = 1E-15f; public float x; public float y; public float z; private static readonly Vector3 zeroVector = new Vector3(0f, 0f, 0f); private static readonly Vector3 oneVector = new Vector3(1f, 1f, 1f); private static readonly Vector3 upVector = new Vector3(0f, 1f, 0f); private static readonly Vector3 downVector = new Vector3(0f, -1f, 0f); private static readonly Vector3 leftVector = new Vector3(-1f, 0f, 0f); private static readonly Vector3 rightVector = new Vector3(1f, 0f, 0f); private static readonly Vector3 forwardVector = new Vector3(0f, 0f, 1f); private static readonly Vector3 backVector = new Vector3(0f, 0f, -1f); private static readonly Vector3 positiveInfinityVector = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); private static readonly Vector3 negativeInfinityVector = new Vector3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity); public float this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return index switch { 0 => x, 1 => y, 2 => z, _ => throw new IndexOutOfRangeException("Invalid Vector3 index!"), }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { switch (index) { case 0: x = value; break; case 1: y = value; break; case 2: z = value; break; default: throw new IndexOutOfRangeException("Invalid Vector3 index!"); } } } public Vector3 normalized { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Normalize(this); } } public float magnitude { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (float)Math.Sqrt(x * x + y * y + z * z); } } public float sqrMagnitude { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return x * x + y * y + z * z; } } public static Vector3 zero { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return zeroVector; } } public static Vector3 one { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return oneVector; } } public static Vector3 forward { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return forwardVector; } } public static Vector3 back { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return backVector; } } public static Vector3 up { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return upVector; } } public static Vector3 down { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return downVector; } } public static Vector3 left { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return leftVector; } } public static Vector3 right { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return rightVector; } } public static Vector3 positiveInfinity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return positiveInfinityVector; } } public static Vector3 negativeInfinity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return negativeInfinityVector; } } [Obsolete("Use Vector3.forward instead.")] public static Vector3 fwd => new Vector3(0f, 0f, 1f); [FreeFunction("VectorScripting::Slerp", IsThreadSafe = true)] public static Vector3 Slerp(Vector3 a, Vector3 b, float t) { Slerp_Injected(ref a, ref b, t, out var ret); return ret; } [FreeFunction("VectorScripting::SlerpUnclamped", IsThreadSafe = true)] public static Vector3 SlerpUnclamped(Vector3 a, Vector3 b, float t) { SlerpUnclamped_Injected(ref a, ref b, t, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("VectorScripting::OrthoNormalize", IsThreadSafe = true)] private static extern void OrthoNormalize2(ref Vector3 a, ref Vector3 b); public static void OrthoNormalize(ref Vector3 normal, ref Vector3 tangent) { OrthoNormalize2(ref normal, ref tangent); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("VectorScripting::OrthoNormalize", IsThreadSafe = true)] private static extern void OrthoNormalize3(ref Vector3 a, ref Vector3 b, ref Vector3 c); public static void OrthoNormalize(ref Vector3 normal, ref Vector3 tangent, ref Vector3 binormal) { OrthoNormalize3(ref normal, ref tangent, ref binormal); } [FreeFunction(IsThreadSafe = true)] public static Vector3 RotateTowards(Vector3 current, Vector3 target, float maxRadiansDelta, float maxMagnitudeDelta) { RotateTowards_Injected(ref current, ref target, maxRadiansDelta, maxMagnitudeDelta, out var ret); return ret; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Lerp(Vector3 a, Vector3 b, float t) { t = Mathf.Clamp01(t); return new Vector3(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 LerpUnclamped(Vector3 a, Vector3 b, float t) { return new Vector3(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta) { float num = target.x - current.x; float num2 = target.y - current.y; float num3 = target.z - current.z; float num4 = num * num + num2 * num2 + num3 * num3; if (num4 == 0f || (maxDistanceDelta >= 0f && num4 <= maxDistanceDelta * maxDistanceDelta)) { return target; } float num5 = (float)Math.Sqrt(num4); return new Vector3(current.x + num / num5 * maxDistanceDelta, current.y + num2 / num5 * maxDistanceDelta, current.z + num3 / num5 * maxDistanceDelta); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [ExcludeFromDocs] public static Vector3 SmoothDamp(Vector3 current, Vector3 target, ref Vector3 currentVelocity, float smoothTime, float maxSpeed) { float deltaTime = Time.deltaTime; return SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [ExcludeFromDocs] public static Vector3 SmoothDamp(Vector3 current, Vector3 target, ref Vector3 currentVelocity, float smoothTime) { float deltaTime = Time.deltaTime; float maxSpeed = float.PositiveInfinity; return SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); } public static Vector3 SmoothDamp(Vector3 current, Vector3 target, ref Vector3 currentVelocity, float smoothTime, [UnityEngine.Internal.DefaultValue("Mathf.Infinity")] float maxSpeed, [UnityEngine.Internal.DefaultValue("Time.deltaTime")] float deltaTime) { float num = 0f; float num2 = 0f; float num3 = 0f; smoothTime = Mathf.Max(0.0001f, smoothTime); float num4 = 2f / smoothTime; float num5 = num4 * deltaTime; float num6 = 1f / (1f + num5 + 0.48f * num5 * num5 + 0.235f * num5 * num5 * num5); float num7 = current.x - target.x; float num8 = current.y - target.y; float num9 = current.z - target.z; Vector3 vector = target; float num10 = maxSpeed * smoothTime; float num11 = num10 * num10; float num12 = num7 * num7 + num8 * num8 + num9 * num9; if (num12 > num11) { float num13 = (float)Math.Sqrt(num12); num7 = num7 / num13 * num10; num8 = num8 / num13 * num10; num9 = num9 / num13 * num10; } target.x = current.x - num7; target.y = current.y - num8; target.z = current.z - num9; float num14 = (currentVelocity.x + num4 * num7) * deltaTime; float num15 = (currentVelocity.y + num4 * num8) * deltaTime; float num16 = (currentVelocity.z + num4 * num9) * deltaTime; currentVelocity.x = (currentVelocity.x - num4 * num14) * num6; currentVelocity.y = (currentVelocity.y - num4 * num15) * num6; currentVelocity.z = (currentVelocity.z - num4 * num16) * num6; num = target.x + (num7 + num14) * num6; num2 = target.y + (num8 + num15) * num6; num3 = target.z + (num9 + num16) * num6; float num17 = vector.x - current.x; float num18 = vector.y - current.y; float num19 = vector.z - current.z; float num20 = num - vector.x; float num21 = num2 - vector.y; float num22 = num3 - vector.z; if (num17 * num20 + num18 * num21 + num19 * num22 > 0f) { num = vector.x; num2 = vector.y; num3 = vector.z; currentVelocity.x = (num - vector.x) / deltaTime; currentVelocity.y = (num2 - vector.y) / deltaTime; currentVelocity.z = (num3 - vector.z) / deltaTime; } return new Vector3(num, num2, num3); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector3(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector3(float x, float y) { this.x = x; this.y = y; z = 0f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Set(float newX, float newY, float newZ) { x = newX; y = newY; z = newZ; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Scale(Vector3 a, Vector3 b) { return new Vector3(a.x * b.x, a.y * b.y, a.z * b.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Scale(Vector3 scale) { x *= scale.x; y *= scale.y; z *= scale.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Cross(Vector3 lhs, Vector3 rhs) { return new Vector3(lhs.y * rhs.z - lhs.z * rhs.y, lhs.z * rhs.x - lhs.x * rhs.z, lhs.x * rhs.y - lhs.y * rhs.x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return x.GetHashCode() ^ (y.GetHashCode() << 2) ^ (z.GetHashCode() >> 2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object other) { if (!(other is Vector3)) { return false; } return Equals((Vector3)other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Vector3 other) { return x == other.x && y == other.y && z == other.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Reflect(Vector3 inDirection, Vector3 inNormal) { float num = -2f * Dot(inNormal, inDirection); return new Vector3(num * inNormal.x + inDirection.x, num * inNormal.y + inDirection.y, num * inNormal.z + inDirection.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Normalize(Vector3 value) { float num = Magnitude(value); if (num > 1E-05f) { return value / num; } return zero; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Normalize() { float num = Magnitude(this); if (num > 1E-05f) { this /= num; } else { this = zero; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(Vector3 lhs, Vector3 rhs) { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Project(Vector3 vector, Vector3 onNormal) { float num = Dot(onNormal, onNormal); if (num < Mathf.Epsilon) { return zero; } float num2 = Dot(vector, onNormal); return new Vector3(onNormal.x * num2 / num, onNormal.y * num2 / num, onNormal.z * num2 / num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 ProjectOnPlane(Vector3 vector, Vector3 planeNormal) { float num = Dot(planeNormal, planeNormal); if (num < Mathf.Epsilon) { return vector; } float num2 = Dot(vector, planeNormal); return new Vector3(vector.x - planeNormal.x * num2 / num, vector.y - planeNormal.y * num2 / num, vector.z - planeNormal.z * num2 / num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Angle(Vector3 from, Vector3 to) { float num = (float)Math.Sqrt(from.sqrMagnitude * to.sqrMagnitude); if (num < 1E-15f) { return 0f; } float num2 = Mathf.Clamp(Dot(from, to) / num, -1f, 1f); return (float)Math.Acos(num2) * 57.29578f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float SignedAngle(Vector3 from, Vector3 to, Vector3 axis) { float num = Angle(from, to); float num2 = from.y * to.z - from.z * to.y; float num3 = from.z * to.x - from.x * to.z; float num4 = from.x * to.y - from.y * to.x; float num5 = Mathf.Sign(axis.x * num2 + axis.y * num3 + axis.z * num4); return num * num5; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector3 a, Vector3 b) { float num = a.x - b.x; float num2 = a.y - b.y; float num3 = a.z - b.z; return (float)Math.Sqrt(num * num + num2 * num2 + num3 * num3); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 ClampMagnitude(Vector3 vector, float maxLength) { float num = vector.sqrMagnitude; if (num > maxLength * maxLength) { float num2 = (float)Math.Sqrt(num); float num3 = vector.x / num2; float num4 = vector.y / num2; float num5 = vector.z / num2; return new Vector3(num3 * maxLength, num4 * maxLength, num5 * maxLength); } return vector; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Magnitude(Vector3 vector) { return (float)Math.Sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float SqrMagnitude(Vector3 vector) { return vector.x * vector.x + vector.y * vector.y + vector.z * vector.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Min(Vector3 lhs, Vector3 rhs) { return new Vector3(Mathf.Min(lhs.x, rhs.x), Mathf.Min(lhs.y, rhs.y), Mathf.Min(lhs.z, rhs.z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Max(Vector3 lhs, Vector3 rhs) { return new Vector3(Mathf.Max(lhs.x, rhs.x), Mathf.Max(lhs.y, rhs.y), Mathf.Max(lhs.z, rhs.z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator +(Vector3 a, Vector3 b) { return new Vector3(a.x + b.x, a.y + b.y, a.z + b.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator -(Vector3 a, Vector3 b) { return new Vector3(a.x - b.x, a.y - b.y, a.z - b.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator -(Vector3 a) { return new Vector3(0f - a.x, 0f - a.y, 0f - a.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator *(Vector3 a, float d) { return new Vector3(a.x * d, a.y * d, a.z * d); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator *(float d, Vector3 a) { return new Vector3(a.x * d, a.y * d, a.z * d); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator /(Vector3 a, float d) { return new Vector3(a.x / d, a.y / d, a.z / d); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector3 lhs, Vector3 rhs) { float num = lhs.x - rhs.x; float num2 = lhs.y - rhs.y; float num3 = lhs.z - rhs.z; float num4 = num * num + num2 * num2 + num3 * num3; return num4 < 9.9999994E-11f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector3 lhs, Vector3 rhs) { return !(lhs == rhs); } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) { format = "F2"; } if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("({0}, {1}, {2})", new object[3] { x.ToString(format, formatProvider), y.ToString(format, formatProvider), z.ToString(format, formatProvider) }); } [Obsolete("Use Vector3.Angle instead. AngleBetween uses radians instead of degrees and was deprecated for this reason")] public static float AngleBetween(Vector3 from, Vector3 to) { return (float)Math.Acos(Mathf.Clamp(Dot(from.normalized, to.normalized), -1f, 1f)); } [Obsolete("Use Vector3.ProjectOnPlane instead.")] public static Vector3 Exclude(Vector3 excludeThis, Vector3 fromThat) { return ProjectOnPlane(fromThat, excludeThis); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Slerp_Injected(ref Vector3 a, ref Vector3 b, float t, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SlerpUnclamped_Injected(ref Vector3 a, ref Vector3 b, float t, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void RotateTowards_Injected(ref Vector3 current, ref Vector3 target, float maxRadiansDelta, float maxMagnitudeDelta, out Vector3 ret); } [NativeHeader("Runtime/Math/MathScripting.h")] [NativeType(Header = "Runtime/Math/Quaternion.h")] [Il2CppEagerStaticClassConstruction] [UsedByNativeCode] public struct Quaternion : IEquatable, IFormattable { public float x; public float y; public float z; public float w; private static readonly Quaternion identityQuaternion = new Quaternion(0f, 0f, 0f, 1f); public const float kEpsilon = 1E-06f; public float this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return index switch { 0 => x, 1 => y, 2 => z, 3 => w, _ => throw new IndexOutOfRangeException("Invalid Quaternion index!"), }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { switch (index) { case 0: x = value; break; case 1: y = value; break; case 2: z = value; break; case 3: w = value; break; default: throw new IndexOutOfRangeException("Invalid Quaternion index!"); } } } public static Quaternion identity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return identityQuaternion; } } public Vector3 eulerAngles { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Internal_MakePositive(Internal_ToEulerRad(this) * 57.29578f); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { this = Internal_FromEulerRad(value * ((float)Math.PI / 180f)); } } public Quaternion normalized { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Normalize(this); } } [FreeFunction("FromToQuaternionSafe", IsThreadSafe = true)] public static Quaternion FromToRotation(Vector3 fromDirection, Vector3 toDirection) { FromToRotation_Injected(ref fromDirection, ref toDirection, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public static Quaternion Inverse(Quaternion rotation) { Inverse_Injected(ref rotation, out var ret); return ret; } [FreeFunction("QuaternionScripting::Slerp", IsThreadSafe = true)] public static Quaternion Slerp(Quaternion a, Quaternion b, float t) { Slerp_Injected(ref a, ref b, t, out var ret); return ret; } [FreeFunction("QuaternionScripting::SlerpUnclamped", IsThreadSafe = true)] public static Quaternion SlerpUnclamped(Quaternion a, Quaternion b, float t) { SlerpUnclamped_Injected(ref a, ref b, t, out var ret); return ret; } [FreeFunction("QuaternionScripting::Lerp", IsThreadSafe = true)] public static Quaternion Lerp(Quaternion a, Quaternion b, float t) { Lerp_Injected(ref a, ref b, t, out var ret); return ret; } [FreeFunction("QuaternionScripting::LerpUnclamped", IsThreadSafe = true)] public static Quaternion LerpUnclamped(Quaternion a, Quaternion b, float t) { LerpUnclamped_Injected(ref a, ref b, t, out var ret); return ret; } [FreeFunction("EulerToQuaternion", IsThreadSafe = true)] private static Quaternion Internal_FromEulerRad(Vector3 euler) { Internal_FromEulerRad_Injected(ref euler, out var ret); return ret; } [FreeFunction("QuaternionScripting::ToEuler", IsThreadSafe = true)] private static Vector3 Internal_ToEulerRad(Quaternion rotation) { Internal_ToEulerRad_Injected(ref rotation, out var ret); return ret; } [FreeFunction("QuaternionScripting::ToAxisAngle", IsThreadSafe = true)] private static void Internal_ToAxisAngleRad(Quaternion q, out Vector3 axis, out float angle) { Internal_ToAxisAngleRad_Injected(ref q, out axis, out angle); } [FreeFunction("QuaternionScripting::AngleAxis", IsThreadSafe = true)] public static Quaternion AngleAxis(float angle, Vector3 axis) { AngleAxis_Injected(angle, ref axis, out var ret); return ret; } [FreeFunction("QuaternionScripting::LookRotation", IsThreadSafe = true)] public static Quaternion LookRotation(Vector3 forward, [UnityEngine.Internal.DefaultValue("Vector3.up")] Vector3 upwards) { LookRotation_Injected(ref forward, ref upwards, out var ret); return ret; } [ExcludeFromDocs] public static Quaternion LookRotation(Vector3 forward) { return LookRotation(forward, Vector3.up); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Quaternion(float x, float y, float z, float w) { this.x = x; this.y = y; this.z = z; this.w = w; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Set(float newX, float newY, float newZ, float newW) { x = newX; y = newY; z = newZ; w = newW; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion operator *(Quaternion lhs, Quaternion rhs) { return new Quaternion(lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y, lhs.w * rhs.y + lhs.y * rhs.w + lhs.z * rhs.x - lhs.x * rhs.z, lhs.w * rhs.z + lhs.z * rhs.w + lhs.x * rhs.y - lhs.y * rhs.x, lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z); } public static Vector3 operator *(Quaternion rotation, Vector3 point) { float num = rotation.x * 2f; float num2 = rotation.y * 2f; float num3 = rotation.z * 2f; float num4 = rotation.x * num; float num5 = rotation.y * num2; float num6 = rotation.z * num3; float num7 = rotation.x * num2; float num8 = rotation.x * num3; float num9 = rotation.y * num3; float num10 = rotation.w * num; float num11 = rotation.w * num2; float num12 = rotation.w * num3; Vector3 result = default(Vector3); result.x = (1f - (num5 + num6)) * point.x + (num7 - num12) * point.y + (num8 + num11) * point.z; result.y = (num7 + num12) * point.x + (1f - (num4 + num6)) * point.y + (num9 - num10) * point.z; result.z = (num8 - num11) * point.x + (num9 + num10) * point.y + (1f - (num4 + num5)) * point.z; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsEqualUsingDot(float dot) { return dot > 0.999999f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Quaternion lhs, Quaternion rhs) { return IsEqualUsingDot(Dot(lhs, rhs)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Quaternion lhs, Quaternion rhs) { return !(lhs == rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(Quaternion a, Quaternion b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [ExcludeFromDocs] public void SetLookRotation(Vector3 view) { Vector3 up = Vector3.up; SetLookRotation(view, up); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetLookRotation(Vector3 view, [UnityEngine.Internal.DefaultValue("Vector3.up")] Vector3 up) { this = LookRotation(view, up); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Angle(Quaternion a, Quaternion b) { float num = Mathf.Min(Mathf.Abs(Dot(a, b)), 1f); return IsEqualUsingDot(num) ? 0f : (Mathf.Acos(num) * 2f * 57.29578f); } private static Vector3 Internal_MakePositive(Vector3 euler) { float num = -0.005729578f; float num2 = 360f + num; if (euler.x < num) { euler.x += 360f; } else if (euler.x > num2) { euler.x -= 360f; } if (euler.y < num) { euler.y += 360f; } else if (euler.y > num2) { euler.y -= 360f; } if (euler.z < num) { euler.z += 360f; } else if (euler.z > num2) { euler.z -= 360f; } return euler; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion Euler(float x, float y, float z) { return Internal_FromEulerRad(new Vector3(x, y, z) * ((float)Math.PI / 180f)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion Euler(Vector3 euler) { return Internal_FromEulerRad(euler * ((float)Math.PI / 180f)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ToAngleAxis(out float angle, out Vector3 axis) { Internal_ToAxisAngleRad(this, out axis, out angle); angle *= 57.29578f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetFromToRotation(Vector3 fromDirection, Vector3 toDirection) { this = FromToRotation(fromDirection, toDirection); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion RotateTowards(Quaternion from, Quaternion to, float maxDegreesDelta) { float num = Angle(from, to); if (num == 0f) { return to; } return SlerpUnclamped(from, to, Mathf.Min(1f, maxDegreesDelta / num)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion Normalize(Quaternion q) { float num = Mathf.Sqrt(Dot(q, q)); if (num < Mathf.Epsilon) { return identity; } return new Quaternion(q.x / num, q.y / num, q.z / num, q.w / num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Normalize() { this = Normalize(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return x.GetHashCode() ^ (y.GetHashCode() << 2) ^ (z.GetHashCode() >> 2) ^ (w.GetHashCode() >> 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object other) { if (!(other is Quaternion)) { return false; } return Equals((Quaternion)other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Quaternion other) { return x.Equals(other.x) && y.Equals(other.y) && z.Equals(other.z) && w.Equals(other.w); } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) { format = "F5"; } if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("({0}, {1}, {2}, {3})", new object[4] { x.ToString(format, formatProvider), y.ToString(format, formatProvider), z.ToString(format, formatProvider), w.ToString(format, formatProvider) }); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees.")] public static Quaternion EulerRotation(float x, float y, float z) { return Internal_FromEulerRad(new Vector3(x, y, z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees.")] public static Quaternion EulerRotation(Vector3 euler) { return Internal_FromEulerRad(euler); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees.")] public void SetEulerRotation(float x, float y, float z) { this = Internal_FromEulerRad(new Vector3(x, y, z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees.")] public void SetEulerRotation(Vector3 euler) { this = Internal_FromEulerRad(euler); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.eulerAngles instead. This function was deprecated because it uses radians instead of degrees.")] public Vector3 ToEuler() { return Internal_ToEulerRad(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees.")] public static Quaternion EulerAngles(float x, float y, float z) { return Internal_FromEulerRad(new Vector3(x, y, z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees.")] public static Quaternion EulerAngles(Vector3 euler) { return Internal_FromEulerRad(euler); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.ToAngleAxis instead. This function was deprecated because it uses radians instead of degrees.")] public void ToAxisAngle(out Vector3 axis, out float angle) { Internal_ToAxisAngleRad(this, out axis, out angle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees.")] public void SetEulerAngles(float x, float y, float z) { SetEulerRotation(new Vector3(x, y, z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.Euler instead. This function was deprecated because it uses radians instead of degrees.")] public void SetEulerAngles(Vector3 euler) { this = EulerRotation(euler); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.eulerAngles instead. This function was deprecated because it uses radians instead of degrees.")] public static Vector3 ToEulerAngles(Quaternion rotation) { return Internal_ToEulerRad(rotation); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.eulerAngles instead. This function was deprecated because it uses radians instead of degrees.")] public Vector3 ToEulerAngles() { return Internal_ToEulerRad(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.AngleAxis instead. This function was deprecated because it uses radians instead of degrees.")] public void SetAxisAngle(Vector3 axis, float angle) { this = AxisAngle(axis, angle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Obsolete("Use Quaternion.AngleAxis instead. This function was deprecated because it uses radians instead of degrees")] public static Quaternion AxisAngle(Vector3 axis, float angle) { return AngleAxis(57.29578f * angle, axis); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void FromToRotation_Injected(ref Vector3 fromDirection, ref Vector3 toDirection, out Quaternion ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Inverse_Injected(ref Quaternion rotation, out Quaternion ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Slerp_Injected(ref Quaternion a, ref Quaternion b, float t, out Quaternion ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SlerpUnclamped_Injected(ref Quaternion a, ref Quaternion b, float t, out Quaternion ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Lerp_Injected(ref Quaternion a, ref Quaternion b, float t, out Quaternion ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void LerpUnclamped_Injected(ref Quaternion a, ref Quaternion b, float t, out Quaternion ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_FromEulerRad_Injected(ref Vector3 euler, out Quaternion ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_ToEulerRad_Injected(ref Quaternion rotation, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_ToAxisAngleRad_Injected(ref Quaternion q, out Vector3 axis, out float angle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void AngleAxis_Injected(float angle, ref Vector3 axis, out Quaternion ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void LookRotation_Injected(ref Vector3 forward, [UnityEngine.Internal.DefaultValue("Vector3.up")] ref Vector3 upwards, out Quaternion ret); } [StructLayout(LayoutKind.Sequential, Size = 1)] [Il2CppEagerStaticClassConstruction] [NativeHeader("Runtime/Math/FloatConversion.h")] [NativeHeader("Runtime/Math/PerlinNoise.h")] [NativeHeader("Runtime/Utilities/BitUtility.h")] [NativeHeader("Runtime/Math/ColorSpaceConversion.h")] public struct Mathf { public const float PI = (float)Math.PI; public const float Infinity = float.PositiveInfinity; public const float NegativeInfinity = float.NegativeInfinity; public const float Deg2Rad = (float)Math.PI / 180f; public const float Rad2Deg = 57.29578f; public static readonly float Epsilon = (MathfInternal.IsFlushToZeroEnabled ? MathfInternal.FloatMinNormal : MathfInternal.FloatMinDenormal); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern int ClosestPowerOfTwo(int value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsPowerOfTwo(int value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern int NextPowerOfTwo(int value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern float GammaToLinearSpace(float value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern float LinearToGammaSpace(float value); [FreeFunction(IsThreadSafe = true)] public static Color CorrelatedColorTemperatureToRGB(float kelvin) { CorrelatedColorTemperatureToRGB_Injected(kelvin, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern ushort FloatToHalf(float val); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern float HalfToFloat(ushort val); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PerlinNoise::NoiseNormalized", IsThreadSafe = true)] public static extern float PerlinNoise(float x, float y); public static float Sin(float f) { return (float)Math.Sin(f); } public static float Cos(float f) { return (float)Math.Cos(f); } public static float Tan(float f) { return (float)Math.Tan(f); } public static float Asin(float f) { return (float)Math.Asin(f); } public static float Acos(float f) { return (float)Math.Acos(f); } public static float Atan(float f) { return (float)Math.Atan(f); } public static float Atan2(float y, float x) { return (float)Math.Atan2(y, x); } public static float Sqrt(float f) { return (float)Math.Sqrt(f); } public static float Abs(float f) { return Math.Abs(f); } public static int Abs(int value) { return Math.Abs(value); } public static float Min(float a, float b) { return (a < b) ? a : b; } public static float Min(params float[] values) { int num = values.Length; if (num == 0) { return 0f; } float num2 = values[0]; for (int i = 1; i < num; i++) { if (values[i] < num2) { num2 = values[i]; } } return num2; } public static int Min(int a, int b) { return (a < b) ? a : b; } public static int Min(params int[] values) { int num = values.Length; if (num == 0) { return 0; } int num2 = values[0]; for (int i = 1; i < num; i++) { if (values[i] < num2) { num2 = values[i]; } } return num2; } public static float Max(float a, float b) { return (a > b) ? a : b; } public static float Max(params float[] values) { int num = values.Length; if (num == 0) { return 0f; } float num2 = values[0]; for (int i = 1; i < num; i++) { if (values[i] > num2) { num2 = values[i]; } } return num2; } public static int Max(int a, int b) { return (a > b) ? a : b; } public static int Max(params int[] values) { int num = values.Length; if (num == 0) { return 0; } int num2 = values[0]; for (int i = 1; i < num; i++) { if (values[i] > num2) { num2 = values[i]; } } return num2; } public static float Pow(float f, float p) { return (float)Math.Pow(f, p); } public static float Exp(float power) { return (float)Math.Exp(power); } public static float Log(float f, float p) { return (float)Math.Log(f, p); } public static float Log(float f) { return (float)Math.Log(f); } public static float Log10(float f) { return (float)Math.Log10(f); } public static float Ceil(float f) { return (float)Math.Ceiling(f); } public static float Floor(float f) { return (float)Math.Floor(f); } public static float Round(float f) { return (float)Math.Round(f); } public static int CeilToInt(float f) { return (int)Math.Ceiling(f); } public static int FloorToInt(float f) { return (int)Math.Floor(f); } public static int RoundToInt(float f) { return (int)Math.Round(f); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Sign(float f) { return (f >= 0f) ? 1f : (-1f); } public static float Clamp(float value, float min, float max) { if (value < min) { value = min; } else if (value > max) { value = max; } return value; } public static int Clamp(int value, int min, int max) { if (value < min) { value = min; } else if (value > max) { value = max; } return value; } public static float Clamp01(float value) { if (value < 0f) { return 0f; } if (value > 1f) { return 1f; } return value; } public static float Lerp(float a, float b, float t) { return a + (b - a) * Clamp01(t); } public static float LerpUnclamped(float a, float b, float t) { return a + (b - a) * t; } public static float LerpAngle(float a, float b, float t) { float num = Repeat(b - a, 360f); if (num > 180f) { num -= 360f; } return a + num * Clamp01(t); } public static float MoveTowards(float current, float target, float maxDelta) { if (Abs(target - current) <= maxDelta) { return target; } return current + Sign(target - current) * maxDelta; } public static float MoveTowardsAngle(float current, float target, float maxDelta) { float num = DeltaAngle(current, target); if (0f - maxDelta < num && num < maxDelta) { return target; } target = current + num; return MoveTowards(current, target, maxDelta); } public static float SmoothStep(float from, float to, float t) { t = Clamp01(t); t = -2f * t * t * t + 3f * t * t; return to * t + from * (1f - t); } public static float Gamma(float value, float absmax, float gamma) { bool flag = value < 0f; float num = Abs(value); if (num > absmax) { return flag ? (0f - num) : num; } float num2 = Pow(num / absmax, gamma) * absmax; return flag ? (0f - num2) : num2; } public static bool Approximately(float a, float b) { return Abs(b - a) < Max(1E-06f * Max(Abs(a), Abs(b)), Epsilon * 8f); } [ExcludeFromDocs] public static float SmoothDamp(float current, float target, ref float currentVelocity, float smoothTime, float maxSpeed) { float deltaTime = Time.deltaTime; return SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); } [ExcludeFromDocs] public static float SmoothDamp(float current, float target, ref float currentVelocity, float smoothTime) { float deltaTime = Time.deltaTime; float maxSpeed = float.PositiveInfinity; return SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); } public static float SmoothDamp(float current, float target, ref float currentVelocity, float smoothTime, [UnityEngine.Internal.DefaultValue("Mathf.Infinity")] float maxSpeed, [UnityEngine.Internal.DefaultValue("Time.deltaTime")] float deltaTime) { smoothTime = Max(0.0001f, smoothTime); float num = 2f / smoothTime; float num2 = num * deltaTime; float num3 = 1f / (1f + num2 + 0.48f * num2 * num2 + 0.235f * num2 * num2 * num2); float value = current - target; float num4 = target; float num5 = maxSpeed * smoothTime; value = Clamp(value, 0f - num5, num5); target = current - value; float num6 = (currentVelocity + num * value) * deltaTime; currentVelocity = (currentVelocity - num * num6) * num3; float num7 = target + (value + num6) * num3; if (num4 - current > 0f == num7 > num4) { num7 = num4; currentVelocity = (num7 - num4) / deltaTime; } return num7; } [ExcludeFromDocs] public static float SmoothDampAngle(float current, float target, ref float currentVelocity, float smoothTime, float maxSpeed) { float deltaTime = Time.deltaTime; return SmoothDampAngle(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); } [ExcludeFromDocs] public static float SmoothDampAngle(float current, float target, ref float currentVelocity, float smoothTime) { float deltaTime = Time.deltaTime; float maxSpeed = float.PositiveInfinity; return SmoothDampAngle(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); } public static float SmoothDampAngle(float current, float target, ref float currentVelocity, float smoothTime, [UnityEngine.Internal.DefaultValue("Mathf.Infinity")] float maxSpeed, [UnityEngine.Internal.DefaultValue("Time.deltaTime")] float deltaTime) { target = current + DeltaAngle(current, target); return SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); } public static float Repeat(float t, float length) { return Clamp(t - Floor(t / length) * length, 0f, length); } public static float PingPong(float t, float length) { t = Repeat(t, length * 2f); return length - Abs(t - length); } public static float InverseLerp(float a, float b, float value) { if (a != b) { return Clamp01((value - a) / (b - a)); } return 0f; } public static float DeltaAngle(float current, float target) { float num = Repeat(target - current, 360f); if (num > 180f) { num -= 360f; } return num; } internal static bool LineIntersection(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, ref Vector2 result) { float num = p2.x - p1.x; float num2 = p2.y - p1.y; float num3 = p4.x - p3.x; float num4 = p4.y - p3.y; float num5 = num * num4 - num2 * num3; if (num5 == 0f) { return false; } float num6 = p3.x - p1.x; float num7 = p3.y - p1.y; float num8 = (num6 * num4 - num7 * num3) / num5; result.x = p1.x + num8 * num; result.y = p1.y + num8 * num2; return true; } internal static bool LineSegmentIntersection(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, ref Vector2 result) { float num = p2.x - p1.x; float num2 = p2.y - p1.y; float num3 = p4.x - p3.x; float num4 = p4.y - p3.y; float num5 = num * num4 - num2 * num3; if (num5 == 0f) { return false; } float num6 = p3.x - p1.x; float num7 = p3.y - p1.y; float num8 = (num6 * num4 - num7 * num3) / num5; if (num8 < 0f || num8 > 1f) { return false; } float num9 = (num6 * num2 - num7 * num) / num5; if (num9 < 0f || num9 > 1f) { return false; } result.x = p1.x + num8 * num; result.y = p1.y + num8 * num2; return true; } internal static long RandomToLong(System.Random r) { byte[] array = new byte[8]; r.NextBytes(array); return (long)(BitConverter.ToUInt64(array, 0) & 0x7FFFFFFFFFFFFFFFL); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CorrelatedColorTemperatureToRGB_Injected(float kelvin, out Color ret); } internal static class MethodImplOptionsEx { public const short AggressiveInlining = 256; } [RequiredByNativeCode(Optional = true, GenerateProxy = true)] [NativeClass("Vector2f")] [Il2CppEagerStaticClassConstruction] public struct Vector2 : IEquatable, IFormattable { public float x; public float y; private static readonly Vector2 zeroVector = new Vector2(0f, 0f); private static readonly Vector2 oneVector = new Vector2(1f, 1f); private static readonly Vector2 upVector = new Vector2(0f, 1f); private static readonly Vector2 downVector = new Vector2(0f, -1f); private static readonly Vector2 leftVector = new Vector2(-1f, 0f); private static readonly Vector2 rightVector = new Vector2(1f, 0f); private static readonly Vector2 positiveInfinityVector = new Vector2(float.PositiveInfinity, float.PositiveInfinity); private static readonly Vector2 negativeInfinityVector = new Vector2(float.NegativeInfinity, float.NegativeInfinity); public const float kEpsilon = 1E-05f; public const float kEpsilonNormalSqrt = 1E-15f; public float this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return index switch { 0 => x, 1 => y, _ => throw new IndexOutOfRangeException("Invalid Vector2 index!"), }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { switch (index) { case 0: x = value; break; case 1: y = value; break; default: throw new IndexOutOfRangeException("Invalid Vector2 index!"); } } } public Vector2 normalized { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Vector2 result = new Vector2(x, y); result.Normalize(); return result; } } public float magnitude { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (float)Math.Sqrt(x * x + y * y); } } public float sqrMagnitude { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return x * x + y * y; } } public static Vector2 zero { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return zeroVector; } } public static Vector2 one { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return oneVector; } } public static Vector2 up { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return upVector; } } public static Vector2 down { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return downVector; } } public static Vector2 left { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return leftVector; } } public static Vector2 right { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return rightVector; } } public static Vector2 positiveInfinity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return positiveInfinityVector; } } public static Vector2 negativeInfinity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return negativeInfinityVector; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector2(float x, float y) { this.x = x; this.y = y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Set(float newX, float newY) { x = newX; y = newY; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Lerp(Vector2 a, Vector2 b, float t) { t = Mathf.Clamp01(t); return new Vector2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 LerpUnclamped(Vector2 a, Vector2 b, float t) { return new Vector2(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 MoveTowards(Vector2 current, Vector2 target, float maxDistanceDelta) { float num = target.x - current.x; float num2 = target.y - current.y; float num3 = num * num + num2 * num2; if (num3 == 0f || (maxDistanceDelta >= 0f && num3 <= maxDistanceDelta * maxDistanceDelta)) { return target; } float num4 = (float)Math.Sqrt(num3); return new Vector2(current.x + num / num4 * maxDistanceDelta, current.y + num2 / num4 * maxDistanceDelta); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Scale(Vector2 a, Vector2 b) { return new Vector2(a.x * b.x, a.y * b.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Scale(Vector2 scale) { x *= scale.x; y *= scale.y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Normalize() { float num = magnitude; if (num > 1E-05f) { this /= num; } else { this = zero; } } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) { format = "F2"; } if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("({0}, {1})", new object[2] { x.ToString(format, formatProvider), y.ToString(format, formatProvider) }); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return x.GetHashCode() ^ (y.GetHashCode() << 2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object other) { if (!(other is Vector2)) { return false; } return Equals((Vector2)other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Vector2 other) { return x == other.x && y == other.y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Reflect(Vector2 inDirection, Vector2 inNormal) { float num = -2f * Dot(inNormal, inDirection); return new Vector2(num * inNormal.x + inDirection.x, num * inNormal.y + inDirection.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Perpendicular(Vector2 inDirection) { return new Vector2(0f - inDirection.y, inDirection.x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(Vector2 lhs, Vector2 rhs) { return lhs.x * rhs.x + lhs.y * rhs.y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Angle(Vector2 from, Vector2 to) { float num = (float)Math.Sqrt(from.sqrMagnitude * to.sqrMagnitude); if (num < 1E-15f) { return 0f; } float num2 = Mathf.Clamp(Dot(from, to) / num, -1f, 1f); return (float)Math.Acos(num2) * 57.29578f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float SignedAngle(Vector2 from, Vector2 to) { float num = Angle(from, to); float num2 = Mathf.Sign(from.x * to.y - from.y * to.x); return num * num2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector2 a, Vector2 b) { float num = a.x - b.x; float num2 = a.y - b.y; return (float)Math.Sqrt(num * num + num2 * num2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 ClampMagnitude(Vector2 vector, float maxLength) { float num = vector.sqrMagnitude; if (num > maxLength * maxLength) { float num2 = (float)Math.Sqrt(num); float num3 = vector.x / num2; float num4 = vector.y / num2; return new Vector2(num3 * maxLength, num4 * maxLength); } return vector; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float SqrMagnitude(Vector2 a) { return a.x * a.x + a.y * a.y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public float SqrMagnitude() { return x * x + y * y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Min(Vector2 lhs, Vector2 rhs) { return new Vector2(Mathf.Min(lhs.x, rhs.x), Mathf.Min(lhs.y, rhs.y)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Max(Vector2 lhs, Vector2 rhs) { return new Vector2(Mathf.Max(lhs.x, rhs.x), Mathf.Max(lhs.y, rhs.y)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [ExcludeFromDocs] public static Vector2 SmoothDamp(Vector2 current, Vector2 target, ref Vector2 currentVelocity, float smoothTime, float maxSpeed) { float deltaTime = Time.deltaTime; return SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [ExcludeFromDocs] public static Vector2 SmoothDamp(Vector2 current, Vector2 target, ref Vector2 currentVelocity, float smoothTime) { float deltaTime = Time.deltaTime; float maxSpeed = float.PositiveInfinity; return SmoothDamp(current, target, ref currentVelocity, smoothTime, maxSpeed, deltaTime); } public static Vector2 SmoothDamp(Vector2 current, Vector2 target, ref Vector2 currentVelocity, float smoothTime, [UnityEngine.Internal.DefaultValue("Mathf.Infinity")] float maxSpeed, [UnityEngine.Internal.DefaultValue("Time.deltaTime")] float deltaTime) { smoothTime = Mathf.Max(0.0001f, smoothTime); float num = 2f / smoothTime; float num2 = num * deltaTime; float num3 = 1f / (1f + num2 + 0.48f * num2 * num2 + 0.235f * num2 * num2 * num2); float num4 = current.x - target.x; float num5 = current.y - target.y; Vector2 vector = target; float num6 = maxSpeed * smoothTime; float num7 = num6 * num6; float num8 = num4 * num4 + num5 * num5; if (num8 > num7) { float num9 = (float)Math.Sqrt(num8); num4 = num4 / num9 * num6; num5 = num5 / num9 * num6; } target.x = current.x - num4; target.y = current.y - num5; float num10 = (currentVelocity.x + num * num4) * deltaTime; float num11 = (currentVelocity.y + num * num5) * deltaTime; currentVelocity.x = (currentVelocity.x - num * num10) * num3; currentVelocity.y = (currentVelocity.y - num * num11) * num3; float num12 = target.x + (num4 + num10) * num3; float num13 = target.y + (num5 + num11) * num3; float num14 = vector.x - current.x; float num15 = vector.y - current.y; float num16 = num12 - vector.x; float num17 = num13 - vector.y; if (num14 * num16 + num15 * num17 > 0f) { num12 = vector.x; num13 = vector.y; currentVelocity.x = (num12 - vector.x) / deltaTime; currentVelocity.y = (num13 - vector.y) / deltaTime; } return new Vector2(num12, num13); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator +(Vector2 a, Vector2 b) { return new Vector2(a.x + b.x, a.y + b.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator -(Vector2 a, Vector2 b) { return new Vector2(a.x - b.x, a.y - b.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator *(Vector2 a, Vector2 b) { return new Vector2(a.x * b.x, a.y * b.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator /(Vector2 a, Vector2 b) { return new Vector2(a.x / b.x, a.y / b.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator -(Vector2 a) { return new Vector2(0f - a.x, 0f - a.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator *(Vector2 a, float d) { return new Vector2(a.x * d, a.y * d); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator *(float d, Vector2 a) { return new Vector2(a.x * d, a.y * d); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator /(Vector2 a, float d) { return new Vector2(a.x / d, a.y / d); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector2 lhs, Vector2 rhs) { float num = lhs.x - rhs.x; float num2 = lhs.y - rhs.y; return num * num + num2 * num2 < 9.9999994E-11f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector2 lhs, Vector2 rhs) { return !(lhs == rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Vector2(Vector3 v) { return new Vector2(v.x, v.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Vector3(Vector2 v) { return new Vector3(v.x, v.y, 0f); } } [Il2CppEagerStaticClassConstruction] [NativeType("Runtime/Math/Vector2Int.h")] [UsedByNativeCode] public struct Vector2Int : IEquatable, IFormattable { private int m_X; private int m_Y; private static readonly Vector2Int s_Zero = new Vector2Int(0, 0); private static readonly Vector2Int s_One = new Vector2Int(1, 1); private static readonly Vector2Int s_Up = new Vector2Int(0, 1); private static readonly Vector2Int s_Down = new Vector2Int(0, -1); private static readonly Vector2Int s_Left = new Vector2Int(-1, 0); private static readonly Vector2Int s_Right = new Vector2Int(1, 0); public int x { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_X; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { m_X = value; } } public int y { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_Y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { m_Y = value; } } public int this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return index switch { 0 => x, 1 => y, _ => throw new IndexOutOfRangeException($"Invalid Vector2Int index addressed: {index}!"), }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { switch (index) { case 0: x = value; break; case 1: y = value; break; default: throw new IndexOutOfRangeException($"Invalid Vector2Int index addressed: {index}!"); } } } public float magnitude { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Mathf.Sqrt(x * x + y * y); } } public int sqrMagnitude { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return x * x + y * y; } } public static Vector2Int zero { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_Zero; } } public static Vector2Int one { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_One; } } public static Vector2Int up { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_Up; } } public static Vector2Int down { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_Down; } } public static Vector2Int left { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_Left; } } public static Vector2Int right { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_Right; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector2Int(int x, int y) { m_X = x; m_Y = y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Set(int x, int y) { m_X = x; m_Y = y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector2Int a, Vector2Int b) { float num = a.x - b.x; float num2 = a.y - b.y; return (float)Math.Sqrt(num * num + num2 * num2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2Int Min(Vector2Int lhs, Vector2Int rhs) { return new Vector2Int(Mathf.Min(lhs.x, rhs.x), Mathf.Min(lhs.y, rhs.y)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2Int Max(Vector2Int lhs, Vector2Int rhs) { return new Vector2Int(Mathf.Max(lhs.x, rhs.x), Mathf.Max(lhs.y, rhs.y)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2Int Scale(Vector2Int a, Vector2Int b) { return new Vector2Int(a.x * b.x, a.y * b.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Scale(Vector2Int scale) { x *= scale.x; y *= scale.y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clamp(Vector2Int min, Vector2Int max) { x = Math.Max(min.x, x); x = Math.Min(max.x, x); y = Math.Max(min.y, y); y = Math.Min(max.y, y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Vector2(Vector2Int v) { return new Vector2(v.x, v.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Vector3Int(Vector2Int v) { return new Vector3Int(v.x, v.y, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2Int FloorToInt(Vector2 v) { return new Vector2Int(Mathf.FloorToInt(v.x), Mathf.FloorToInt(v.y)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2Int CeilToInt(Vector2 v) { return new Vector2Int(Mathf.CeilToInt(v.x), Mathf.CeilToInt(v.y)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2Int RoundToInt(Vector2 v) { return new Vector2Int(Mathf.RoundToInt(v.x), Mathf.RoundToInt(v.y)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2Int operator -(Vector2Int v) { return new Vector2Int(-v.x, -v.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2Int operator +(Vector2Int a, Vector2Int b) { return new Vector2Int(a.x + b.x, a.y + b.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2Int operator -(Vector2Int a, Vector2Int b) { return new Vector2Int(a.x - b.x, a.y - b.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2Int operator *(Vector2Int a, Vector2Int b) { return new Vector2Int(a.x * b.x, a.y * b.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2Int operator *(int a, Vector2Int b) { return new Vector2Int(a * b.x, a * b.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2Int operator *(Vector2Int a, int b) { return new Vector2Int(a.x * b, a.y * b); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2Int operator /(Vector2Int a, int b) { return new Vector2Int(a.x / b, a.y / b); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector2Int lhs, Vector2Int rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector2Int lhs, Vector2Int rhs) { return !(lhs == rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object other) { if (!(other is Vector2Int)) { return false; } return Equals((Vector2Int)other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Vector2Int other) { return x == other.x && y == other.y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return x.GetHashCode() ^ (y.GetHashCode() << 2); } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("({0}, {1})", new object[2] { x.ToString(format, formatProvider), y.ToString(format, formatProvider) }); } } [Il2CppEagerStaticClassConstruction] [UsedByNativeCode] public struct Vector3Int : IEquatable, IFormattable { private int m_X; private int m_Y; private int m_Z; private static readonly Vector3Int s_Zero = new Vector3Int(0, 0, 0); private static readonly Vector3Int s_One = new Vector3Int(1, 1, 1); private static readonly Vector3Int s_Up = new Vector3Int(0, 1, 0); private static readonly Vector3Int s_Down = new Vector3Int(0, -1, 0); private static readonly Vector3Int s_Left = new Vector3Int(-1, 0, 0); private static readonly Vector3Int s_Right = new Vector3Int(1, 0, 0); private static readonly Vector3Int s_Forward = new Vector3Int(0, 0, 1); private static readonly Vector3Int s_Back = new Vector3Int(0, 0, -1); public int x { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_X; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { m_X = value; } } public int y { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_Y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { m_Y = value; } } public int z { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_Z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { m_Z = value; } } public int this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return index switch { 0 => x, 1 => y, 2 => z, _ => throw new IndexOutOfRangeException(UnityString.Format("Invalid Vector3Int index addressed: {0}!", new object[1] { index })), }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { switch (index) { case 0: x = value; break; case 1: y = value; break; case 2: z = value; break; default: throw new IndexOutOfRangeException(UnityString.Format("Invalid Vector3Int index addressed: {0}!", new object[1] { index })); } } } public float magnitude { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Mathf.Sqrt(x * x + y * y + z * z); } } public int sqrMagnitude { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return x * x + y * y + z * z; } } public static Vector3Int zero { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_Zero; } } public static Vector3Int one { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_One; } } public static Vector3Int up { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_Up; } } public static Vector3Int down { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_Down; } } public static Vector3Int left { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_Left; } } public static Vector3Int right { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_Right; } } public static Vector3Int forward { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_Forward; } } public static Vector3Int back { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return s_Back; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector3Int(int x, int y) { m_X = x; m_Y = y; m_Z = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector3Int(int x, int y, int z) { m_X = x; m_Y = y; m_Z = z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Set(int x, int y, int z) { m_X = x; m_Y = y; m_Z = z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector3Int a, Vector3Int b) { return (a - b).magnitude; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3Int Min(Vector3Int lhs, Vector3Int rhs) { return new Vector3Int(Mathf.Min(lhs.x, rhs.x), Mathf.Min(lhs.y, rhs.y), Mathf.Min(lhs.z, rhs.z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3Int Max(Vector3Int lhs, Vector3Int rhs) { return new Vector3Int(Mathf.Max(lhs.x, rhs.x), Mathf.Max(lhs.y, rhs.y), Mathf.Max(lhs.z, rhs.z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3Int Scale(Vector3Int a, Vector3Int b) { return new Vector3Int(a.x * b.x, a.y * b.y, a.z * b.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Scale(Vector3Int scale) { x *= scale.x; y *= scale.y; z *= scale.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Clamp(Vector3Int min, Vector3Int max) { x = Math.Max(min.x, x); x = Math.Min(max.x, x); y = Math.Max(min.y, y); y = Math.Min(max.y, y); z = Math.Max(min.z, z); z = Math.Min(max.z, z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Vector3(Vector3Int v) { return new Vector3(v.x, v.y, v.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static explicit operator Vector2Int(Vector3Int v) { return new Vector2Int(v.x, v.y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3Int FloorToInt(Vector3 v) { return new Vector3Int(Mathf.FloorToInt(v.x), Mathf.FloorToInt(v.y), Mathf.FloorToInt(v.z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3Int CeilToInt(Vector3 v) { return new Vector3Int(Mathf.CeilToInt(v.x), Mathf.CeilToInt(v.y), Mathf.CeilToInt(v.z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3Int RoundToInt(Vector3 v) { return new Vector3Int(Mathf.RoundToInt(v.x), Mathf.RoundToInt(v.y), Mathf.RoundToInt(v.z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3Int operator +(Vector3Int a, Vector3Int b) { return new Vector3Int(a.x + b.x, a.y + b.y, a.z + b.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3Int operator -(Vector3Int a, Vector3Int b) { return new Vector3Int(a.x - b.x, a.y - b.y, a.z - b.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3Int operator *(Vector3Int a, Vector3Int b) { return new Vector3Int(a.x * b.x, a.y * b.y, a.z * b.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3Int operator -(Vector3Int a) { return new Vector3Int(-a.x, -a.y, -a.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3Int operator *(Vector3Int a, int b) { return new Vector3Int(a.x * b, a.y * b, a.z * b); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3Int operator *(int a, Vector3Int b) { return new Vector3Int(a * b.x, a * b.y, a * b.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3Int operator /(Vector3Int a, int b) { return new Vector3Int(a.x / b, a.y / b, a.z / b); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector3Int lhs, Vector3Int rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector3Int lhs, Vector3Int rhs) { return !(lhs == rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object other) { if (!(other is Vector3Int)) { return false; } return Equals((Vector3Int)other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Vector3Int other) { return this == other; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { int hashCode = y.GetHashCode(); int hashCode2 = z.GetHashCode(); return x.GetHashCode() ^ (hashCode << 4) ^ (hashCode >> 28) ^ (hashCode2 >> 4) ^ (hashCode2 << 28); } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("({0}, {1}, {2})", new object[3] { x.ToString(format, formatProvider), y.ToString(format, formatProvider), z.ToString(format, formatProvider) }); } } [NativeClass("Vector4f")] [NativeHeader("Runtime/Math/Vector4.h")] [RequiredByNativeCode(Optional = true, GenerateProxy = true)] [Il2CppEagerStaticClassConstruction] public struct Vector4 : IEquatable, IFormattable { public const float kEpsilon = 1E-05f; public float x; public float y; public float z; public float w; private static readonly Vector4 zeroVector = new Vector4(0f, 0f, 0f, 0f); private static readonly Vector4 oneVector = new Vector4(1f, 1f, 1f, 1f); private static readonly Vector4 positiveInfinityVector = new Vector4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); private static readonly Vector4 negativeInfinityVector = new Vector4(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity); public float this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return index switch { 0 => x, 1 => y, 2 => z, 3 => w, _ => throw new IndexOutOfRangeException("Invalid Vector4 index!"), }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { switch (index) { case 0: x = value; break; case 1: y = value; break; case 2: z = value; break; case 3: w = value; break; default: throw new IndexOutOfRangeException("Invalid Vector4 index!"); } } } public Vector4 normalized { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Normalize(this); } } public float magnitude { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (float)Math.Sqrt(Dot(this, this)); } } public float sqrMagnitude { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Dot(this, this); } } public static Vector4 zero { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return zeroVector; } } public static Vector4 one { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return oneVector; } } public static Vector4 positiveInfinity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return positiveInfinityVector; } } public static Vector4 negativeInfinity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return negativeInfinityVector; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector4(float x, float y, float z, float w) { this.x = x; this.y = y; this.z = z; this.w = w; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector4(float x, float y, float z) { this.x = x; this.y = y; this.z = z; w = 0f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector4(float x, float y) { this.x = x; this.y = y; z = 0f; w = 0f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Set(float newX, float newY, float newZ, float newW) { x = newX; y = newY; z = newZ; w = newW; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Lerp(Vector4 a, Vector4 b, float t) { t = Mathf.Clamp01(t); return new Vector4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 LerpUnclamped(Vector4 a, Vector4 b, float t) { return new Vector4(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w + (b.w - a.w) * t); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 MoveTowards(Vector4 current, Vector4 target, float maxDistanceDelta) { float num = target.x - current.x; float num2 = target.y - current.y; float num3 = target.z - current.z; float num4 = target.w - current.w; float num5 = num * num + num2 * num2 + num3 * num3 + num4 * num4; if (num5 == 0f || (maxDistanceDelta >= 0f && num5 <= maxDistanceDelta * maxDistanceDelta)) { return target; } float num6 = (float)Math.Sqrt(num5); return new Vector4(current.x + num / num6 * maxDistanceDelta, current.y + num2 / num6 * maxDistanceDelta, current.z + num3 / num6 * maxDistanceDelta, current.w + num4 / num6 * maxDistanceDelta); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Scale(Vector4 a, Vector4 b) { return new Vector4(a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Scale(Vector4 scale) { x *= scale.x; y *= scale.y; z *= scale.z; w *= scale.w; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { return x.GetHashCode() ^ (y.GetHashCode() << 2) ^ (z.GetHashCode() >> 2) ^ (w.GetHashCode() >> 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Equals(object other) { if (!(other is Vector4)) { return false; } return Equals((Vector4)other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Vector4 other) { return x == other.x && y == other.y && z == other.z && w == other.w; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Normalize(Vector4 a) { float num = Magnitude(a); if (num > 1E-05f) { return a / num; } return zero; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Normalize() { float num = Magnitude(this); if (num > 1E-05f) { this /= num; } else { this = zero; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(Vector4 a, Vector4 b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Project(Vector4 a, Vector4 b) { return b * (Dot(a, b) / Dot(b, b)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector4 a, Vector4 b) { return Magnitude(a - b); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Magnitude(Vector4 a) { return (float)Math.Sqrt(Dot(a, a)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Min(Vector4 lhs, Vector4 rhs) { return new Vector4(Mathf.Min(lhs.x, rhs.x), Mathf.Min(lhs.y, rhs.y), Mathf.Min(lhs.z, rhs.z), Mathf.Min(lhs.w, rhs.w)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Max(Vector4 lhs, Vector4 rhs) { return new Vector4(Mathf.Max(lhs.x, rhs.x), Mathf.Max(lhs.y, rhs.y), Mathf.Max(lhs.z, rhs.z), Mathf.Max(lhs.w, rhs.w)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator +(Vector4 a, Vector4 b) { return new Vector4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator -(Vector4 a, Vector4 b) { return new Vector4(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator -(Vector4 a) { return new Vector4(0f - a.x, 0f - a.y, 0f - a.z, 0f - a.w); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator *(Vector4 a, float d) { return new Vector4(a.x * d, a.y * d, a.z * d, a.w * d); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator *(float d, Vector4 a) { return new Vector4(a.x * d, a.y * d, a.z * d, a.w * d); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator /(Vector4 a, float d) { return new Vector4(a.x / d, a.y / d, a.z / d, a.w / d); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Vector4 lhs, Vector4 rhs) { float num = lhs.x - rhs.x; float num2 = lhs.y - rhs.y; float num3 = lhs.z - rhs.z; float num4 = lhs.w - rhs.w; float num5 = num * num + num2 * num2 + num3 * num3 + num4 * num4; return num5 < 9.9999994E-11f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Vector4 lhs, Vector4 rhs) { return !(lhs == rhs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Vector4(Vector3 v) { return new Vector4(v.x, v.y, v.z, 0f); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Vector3(Vector4 v) { return new Vector3(v.x, v.y, v.z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Vector4(Vector2 v) { return new Vector4(v.x, v.y, 0f, 0f); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Vector2(Vector4 v) { return new Vector2(v.x, v.y); } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) { format = "F2"; } if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("({0}, {1}, {2}, {3})", new object[4] { x.ToString(format, formatProvider), y.ToString(format, formatProvider), z.ToString(format, formatProvider), w.ToString(format, formatProvider) }); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float SqrMagnitude(Vector4 a) { return Dot(a, a); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public float SqrMagnitude() { return Dot(this, this); } } [NativeHeader("Runtime/Export/Networking/Ping.bindings.h")] public sealed class Ping { internal IntPtr m_Ptr; public bool isDone { get { if (m_Ptr == IntPtr.Zero) { return false; } return Internal_IsDone(); } } public extern int time { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern string ip { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetIP")] get; } public Ping(string address) { m_Ptr = Internal_Create(address); } ~Ping() { DestroyPing(); } [ThreadAndSerializationSafe] public void DestroyPing() { if (!(m_Ptr == IntPtr.Zero)) { Internal_Destroy(m_Ptr); m_Ptr = IntPtr.Zero; } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("DestroyPing", IsThreadSafe = true)] private static extern void Internal_Destroy(IntPtr ptr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CreatePing")] private static extern IntPtr Internal_Create(string address); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetIsDone")] private extern bool Internal_IsDone(); } internal interface IPlayerEditorConnectionNative { void Initialize(); void DisconnectAll(); void SendMessage(Guid messageId, byte[] data, int playerId); bool TrySendMessage(Guid messageId, byte[] data, int playerId); void Poll(); void RegisterInternal(Guid messageId); void UnregisterInternal(Guid messageId); bool IsConnected(); } [NativeHeader("Runtime/Export/PlayerConnection/PlayerConnectionInternal.bindings.h")] internal class PlayerConnectionInternal : IPlayerEditorConnectionNative { [Flags] public enum MulticastFlags { kRequestImmediateConnect = 1, kSupportsProfile = 2, kCustomMessage = 4, kUseAlternateIP = 8 } void IPlayerEditorConnectionNative.SendMessage(Guid messageId, byte[] data, int playerId) { if (messageId == Guid.Empty) { throw new ArgumentException("messageId must not be empty"); } SendMessage(messageId.ToString("N"), data, playerId); } bool IPlayerEditorConnectionNative.TrySendMessage(Guid messageId, byte[] data, int playerId) { if (messageId == Guid.Empty) { throw new ArgumentException("messageId must not be empty"); } return TrySendMessage(messageId.ToString("N"), data, playerId); } void IPlayerEditorConnectionNative.Poll() { PollInternal(); } void IPlayerEditorConnectionNative.RegisterInternal(Guid messageId) { RegisterInternal(messageId.ToString("N")); } void IPlayerEditorConnectionNative.UnregisterInternal(Guid messageId) { UnregisterInternal(messageId.ToString("N")); } void IPlayerEditorConnectionNative.Initialize() { Initialize(); } bool IPlayerEditorConnectionNative.IsConnected() { return IsConnected(); } void IPlayerEditorConnectionNative.DisconnectAll() { DisconnectAll(); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PlayerConnection_Bindings::IsConnected")] private static extern bool IsConnected(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PlayerConnection_Bindings::Initialize")] private static extern void Initialize(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PlayerConnection_Bindings::RegisterInternal")] private static extern void RegisterInternal(string messageId); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PlayerConnection_Bindings::UnregisterInternal")] private static extern void UnregisterInternal(string messageId); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PlayerConnection_Bindings::SendMessage")] private static extern void SendMessage(string messageId, [Unmarshalled] byte[] data, int playerId); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PlayerConnection_Bindings::TrySendMessage")] private static extern bool TrySendMessage(string messageId, [Unmarshalled] byte[] data, int playerId); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PlayerConnection_Bindings::PollInternal")] private static extern void PollInternal(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PlayerConnection_Bindings::DisconnectAll")] private static extern void DisconnectAll(); } public class PlayerPrefsException : Exception { public PlayerPrefsException(string error) : base(error) { } } [NativeHeader("Runtime/Utilities/PlayerPrefs.h")] public class PlayerPrefs { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("SetInt")] private static extern bool TrySetInt(string key, int value); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("SetFloat")] private static extern bool TrySetFloat(string key, float value); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("SetString")] private static extern bool TrySetSetString(string key, string value); public static void SetInt(string key, int value) { if (!TrySetInt(key, value)) { throw new PlayerPrefsException("Could not store preference value"); } } [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetInt(string key, int defaultValue); public static int GetInt(string key) { return GetInt(key, 0); } public static void SetFloat(string key, float value) { if (!TrySetFloat(key, value)) { throw new PlayerPrefsException("Could not store preference value"); } } [MethodImpl(MethodImplOptions.InternalCall)] public static extern float GetFloat(string key, float defaultValue); public static float GetFloat(string key) { return GetFloat(key, 0f); } public static void SetString(string key, string value) { if (!TrySetSetString(key, value)) { throw new PlayerPrefsException("Could not store preference value"); } } [MethodImpl(MethodImplOptions.InternalCall)] public static extern string GetString(string key, string defaultValue); public static string GetString(string key) { return GetString(key, ""); } [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool HasKey(string key); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void DeleteKey(string key); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("DeleteAllWithCallback")] public static extern void DeleteAll(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("Sync")] public static extern void Save(); } [NativeHeader("Editor/Src/Properties/DrivenPropertyManager.h")] internal class DrivenPropertyManager { [Conditional("UNITY_EDITOR")] public static void RegisterProperty(Object driver, Object target, string propertyPath) { RegisterPropertyPartial(driver, target, propertyPath); } [Conditional("UNITY_EDITOR")] public static void TryRegisterProperty(Object driver, Object target, string propertyPath) { TryRegisterPropertyPartial(driver, target, propertyPath); } [Conditional("UNITY_EDITOR")] public static void UnregisterProperty(Object driver, Object target, string propertyPath) { UnregisterPropertyPartial(driver, target, propertyPath); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("UNITY_EDITOR")] [Conditional("UNITY_EDITOR")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern void UnregisterProperties([NotNull("ArgumentNullException")] Object driver); [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("UNITY_EDITOR")] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern void RegisterPropertyPartial([NotNull("ArgumentNullException")] Object driver, [NotNull("ArgumentNullException")] Object target, [NotNull("ArgumentNullException")] string propertyPath); [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("UNITY_EDITOR")] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern void TryRegisterPropertyPartial([NotNull("ArgumentNullException")] Object driver, [NotNull("ArgumentNullException")] Object target, [NotNull("ArgumentNullException")] string propertyPath); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeConditional("UNITY_EDITOR")] private static extern void UnregisterPropertyPartial([NotNull("ArgumentNullException")] Object driver, [NotNull("ArgumentNullException")] Object target, [NotNull("ArgumentNullException")] string propertyPath); } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public abstract class PropertyAttribute : Attribute { public int order { get; set; } } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = true)] public class ContextMenuItemAttribute : PropertyAttribute { public readonly string name; public readonly string function; public ContextMenuItemAttribute(string name, string function) { this.name = name; this.function = function; } } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public class InspectorNameAttribute : PropertyAttribute { public readonly string displayName; public InspectorNameAttribute(string displayName) { this.displayName = displayName; } } [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] public class TooltipAttribute : PropertyAttribute { public readonly string tooltip; public TooltipAttribute(string tooltip) { this.tooltip = tooltip; } } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = true)] public class SpaceAttribute : PropertyAttribute { public readonly float height; public SpaceAttribute() { height = 8f; } public SpaceAttribute(float height) { this.height = height; } } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = true)] public class HeaderAttribute : PropertyAttribute { public readonly string header; public HeaderAttribute(string header) { this.header = header; } } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class RangeAttribute : PropertyAttribute { public readonly float min; public readonly float max; public RangeAttribute(float min, float max) { this.min = min; this.max = max; } } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class MinAttribute : PropertyAttribute { public readonly float min; public MinAttribute(float min) { this.min = min; } } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class MultilineAttribute : PropertyAttribute { public readonly int lines; public MultilineAttribute() { lines = 3; } public MultilineAttribute(int lines) { this.lines = lines; } } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class TextAreaAttribute : PropertyAttribute { public readonly int minLines; public readonly int maxLines; public TextAreaAttribute() { minLines = 3; maxLines = 3; } public TextAreaAttribute(int minLines, int maxLines) { this.minLines = minLines; this.maxLines = maxLines; } } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class ColorUsageAttribute : PropertyAttribute { public readonly bool showAlpha = true; public readonly bool hdr = false; [Obsolete("This field is no longer used for anything.")] public readonly float minBrightness = 0f; [Obsolete("This field is no longer used for anything.")] public readonly float maxBrightness = 8f; [Obsolete("This field is no longer used for anything.")] public readonly float minExposureValue = 0.125f; [Obsolete("This field is no longer used for anything.")] public readonly float maxExposureValue = 3f; public ColorUsageAttribute(bool showAlpha) { this.showAlpha = showAlpha; } public ColorUsageAttribute(bool showAlpha, bool hdr) { this.showAlpha = showAlpha; this.hdr = hdr; } [Obsolete("Brightness and exposure parameters are no longer used for anything. Use ColorUsageAttribute(bool showAlpha, bool hdr)")] public ColorUsageAttribute(bool showAlpha, bool hdr, float minBrightness, float maxBrightness, float minExposureValue, float maxExposureValue) { this.showAlpha = showAlpha; this.hdr = hdr; this.minBrightness = minBrightness; this.maxBrightness = maxBrightness; this.minExposureValue = minExposureValue; this.maxExposureValue = maxExposureValue; } } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class GradientUsageAttribute : PropertyAttribute { public readonly bool hdr = false; public readonly ColorSpace colorSpace = ColorSpace.Gamma; public GradientUsageAttribute(bool hdr) { this.hdr = hdr; colorSpace = ColorSpace.Gamma; } public GradientUsageAttribute(bool hdr, ColorSpace colorSpace) { this.hdr = hdr; this.colorSpace = colorSpace; } } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class DelayedAttribute : PropertyAttribute { } [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class NonReorderableAttribute : PropertyAttribute { } [NativeHeader("Runtime/Utilities/PropertyName.h")] internal class PropertyNameUtils { [FreeFunction(IsThreadSafe = true)] public static PropertyName PropertyNameFromString([Unmarshalled] string name) { PropertyNameFromString_Injected(name, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void PropertyNameFromString_Injected(string name, out PropertyName ret); } [UsedByNativeCode] public struct PropertyName : IEquatable { internal int id; public PropertyName(string name) : this(PropertyNameUtils.PropertyNameFromString(name)) { } public PropertyName(PropertyName other) { id = other.id; } public PropertyName(int id) { this.id = id; } public static bool IsNullOrEmpty(PropertyName prop) { return prop.id == 0; } public static bool operator ==(PropertyName lhs, PropertyName rhs) { return lhs.id == rhs.id; } public static bool operator !=(PropertyName lhs, PropertyName rhs) { return lhs.id != rhs.id; } public override int GetHashCode() { return id; } public override bool Equals(object other) { return other is PropertyName && Equals((PropertyName)other); } public bool Equals(PropertyName other) { return this == other; } public static implicit operator PropertyName(string name) { return new PropertyName(name); } public static implicit operator PropertyName(int id) { return new PropertyName(id); } public override string ToString() { return $"Unknown:{id}"; } } [NativeHeader("Runtime/Export/Random/Random.bindings.h")] public static class Random { [Serializable] public struct State { [SerializeField] private int s0; [SerializeField] private int s1; [SerializeField] private int s2; [SerializeField] private int s3; } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static State state { get { get_state_Injected(out var ret); return ret; } set { set_state_Injected(ref value); } } public static extern float value { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] get; } public static Vector3 insideUnitSphere { [FreeFunction] get { get_insideUnitSphere_Injected(out var ret); return ret; } } public static Vector2 insideUnitCircle { get { GetRandomUnitCircle(out var output); return output; } } public static Vector3 onUnitSphere { [FreeFunction] get { get_onUnitSphere_Injected(out var ret); return ret; } } public static Quaternion rotation { [FreeFunction] get { get_rotation_Injected(out var ret); return ret; } } public static Quaternion rotationUniform { [FreeFunction] get { get_rotationUniform_Injected(out var ret); return ret; } } [Obsolete("Deprecated. Use InitState() function or Random.state property instead.")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern int seed { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("SetSeed")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern void InitState(int seed); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern float Range(float minInclusive, float maxInclusive); public static int Range(int minInclusive, int maxExclusive) { return RandomRangeInt(minInclusive, maxExclusive); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern int RandomRangeInt(int minInclusive, int maxExclusive); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern void GetRandomUnitCircle(out Vector2 output); [Obsolete("Use Random.Range instead")] public static float RandomRange(float min, float max) { return Range(min, max); } [Obsolete("Use Random.Range instead")] public static int RandomRange(int min, int max) { return Range(min, max); } public static Color ColorHSV() { return ColorHSV(0f, 1f, 0f, 1f, 0f, 1f, 1f, 1f); } public static Color ColorHSV(float hueMin, float hueMax) { return ColorHSV(hueMin, hueMax, 0f, 1f, 0f, 1f, 1f, 1f); } public static Color ColorHSV(float hueMin, float hueMax, float saturationMin, float saturationMax) { return ColorHSV(hueMin, hueMax, saturationMin, saturationMax, 0f, 1f, 1f, 1f); } public static Color ColorHSV(float hueMin, float hueMax, float saturationMin, float saturationMax, float valueMin, float valueMax) { return ColorHSV(hueMin, hueMax, saturationMin, saturationMax, valueMin, valueMax, 1f, 1f); } public static Color ColorHSV(float hueMin, float hueMax, float saturationMin, float saturationMax, float valueMin, float valueMax, float alphaMin, float alphaMax) { float h = Mathf.Lerp(hueMin, hueMax, value); float s = Mathf.Lerp(saturationMin, saturationMax, value); float v = Mathf.Lerp(valueMin, valueMax, value); Color result = Color.HSVToRGB(h, s, v, hdr: true); result.a = Mathf.Lerp(alphaMin, alphaMax, value); return result; } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_state_Injected(out State ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_state_Injected(ref State value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_insideUnitSphere_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_onUnitSphere_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_rotation_Injected(out Quaternion ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_rotationUniform_Injected(out Quaternion ret); } [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] [Conditional("UNITY_EDITOR")] public class IconAttribute : Attribute { private string m_IconPath; public string path => m_IconPath; private IconAttribute() { } public IconAttribute(string path) { m_IconPath = path; } } [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] public class ResourceRequest : AsyncOperation { internal string m_Path; internal Type m_Type; public Object asset => GetResult(); protected virtual Object GetResult() { return Resources.Load(m_Path, m_Type); } } [NativeHeader("Runtime/Export/Resources/Resources.bindings.h")] [NativeHeader("Runtime/Misc/ResourceManagerUtility.h")] internal static class ResourcesAPIInternal { [MethodImpl(MethodImplOptions.InternalCall)] [TypeInferenceRule(TypeInferenceRules.ArrayOfTypeReferencedByFirstArgument)] [FreeFunction("Resources_Bindings::FindObjectsOfTypeAll")] public static extern Object[] FindObjectsOfTypeAll(Type type); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetShaderNameRegistry().FindShader")] public static extern Shader FindShaderByName(string name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Resources_Bindings::Load")] [TypeInferenceRule(TypeInferenceRules.TypeReferencedBySecondArgument)] [NativeThrows] public static extern Object Load(string path, [NotNull("ArgumentNullException")] Type systemTypeInstance); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Resources_Bindings::LoadAll")] [NativeThrows] public static extern Object[] LoadAll([NotNull("ArgumentNullException")] string path, [NotNull("ArgumentNullException")] Type systemTypeInstance); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Resources_Bindings::LoadAsyncInternal")] internal static extern ResourceRequest LoadAsyncInternal(string path, Type type); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Scripting::UnloadAssetFromScripting")] public static extern void UnloadAsset(Object assetToUnload); } public class ResourcesAPI { private static ResourcesAPI s_DefaultAPI = new ResourcesAPI(); internal static ResourcesAPI ActiveAPI => overrideAPI ?? s_DefaultAPI; public static ResourcesAPI overrideAPI { get; set; } protected internal ResourcesAPI() { } protected internal virtual Object[] FindObjectsOfTypeAll(Type systemTypeInstance) { return ResourcesAPIInternal.FindObjectsOfTypeAll(systemTypeInstance); } protected internal virtual Shader FindShaderByName(string name) { return ResourcesAPIInternal.FindShaderByName(name); } protected internal virtual Object Load(string path, Type systemTypeInstance) { return ResourcesAPIInternal.Load(path, systemTypeInstance); } protected internal virtual Object[] LoadAll(string path, Type systemTypeInstance) { return ResourcesAPIInternal.LoadAll(path, systemTypeInstance); } protected internal virtual ResourceRequest LoadAsync(string path, Type systemTypeInstance) { ResourceRequest resourceRequest = ResourcesAPIInternal.LoadAsyncInternal(path, systemTypeInstance); resourceRequest.m_Path = path; resourceRequest.m_Type = systemTypeInstance; return resourceRequest; } protected internal virtual void UnloadAsset(Object assetToUnload) { ResourcesAPIInternal.UnloadAsset(assetToUnload); } } [NativeHeader("Runtime/Export/Resources/Resources.bindings.h")] [NativeHeader("Runtime/Misc/ResourceManagerUtility.h")] public sealed class Resources { internal static T[] ConvertObjects(Object[] rawObjects) where T : Object { if (rawObjects == null) { return null; } T[] array = new T[rawObjects.Length]; for (int i = 0; i < array.Length; i++) { array[i] = (T)rawObjects[i]; } return array; } public static Object[] FindObjectsOfTypeAll(Type type) { return ResourcesAPI.ActiveAPI.FindObjectsOfTypeAll(type); } public static T[] FindObjectsOfTypeAll() where T : Object { return ConvertObjects(FindObjectsOfTypeAll(typeof(T))); } public static Object Load(string path) { return Load(path, typeof(Object)); } public static T Load(string path) where T : Object { return (T)Load(path, typeof(T)); } public static Object Load(string path, Type systemTypeInstance) { return ResourcesAPI.ActiveAPI.Load(path, systemTypeInstance); } public static ResourceRequest LoadAsync(string path) { return LoadAsync(path, typeof(Object)); } public static ResourceRequest LoadAsync(string path) where T : Object { return LoadAsync(path, typeof(T)); } public static ResourceRequest LoadAsync(string path, Type type) { return ResourcesAPI.ActiveAPI.LoadAsync(path, type); } public static Object[] LoadAll(string path, Type systemTypeInstance) { return ResourcesAPI.ActiveAPI.LoadAll(path, systemTypeInstance); } public static Object[] LoadAll(string path) { return LoadAll(path, typeof(Object)); } public static T[] LoadAll(string path) where T : Object { return ConvertObjects(LoadAll(path, typeof(T))); } [MethodImpl(MethodImplOptions.InternalCall)] [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] [FreeFunction("GetScriptingBuiltinResource", ThrowsException = true)] public static extern Object GetBuiltinResource([NotNull("ArgumentNullException")] Type type, string path); public static T GetBuiltinResource(string path) where T : Object { return (T)GetBuiltinResource(typeof(T), path); } public static void UnloadAsset(Object assetToUnload) { ResourcesAPI.ActiveAPI.UnloadAsset(assetToUnload); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Scripting::UnloadAssetFromScripting")] private static extern void UnloadAssetImplResourceManager(Object assetToUnload); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Resources_Bindings::UnloadUnusedAssets")] public static extern AsyncOperation UnloadUnusedAssets(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Resources_Bindings::InstanceIDToObject")] public static extern Object InstanceIDToObject(int instanceID); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Resources_Bindings::InstanceIDToObjectList")] private static extern void InstanceIDToObjectList(IntPtr instanceIDs, int instanceCount, List objects); public unsafe static void InstanceIDToObjectList(NativeArray instanceIDs, List objects) { if (!instanceIDs.IsCreated) { throw new ArgumentException("NativeArray is uninitialized", "instanceIDs"); } if (objects == null) { throw new ArgumentNullException("objects"); } if (instanceIDs.Length == 0) { objects.Clear(); } else { InstanceIDToObjectList((IntPtr)instanceIDs.GetUnsafeReadOnlyPtr(), instanceIDs.Length, objects); } } } [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] [NativeHeader("Runtime/Misc/AsyncOperation.h")] [NativeHeader("Runtime/Export/Scripting/AsyncOperation.bindings.h")] public class AsyncOperation : YieldInstruction { internal IntPtr m_Ptr; private Action m_completeCallback; public extern bool isDone { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("IsDone")] get; } public extern float progress { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetProgress")] get; } public extern int priority { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetPriority")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("SetPriority")] set; } public extern bool allowSceneActivation { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetAllowSceneActivation")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("SetAllowSceneActivation")] set; } public event Action completed { add { if (isDone) { value(this); } else { m_completeCallback = (Action)Delegate.Combine(m_completeCallback, value); } } remove { m_completeCallback = (Action)Delegate.Remove(m_completeCallback, value); } } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern void InternalDestroy(IntPtr ptr); ~AsyncOperation() { InternalDestroy(m_Ptr); } [RequiredByNativeCode] internal void InvokeCompletionEvent() { if (m_completeCallback != null) { m_completeCallback(this); m_completeCallback = null; } } } internal class AttributeHelperEngine { [RequiredByNativeCode] private static Type GetParentTypeDisallowingMultipleInclusion(Type type) { Type result = null; while ((object)type != null && (object)type != typeof(MonoBehaviour)) { if (Attribute.IsDefined(type, typeof(DisallowMultipleComponent))) { result = type; } type = type.BaseType; } return result; } [RequiredByNativeCode] private static Type[] GetRequiredComponents(Type klass) { List list = null; while ((object)klass != null && (object)klass != typeof(MonoBehaviour)) { RequireComponent[] array = (RequireComponent[])klass.GetCustomAttributes(typeof(RequireComponent), inherit: false); Type baseType = klass.BaseType; RequireComponent[] array2 = array; foreach (RequireComponent requireComponent in array2) { if (list == null && array.Length == 1 && (object)baseType == typeof(MonoBehaviour)) { return new Type[3] { requireComponent.m_Type0, requireComponent.m_Type1, requireComponent.m_Type2 }; } if (list == null) { list = new List(); } if ((object)requireComponent.m_Type0 != null) { list.Add(requireComponent.m_Type0); } if ((object)requireComponent.m_Type1 != null) { list.Add(requireComponent.m_Type1); } if ((object)requireComponent.m_Type2 != null) { list.Add(requireComponent.m_Type2); } } klass = baseType; } return list?.ToArray(); } private static int GetExecuteMode(Type klass) { object[] customAttributes = klass.GetCustomAttributes(typeof(ExecuteAlways), inherit: false); if (customAttributes.Length != 0) { return 2; } object[] customAttributes2 = klass.GetCustomAttributes(typeof(ExecuteInEditMode), inherit: false); if (customAttributes2.Length != 0) { return 1; } return 0; } [RequiredByNativeCode] private static int CheckIsEditorScript(Type klass) { while ((object)klass != null && (object)klass != typeof(MonoBehaviour)) { int executeMode = GetExecuteMode(klass); if (executeMode > 0) { return executeMode; } klass = klass.BaseType; } return 0; } [RequiredByNativeCode] private static int GetDefaultExecutionOrderFor(Type klass) { return GetCustomAttributeOfType(klass)?.order ?? 0; } private static T GetCustomAttributeOfType(Type klass) where T : Attribute { Type typeFromHandle = typeof(T); object[] customAttributes = klass.GetCustomAttributes(typeFromHandle, inherit: true); if (customAttributes != null && customAttributes.Length != 0) { return (T)customAttributes[0]; } return null; } } [AttributeUsage(AttributeTargets.Class, Inherited = false)] [RequiredByNativeCode] public sealed class DisallowMultipleComponent : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [RequiredByNativeCode] public sealed class RequireComponent : Attribute { public Type m_Type0; public Type m_Type1; public Type m_Type2; public RequireComponent(Type requiredComponent) { m_Type0 = requiredComponent; } public RequireComponent(Type requiredComponent, Type requiredComponent2) { m_Type0 = requiredComponent; m_Type1 = requiredComponent2; } public RequireComponent(Type requiredComponent, Type requiredComponent2, Type requiredComponent3) { m_Type0 = requiredComponent; m_Type1 = requiredComponent2; m_Type2 = requiredComponent3; } } public sealed class AddComponentMenu : Attribute { private string m_AddComponentMenu; private int m_Ordering; public string componentMenu => m_AddComponentMenu; public int componentOrder => m_Ordering; public AddComponentMenu(string menuName) { m_AddComponentMenu = menuName; m_Ordering = 0; } public AddComponentMenu(string menuName, int order) { m_AddComponentMenu = menuName; m_Ordering = order; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class CreateAssetMenuAttribute : Attribute { public string menuName { get; set; } public string fileName { get; set; } public int order { get; set; } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] [RequiredByNativeCode] public sealed class ContextMenu : Attribute { public readonly string menuItem; public readonly bool validate; public readonly int priority; public ContextMenu(string itemName) : this(itemName, isValidateFunction: false) { } public ContextMenu(string itemName, bool isValidateFunction) : this(itemName, isValidateFunction, 1000000) { } public ContextMenu(string itemName, bool isValidateFunction, int priority) { menuItem = itemName; validate = isValidateFunction; this.priority = priority; } } [UsedByNativeCode] public sealed class ExecuteInEditMode : Attribute { } [UsedByNativeCode] public sealed class ExecuteAlways : Attribute { } [UsedByNativeCode] public sealed class HideInInspector : Attribute { } [AttributeUsage(AttributeTargets.Method)] public sealed class HideInCallstackAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] [UsedByNativeCode] public class HelpURLAttribute : Attribute { internal readonly string m_Url; internal readonly bool m_Dispatcher; internal readonly string m_DispatchingFieldName; public string URL => m_Url; public HelpURLAttribute(string url) { m_Url = url; m_DispatchingFieldName = ""; m_Dispatcher = false; } internal HelpURLAttribute(string defaultURL, string dispatchingFieldName) { m_Url = defaultURL; m_DispatchingFieldName = dispatchingFieldName; m_Dispatcher = !string.IsNullOrEmpty(dispatchingFieldName); } } [UsedByNativeCode] [AttributeUsage(AttributeTargets.Class)] public class DefaultExecutionOrder : Attribute { private int m_Order; public int order => m_Order; public DefaultExecutionOrder(int order) { m_Order = order; } } [RequiredByNativeCode] [AttributeUsage(AttributeTargets.Assembly)] public class AssemblyIsEditorAssembly : Attribute { } [AttributeUsage(AttributeTargets.Class, Inherited = false)] [UsedByNativeCode] public class ExcludeFromPresetAttribute : Attribute { } [UsedByNativeCode] [NativeHeader("Runtime/Mono/MonoBehaviour.h")] public class Behaviour : Component { [RequiredByNativeCode] [NativeProperty] public extern bool enabled { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeProperty] public extern bool isActiveAndEnabled { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("IsAddedToManager")] get; } } internal struct CastHelper { public T t; public IntPtr onePointerFurtherThanT; } internal static class ClassLibraryInitializer { [RequiredByNativeCode] private static void Init() { UnityLogWriter.Init(); } } [NativeClass("Unity::Component")] [RequiredByNativeCode] [NativeHeader("Runtime/Export/Scripting/Component.bindings.h")] public class Component : Object { public extern Transform transform { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTransform", HasExplicitThis = true, ThrowsException = true)] get; } public extern GameObject gameObject { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetGameObject", HasExplicitThis = true)] get; } public string tag { get { return gameObject.tag; } set { gameObject.tag = value; } } [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public Component GetComponent(Type type) { return gameObject.GetComponent(type); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(HasExplicitThis = true, ThrowsException = true)] internal extern void GetComponentFastPath(Type type, IntPtr oneFurtherThanResultValue); [SecuritySafeCritical] public unsafe T GetComponent() { CastHelper castHelper = default(CastHelper); GetComponentFastPath(typeof(T), new IntPtr(&castHelper.onePointerFurtherThanT)); return castHelper.t; } [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public bool TryGetComponent(Type type, out Component component) { return gameObject.TryGetComponent(type, out component); } [SecuritySafeCritical] public bool TryGetComponent(out T component) { return gameObject.TryGetComponent(out component); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(HasExplicitThis = true)] public extern Component GetComponent(string type); [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public Component GetComponentInChildren(Type t, bool includeInactive) { return gameObject.GetComponentInChildren(t, includeInactive); } [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public Component GetComponentInChildren(Type t) { return GetComponentInChildren(t, includeInactive: false); } public T GetComponentInChildren([UnityEngine.Internal.DefaultValue("false")] bool includeInactive) { return (T)(object)GetComponentInChildren(typeof(T), includeInactive); } [ExcludeFromDocs] public T GetComponentInChildren() { return (T)(object)GetComponentInChildren(typeof(T), includeInactive: false); } public Component[] GetComponentsInChildren(Type t, bool includeInactive) { return gameObject.GetComponentsInChildren(t, includeInactive); } [ExcludeFromDocs] public Component[] GetComponentsInChildren(Type t) { return gameObject.GetComponentsInChildren(t, includeInactive: false); } public T[] GetComponentsInChildren(bool includeInactive) { return gameObject.GetComponentsInChildren(includeInactive); } public void GetComponentsInChildren(bool includeInactive, List result) { gameObject.GetComponentsInChildren(includeInactive, result); } public T[] GetComponentsInChildren() { return GetComponentsInChildren(includeInactive: false); } public void GetComponentsInChildren(List results) { GetComponentsInChildren(includeInactive: false, results); } [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public Component GetComponentInParent(Type t, bool includeInactive) { return gameObject.GetComponentInParent(t, includeInactive); } [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public Component GetComponentInParent(Type t) { return gameObject.GetComponentInParent(t, includeInactive: false); } public T GetComponentInParent([UnityEngine.Internal.DefaultValue("false")] bool includeInactive) { return (T)(object)GetComponentInParent(typeof(T), includeInactive); } public T GetComponentInParent() { return (T)(object)GetComponentInParent(typeof(T), includeInactive: false); } public Component[] GetComponentsInParent(Type t, [UnityEngine.Internal.DefaultValue("false")] bool includeInactive) { return gameObject.GetComponentsInParent(t, includeInactive); } [ExcludeFromDocs] public Component[] GetComponentsInParent(Type t) { return GetComponentsInParent(t, includeInactive: false); } public T[] GetComponentsInParent(bool includeInactive) { return gameObject.GetComponentsInParent(includeInactive); } public void GetComponentsInParent(bool includeInactive, List results) { gameObject.GetComponentsInParent(includeInactive, results); } public T[] GetComponentsInParent() { return GetComponentsInParent(includeInactive: false); } public Component[] GetComponents(Type type) { return gameObject.GetComponents(type); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(HasExplicitThis = true, ThrowsException = true)] private extern void GetComponentsForListInternal(Type searchType, object resultList); public void GetComponents(Type type, List results) { GetComponentsForListInternal(type, results); } public void GetComponents(List results) { GetComponentsForListInternal(typeof(T), results); } public T[] GetComponents() { return gameObject.GetComponents(); } public bool CompareTag(string tag) { return gameObject.CompareTag(tag); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(HasExplicitThis = true)] public extern void SendMessageUpwards(string methodName, [UnityEngine.Internal.DefaultValue("null")] object value, [UnityEngine.Internal.DefaultValue("SendMessageOptions.RequireReceiver")] SendMessageOptions options); [ExcludeFromDocs] public void SendMessageUpwards(string methodName, object value) { SendMessageUpwards(methodName, value, SendMessageOptions.RequireReceiver); } [ExcludeFromDocs] public void SendMessageUpwards(string methodName) { SendMessageUpwards(methodName, null, SendMessageOptions.RequireReceiver); } public void SendMessageUpwards(string methodName, SendMessageOptions options) { SendMessageUpwards(methodName, null, options); } public void SendMessage(string methodName, object value) { SendMessage(methodName, value, SendMessageOptions.RequireReceiver); } public void SendMessage(string methodName) { SendMessage(methodName, null, SendMessageOptions.RequireReceiver); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SendMessage", HasExplicitThis = true)] public extern void SendMessage(string methodName, object value, SendMessageOptions options); public void SendMessage(string methodName, SendMessageOptions options) { SendMessage(methodName, null, options); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("BroadcastMessage", HasExplicitThis = true)] public extern void BroadcastMessage(string methodName, [UnityEngine.Internal.DefaultValue("null")] object parameter, [UnityEngine.Internal.DefaultValue("SendMessageOptions.RequireReceiver")] SendMessageOptions options); [ExcludeFromDocs] public void BroadcastMessage(string methodName, object parameter) { BroadcastMessage(methodName, parameter, SendMessageOptions.RequireReceiver); } [ExcludeFromDocs] public void BroadcastMessage(string methodName) { BroadcastMessage(methodName, null, SendMessageOptions.RequireReceiver); } public void BroadcastMessage(string methodName, SendMessageOptions options) { BroadcastMessage(methodName, null, options); } } [StructLayout(LayoutKind.Sequential)] [NativeHeader("Runtime/Mono/Coroutine.h")] [RequiredByNativeCode] public sealed class Coroutine : YieldInstruction { internal IntPtr m_Ptr; private Coroutine() { } ~Coroutine() { ReleaseCoroutine(m_Ptr); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Coroutine::CleanupCoroutineGC", true)] private static extern void ReleaseCoroutine(IntPtr ptr); } [RequiredByNativeCode] internal class SetupCoroutine { [RequiredByNativeCode] [SecuritySafeCritical] public unsafe static void InvokeMoveNext(IEnumerator enumerator, IntPtr returnValueAddress) { if (returnValueAddress == IntPtr.Zero) { throw new ArgumentException("Return value address cannot be 0.", "returnValueAddress"); } *(bool*)(void*)returnValueAddress = enumerator.MoveNext(); } [RequiredByNativeCode] public static object InvokeMember(object behaviour, string name, object variable) { object[] args = null; if (variable != null) { args = new object[1] { variable }; } return behaviour.GetType().InvokeMember(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, behaviour, args, null, null, null); } public static object InvokeStatic(Type klass, string name, object variable) { object[] args = null; if (variable != null) { args = new object[1] { variable }; } return klass.InvokeMember(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, null, args, null, null, null); } } public abstract class CustomYieldInstruction : IEnumerator { public abstract bool keepWaiting { get; } public object Current => null; public bool MoveNext() { return keepWaiting; } public virtual void Reset() { } } internal struct EnumData { public Enum[] values; public int[] flagValues; public string[] displayNames; public string[] names; public string[] tooltip; public bool flags; public Type underlyingType; public bool unsigned; public bool serializable; } internal static class EnumDataUtility { private static readonly Dictionary s_NonObsoleteEnumData = new Dictionary(); private static readonly Dictionary s_EnumData = new Dictionary(); internal static EnumData GetCachedEnumData(Type enumType, bool excludeObsolete = true, Func nicifyName = null) { if (excludeObsolete && s_NonObsoleteEnumData.TryGetValue(enumType, out var value)) { return value; } if (!excludeObsolete && s_EnumData.TryGetValue(enumType, out value)) { return value; } value = new EnumData { underlyingType = Enum.GetUnderlyingType(enumType) }; value.unsigned = (object)value.underlyingType == typeof(byte) || (object)value.underlyingType == typeof(ushort) || (object)value.underlyingType == typeof(uint) || (object)value.underlyingType == typeof(ulong); FieldInfo[] fields = enumType.GetFields(BindingFlags.Static | BindingFlags.Public); List list = new List(); int num = fields.Length; for (int i = 0; i < num; i++) { if (CheckObsoleteAddition(fields[i], excludeObsolete)) { list.Add(fields[i]); } } if (!list.Any()) { string[] array = new string[1] { "" }; Enum[] values = new Enum[0]; int[] flagValues = new int[1]; value.values = values; value.flagValues = flagValues; value.displayNames = array; value.names = array; value.tooltip = array; value.flags = true; value.serializable = true; return value; } try { string location = list.First().Module.Assembly.Location; if (!string.IsNullOrEmpty(location)) { list = list.OrderBy((FieldInfo f) => f.MetadataToken).ToList(); } } catch { } value.displayNames = list.Select((FieldInfo f) => EnumNameFromEnumField(f, nicifyName)).ToArray(); if (value.displayNames.Distinct().Count() != value.displayNames.Length) { Debug.LogWarning("Enum " + enumType.Name + " has multiple entries with the same display name, this prevents selection in EnumPopup."); } value.tooltip = list.Select((FieldInfo f) => EnumTooltipFromEnumField(f)).ToArray(); value.values = list.Select((FieldInfo f) => (Enum)f.GetValue(null)).ToArray(); value.flagValues = (value.unsigned ? value.values.Select((Enum v) => (int)Convert.ToUInt64(v)).ToArray() : value.values.Select((Enum v) => (int)Convert.ToInt64(v)).ToArray()); value.names = new string[value.values.Length]; for (int num2 = 0; num2 < value.values.Length; num2++) { value.names[num2] = value.values[num2].ToString(); } if ((object)value.underlyingType == typeof(ushort)) { int num3 = 0; for (int num4 = value.flagValues.Length; num3 < num4; num3++) { if ((long)value.flagValues[num3] == 65535) { value.flagValues[num3] = -1; } } } else if ((object)value.underlyingType == typeof(byte)) { int num5 = 0; for (int num6 = value.flagValues.Length; num5 < num6; num5++) { if ((long)value.flagValues[num5] == 255) { value.flagValues[num5] = -1; } } } value.flags = enumType.IsDefined(typeof(FlagsAttribute), inherit: false); value.serializable = (object)value.underlyingType != typeof(long) && (object)value.underlyingType != typeof(ulong); if (excludeObsolete) { s_NonObsoleteEnumData[enumType] = value; } else { s_EnumData[enumType] = value; } return value; } internal static int EnumFlagsToInt(EnumData enumData, Enum enumValue) { if (enumData.unsigned) { if ((object)enumData.underlyingType == typeof(uint)) { return (int)Convert.ToUInt32(enumValue); } if ((object)enumData.underlyingType == typeof(ushort)) { ushort num = Convert.ToUInt16(enumValue); return (num == ushort.MaxValue) ? (-1) : num; } byte b = Convert.ToByte(enumValue); return (b == byte.MaxValue) ? (-1) : b; } return Convert.ToInt32(enumValue); } internal static Enum IntToEnumFlags(Type enumType, int value) { EnumData cachedEnumData = GetCachedEnumData(enumType); if (cachedEnumData.unsigned) { if ((object)cachedEnumData.underlyingType == typeof(uint)) { uint num = (uint)value; return Enum.Parse(enumType, num.ToString()) as Enum; } if ((object)cachedEnumData.underlyingType == typeof(ushort)) { return Enum.Parse(enumType, ((ushort)value).ToString()) as Enum; } return Enum.Parse(enumType, ((byte)value).ToString()) as Enum; } return Enum.Parse(enumType, value.ToString()) as Enum; } private static bool CheckObsoleteAddition(FieldInfo field, bool excludeObsolete) { object[] customAttributes = field.GetCustomAttributes(typeof(ObsoleteAttribute), inherit: false); if (customAttributes.Length != 0) { if (excludeObsolete) { return false; } return !((ObsoleteAttribute)customAttributes.First()).IsError; } return true; } private static string EnumTooltipFromEnumField(FieldInfo field) { object[] customAttributes = field.GetCustomAttributes(typeof(TooltipAttribute), inherit: false); if (customAttributes.Length != 0) { return ((TooltipAttribute)customAttributes.First()).tooltip; } return string.Empty; } private static string EnumNameFromEnumField(FieldInfo field, Func nicifyName) { object[] customAttributes = field.GetCustomAttributes(typeof(InspectorNameAttribute), inherit: false); if (customAttributes.Length != 0) { return ((InspectorNameAttribute)customAttributes.First()).displayName; } if (field.IsDefined(typeof(ObsoleteAttribute), inherit: false)) { return NicifyName() + " (Obsolete)"; } return NicifyName(); string NicifyName() { return (nicifyName == null) ? field.Name : nicifyName(field.Name); } } } internal class EnumInfo { public string[] names; public int[] values; public string[] annotations; public bool isFlags; [UsedByNativeCode] internal static EnumInfo CreateEnumInfoFromNativeEnum(string[] names, int[] values, string[] annotations, bool isFlags) { EnumInfo enumInfo = new EnumInfo(); enumInfo.names = names; enumInfo.values = values; enumInfo.annotations = annotations; enumInfo.isFlags = isFlags; return enumInfo; } } [AttributeUsage(AttributeTargets.Class)] [UsedByNativeCode] public class ExcludeFromObjectFactoryAttribute : Attribute { } [RequiredByNativeCode] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = true)] internal sealed class ExtensionOfNativeClassAttribute : Attribute { } [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] [NativeClass(null)] [ExcludeFromObjectFactory] internal class FailedToLoadScriptObject : Object { private FailedToLoadScriptObject() { } } [NativeHeader("Runtime/Export/Scripting/GameObject.bindings.h")] [UsedByNativeCode] [ExcludeFromPreset] public sealed class GameObject : Object { public extern Transform transform { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GameObjectBindings::GetTransform", HasExplicitThis = true)] get; } public extern int layer { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [Obsolete("GameObject.active is obsolete. Use GameObject.SetActive(), GameObject.activeSelf or GameObject.activeInHierarchy.")] public extern bool active { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "IsActive")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "SetSelfActive")] set; } public extern bool activeSelf { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "IsSelfActive")] get; } public extern bool activeInHierarchy { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "IsActive")] get; } public extern bool isStatic { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GetIsStaticDeprecated")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "SetIsStaticDeprecated")] set; } internal extern bool isStaticBatchable { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "IsStaticBatchable")] get; } public extern string tag { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GameObjectBindings::GetTag", HasExplicitThis = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GameObjectBindings::SetTag", HasExplicitThis = true)] set; } public Scene scene { [FreeFunction("GameObjectBindings::GetScene", HasExplicitThis = true)] get { get_scene_Injected(out var ret); return ret; } } public extern ulong sceneCullingMask { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GameObjectBindings::GetSceneCullingMask", HasExplicitThis = true)] get; } public GameObject gameObject => this; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GameObjectBindings::CreatePrimitive")] public static extern GameObject CreatePrimitive(PrimitiveType type); [SecuritySafeCritical] public unsafe T GetComponent() { CastHelper castHelper = default(CastHelper); GetComponentFastPath(typeof(T), new IntPtr(&castHelper.onePointerFurtherThanT)); return castHelper.t; } [MethodImpl(MethodImplOptions.InternalCall)] [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] [FreeFunction(Name = "GameObjectBindings::GetComponentFromType", HasExplicitThis = true, ThrowsException = true)] public extern Component GetComponent(Type type); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GameObjectBindings::GetComponentFastPath", HasExplicitThis = true, ThrowsException = true)] [NativeWritableSelf] internal extern void GetComponentFastPath(Type type, IntPtr oneFurtherThanResultValue); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Scripting::GetScriptingWrapperOfComponentOfGameObject", HasExplicitThis = true)] internal extern Component GetComponentByName(string type); public Component GetComponent(string type) { return GetComponentByName(type); } [MethodImpl(MethodImplOptions.InternalCall)] [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] [FreeFunction(Name = "GameObjectBindings::GetComponentInChildren", HasExplicitThis = true, ThrowsException = true)] public extern Component GetComponentInChildren(Type type, bool includeInactive); [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public Component GetComponentInChildren(Type type) { return GetComponentInChildren(type, includeInactive: false); } [ExcludeFromDocs] public T GetComponentInChildren() { bool includeInactive = false; return GetComponentInChildren(includeInactive); } public T GetComponentInChildren([UnityEngine.Internal.DefaultValue("false")] bool includeInactive) { return (T)(object)GetComponentInChildren(typeof(T), includeInactive); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GameObjectBindings::GetComponentInParent", HasExplicitThis = true, ThrowsException = true)] [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public extern Component GetComponentInParent(Type type, bool includeInactive); [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public Component GetComponentInParent(Type type) { return GetComponentInParent(type, includeInactive: false); } [ExcludeFromDocs] public T GetComponentInParent() { bool includeInactive = false; return GetComponentInParent(includeInactive); } public T GetComponentInParent([UnityEngine.Internal.DefaultValue("false")] bool includeInactive) { return (T)(object)GetComponentInParent(typeof(T), includeInactive); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GameObjectBindings::GetComponentsInternal", HasExplicitThis = true, ThrowsException = true)] private extern Array GetComponentsInternal(Type type, bool useSearchTypeAsArrayReturnType, bool recursive, bool includeInactive, bool reverse, object resultList); public Component[] GetComponents(Type type) { return (Component[])GetComponentsInternal(type, useSearchTypeAsArrayReturnType: false, recursive: false, includeInactive: true, reverse: false, null); } public T[] GetComponents() { return (T[])GetComponentsInternal(typeof(T), useSearchTypeAsArrayReturnType: true, recursive: false, includeInactive: true, reverse: false, null); } public void GetComponents(Type type, List results) { GetComponentsInternal(type, useSearchTypeAsArrayReturnType: false, recursive: false, includeInactive: true, reverse: false, results); } public void GetComponents(List results) { GetComponentsInternal(typeof(T), useSearchTypeAsArrayReturnType: true, recursive: false, includeInactive: true, reverse: false, results); } [ExcludeFromDocs] public Component[] GetComponentsInChildren(Type type) { bool includeInactive = false; return GetComponentsInChildren(type, includeInactive); } public Component[] GetComponentsInChildren(Type type, [UnityEngine.Internal.DefaultValue("false")] bool includeInactive) { return (Component[])GetComponentsInternal(type, useSearchTypeAsArrayReturnType: false, recursive: true, includeInactive, reverse: false, null); } public T[] GetComponentsInChildren(bool includeInactive) { return (T[])GetComponentsInternal(typeof(T), useSearchTypeAsArrayReturnType: true, recursive: true, includeInactive, reverse: false, null); } public void GetComponentsInChildren(bool includeInactive, List results) { GetComponentsInternal(typeof(T), useSearchTypeAsArrayReturnType: true, recursive: true, includeInactive, reverse: false, results); } public T[] GetComponentsInChildren() { return GetComponentsInChildren(includeInactive: false); } public void GetComponentsInChildren(List results) { GetComponentsInChildren(includeInactive: false, results); } [ExcludeFromDocs] public Component[] GetComponentsInParent(Type type) { bool includeInactive = false; return GetComponentsInParent(type, includeInactive); } public Component[] GetComponentsInParent(Type type, [UnityEngine.Internal.DefaultValue("false")] bool includeInactive) { return (Component[])GetComponentsInternal(type, useSearchTypeAsArrayReturnType: false, recursive: true, includeInactive, reverse: true, null); } public void GetComponentsInParent(bool includeInactive, List results) { GetComponentsInternal(typeof(T), useSearchTypeAsArrayReturnType: true, recursive: true, includeInactive, reverse: true, results); } public T[] GetComponentsInParent(bool includeInactive) { return (T[])GetComponentsInternal(typeof(T), useSearchTypeAsArrayReturnType: true, recursive: true, includeInactive, reverse: true, null); } public T[] GetComponentsInParent() { return GetComponentsInParent(includeInactive: false); } [SecuritySafeCritical] public unsafe bool TryGetComponent(out T component) { CastHelper castHelper = default(CastHelper); TryGetComponentFastPath(typeof(T), new IntPtr(&castHelper.onePointerFurtherThanT)); component = castHelper.t; return castHelper.t != null; } public bool TryGetComponent(Type type, out Component component) { component = TryGetComponentInternal(type); return component != null; } [MethodImpl(MethodImplOptions.InternalCall)] [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] [FreeFunction(Name = "GameObjectBindings::TryGetComponentFromType", HasExplicitThis = true, ThrowsException = true)] internal extern Component TryGetComponentInternal(Type type); [MethodImpl(MethodImplOptions.InternalCall)] [NativeWritableSelf] [FreeFunction(Name = "GameObjectBindings::TryGetComponentFastPath", HasExplicitThis = true, ThrowsException = true)] internal extern void TryGetComponentFastPath(Type type, IntPtr oneFurtherThanResultValue); public static GameObject FindWithTag(string tag) { return FindGameObjectWithTag(tag); } public void SendMessageUpwards(string methodName, SendMessageOptions options) { SendMessageUpwards(methodName, null, options); } public void SendMessage(string methodName, SendMessageOptions options) { SendMessage(methodName, null, options); } public void BroadcastMessage(string methodName, SendMessageOptions options) { BroadcastMessage(methodName, null, options); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MonoAddComponent", HasExplicitThis = true)] internal extern Component AddComponentInternal(string className); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "MonoAddComponentWithType", HasExplicitThis = true)] private extern Component Internal_AddComponentWithType(Type componentType); [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public Component AddComponent(Type componentType) { return Internal_AddComponentWithType(componentType); } public T AddComponent() where T : Component { return AddComponent(typeof(T)) as T; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "SetSelfActive")] public extern void SetActive(bool value); [MethodImpl(MethodImplOptions.InternalCall)] [Obsolete("gameObject.SetActiveRecursively() is obsolete. Use GameObject.SetActive(), which is now inherited by children.")] [NativeMethod(Name = "SetActiveRecursivelyDeprecated")] public extern void SetActiveRecursively(bool state); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GameObjectBindings::CompareTag", HasExplicitThis = true)] public extern bool CompareTag(string tag); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GameObjectBindings::FindGameObjectWithTag", ThrowsException = true)] public static extern GameObject FindGameObjectWithTag(string tag); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GameObjectBindings::FindGameObjectsWithTag", ThrowsException = true)] public static extern GameObject[] FindGameObjectsWithTag(string tag); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Scripting::SendScriptingMessageUpwards", HasExplicitThis = true)] public extern void SendMessageUpwards(string methodName, [UnityEngine.Internal.DefaultValue("null")] object value, [UnityEngine.Internal.DefaultValue("SendMessageOptions.RequireReceiver")] SendMessageOptions options); [ExcludeFromDocs] public void SendMessageUpwards(string methodName, object value) { SendMessageOptions options = SendMessageOptions.RequireReceiver; SendMessageUpwards(methodName, value, options); } [ExcludeFromDocs] public void SendMessageUpwards(string methodName) { SendMessageOptions options = SendMessageOptions.RequireReceiver; object value = null; SendMessageUpwards(methodName, value, options); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Scripting::SendScriptingMessage", HasExplicitThis = true)] public extern void SendMessage(string methodName, [UnityEngine.Internal.DefaultValue("null")] object value, [UnityEngine.Internal.DefaultValue("SendMessageOptions.RequireReceiver")] SendMessageOptions options); [ExcludeFromDocs] public void SendMessage(string methodName, object value) { SendMessageOptions options = SendMessageOptions.RequireReceiver; SendMessage(methodName, value, options); } [ExcludeFromDocs] public void SendMessage(string methodName) { SendMessageOptions options = SendMessageOptions.RequireReceiver; object value = null; SendMessage(methodName, value, options); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "Scripting::BroadcastScriptingMessage", HasExplicitThis = true)] public extern void BroadcastMessage(string methodName, [UnityEngine.Internal.DefaultValue("null")] object parameter, [UnityEngine.Internal.DefaultValue("SendMessageOptions.RequireReceiver")] SendMessageOptions options); [ExcludeFromDocs] public void BroadcastMessage(string methodName, object parameter) { SendMessageOptions options = SendMessageOptions.RequireReceiver; BroadcastMessage(methodName, parameter, options); } [ExcludeFromDocs] public void BroadcastMessage(string methodName) { SendMessageOptions options = SendMessageOptions.RequireReceiver; object parameter = null; BroadcastMessage(methodName, parameter, options); } public GameObject(string name) { Internal_CreateGameObject(this, name); } public GameObject() { Internal_CreateGameObject(this, null); } public GameObject(string name, params Type[] components) { Internal_CreateGameObject(this, name); foreach (Type componentType in components) { AddComponent(componentType); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GameObjectBindings::Internal_CreateGameObject")] private static extern void Internal_CreateGameObject([Writable] GameObject self, string name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GameObjectBindings::Find")] public static extern GameObject Find(string name); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_scene_Injected(out Scene ret); } [RequiredByNativeCode(Optional = true, GenerateProxy = true)] [NativeHeader("Runtime/BaseClasses/BitField.h")] [NativeHeader("Runtime/BaseClasses/TagManager.h")] [NativeClass("BitField", "struct BitField;")] public struct LayerMask { [NativeName("m_Bits")] private int m_Mask; public int value { get { return m_Mask; } set { m_Mask = value; } } public static implicit operator int(LayerMask mask) { return mask.m_Mask; } public static implicit operator LayerMask(int intVal) { LayerMask result = default(LayerMask); result.m_Mask = intVal; return result; } [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeMethod("LayerToString")] public static extern string LayerToName(int layer); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeMethod("StringToLayer")] public static extern int NameToLayer(string layerName); public static int GetMask(params string[] layerNames) { if (layerNames == null) { throw new ArgumentNullException("layerNames"); } int num = 0; foreach (string layerName in layerNames) { int num2 = NameToLayer(layerName); if (num2 != -1) { num |= 1 << num2; } } return num; } } [Serializable] public struct LazyLoadReference where T : Object { private const int kInstanceID_None = 0; [SerializeField] private int m_InstanceID; public bool isSet => m_InstanceID != 0; public bool isBroken => m_InstanceID != 0 && !Object.DoesObjectWithInstanceIDExist(m_InstanceID); public T asset { get { if (m_InstanceID == 0) { return null; } return (T)Object.ForceLoadFromInstanceID(m_InstanceID); } set { if (value == null) { m_InstanceID = 0; return; } if (!Object.IsPersistent(value)) { throw new ArgumentException("Object that does not belong to a persisted asset cannot be set as the target of a LazyLoadReference."); } m_InstanceID = value.GetInstanceID(); } } public int instanceID { get { return m_InstanceID; } set { m_InstanceID = value; } } public LazyLoadReference(T asset) { if (asset == null) { m_InstanceID = 0; return; } if (!Object.IsPersistent(asset)) { throw new ArgumentException("Object that does not belong to a persisted asset cannot be set as the target of a LazyLoadReference."); } m_InstanceID = asset.GetInstanceID(); } public LazyLoadReference(int instanceID) { m_InstanceID = instanceID; } public static implicit operator LazyLoadReference(T asset) { return new LazyLoadReference { asset = asset }; } public static implicit operator LazyLoadReference(int instanceID) { return new LazyLoadReference { instanceID = instanceID }; } } internal static class ManagedStreamHelpers { internal static void ValidateLoadFromStream(Stream stream) { if (stream == null) { throw new ArgumentNullException("ManagedStream object must be non-null", "stream"); } if (!stream.CanRead) { throw new ArgumentException("ManagedStream object must be readable (stream.CanRead must return true)", "stream"); } if (!stream.CanSeek) { throw new ArgumentException("ManagedStream object must be seekable (stream.CanSeek must return true)", "stream"); } } [RequiredByNativeCode] internal unsafe static void ManagedStreamRead(byte[] buffer, int offset, int count, Stream stream, IntPtr returnValueAddress) { if (returnValueAddress == IntPtr.Zero) { throw new ArgumentException("Return value address cannot be 0.", "returnValueAddress"); } ValidateLoadFromStream(stream); *(int*)(void*)returnValueAddress = stream.Read(buffer, offset, count); } [RequiredByNativeCode] internal unsafe static void ManagedStreamSeek(long offset, uint origin, Stream stream, IntPtr returnValueAddress) { if (returnValueAddress == IntPtr.Zero) { throw new ArgumentException("Return value address cannot be 0.", "returnValueAddress"); } ValidateLoadFromStream(stream); *(long*)(void*)returnValueAddress = stream.Seek(offset, (SeekOrigin)origin); } [RequiredByNativeCode] internal unsafe static void ManagedStreamLength(Stream stream, IntPtr returnValueAddress) { if (returnValueAddress == IntPtr.Zero) { throw new ArgumentException("Return value address cannot be 0.", "returnValueAddress"); } ValidateLoadFromStream(stream); *(long*)(void*)returnValueAddress = stream.Length; } } [NativeHeader("Runtime/Scripting/DelayedCallUtility.h")] [ExtensionOfNativeClass] [RequiredByNativeCode] [NativeHeader("Runtime/Mono/MonoBehaviour.h")] public class MonoBehaviour : Behaviour { public extern bool useGUILayout { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public bool IsInvoking() { return Internal_IsInvokingAll(this); } public void CancelInvoke() { Internal_CancelInvokeAll(this); } public void Invoke(string methodName, float time) { InvokeDelayed(this, methodName, time, 0f); } public void InvokeRepeating(string methodName, float time, float repeatRate) { if (repeatRate <= 1E-05f && repeatRate != 0f) { throw new UnityException("Invoke repeat rate has to be larger than 0.00001F)"); } InvokeDelayed(this, methodName, time, repeatRate); } public void CancelInvoke(string methodName) { CancelInvoke(this, methodName); } public bool IsInvoking(string methodName) { return IsInvoking(this, methodName); } [ExcludeFromDocs] public Coroutine StartCoroutine(string methodName) { object value = null; return StartCoroutine(methodName, value); } public Coroutine StartCoroutine(string methodName, [UnityEngine.Internal.DefaultValue("null")] object value) { if (string.IsNullOrEmpty(methodName)) { throw new NullReferenceException("methodName is null or empty"); } if (!IsObjectMonoBehaviour(this)) { throw new ArgumentException("Coroutines can only be stopped on a MonoBehaviour"); } return StartCoroutineManaged(methodName, value); } public Coroutine StartCoroutine(IEnumerator routine) { if (routine == null) { throw new NullReferenceException("routine is null"); } if (!IsObjectMonoBehaviour(this)) { throw new ArgumentException("Coroutines can only be stopped on a MonoBehaviour"); } return StartCoroutineManaged2(routine); } [Obsolete("StartCoroutine_Auto has been deprecated. Use StartCoroutine instead (UnityUpgradable) -> StartCoroutine([mscorlib] System.Collections.IEnumerator)", false)] public Coroutine StartCoroutine_Auto(IEnumerator routine) { return StartCoroutine(routine); } public void StopCoroutine(IEnumerator routine) { if (routine == null) { throw new NullReferenceException("routine is null"); } if (!IsObjectMonoBehaviour(this)) { throw new ArgumentException("Coroutines can only be stopped on a MonoBehaviour"); } StopCoroutineFromEnumeratorManaged(routine); } public void StopCoroutine(Coroutine routine) { if (routine == null) { throw new NullReferenceException("routine is null"); } if (!IsObjectMonoBehaviour(this)) { throw new ArgumentException("Coroutines can only be stopped on a MonoBehaviour"); } StopCoroutineManaged(routine); } [MethodImpl(MethodImplOptions.InternalCall)] public extern void StopCoroutine(string methodName); [MethodImpl(MethodImplOptions.InternalCall)] public extern void StopAllCoroutines(); public static void print(object message) { Debug.Log(message); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CancelInvoke")] private static extern void Internal_CancelInvokeAll([NotNull("NullExceptionObject")] MonoBehaviour self); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("IsInvoking")] private static extern bool Internal_IsInvokingAll([NotNull("NullExceptionObject")] MonoBehaviour self); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern void InvokeDelayed([NotNull("NullExceptionObject")] MonoBehaviour self, string methodName, float time, float repeatRate); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern void CancelInvoke([NotNull("NullExceptionObject")] MonoBehaviour self, string methodName); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern bool IsInvoking([NotNull("NullExceptionObject")] MonoBehaviour self, string methodName); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern bool IsObjectMonoBehaviour([NotNull("NullExceptionObject")] Object obj); [MethodImpl(MethodImplOptions.InternalCall)] private extern Coroutine StartCoroutineManaged(string methodName, object value); [MethodImpl(MethodImplOptions.InternalCall)] private extern Coroutine StartCoroutineManaged2(IEnumerator enumerator); [MethodImpl(MethodImplOptions.InternalCall)] private extern void StopCoroutineManaged(Coroutine routine); [MethodImpl(MethodImplOptions.InternalCall)] private extern void StopCoroutineFromEnumeratorManaged(IEnumerator routine); [MethodImpl(MethodImplOptions.InternalCall)] internal extern string GetScriptClassName(); } [NativeHeader("Runtime/Export/Scripting/NoAllocHelpers.bindings.h")] internal sealed class NoAllocHelpers { public static void ResizeList(List list, int size) { if (list == null) { throw new ArgumentNullException("list"); } if (size < 0 || size > list.Capacity) { throw new ArgumentException("invalid size to resize.", "list"); } if (size != list.Count) { Internal_ResizeList(list, size); } } public static void EnsureListElemCount(List list, int count) { list.Clear(); if (list.Capacity < count) { list.Capacity = count; } ResizeList(list, count); } public static int SafeLength(Array values) { return values?.Length ?? 0; } public static int SafeLength(List values) { return values?.Count ?? 0; } public static T[] ExtractArrayFromListT(List list) { return (T[])ExtractArrayFromList(list); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("NoAllocHelpers_Bindings::Internal_ResizeList")] internal static extern void Internal_ResizeList(object list, int size); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("NoAllocHelpers_Bindings::ExtractArrayFromList")] public static extern Array ExtractArrayFromList(object list); } public struct RangeInt { public int start; public int length; public int end => start + length; public RangeInt(int start, int length) { this.start = start; this.length = length; } } public enum RuntimeInitializeLoadType { AfterSceneLoad, BeforeSceneLoad, AfterAssembliesLoaded, BeforeSplashScreen, SubsystemRegistration } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] [RequiredByNativeCode] public class RuntimeInitializeOnLoadMethodAttribute : PreserveAttribute { private RuntimeInitializeLoadType m_LoadType; public RuntimeInitializeLoadType loadType { get { return m_LoadType; } private set { m_LoadType = value; } } public RuntimeInitializeOnLoadMethodAttribute() { loadType = RuntimeInitializeLoadType.AfterSceneLoad; } public RuntimeInitializeOnLoadMethodAttribute(RuntimeInitializeLoadType loadType) { this.loadType = loadType; } } [StructLayout(LayoutKind.Sequential)] [NativeHeader("Runtime/Mono/MonoBehaviour.h")] [RequiredByNativeCode] [NativeClass(null)] [ExtensionOfNativeClass] public class ScriptableObject : Object { public ScriptableObject() { CreateScriptableObject(this); } [MethodImpl(MethodImplOptions.InternalCall)] [Obsolete("Use EditorUtility.SetDirty instead")] [NativeConditional("ENABLE_MONO")] public extern void SetDirty(); public static ScriptableObject CreateInstance(string className) { return CreateScriptableObjectInstanceFromName(className); } public static ScriptableObject CreateInstance(Type type) { return CreateScriptableObjectInstanceFromType(type, applyDefaultsAndReset: true); } public static T CreateInstance() where T : ScriptableObject { return (T)CreateInstance(typeof(T)); } [EditorBrowsable(EditorBrowsableState.Never)] internal static ScriptableObject CreateInstance(Type type, Action initialize) { if (!typeof(ScriptableObject).IsAssignableFrom(type)) { throw new ArgumentException("Type must inherit ScriptableObject.", "type"); } ScriptableObject scriptableObject = CreateScriptableObjectInstanceFromType(type, applyDefaultsAndReset: false); try { initialize(scriptableObject); } finally { ResetAndApplyDefaultInstances(scriptableObject); } return scriptableObject; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true)] private static extern void CreateScriptableObject([Writable] ScriptableObject self); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Scripting::CreateScriptableObject")] private static extern ScriptableObject CreateScriptableObjectInstanceFromName(string className); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Scripting::CreateScriptableObjectWithType")] internal static extern ScriptableObject CreateScriptableObjectInstanceFromType(Type type, bool applyDefaultsAndReset); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Scripting::ResetAndApplyDefaultInstances")] internal static extern void ResetAndApplyDefaultInstances([NotNull("NullExceptionObject")] Object obj); } [NativeHeader("Runtime/Export/Scripting/ScriptingRuntime.h")] [VisibleToOtherModules] internal class ScriptingRuntime { [MethodImpl(MethodImplOptions.InternalCall)] public static extern string[] GetAllUserAssemblies(); } internal class ScriptingUtility { private struct TestClass { public int value; } [RequiredByNativeCode] private static bool IsManagedCodeWorking() { TestClass testClass = new TestClass { value = 42 }; return testClass.value == 42; } } [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public class SelectionBaseAttribute : Attribute { } public static class StackTraceUtility { private static string projectFolder = ""; [RequiredByNativeCode] internal static void SetProjectFolder(string folder) { projectFolder = folder; if (!string.IsNullOrEmpty(projectFolder)) { projectFolder = projectFolder.Replace("\\", "/"); } } [RequiredByNativeCode] [SecuritySafeCritical] public unsafe static string ExtractStackTrace() { int num = 16384; byte* ptr = stackalloc byte[(int)(uint)num]; int num2 = Debug.ExtractStackTraceNoAlloc(ptr, num, projectFolder); if (num2 > 0) { return new string((sbyte*)ptr, 0, num2, Encoding.UTF8); } StackTrace stackTrace = new StackTrace(1, fNeedFileInfo: true); return ExtractFormattedStackTrace(stackTrace); } public static string ExtractStringFromException(object exception) { ExtractStringFromExceptionInternal(exception, out var message, out var stackTrace); return message + "\n" + stackTrace; } [RequiredByNativeCode] [SecuritySafeCritical] internal static void ExtractStringFromExceptionInternal(object exceptiono, out string message, out string stackTrace) { if (exceptiono == null) { throw new ArgumentException("ExtractStringFromExceptionInternal called with null exception"); } Exception ex = exceptiono as Exception; if (ex == null) { throw new ArgumentException("ExtractStringFromExceptionInternal called with an exceptoin that was not of type System.Exception"); } StringBuilder stringBuilder = new StringBuilder((ex.StackTrace == null) ? 512 : (ex.StackTrace.Length * 2)); message = ""; string text = ""; while (ex != null) { text = ((text.Length != 0) ? (ex.StackTrace + "\n" + text) : ex.StackTrace); string text2 = ex.GetType().Name; string text3 = ""; if (ex.Message != null) { text3 = ex.Message; } if (text3.Trim().Length != 0) { text2 += ": "; text2 += text3; } message = text2; if (ex.InnerException != null) { text = "Rethrow as " + text2 + "\n" + text; } ex = ex.InnerException; } stringBuilder.Append(text + "\n"); StackTrace stackTrace2 = new StackTrace(1, fNeedFileInfo: true); stringBuilder.Append(ExtractFormattedStackTrace(stackTrace2)); stackTrace = stringBuilder.ToString(); } [SecuritySafeCritical] internal static string ExtractFormattedStackTrace(StackTrace stackTrace) { StringBuilder stringBuilder = new StringBuilder(255); for (int i = 0; i < stackTrace.FrameCount; i++) { StackFrame frame = stackTrace.GetFrame(i); MethodBase method = frame.GetMethod(); if ((object)method == null) { continue; } Type declaringType = method.DeclaringType; if ((object)declaringType == null) { continue; } string value = declaringType.Namespace; if (!string.IsNullOrEmpty(value)) { stringBuilder.Append(value); stringBuilder.Append("."); } stringBuilder.Append(declaringType.Name); stringBuilder.Append(":"); stringBuilder.Append(method.Name); stringBuilder.Append("("); int j = 0; ParameterInfo[] parameters = method.GetParameters(); bool flag = true; for (; j < parameters.Length; j++) { if (!flag) { stringBuilder.Append(", "); } else { flag = false; } stringBuilder.Append(parameters[j].ParameterType.Name); } stringBuilder.Append(")"); string text = frame.GetFileName(); if (text != null && (!(declaringType.Name == "Debug") || !(declaringType.Namespace == "UnityEngine")) && (!(declaringType.Name == "Logger") || !(declaringType.Namespace == "UnityEngine")) && (!(declaringType.Name == "DebugLogHandler") || !(declaringType.Namespace == "UnityEngine")) && (!(declaringType.Name == "Assert") || !(declaringType.Namespace == "UnityEngine.Assertions")) && (!(method.Name == "print") || !(declaringType.Name == "MonoBehaviour") || !(declaringType.Namespace == "UnityEngine"))) { stringBuilder.Append(" (at "); if (!string.IsNullOrEmpty(projectFolder) && text.Replace("\\", "/").StartsWith(projectFolder)) { text = text.Substring(projectFolder.Length, text.Length - projectFolder.Length); } stringBuilder.Append(text); stringBuilder.Append(":"); stringBuilder.Append(frame.GetFileLineNumber().ToString()); stringBuilder.Append(")"); } stringBuilder.Append("\n"); } return stringBuilder.ToString(); } } [Serializable] [RequiredByNativeCode] public class UnityException : SystemException { private const int Result = -2147467261; private string unityStackTrace; public UnityException() : base("A Unity Runtime error occurred!") { base.HResult = -2147467261; } public UnityException(string message) : base(message) { base.HResult = -2147467261; } public UnityException(string message, Exception innerException) : base(message, innerException) { base.HResult = -2147467261; } protected UnityException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class MissingComponentException : SystemException { private const int Result = -2147467261; private string unityStackTrace; public MissingComponentException() : base("A Unity Runtime error occurred!") { base.HResult = -2147467261; } public MissingComponentException(string message) : base(message) { base.HResult = -2147467261; } public MissingComponentException(string message, Exception innerException) : base(message, innerException) { base.HResult = -2147467261; } protected MissingComponentException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class UnassignedReferenceException : SystemException { private const int Result = -2147467261; private string unityStackTrace; public UnassignedReferenceException() : base("A Unity Runtime error occurred!") { base.HResult = -2147467261; } public UnassignedReferenceException(string message) : base(message) { base.HResult = -2147467261; } public UnassignedReferenceException(string message, Exception innerException) : base(message, innerException) { base.HResult = -2147467261; } protected UnassignedReferenceException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public class MissingReferenceException : SystemException { private const int Result = -2147467261; private string unityStackTrace; public MissingReferenceException() : base("A Unity Runtime error occurred!") { base.HResult = -2147467261; } public MissingReferenceException(string message) : base(message) { base.HResult = -2147467261; } public MissingReferenceException(string message, Exception innerException) : base(message, innerException) { base.HResult = -2147467261; } protected MissingReferenceException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [NativeHeader("Runtime/Scripting/TextAsset.h")] public class TextAsset : Object { internal enum CreateOptions { None, CreateNativeObject } private static class EncodingUtility { internal static readonly KeyValuePair[] encodingLookup; internal static readonly Encoding targetEncoding; static EncodingUtility() { targetEncoding = Encoding.GetEncoding(Encoding.UTF8.CodePage, new EncoderReplacementFallback("\ufffd"), new DecoderReplacementFallback("\ufffd")); Encoding encoding = new UTF32Encoding(bigEndian: true, byteOrderMark: true, throwOnInvalidCharacters: true); Encoding encoding2 = new UTF32Encoding(bigEndian: false, byteOrderMark: true, throwOnInvalidCharacters: true); Encoding encoding3 = new UnicodeEncoding(bigEndian: true, byteOrderMark: true, throwOnInvalidBytes: true); Encoding encoding4 = new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true); Encoding encoding5 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true, throwOnInvalidBytes: true); encodingLookup = new KeyValuePair[5] { new KeyValuePair(encoding.GetPreamble(), encoding), new KeyValuePair(encoding2.GetPreamble(), encoding2), new KeyValuePair(encoding3.GetPreamble(), encoding3), new KeyValuePair(encoding4.GetPreamble(), encoding4), new KeyValuePair(encoding5.GetPreamble(), encoding5) }; } } public extern byte[] bytes { [MethodImpl(MethodImplOptions.InternalCall)] get; } public string text => DecodeString(bytes); public long dataSize => GetDataSize(); [MethodImpl(MethodImplOptions.InternalCall)] private extern byte[] GetPreviewBytes(int maxByteCount); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_CreateInstance([Writable] TextAsset self, string text); [MethodImpl(MethodImplOptions.InternalCall)] private extern IntPtr GetDataPtr(); [MethodImpl(MethodImplOptions.InternalCall)] private extern long GetDataSize(); public override string ToString() { return text; } public TextAsset() : this(CreateOptions.CreateNativeObject, null) { } public TextAsset(string text) : this(CreateOptions.CreateNativeObject, text) { } internal TextAsset(CreateOptions options, string text) { if (options == CreateOptions.CreateNativeObject) { Internal_CreateInstance(this, text); } } public unsafe NativeArray GetData() where T : struct { long num = GetDataSize(); long num2 = UnsafeUtility.SizeOf(); if (num % num2 != 0) { throw new ArgumentException(string.Format("Type passed to {0} can't capture the asset data. Data size is {1} which is not a multiple of type size {2}", "GetData", num, num2)); } long num3 = num / num2; return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)GetDataPtr(), (int)num3, Allocator.None); } internal string GetPreview(int maxChars) { return DecodeString(GetPreviewBytes(maxChars * 4)); } internal static string DecodeString(byte[] bytes) { int num = EncodingUtility.encodingLookup.Length; int num2; for (int i = 0; i < num; i++) { byte[] key = EncodingUtility.encodingLookup[i].Key; num2 = key.Length; if (bytes.Length < num2) { continue; } for (int j = 0; j < num2; j++) { if (key[j] != bytes[j]) { num2 = -1; } } if (num2 >= 0) { try { Encoding value = EncodingUtility.encodingLookup[i].Value; return value.GetString(bytes, num2, bytes.Length - num2); } catch { } } } num2 = 0; Encoding targetEncoding = EncodingUtility.targetEncoding; return targetEncoding.GetString(bytes, num2, bytes.Length - num2); } } [StructLayout(LayoutKind.Sequential)] [UsedByNativeCode] public class TrackedReference { internal IntPtr m_Ptr; protected TrackedReference() { } public static bool operator ==(TrackedReference x, TrackedReference y) { if ((object)y == null && (object)x == null) { return true; } if ((object)y == null) { return x.m_Ptr == IntPtr.Zero; } if ((object)x == null) { return y.m_Ptr == IntPtr.Zero; } return x.m_Ptr == y.m_Ptr; } public static bool operator !=(TrackedReference x, TrackedReference y) { return !(x == y); } public override bool Equals(object o) { return o as TrackedReference == this; } public override int GetHashCode() { return (int)m_Ptr; } public static implicit operator bool(TrackedReference exists) { return exists != null; } } [NativeHeader("PlatformDependent/iPhonePlayer/IOSScriptBindings.h")] internal sealed class UnhandledExceptionHandler { [RequiredByNativeCode] private static void RegisterUECatcher() { AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs e) { Debug.LogException(e.ExceptionObject as Exception); }; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public class UnityAPICompatibilityVersionAttribute : Attribute { private string _version; private string[] _configurationAssembliesHashes; public string version => _version; internal string[] configurationAssembliesHashes => _configurationAssembliesHashes; [Obsolete("This overload of the attribute has been deprecated. Use the constructor that takes the version and a boolean", true)] public UnityAPICompatibilityVersionAttribute(string version) { _version = version; } public UnityAPICompatibilityVersionAttribute(string version, bool checkOnlyUnityVersion) { if (!checkOnlyUnityVersion) { throw new ArgumentException("You must pass 'true' to checkOnlyUnityVersion parameter."); } _version = version; } public UnityAPICompatibilityVersionAttribute(string version, string[] configurationAssembliesHashes) { _version = version; _configurationAssembliesHashes = configurationAssembliesHashes; } } [Flags] public enum HideFlags { None = 0, HideInHierarchy = 1, HideInInspector = 2, DontSaveInEditor = 4, NotEditable = 8, DontSaveInBuild = 0x10, DontUnloadUnusedAsset = 0x20, DontSave = 0x34, HideAndDontSave = 0x3D } public enum FindObjectsSortMode { None, InstanceID } public enum FindObjectsInactive { Exclude, Include } [StructLayout(LayoutKind.Sequential)] [NativeHeader("Runtime/SceneManager/SceneManager.h")] [RequiredByNativeCode(GenerateProxy = true)] [NativeHeader("Runtime/Export/Scripting/UnityEngineObject.bindings.h")] [NativeHeader("Runtime/GameCode/CloneObject.h")] public class Object { private IntPtr m_CachedPtr; internal static int OffsetOfInstanceIDInCPlusPlusObject = -1; private const string objectIsNullMessage = "The Object you want to instantiate is null."; private const string cloneDestroyedMessage = "Instantiate failed because the clone was destroyed during creation. This can happen if DestroyImmediate is called in MonoBehaviour.Awake."; public string name { get { return GetName(this); } set { SetName(this, value); } } public extern HideFlags hideFlags { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [SecuritySafeCritical] public unsafe int GetInstanceID() { if (m_CachedPtr == IntPtr.Zero) { return 0; } if (OffsetOfInstanceIDInCPlusPlusObject == -1) { OffsetOfInstanceIDInCPlusPlusObject = GetOffsetOfInstanceIDInCPlusPlusObject(); } return *(int*)(void*)new IntPtr(m_CachedPtr.ToInt64() + OffsetOfInstanceIDInCPlusPlusObject); } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object other) { Object obj = other as Object; if (obj == null && other != null && !(other is Object)) { return false; } return CompareBaseObjects(this, obj); } public static implicit operator bool(Object exists) { return !CompareBaseObjects(exists, null); } private static bool CompareBaseObjects(Object lhs, Object rhs) { bool flag = (object)lhs == null; bool flag2 = (object)rhs == null; if (flag2 && flag) { return true; } if (flag2) { return !IsNativeObjectAlive(lhs); } if (flag) { return !IsNativeObjectAlive(rhs); } return (object)lhs == rhs; } private void EnsureRunningOnMainThread() { if (!CurrentThreadIsMainThread()) { throw new InvalidOperationException("EnsureRunningOnMainThread can only be called from the main thread"); } } private static bool IsNativeObjectAlive(Object o) { return o.GetCachedPtr() != IntPtr.Zero; } private IntPtr GetCachedPtr() { return m_CachedPtr; } [TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)] public static Object Instantiate(Object original, Vector3 position, Quaternion rotation) { CheckNullArgument(original, "The Object you want to instantiate is null."); if (original is ScriptableObject) { throw new ArgumentException("Cannot instantiate a ScriptableObject with a position and rotation"); } Object obj = Internal_InstantiateSingle(original, position, rotation); if (obj == null) { throw new UnityException("Instantiate failed because the clone was destroyed during creation. This can happen if DestroyImmediate is called in MonoBehaviour.Awake."); } return obj; } [TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)] public static Object Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent) { if (parent == null) { return Instantiate(original, position, rotation); } CheckNullArgument(original, "The Object you want to instantiate is null."); Object obj = Internal_InstantiateSingleWithParent(original, parent, position, rotation); if (obj == null) { throw new UnityException("Instantiate failed because the clone was destroyed during creation. This can happen if DestroyImmediate is called in MonoBehaviour.Awake."); } return obj; } [TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)] public static Object Instantiate(Object original) { CheckNullArgument(original, "The Object you want to instantiate is null."); Object obj = Internal_CloneSingle(original); if (obj == null) { throw new UnityException("Instantiate failed because the clone was destroyed during creation. This can happen if DestroyImmediate is called in MonoBehaviour.Awake."); } return obj; } [TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)] public static Object Instantiate(Object original, Transform parent) { return Instantiate(original, parent, instantiateInWorldSpace: false); } [TypeInferenceRule(TypeInferenceRules.TypeOfFirstArgument)] public static Object Instantiate(Object original, Transform parent, bool instantiateInWorldSpace) { if (parent == null) { return Instantiate(original); } CheckNullArgument(original, "The Object you want to instantiate is null."); Object obj = Internal_CloneSingleWithParent(original, parent, instantiateInWorldSpace); if (obj == null) { throw new UnityException("Instantiate failed because the clone was destroyed during creation. This can happen if DestroyImmediate is called in MonoBehaviour.Awake."); } return obj; } public static T Instantiate(T original) where T : Object { CheckNullArgument(original, "The Object you want to instantiate is null."); T val = (T)Internal_CloneSingle(original); if (val == null) { throw new UnityException("Instantiate failed because the clone was destroyed during creation. This can happen if DestroyImmediate is called in MonoBehaviour.Awake."); } return val; } public static T Instantiate(T original, Vector3 position, Quaternion rotation) where T : Object { return (T)Instantiate((Object)original, position, rotation); } public static T Instantiate(T original, Vector3 position, Quaternion rotation, Transform parent) where T : Object { return (T)Instantiate((Object)original, position, rotation, parent); } public static T Instantiate(T original, Transform parent) where T : Object { return Instantiate(original, parent, worldPositionStays: false); } public static T Instantiate(T original, Transform parent, bool worldPositionStays) where T : Object { return (T)Instantiate((Object)original, parent, worldPositionStays); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "Scripting::DestroyObjectFromScripting", IsFreeFunction = true, ThrowsException = true)] public static extern void Destroy(Object obj, [UnityEngine.Internal.DefaultValue("0.0F")] float t); [ExcludeFromDocs] public static void Destroy(Object obj) { float t = 0f; Destroy(obj, t); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "Scripting::DestroyObjectFromScriptingImmediate", IsFreeFunction = true, ThrowsException = true)] public static extern void DestroyImmediate(Object obj, [UnityEngine.Internal.DefaultValue("false")] bool allowDestroyingAssets); [ExcludeFromDocs] public static void DestroyImmediate(Object obj) { bool allowDestroyingAssets = false; DestroyImmediate(obj, allowDestroyingAssets); } public static Object[] FindObjectsOfType(Type type) { return FindObjectsOfType(type, includeInactive: false); } [MethodImpl(MethodImplOptions.InternalCall)] [TypeInferenceRule(TypeInferenceRules.ArrayOfTypeReferencedByFirstArgument)] [FreeFunction("UnityEngineObjectBindings::FindObjectsOfType")] public static extern Object[] FindObjectsOfType(Type type, bool includeInactive); public static Object[] FindObjectsByType(Type type, FindObjectsSortMode sortMode) { return FindObjectsByType(type, FindObjectsInactive.Exclude, sortMode); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityEngineObjectBindings::FindObjectsByType")] [TypeInferenceRule(TypeInferenceRules.ArrayOfTypeReferencedByFirstArgument)] public static extern Object[] FindObjectsByType(Type type, FindObjectsInactive findObjectsInactive, FindObjectsSortMode sortMode); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetSceneManager().DontDestroyOnLoad", ThrowsException = true)] public static extern void DontDestroyOnLoad([NotNull("NullExceptionObject")] Object target); [Obsolete("use Object.Destroy instead.")] public static void DestroyObject(Object obj, [UnityEngine.Internal.DefaultValue("0.0F")] float t) { Destroy(obj, t); } [Obsolete("use Object.Destroy instead.")] [ExcludeFromDocs] public static void DestroyObject(Object obj) { float t = 0f; Destroy(obj, t); } [Obsolete("warning use Object.FindObjectsByType instead.")] public static Object[] FindSceneObjectsOfType(Type type) { return FindObjectsOfType(type); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityEngineObjectBindings::FindObjectsOfTypeIncludingAssets")] [Obsolete("use Resources.FindObjectsOfTypeAll instead.")] public static extern Object[] FindObjectsOfTypeIncludingAssets(Type type); public static T[] FindObjectsOfType() where T : Object { return Resources.ConvertObjects(FindObjectsOfType(typeof(T), includeInactive: false)); } public static T[] FindObjectsByType(FindObjectsSortMode sortMode) where T : Object { return Resources.ConvertObjects(FindObjectsByType(typeof(T), FindObjectsInactive.Exclude, sortMode)); } public static T[] FindObjectsOfType(bool includeInactive) where T : Object { return Resources.ConvertObjects(FindObjectsOfType(typeof(T), includeInactive)); } public static T[] FindObjectsByType(FindObjectsInactive findObjectsInactive, FindObjectsSortMode sortMode) where T : Object { return Resources.ConvertObjects(FindObjectsByType(typeof(T), findObjectsInactive, sortMode)); } public static T FindObjectOfType() where T : Object { return (T)FindObjectOfType(typeof(T), includeInactive: false); } public static T FindObjectOfType(bool includeInactive) where T : Object { return (T)FindObjectOfType(typeof(T), includeInactive); } public static T FindFirstObjectByType() where T : Object { return (T)FindFirstObjectByType(typeof(T), FindObjectsInactive.Exclude); } public static T FindAnyObjectByType() where T : Object { return (T)FindAnyObjectByType(typeof(T), FindObjectsInactive.Exclude); } public static T FindFirstObjectByType(FindObjectsInactive findObjectsInactive) where T : Object { return (T)FindFirstObjectByType(typeof(T), findObjectsInactive); } public static T FindAnyObjectByType(FindObjectsInactive findObjectsInactive) where T : Object { return (T)FindAnyObjectByType(typeof(T), findObjectsInactive); } [Obsolete("Please use Resources.FindObjectsOfTypeAll instead")] public static Object[] FindObjectsOfTypeAll(Type type) { return Resources.FindObjectsOfTypeAll(type); } private static void CheckNullArgument(object arg, string message) { if (arg == null) { throw new ArgumentException(message); } } [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public static Object FindObjectOfType(Type type) { Object[] array = FindObjectsOfType(type, includeInactive: false); if (array.Length != 0) { return array[0]; } return null; } public static Object FindFirstObjectByType(Type type) { Object[] array = FindObjectsByType(type, FindObjectsInactive.Exclude, FindObjectsSortMode.InstanceID); return (array.Length != 0) ? array[0] : null; } public static Object FindAnyObjectByType(Type type) { Object[] array = FindObjectsByType(type, FindObjectsInactive.Exclude, FindObjectsSortMode.None); return (array.Length != 0) ? array[0] : null; } [TypeInferenceRule(TypeInferenceRules.TypeReferencedByFirstArgument)] public static Object FindObjectOfType(Type type, bool includeInactive) { Object[] array = FindObjectsOfType(type, includeInactive); if (array.Length != 0) { return array[0]; } return null; } public static Object FindFirstObjectByType(Type type, FindObjectsInactive findObjectsInactive) { Object[] array = FindObjectsByType(type, findObjectsInactive, FindObjectsSortMode.InstanceID); return (array.Length != 0) ? array[0] : null; } public static Object FindAnyObjectByType(Type type, FindObjectsInactive findObjectsInactive) { Object[] array = FindObjectsByType(type, findObjectsInactive, FindObjectsSortMode.None); return (array.Length != 0) ? array[0] : null; } public override string ToString() { return ToString(this); } public static bool operator ==(Object x, Object y) { return CompareBaseObjects(x, y); } public static bool operator !=(Object x, Object y) { return !CompareBaseObjects(x, y); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "Object::GetOffsetOfInstanceIdMember", IsFreeFunction = true, IsThreadSafe = true)] private static extern int GetOffsetOfInstanceIDInCPlusPlusObject(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "CurrentThreadIsMainThread", IsFreeFunction = true, IsThreadSafe = true)] private static extern bool CurrentThreadIsMainThread(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "CloneObject", IsFreeFunction = true, ThrowsException = true)] private static extern Object Internal_CloneSingle([NotNull("NullExceptionObject")] Object data); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("CloneObject")] private static extern Object Internal_CloneSingleWithParent([NotNull("NullExceptionObject")] Object data, [NotNull("NullExceptionObject")] Transform parent, bool worldPositionStays); [FreeFunction("InstantiateObject")] private static Object Internal_InstantiateSingle([NotNull("NullExceptionObject")] Object data, Vector3 pos, Quaternion rot) { return Internal_InstantiateSingle_Injected(data, ref pos, ref rot); } [FreeFunction("InstantiateObject")] private static Object Internal_InstantiateSingleWithParent([NotNull("NullExceptionObject")] Object data, [NotNull("NullExceptionObject")] Transform parent, Vector3 pos, Quaternion rot) { return Internal_InstantiateSingleWithParent_Injected(data, parent, ref pos, ref rot); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityEngineObjectBindings::ToString")] private static extern string ToString(Object obj); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityEngineObjectBindings::GetName")] private static extern string GetName([NotNull("NullExceptionObject")] Object obj); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityEngineObjectBindings::IsPersistent")] internal static extern bool IsPersistent([NotNull("NullExceptionObject")] Object obj); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityEngineObjectBindings::SetName")] private static extern void SetName([NotNull("NullExceptionObject")] Object obj, string name); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "UnityEngineObjectBindings::DoesObjectWithInstanceIDExist", IsFreeFunction = true, IsThreadSafe = true)] internal static extern bool DoesObjectWithInstanceIDExist(int instanceID); [MethodImpl(MethodImplOptions.InternalCall)] [VisibleToOtherModules] [FreeFunction("UnityEngineObjectBindings::FindObjectFromInstanceID")] internal static extern Object FindObjectFromInstanceID(int instanceID); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("UnityEngineObjectBindings::ForceLoadFromInstanceID")] [VisibleToOtherModules] internal static extern Object ForceLoadFromInstanceID(int instanceID); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Object Internal_InstantiateSingle_Injected(Object data, ref Vector3 pos, ref Quaternion rot); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Object Internal_InstantiateSingleWithParent_Injected(Object data, Transform parent, ref Vector3 pos, ref Quaternion rot); } internal sealed class UnitySynchronizationContext : SynchronizationContext { private struct WorkRequest { private readonly SendOrPostCallback m_DelagateCallback; private readonly object m_DelagateState; private readonly ManualResetEvent m_WaitHandle; public WorkRequest(SendOrPostCallback callback, object state, ManualResetEvent waitHandle = null) { m_DelagateCallback = callback; m_DelagateState = state; m_WaitHandle = waitHandle; } public void Invoke() { try { m_DelagateCallback(m_DelagateState); } finally { m_WaitHandle?.Set(); } } } private const int kAwqInitialCapacity = 20; private readonly List m_AsyncWorkQueue; private readonly List m_CurrentFrameWork = new List(20); private readonly int m_MainThreadID; private int m_TrackedCount = 0; private UnitySynchronizationContext(int mainThreadID) { m_AsyncWorkQueue = new List(20); m_MainThreadID = mainThreadID; } private UnitySynchronizationContext(List queue, int mainThreadID) { m_AsyncWorkQueue = queue; m_MainThreadID = mainThreadID; } public override void Send(SendOrPostCallback callback, object state) { if (m_MainThreadID == Thread.CurrentThread.ManagedThreadId) { callback(state); return; } using ManualResetEvent manualResetEvent = new ManualResetEvent(initialState: false); lock (m_AsyncWorkQueue) { m_AsyncWorkQueue.Add(new WorkRequest(callback, state, manualResetEvent)); } manualResetEvent.WaitOne(); } public override void OperationStarted() { Interlocked.Increment(ref m_TrackedCount); } public override void OperationCompleted() { Interlocked.Decrement(ref m_TrackedCount); } public override void Post(SendOrPostCallback callback, object state) { lock (m_AsyncWorkQueue) { m_AsyncWorkQueue.Add(new WorkRequest(callback, state)); } } public override SynchronizationContext CreateCopy() { return new UnitySynchronizationContext(m_AsyncWorkQueue, m_MainThreadID); } private void Exec() { lock (m_AsyncWorkQueue) { m_CurrentFrameWork.AddRange(m_AsyncWorkQueue); m_AsyncWorkQueue.Clear(); } while (m_CurrentFrameWork.Count > 0) { WorkRequest workRequest = m_CurrentFrameWork[0]; m_CurrentFrameWork.RemoveAt(0); workRequest.Invoke(); } } private bool HasPendingTasks() { return m_AsyncWorkQueue.Count != 0 || m_TrackedCount != 0; } [RequiredByNativeCode] private static void InitializeSynchronizationContext() { SynchronizationContext.SetSynchronizationContext(new UnitySynchronizationContext(Thread.CurrentThread.ManagedThreadId)); } [RequiredByNativeCode] private static void ExecuteTasks() { if (SynchronizationContext.Current is UnitySynchronizationContext unitySynchronizationContext) { unitySynchronizationContext.Exec(); } } [RequiredByNativeCode] private static bool ExecutePendingTasks(long millisecondsTimeout) { if (!(SynchronizationContext.Current is UnitySynchronizationContext unitySynchronizationContext)) { return true; } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); while (unitySynchronizationContext.HasPendingTasks() && stopwatch.ElapsedMilliseconds <= millisecondsTimeout) { unitySynchronizationContext.Exec(); Thread.Sleep(1); } return !unitySynchronizationContext.HasPendingTasks(); } } [RequiredByNativeCode] public sealed class WaitForEndOfFrame : YieldInstruction { } [RequiredByNativeCode] public sealed class WaitForFixedUpdate : YieldInstruction { } [StructLayout(LayoutKind.Sequential)] [RequiredByNativeCode] public sealed class WaitForSeconds : YieldInstruction { internal float m_Seconds; public WaitForSeconds(float seconds) { m_Seconds = seconds; } } public class WaitForSecondsRealtime : CustomYieldInstruction { private float m_WaitUntilTime = -1f; public float waitTime { get; set; } public override bool keepWaiting { get { if (m_WaitUntilTime < 0f) { m_WaitUntilTime = Time.realtimeSinceStartup + waitTime; } bool flag = Time.realtimeSinceStartup < m_WaitUntilTime; if (!flag) { Reset(); } return flag; } } public WaitForSecondsRealtime(float time) { waitTime = time; } public override void Reset() { m_WaitUntilTime = -1f; } } public sealed class WaitUntil : CustomYieldInstruction { private Func m_Predicate; public override bool keepWaiting => !m_Predicate(); public WaitUntil(Func predicate) { m_Predicate = predicate; } } public sealed class WaitWhile : CustomYieldInstruction { private Func m_Predicate; public override bool keepWaiting => m_Predicate(); public WaitWhile(Func predicate) { m_Predicate = predicate; } } [StructLayout(LayoutKind.Sequential)] [UsedByNativeCode] public class YieldInstruction { } public sealed class Security { [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This was an internal method which is no longer used", true)] public static Assembly LoadAndVerifyAssembly(byte[] assemblyData, string authorizationKey) { return null; } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("This was an internal method which is no longer used", true)] public static Assembly LoadAndVerifyAssembly(byte[] assemblyData) { return null; } [Obsolete("Security.PrefetchSocketPolicy is no longer supported, since the Unity Web Player is no longer supported by Unity.", true)] [ExcludeFromDocs] public static bool PrefetchSocketPolicy(string ip, int atPort) { int timeout = 3000; return PrefetchSocketPolicy(ip, atPort, timeout); } [Obsolete("Security.PrefetchSocketPolicy is no longer supported, since the Unity Web Player is no longer supported by Unity.", true)] public static bool PrefetchSocketPolicy(string ip, int atPort, [UnityEngine.Internal.DefaultValue("3000")] int timeout) { return false; } } public static class Types { [Obsolete("This was an internal method which is no longer used", true)] [EditorBrowsable(EditorBrowsableState.Never)] public static Type GetType(string typeName, string assemblyName) { return null; } } [RequiredByNativeCode] public sealed class SerializeField : Attribute { } [AttributeUsage(AttributeTargets.Field)] [RequiredByNativeCode] public sealed class SerializeReference : Attribute { [ExcludeFromDocs] public SerializeReference() { } } [AttributeUsage(AttributeTargets.Class)] [RequiredByNativeCode] public sealed class PreferBinarySerialization : Attribute { } [RequiredByNativeCode] public interface ISerializationCallbackReceiver { [RequiredByNativeCode] void OnBeforeSerialize(); [RequiredByNativeCode] void OnAfterDeserialize(); } [NativeClass("GraphicsBuffer")] [NativeHeader("Runtime/Export/Graphics/GraphicsBuffer.bindings.h")] [UsedByNativeCode] [NativeHeader("Runtime/Shaders/GraphicsBuffer.h")] public sealed class ComputeBuffer : IDisposable { internal IntPtr m_Ptr; public extern int count { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern int stride { [MethodImpl(MethodImplOptions.InternalCall)] get; } private extern ComputeBufferMode usage { [MethodImpl(MethodImplOptions.InternalCall)] get; } public string name { set { SetName(value); } } ~ComputeBuffer() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposing) { DestroyBuffer(this); } else if (m_Ptr != IntPtr.Zero) { Debug.LogWarning("GarbageCollector disposing of ComputeBuffer. Please use ComputeBuffer.Release() or .Dispose() to manually release the buffer."); } m_Ptr = IntPtr.Zero; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsBuffer_Bindings::InitComputeBuffer")] private static extern IntPtr InitBuffer(int count, int stride, ComputeBufferType type, ComputeBufferMode usage); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsBuffer_Bindings::DestroyBuffer")] private static extern void DestroyBuffer(ComputeBuffer buf); public ComputeBuffer(int count, int stride) : this(count, stride, ComputeBufferType.Default, ComputeBufferMode.Immutable, 3) { } public ComputeBuffer(int count, int stride, ComputeBufferType type) : this(count, stride, type, ComputeBufferMode.Immutable, 3) { } public ComputeBuffer(int count, int stride, ComputeBufferType type, ComputeBufferMode usage) : this(count, stride, type, usage, 3) { } private ComputeBuffer(int count, int stride, ComputeBufferType type, ComputeBufferMode usage, int stackDepth) { if (count <= 0) { throw new ArgumentException("Attempting to create a zero length compute buffer", "count"); } if (stride <= 0) { throw new ArgumentException("Attempting to create a compute buffer with a negative or null stride", "stride"); } long num = (long)count * (long)stride; long maxGraphicsBufferSize = SystemInfo.maxGraphicsBufferSize; if (num > maxGraphicsBufferSize) { throw new ArgumentException($"The total size of the compute buffer ({num} bytes) exceeds the maximum buffer size. Maximum supported buffer size: {maxGraphicsBufferSize} bytes."); } m_Ptr = InitBuffer(count, stride, type, usage); } public void Release() { Dispose(); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GraphicsBuffer_Bindings::IsValidBuffer")] private static extern bool IsValidBuffer(ComputeBuffer buf); public bool IsValid() { return m_Ptr != IntPtr.Zero && IsValidBuffer(this); } [SecuritySafeCritical] public void SetData(Array data) { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException($"Array passed to ComputeBuffer.SetData(array) must be blittable.\n{UnsafeUtility.GetReasonForArrayNonBlittable(data)}"); } InternalSetData(data, 0, 0, data.Length, UnsafeUtility.SizeOf(data.GetType().GetElementType())); } [SecuritySafeCritical] public void SetData(List data) where T : struct { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException($"List<{typeof(T)}> passed to ComputeBuffer.SetData(List<>) must be blittable.\n{UnsafeUtility.GetReasonForGenericListNonBlittable()}"); } InternalSetData(NoAllocHelpers.ExtractArrayFromList(data), 0, 0, NoAllocHelpers.SafeLength(data), Marshal.SizeOf(typeof(T))); } [SecuritySafeCritical] public unsafe void SetData(NativeArray data) where T : struct { InternalSetNativeData((IntPtr)data.GetUnsafeReadOnlyPtr(), 0, 0, data.Length, UnsafeUtility.SizeOf()); } [SecuritySafeCritical] public void SetData(Array data, int managedBufferStartIndex, int computeBufferStartIndex, int count) { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException($"Array passed to ComputeBuffer.SetData(array) must be blittable.\n{UnsafeUtility.GetReasonForArrayNonBlittable(data)}"); } if (managedBufferStartIndex < 0 || computeBufferStartIndex < 0 || count < 0 || managedBufferStartIndex + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (managedBufferStartIndex:{managedBufferStartIndex} computeBufferStartIndex:{computeBufferStartIndex} count:{count})"); } InternalSetData(data, managedBufferStartIndex, computeBufferStartIndex, count, Marshal.SizeOf(data.GetType().GetElementType())); } [SecuritySafeCritical] public void SetData(List data, int managedBufferStartIndex, int computeBufferStartIndex, int count) where T : struct { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException($"List<{typeof(T)}> passed to ComputeBuffer.SetData(List<>) must be blittable.\n{UnsafeUtility.GetReasonForGenericListNonBlittable()}"); } if (managedBufferStartIndex < 0 || computeBufferStartIndex < 0 || count < 0 || managedBufferStartIndex + count > data.Count) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (managedBufferStartIndex:{managedBufferStartIndex} computeBufferStartIndex:{computeBufferStartIndex} count:{count})"); } InternalSetData(NoAllocHelpers.ExtractArrayFromList(data), managedBufferStartIndex, computeBufferStartIndex, count, Marshal.SizeOf(typeof(T))); } [SecuritySafeCritical] public unsafe void SetData(NativeArray data, int nativeBufferStartIndex, int computeBufferStartIndex, int count) where T : struct { if (nativeBufferStartIndex < 0 || computeBufferStartIndex < 0 || count < 0 || nativeBufferStartIndex + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (nativeBufferStartIndex:{nativeBufferStartIndex} computeBufferStartIndex:{computeBufferStartIndex} count:{count})"); } InternalSetNativeData((IntPtr)data.GetUnsafeReadOnlyPtr(), nativeBufferStartIndex, computeBufferStartIndex, count, UnsafeUtility.SizeOf()); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GraphicsBuffer_Bindings::InternalSetNativeData", HasExplicitThis = true, ThrowsException = true)] private extern void InternalSetNativeData(IntPtr data, int nativeBufferStartIndex, int computeBufferStartIndex, int count, int elemSize); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GraphicsBuffer_Bindings::InternalSetData", HasExplicitThis = true, ThrowsException = true)] private extern void InternalSetData(Array data, int managedBufferStartIndex, int computeBufferStartIndex, int count, int elemSize); [SecurityCritical] public void GetData(Array data) { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException($"Array passed to ComputeBuffer.GetData(array) must be blittable.\n{UnsafeUtility.GetReasonForArrayNonBlittable(data)}"); } InternalGetData(data, 0, 0, data.Length, Marshal.SizeOf(data.GetType().GetElementType())); } [SecurityCritical] public void GetData(Array data, int managedBufferStartIndex, int computeBufferStartIndex, int count) { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException($"Array passed to ComputeBuffer.GetData(array) must be blittable.\n{UnsafeUtility.GetReasonForArrayNonBlittable(data)}"); } if (managedBufferStartIndex < 0 || computeBufferStartIndex < 0 || count < 0 || managedBufferStartIndex + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad indices/count argument (managedBufferStartIndex:{managedBufferStartIndex} computeBufferStartIndex:{computeBufferStartIndex} count:{count})"); } InternalGetData(data, managedBufferStartIndex, computeBufferStartIndex, count, Marshal.SizeOf(data.GetType().GetElementType())); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GraphicsBuffer_Bindings::InternalGetData", HasExplicitThis = true, ThrowsException = true)] private extern void InternalGetData(Array data, int managedBufferStartIndex, int computeBufferStartIndex, int count, int elemSize); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe extern void* BeginBufferWrite(int offset = 0, int size = 0); public unsafe NativeArray BeginWrite(int computeBufferStartIndex, int count) where T : struct { if (!IsValid()) { throw new InvalidOperationException("BeginWrite requires a valid ComputeBuffer"); } if (usage != ComputeBufferMode.SubUpdates) { throw new ArgumentException("ComputeBuffer must be created with usage mode ComputeBufferMode.SubUpdates to be able to be mapped with BeginWrite"); } int num = UnsafeUtility.SizeOf(); if (computeBufferStartIndex < 0 || count < 0 || (computeBufferStartIndex + count) * num > this.count * stride) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (computeBufferStartIndex:{computeBufferStartIndex} count:{count} elementSize:{num}, this.count:{this.count}, this.stride{stride})"); } void* dataPointer = BeginBufferWrite(computeBufferStartIndex * num, count * num); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(dataPointer, count, Allocator.Invalid); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void EndBufferWrite(int bytesWritten = 0); public void EndWrite(int countWritten) where T : struct { if (countWritten < 0) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (countWritten:{countWritten})"); } int num = UnsafeUtility.SizeOf(); EndBufferWrite(countWritten * num); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "GraphicsBuffer_Bindings::SetName", HasExplicitThis = true)] private extern void SetName(string name); [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetCounterValue(uint counterValue); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void CopyCount(ComputeBuffer src, ComputeBuffer dst, int dstOffsetBytes); [MethodImpl(MethodImplOptions.InternalCall)] public extern IntPtr GetNativeBufferPtr(); } [UsedByNativeCode] [NativeHeader("Runtime/Graphics/ShaderScriptBindings.h")] [NativeHeader("Runtime/Shaders/ComputeShader.h")] public sealed class ComputeShader : Object { public LocalKeywordSpace keywordSpace { get { get_keywordSpace_Injected(out var ret); return ret; } } public string[] shaderKeywords { get { return GetShaderKeywords(); } set { SetShaderKeywords(value); } } public LocalKeyword[] enabledKeywords { get { return GetEnabledKeywords(); } set { SetEnabledKeywords(value); } } [MethodImpl(MethodImplOptions.InternalCall)] [RequiredByNativeCode] [NativeMethod(Name = "ComputeShaderScripting::FindKernel", HasExplicitThis = true, IsFreeFunction = true, ThrowsException = true)] public extern int FindKernel(string name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ComputeShaderScripting::HasKernel", HasExplicitThis = true)] public extern bool HasKernel(string name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ComputeShaderScripting::SetValue", HasExplicitThis = true)] public extern void SetFloat(int nameID, float val); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ComputeShaderScripting::SetValue", HasExplicitThis = true)] public extern void SetInt(int nameID, int val); [FreeFunction(Name = "ComputeShaderScripting::SetValue", HasExplicitThis = true)] public void SetVector(int nameID, Vector4 val) { SetVector_Injected(nameID, ref val); } [FreeFunction(Name = "ComputeShaderScripting::SetValue", HasExplicitThis = true)] public void SetMatrix(int nameID, Matrix4x4 val) { SetMatrix_Injected(nameID, ref val); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ComputeShaderScripting::SetArray", HasExplicitThis = true)] private extern void SetFloatArray(int nameID, float[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ComputeShaderScripting::SetArray", HasExplicitThis = true)] private extern void SetIntArray(int nameID, int[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ComputeShaderScripting::SetArray", HasExplicitThis = true)] public extern void SetVectorArray(int nameID, Vector4[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ComputeShaderScripting::SetArray", HasExplicitThis = true)] public extern void SetMatrixArray(int nameID, Matrix4x4[] values); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ComputeShaderScripting::SetTexture", HasExplicitThis = true, IsFreeFunction = true, ThrowsException = true)] public extern void SetTexture(int kernelIndex, int nameID, [NotNull("ArgumentNullException")] Texture texture, int mipLevel); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ComputeShaderScripting::SetRenderTexture", HasExplicitThis = true, IsFreeFunction = true, ThrowsException = true)] private extern void SetRenderTexture(int kernelIndex, int nameID, [NotNull("ArgumentNullException")] RenderTexture texture, int mipLevel, RenderTextureSubElement element); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ComputeShaderScripting::SetTextureFromGlobal", HasExplicitThis = true, IsFreeFunction = true, ThrowsException = true)] public extern void SetTextureFromGlobal(int kernelIndex, int nameID, int globalTextureNameID); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ComputeShaderScripting::SetBuffer", HasExplicitThis = true)] private extern void Internal_SetBuffer(int kernelIndex, int nameID, [NotNull("ArgumentNullException")] ComputeBuffer buffer); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ComputeShaderScripting::SetBuffer", HasExplicitThis = true)] private extern void Internal_SetGraphicsBuffer(int kernelIndex, int nameID, [NotNull("ArgumentNullException")] GraphicsBuffer buffer); public void SetBuffer(int kernelIndex, int nameID, ComputeBuffer buffer) { Internal_SetBuffer(kernelIndex, nameID, buffer); } public void SetBuffer(int kernelIndex, int nameID, GraphicsBuffer buffer) { Internal_SetGraphicsBuffer(kernelIndex, nameID, buffer); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ComputeShaderScripting::SetConstantBuffer", HasExplicitThis = true)] private extern void SetConstantComputeBuffer(int nameID, [NotNull("ArgumentNullException")] ComputeBuffer buffer, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ComputeShaderScripting::SetConstantBuffer", HasExplicitThis = true)] private extern void SetConstantGraphicsBuffer(int nameID, [NotNull("ArgumentNullException")] GraphicsBuffer buffer, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ComputeShaderScripting::GetKernelThreadGroupSizes", HasExplicitThis = true, IsFreeFunction = true, ThrowsException = true)] public extern void GetKernelThreadGroupSizes(int kernelIndex, out uint x, out uint y, out uint z); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("DispatchComputeShader")] public extern void Dispatch(int kernelIndex, int threadGroupsX, int threadGroupsY, int threadGroupsZ); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ComputeShaderScripting::DispatchIndirect", HasExplicitThis = true)] private extern void Internal_DispatchIndirect(int kernelIndex, [NotNull("ArgumentNullException")] ComputeBuffer argsBuffer, uint argsOffset); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "ComputeShaderScripting::DispatchIndirect", HasExplicitThis = true)] private extern void Internal_DispatchIndirectGraphicsBuffer(int kernelIndex, [NotNull("ArgumentNullException")] GraphicsBuffer argsBuffer, uint argsOffset); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ComputeShaderScripting::EnableKeyword", HasExplicitThis = true)] public extern void EnableKeyword(string keyword); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ComputeShaderScripting::DisableKeyword", HasExplicitThis = true)] public extern void DisableKeyword(string keyword); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ComputeShaderScripting::IsKeywordEnabled", HasExplicitThis = true)] public extern bool IsKeywordEnabled(string keyword); [FreeFunction("ComputeShaderScripting::EnableKeyword", HasExplicitThis = true)] private void EnableLocalKeyword(LocalKeyword keyword) { EnableLocalKeyword_Injected(ref keyword); } [FreeFunction("ComputeShaderScripting::DisableKeyword", HasExplicitThis = true)] private void DisableLocalKeyword(LocalKeyword keyword) { DisableLocalKeyword_Injected(ref keyword); } [FreeFunction("ComputeShaderScripting::SetKeyword", HasExplicitThis = true)] private void SetLocalKeyword(LocalKeyword keyword, bool value) { SetLocalKeyword_Injected(ref keyword, value); } [FreeFunction("ComputeShaderScripting::IsKeywordEnabled", HasExplicitThis = true)] private bool IsLocalKeywordEnabled(LocalKeyword keyword) { return IsLocalKeywordEnabled_Injected(ref keyword); } public void EnableKeyword(in LocalKeyword keyword) { EnableLocalKeyword(keyword); } public void DisableKeyword(in LocalKeyword keyword) { DisableLocalKeyword(keyword); } public void SetKeyword(in LocalKeyword keyword, bool value) { SetLocalKeyword(keyword, value); } public bool IsKeywordEnabled(in LocalKeyword keyword) { return IsLocalKeywordEnabled(keyword); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ComputeShaderScripting::IsSupported", HasExplicitThis = true)] public extern bool IsSupported(int kernelIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ComputeShaderScripting::GetShaderKeywords", HasExplicitThis = true)] private extern string[] GetShaderKeywords(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ComputeShaderScripting::SetShaderKeywords", HasExplicitThis = true)] private extern void SetShaderKeywords(string[] names); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ComputeShaderScripting::GetEnabledKeywords", HasExplicitThis = true)] private extern LocalKeyword[] GetEnabledKeywords(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ComputeShaderScripting::SetEnabledKeywords", HasExplicitThis = true)] private extern void SetEnabledKeywords(LocalKeyword[] keywords); private ComputeShader() { } public void SetFloat(string name, float val) { SetFloat(Shader.PropertyToID(name), val); } public void SetInt(string name, int val) { SetInt(Shader.PropertyToID(name), val); } public void SetVector(string name, Vector4 val) { SetVector(Shader.PropertyToID(name), val); } public void SetMatrix(string name, Matrix4x4 val) { SetMatrix(Shader.PropertyToID(name), val); } public void SetVectorArray(string name, Vector4[] values) { SetVectorArray(Shader.PropertyToID(name), values); } public void SetMatrixArray(string name, Matrix4x4[] values) { SetMatrixArray(Shader.PropertyToID(name), values); } public void SetFloats(string name, params float[] values) { SetFloatArray(Shader.PropertyToID(name), values); } public void SetFloats(int nameID, params float[] values) { SetFloatArray(nameID, values); } public void SetInts(string name, params int[] values) { SetIntArray(Shader.PropertyToID(name), values); } public void SetInts(int nameID, params int[] values) { SetIntArray(nameID, values); } public void SetBool(string name, bool val) { SetInt(Shader.PropertyToID(name), val ? 1 : 0); } public void SetBool(int nameID, bool val) { SetInt(nameID, val ? 1 : 0); } public void SetTexture(int kernelIndex, int nameID, Texture texture) { SetTexture(kernelIndex, nameID, texture, 0); } public void SetTexture(int kernelIndex, string name, Texture texture) { SetTexture(kernelIndex, Shader.PropertyToID(name), texture, 0); } public void SetTexture(int kernelIndex, string name, Texture texture, int mipLevel) { SetTexture(kernelIndex, Shader.PropertyToID(name), texture, mipLevel); } public void SetTexture(int kernelIndex, int nameID, RenderTexture texture, int mipLevel, RenderTextureSubElement element) { SetRenderTexture(kernelIndex, nameID, texture, mipLevel, element); } public void SetTexture(int kernelIndex, string name, RenderTexture texture, int mipLevel, RenderTextureSubElement element) { SetRenderTexture(kernelIndex, Shader.PropertyToID(name), texture, mipLevel, element); } public void SetTextureFromGlobal(int kernelIndex, string name, string globalTextureName) { SetTextureFromGlobal(kernelIndex, Shader.PropertyToID(name), Shader.PropertyToID(globalTextureName)); } public void SetBuffer(int kernelIndex, string name, ComputeBuffer buffer) { SetBuffer(kernelIndex, Shader.PropertyToID(name), buffer); } public void SetBuffer(int kernelIndex, string name, GraphicsBuffer buffer) { SetBuffer(kernelIndex, Shader.PropertyToID(name), buffer); } public void SetConstantBuffer(int nameID, ComputeBuffer buffer, int offset, int size) { SetConstantComputeBuffer(nameID, buffer, offset, size); } public void SetConstantBuffer(string name, ComputeBuffer buffer, int offset, int size) { SetConstantBuffer(Shader.PropertyToID(name), buffer, offset, size); } public void SetConstantBuffer(int nameID, GraphicsBuffer buffer, int offset, int size) { SetConstantGraphicsBuffer(nameID, buffer, offset, size); } public void SetConstantBuffer(string name, GraphicsBuffer buffer, int offset, int size) { SetConstantBuffer(Shader.PropertyToID(name), buffer, offset, size); } public void DispatchIndirect(int kernelIndex, ComputeBuffer argsBuffer, [UnityEngine.Internal.DefaultValue("0")] uint argsOffset) { if (argsBuffer == null) { throw new ArgumentNullException("argsBuffer"); } if (argsBuffer.m_Ptr == IntPtr.Zero) { throw new ObjectDisposedException("argsBuffer"); } Internal_DispatchIndirect(kernelIndex, argsBuffer, argsOffset); } [ExcludeFromDocs] public void DispatchIndirect(int kernelIndex, ComputeBuffer argsBuffer) { DispatchIndirect(kernelIndex, argsBuffer, 0u); } public void DispatchIndirect(int kernelIndex, GraphicsBuffer argsBuffer, [UnityEngine.Internal.DefaultValue("0")] uint argsOffset) { if (argsBuffer == null) { throw new ArgumentNullException("argsBuffer"); } if (argsBuffer.m_Ptr == IntPtr.Zero) { throw new ObjectDisposedException("argsBuffer"); } Internal_DispatchIndirectGraphicsBuffer(kernelIndex, argsBuffer, argsOffset); } [ExcludeFromDocs] public void DispatchIndirect(int kernelIndex, GraphicsBuffer argsBuffer) { DispatchIndirect(kernelIndex, argsBuffer, 0u); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetVector_Injected(int nameID, ref Vector4 val); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetMatrix_Injected(int nameID, ref Matrix4x4 val); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_keywordSpace_Injected(out LocalKeywordSpace ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void EnableLocalKeyword_Injected(ref LocalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private extern void DisableLocalKeyword_Injected(ref LocalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetLocalKeyword_Injected(ref LocalKeyword keyword, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private extern bool IsLocalKeywordEnabled_Injected(ref LocalKeyword keyword); } internal enum DisableBatchingType { False, True, WhenLODFading } public sealed class ShaderVariantCollection : Object { public struct ShaderVariant { public Shader shader; public PassType passType; public string[] keywords; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] [NativeConditional("UNITY_EDITOR")] private static extern string CheckShaderVariant(Shader shader, PassType passType, string[] keywords); public ShaderVariant(Shader shader, PassType passType, params string[] keywords) { this.shader = shader; this.passType = passType; this.keywords = keywords; } } public extern int shaderCount { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern int variantCount { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern bool isWarmedUp { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("IsWarmedUp")] get; } [MethodImpl(MethodImplOptions.InternalCall)] private extern bool AddVariant(Shader shader, PassType passType, [Unmarshalled] string[] keywords); [MethodImpl(MethodImplOptions.InternalCall)] private extern bool RemoveVariant(Shader shader, PassType passType, [Unmarshalled] string[] keywords); [MethodImpl(MethodImplOptions.InternalCall)] private extern bool ContainsVariant(Shader shader, PassType passType, [Unmarshalled] string[] keywords); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("ClearVariants")] public extern void Clear(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("WarmupShaders")] public extern void WarmUp(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("CreateFromScript")] private static extern void Internal_Create([Writable] ShaderVariantCollection svc); public ShaderVariantCollection() { Internal_Create(this); } public bool Add(ShaderVariant variant) { return AddVariant(variant.shader, variant.passType, variant.keywords); } public bool Remove(ShaderVariant variant) { return RemoveVariant(variant.shader, variant.passType, variant.keywords); } public bool Contains(ShaderVariant variant) { return ContainsVariant(variant.shader, variant.passType, variant.keywords); } } [Flags] public enum SnapAxis : byte { None = 0, X = 1, Y = 2, Z = 4, All = 7 } internal struct SnapAxisFilter : IEquatable { private const SnapAxis X = SnapAxis.X; private const SnapAxis Y = SnapAxis.Y; private const SnapAxis Z = SnapAxis.Z; public static readonly SnapAxisFilter all = new SnapAxisFilter(SnapAxis.All); private SnapAxis m_Mask; public float x => ((m_Mask & SnapAxis.X) == SnapAxis.X) ? 1f : 0f; public float y => ((m_Mask & SnapAxis.Y) == SnapAxis.Y) ? 1f : 0f; public float z => ((m_Mask & SnapAxis.Z) == SnapAxis.Z) ? 1f : 0f; public int active { get { int num = 0; if ((int)(m_Mask & SnapAxis.X) > 0) { num++; } if ((int)(m_Mask & SnapAxis.Y) > 0) { num++; } if ((int)(m_Mask & SnapAxis.Z) > 0) { num++; } return num; } } public float this[int i] { get { if (i < 0 || i > 2) { throw new IndexOutOfRangeException(); } return (float)(1 & ((int)m_Mask >> i)) * 1f; } set { if (i < 0 || i > 2) { throw new IndexOutOfRangeException(); } m_Mask &= (SnapAxis)(byte)(~(1 << i)); m_Mask |= (SnapAxis)(byte)(((value > 0f) ? 1u : 0u) << i); } } public SnapAxisFilter(Vector3 v) { m_Mask = SnapAxis.None; float num = 1E-06f; if (Mathf.Abs(v.x) > num) { m_Mask |= SnapAxis.X; } if (Mathf.Abs(v.y) > num) { m_Mask |= SnapAxis.Y; } if (Mathf.Abs(v.z) > num) { m_Mask |= SnapAxis.Z; } } public SnapAxisFilter(SnapAxis axis) { m_Mask = SnapAxis.None; if ((axis & SnapAxis.X) == SnapAxis.X) { m_Mask |= SnapAxis.X; } if ((axis & SnapAxis.Y) == SnapAxis.Y) { m_Mask |= SnapAxis.Y; } if ((axis & SnapAxis.Z) == SnapAxis.Z) { m_Mask |= SnapAxis.Z; } } public override string ToString() { return $"{{{x}, {y}, {z}}}"; } public static implicit operator Vector3(SnapAxisFilter mask) { return new Vector3(mask.x, mask.y, mask.z); } public static explicit operator SnapAxisFilter(Vector3 v) { return new SnapAxisFilter(v); } public static explicit operator SnapAxis(SnapAxisFilter mask) { return mask.m_Mask; } public static SnapAxisFilter operator |(SnapAxisFilter left, SnapAxisFilter right) { return new SnapAxisFilter(left.m_Mask | right.m_Mask); } public static SnapAxisFilter operator &(SnapAxisFilter left, SnapAxisFilter right) { return new SnapAxisFilter(left.m_Mask & right.m_Mask); } public static SnapAxisFilter operator ^(SnapAxisFilter left, SnapAxisFilter right) { return new SnapAxisFilter(left.m_Mask ^ right.m_Mask); } public static SnapAxisFilter operator ~(SnapAxisFilter left) { return new SnapAxisFilter((SnapAxis)(~(uint)left.m_Mask)); } public static Vector3 operator *(SnapAxisFilter mask, float value) { return new Vector3(mask.x * value, mask.y * value, mask.z * value); } public static Vector3 operator *(SnapAxisFilter mask, Vector3 right) { return new Vector3(mask.x * right.x, mask.y * right.y, mask.z * right.z); } public static Vector3 operator *(Quaternion rotation, SnapAxisFilter mask) { int num = mask.active; if (num > 2) { return mask; } Vector3 vector = rotation * (Vector3)mask; vector = new Vector3(Mathf.Abs(vector.x), Mathf.Abs(vector.y), Mathf.Abs(vector.z)); if (num > 1) { return new Vector3((vector.x > vector.y || vector.x > vector.z) ? 1 : 0, (vector.y > vector.x || vector.y > vector.z) ? 1 : 0, (vector.z > vector.x || vector.z > vector.y) ? 1 : 0); } return new Vector3((vector.x > vector.y && vector.x > vector.z) ? 1 : 0, (vector.y > vector.z && vector.y > vector.x) ? 1 : 0, (vector.z > vector.x && vector.z > vector.y) ? 1 : 0); } public static bool operator ==(SnapAxisFilter left, SnapAxisFilter right) { return left.m_Mask == right.m_Mask; } public static bool operator !=(SnapAxisFilter left, SnapAxisFilter right) { return !(left == right); } public bool Equals(SnapAxisFilter other) { return m_Mask == other.m_Mask; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is SnapAxisFilter && Equals((SnapAxisFilter)obj); } public override int GetHashCode() { return m_Mask.GetHashCode(); } } public static class Snapping { internal static bool IsCardinalDirection(Vector3 direction) { return (Mathf.Abs(direction.x) > 0f && Mathf.Approximately(direction.y, 0f) && Mathf.Approximately(direction.z, 0f)) || (Mathf.Abs(direction.y) > 0f && Mathf.Approximately(direction.x, 0f) && Mathf.Approximately(direction.z, 0f)) || (Mathf.Abs(direction.z) > 0f && Mathf.Approximately(direction.x, 0f) && Mathf.Approximately(direction.y, 0f)); } public static float Snap(float val, float snap) { if (snap == 0f) { return val; } return snap * Mathf.Round(val / snap); } public static Vector2 Snap(Vector2 val, Vector2 snap) { return new Vector3((Mathf.Abs(snap.x) < Mathf.Epsilon) ? val.x : (snap.x * Mathf.Round(val.x / snap.x)), (Mathf.Abs(snap.y) < Mathf.Epsilon) ? val.y : (snap.y * Mathf.Round(val.y / snap.y))); } public static Vector3 Snap(Vector3 val, Vector3 snap, SnapAxis axis = SnapAxis.All) { return new Vector3(((axis & SnapAxis.X) == SnapAxis.X) ? Snap(val.x, snap.x) : val.x, ((axis & SnapAxis.Y) == SnapAxis.Y) ? Snap(val.y, snap.y) : val.y, ((axis & SnapAxis.Z) == SnapAxis.Z) ? Snap(val.z, snap.z) : val.z); } } public sealed class StaticBatchingUtility { internal static ProfilerMarker s_CombineMarker = new ProfilerMarker("StaticBatching.Combine"); internal static ProfilerMarker s_SortMarker = new ProfilerMarker("StaticBatching.SortObjects"); internal static ProfilerMarker s_MakeBatchMarker = new ProfilerMarker("StaticBatching.MakeBatch"); public static void Combine(GameObject staticBatchRoot) { using (s_CombineMarker.Auto()) { InternalStaticBatchingUtility.CombineRoot(staticBatchRoot, null); } } public static void Combine(GameObject[] gos, GameObject staticBatchRoot) { using (s_CombineMarker.Auto()) { InternalStaticBatchingUtility.CombineGameObjects(gos, staticBatchRoot, isEditorPostprocessScene: false, null); } } } internal class InternalStaticBatchingUtility { public class StaticBatcherGOSorter { public virtual long GetMaterialId(Renderer renderer) { if (renderer == null || renderer.sharedMaterial == null) { return 0L; } return renderer.sharedMaterial.GetInstanceID(); } public int GetLightmapIndex(Renderer renderer) { if (renderer == null) { return -1; } return renderer.lightmapIndex; } public static Renderer GetRenderer(GameObject go) { if (go == null) { return null; } MeshFilter meshFilter = go.GetComponent(typeof(MeshFilter)) as MeshFilter; if (meshFilter == null) { return null; } return meshFilter.GetComponent(); } public static Mesh GetMesh(GameObject go) { if (go == null) { return null; } MeshFilter component = go.GetComponent(); if (component == null) { return null; } return component.sharedMesh; } public virtual long GetRendererId(Renderer renderer) { if (renderer == null) { return -1L; } return renderer.GetInstanceID(); } public static bool GetScaleFlip(GameObject go) { Transform transform = go.transform; float determinant = transform.localToWorldMatrix.determinant; return determinant < 0f; } } private const int MaxVerticesInBatch = 64000; private const string CombinedMeshPrefix = "Combined Mesh"; public static void CombineRoot(GameObject staticBatchRoot, StaticBatcherGOSorter sorter) { Combine(staticBatchRoot, combineOnlyStatic: false, isEditorPostprocessScene: false, sorter); } public static void Combine(GameObject staticBatchRoot, bool combineOnlyStatic, bool isEditorPostprocessScene, StaticBatcherGOSorter sorter) { GameObject[] array = (GameObject[])Object.FindObjectsOfType(typeof(GameObject)); List list = new List(); GameObject[] array2 = array; foreach (GameObject gameObject in array2) { if ((!(staticBatchRoot != null) || gameObject.transform.IsChildOf(staticBatchRoot.transform)) && (!combineOnlyStatic || gameObject.isStaticBatchable)) { list.Add(gameObject); } } array = list.ToArray(); CombineGameObjects(array, staticBatchRoot, isEditorPostprocessScene, sorter); } private static uint GetMeshFormatHash(Mesh mesh) { if (mesh == null) { return 0u; } uint num = 1u; int vertexAttributeCount = mesh.vertexAttributeCount; for (int i = 0; i < vertexAttributeCount; i++) { VertexAttributeDescriptor vertexAttribute = mesh.GetVertexAttribute(i); uint num2 = (uint)vertexAttribute.attribute | (uint)((int)vertexAttribute.format << 4) | (uint)(vertexAttribute.dimension << 8); num = (uint)((int)num * -1640531535) + num2; } return num; } private static GameObject[] SortGameObjectsForStaticBatching(GameObject[] gos, StaticBatcherGOSorter sorter) { gos = gos.OrderBy((GameObject g) => StaticBatcherGOSorter.GetScaleFlip(g)).ThenBy(delegate(GameObject g) { Renderer renderer = StaticBatcherGOSorter.GetRenderer(g); return sorter.GetMaterialId(renderer); }).ThenBy(delegate(GameObject g) { Renderer renderer = StaticBatcherGOSorter.GetRenderer(g); return sorter.GetLightmapIndex(renderer); }) .ThenBy(delegate(GameObject g) { Mesh mesh = StaticBatcherGOSorter.GetMesh(g); return GetMeshFormatHash(mesh); }) .ThenBy(delegate(GameObject g) { Renderer renderer = StaticBatcherGOSorter.GetRenderer(g); return sorter.GetRendererId(renderer); }) .ToArray(); return gos; } public static void CombineGameObjects(GameObject[] gos, GameObject staticBatchRoot, bool isEditorPostprocessScene, StaticBatcherGOSorter sorter) { Matrix4x4 matrix4x = Matrix4x4.identity; Transform staticBatchRootTransform = null; if ((bool)staticBatchRoot) { matrix4x = staticBatchRoot.transform.worldToLocalMatrix; staticBatchRootTransform = staticBatchRoot.transform; } int batchIndex = 0; int num = 0; List list = new List(); using (StaticBatchingUtility.s_SortMarker.Auto()) { gos = SortGameObjectsForStaticBatching(gos, sorter ?? new StaticBatcherGOSorter()); } uint num2 = 0u; bool flag = false; GameObject[] array = gos; foreach (GameObject gameObject in array) { MeshFilter meshFilter = gameObject.GetComponent(typeof(MeshFilter)) as MeshFilter; if (meshFilter == null) { continue; } Mesh sharedMesh = meshFilter.sharedMesh; if (sharedMesh == null || (!isEditorPostprocessScene && !sharedMesh.canAccess) || !StaticBatchingHelper.IsMeshBatchable(sharedMesh)) { continue; } Renderer component = meshFilter.GetComponent(); if (component == null || !component.enabled || component.staticBatchIndex != 0) { continue; } Material[] array2 = component.sharedMaterials; if (array2.Any((Material m) => m != null && m.shader != null && m.shader.disableBatching != DisableBatchingType.False)) { continue; } int vertexCount = sharedMesh.vertexCount; if (vertexCount == 0) { continue; } MeshRenderer meshRenderer = component as MeshRenderer; if (meshRenderer != null && ((meshRenderer.additionalVertexStreams != null && vertexCount != meshRenderer.additionalVertexStreams.vertexCount) || (meshRenderer.enlightenVertexStream != null && vertexCount != meshRenderer.enlightenVertexStream.vertexCount))) { continue; } uint meshFormatHash = GetMeshFormatHash(sharedMesh); bool scaleFlip = StaticBatcherGOSorter.GetScaleFlip(gameObject); if (num + vertexCount > 64000 || meshFormatHash != num2 || scaleFlip != flag) { MakeBatch(list, staticBatchRootTransform, batchIndex++); list.Clear(); num = 0; flag = scaleFlip; } num2 = meshFormatHash; MeshSubsetCombineUtility.MeshInstance instance = new MeshSubsetCombineUtility.MeshInstance { meshInstanceID = sharedMesh.GetInstanceID(), rendererInstanceID = component.GetInstanceID() }; if (meshRenderer != null) { if (meshRenderer.additionalVertexStreams != null) { instance.additionalVertexStreamsMeshInstanceID = meshRenderer.additionalVertexStreams.GetInstanceID(); } if (meshRenderer.enlightenVertexStream != null) { instance.enlightenVertexStreamMeshInstanceID = meshRenderer.enlightenVertexStream.GetInstanceID(); } } instance.transform = matrix4x * meshFilter.transform.localToWorldMatrix; instance.lightmapScaleOffset = component.lightmapScaleOffset; instance.realtimeLightmapScaleOffset = component.realtimeLightmapScaleOffset; MeshSubsetCombineUtility.MeshContainer item = new MeshSubsetCombineUtility.MeshContainer { gameObject = gameObject, instance = instance, subMeshInstances = new List() }; list.Add(item); if (array2.Length > sharedMesh.subMeshCount) { Debug.LogWarning("Mesh '" + sharedMesh.name + "' has more materials (" + array2.Length + ") than subsets (" + sharedMesh.subMeshCount + ")", component); Material[] array3 = new Material[sharedMesh.subMeshCount]; for (int num3 = 0; num3 < sharedMesh.subMeshCount; num3++) { array3[num3] = component.sharedMaterials[num3]; } component.sharedMaterials = array3; array2 = array3; } for (int num4 = 0; num4 < Math.Min(array2.Length, sharedMesh.subMeshCount); num4++) { MeshSubsetCombineUtility.SubMeshInstance item2 = new MeshSubsetCombineUtility.SubMeshInstance { meshInstanceID = meshFilter.sharedMesh.GetInstanceID(), vertexOffset = num, subMeshIndex = num4, gameObjectInstanceID = gameObject.GetInstanceID(), transform = instance.transform }; item.subMeshInstances.Add(item2); } num += sharedMesh.vertexCount; } MakeBatch(list, staticBatchRootTransform, batchIndex); } private static void MakeBatch(List meshes, Transform staticBatchRootTransform, int batchIndex) { if (meshes.Count < 2) { return; } using (StaticBatchingUtility.s_MakeBatchMarker.Auto()) { List list = new List(); List list2 = new List(); foreach (MeshSubsetCombineUtility.MeshContainer mesh2 in meshes) { list.Add(mesh2.instance); list2.AddRange(mesh2.subMeshInstances); } string text = "Combined Mesh"; text = text + " (root: " + ((staticBatchRootTransform != null) ? staticBatchRootTransform.name : "scene") + ")"; if (batchIndex > 0) { text = text + " " + (batchIndex + 1); } Mesh mesh = StaticBatchingHelper.InternalCombineVertices(list.ToArray(), text); StaticBatchingHelper.InternalCombineIndices(list2.ToArray(), mesh); int num = 0; foreach (MeshSubsetCombineUtility.MeshContainer mesh3 in meshes) { MeshFilter meshFilter = (MeshFilter)mesh3.gameObject.GetComponent(typeof(MeshFilter)); meshFilter.sharedMesh = mesh; int count = mesh3.subMeshInstances.Count; Renderer component = mesh3.gameObject.GetComponent(); component.SetStaticBatchInfo(num, count); component.staticBatchRootTransform = staticBatchRootTransform; component.enabled = false; component.enabled = true; MeshRenderer meshRenderer = component as MeshRenderer; if (meshRenderer != null) { meshRenderer.additionalVertexStreams = null; meshRenderer.enlightenVertexStream = null; } num += count; } } } } internal class MeshSubsetCombineUtility { public struct MeshInstance { public int meshInstanceID; public int rendererInstanceID; public int additionalVertexStreamsMeshInstanceID; public int enlightenVertexStreamMeshInstanceID; public Matrix4x4 transform; public Vector4 lightmapScaleOffset; public Vector4 realtimeLightmapScaleOffset; } public struct SubMeshInstance { public int meshInstanceID; public int vertexOffset; public int gameObjectInstanceID; public int subMeshIndex; public Matrix4x4 transform; } public struct MeshContainer { public GameObject gameObject; public MeshInstance instance; public List subMeshInstances; } } internal class LowerResBlitTexture : Object { [RequiredByNativeCode] internal void LowerResBlitTextureDontStripMe() { } } internal class PreloadData : Object { [RequiredByNativeCode] internal void PreloadDataDontStripMe() { } } public enum BatteryStatus { Unknown, Charging, Discharging, NotCharging, Full } public enum OperatingSystemFamily { Other, MacOSX, Windows, Linux } public enum DeviceType { Unknown, Handheld, Console, Desktop } [NativeHeader("Runtime/Misc/SystemInfo.h")] [NativeHeader("Runtime/Graphics/GraphicsFormatUtility.bindings.h")] [NativeHeader("Runtime/Camera/RenderLoops/MotionVectorRenderLoop.h")] [NativeHeader("Runtime/Input/GetInput.h")] [NativeHeader("Runtime/Shaders/GraphicsCapsScriptBindings.h")] [NativeHeader("Runtime/Graphics/Mesh/MeshScriptBindings.h")] public sealed class SystemInfo { public const string unsupportedIdentifier = "n/a"; [NativeProperty] public static float batteryLevel => GetBatteryLevel(); public static BatteryStatus batteryStatus => GetBatteryStatus(); public static string operatingSystem => GetOperatingSystem(); public static OperatingSystemFamily operatingSystemFamily => GetOperatingSystemFamily(); public static string processorType => GetProcessorType(); public static int processorFrequency => GetProcessorFrequencyMHz(); public static int processorCount => GetProcessorCount(); public static int systemMemorySize => GetPhysicalMemoryMB(); public static string deviceUniqueIdentifier => GetDeviceUniqueIdentifier(); public static string deviceName => GetDeviceName(); public static string deviceModel => GetDeviceModel(); public static bool supportsAccelerometer => SupportsAccelerometer(); public static bool supportsGyroscope => IsGyroAvailable(); public static bool supportsLocationService => SupportsLocationService(); public static bool supportsVibration => SupportsVibration(); public static bool supportsAudio => SupportsAudio(); public static DeviceType deviceType => GetDeviceType(); public static int graphicsMemorySize => GetGraphicsMemorySize(); public static string graphicsDeviceName => GetGraphicsDeviceName(); public static string graphicsDeviceVendor => GetGraphicsDeviceVendor(); public static int graphicsDeviceID => GetGraphicsDeviceID(); public static int graphicsDeviceVendorID => GetGraphicsDeviceVendorID(); public static GraphicsDeviceType graphicsDeviceType => GetGraphicsDeviceType(); public static bool graphicsUVStartsAtTop => GetGraphicsUVStartsAtTop(); public static string graphicsDeviceVersion => GetGraphicsDeviceVersion(); public static int graphicsShaderLevel => GetGraphicsShaderLevel(); public static bool graphicsMultiThreaded => GetGraphicsMultiThreaded(); public static RenderingThreadingMode renderingThreadingMode => GetRenderingThreadingMode(); public static bool hasHiddenSurfaceRemovalOnGPU => HasHiddenSurfaceRemovalOnGPU(); public static bool hasDynamicUniformArrayIndexingInFragmentShaders => HasDynamicUniformArrayIndexingInFragmentShaders(); public static bool supportsShadows => SupportsShadows(); public static bool supportsRawShadowDepthSampling => SupportsRawShadowDepthSampling(); [Obsolete("supportsRenderTextures always returns true, no need to call it")] public static bool supportsRenderTextures => true; public static bool supportsMotionVectors => SupportsMotionVectors(); [Obsolete("supportsRenderToCubemap always returns true, no need to call it")] public static bool supportsRenderToCubemap => true; [Obsolete("supportsImageEffects always returns true, no need to call it")] public static bool supportsImageEffects => true; public static bool supports3DTextures => Supports3DTextures(); public static bool supportsCompressed3DTextures => SupportsCompressed3DTextures(); public static bool supports2DArrayTextures => Supports2DArrayTextures(); public static bool supports3DRenderTextures => Supports3DRenderTextures(); public static bool supportsCubemapArrayTextures => SupportsCubemapArrayTextures(); public static bool supportsAnisotropicFilter => SupportsAnisotropicFilter(); public static CopyTextureSupport copyTextureSupport => GetCopyTextureSupport(); public static bool supportsComputeShaders => SupportsComputeShaders(); public static bool supportsGeometryShaders => SupportsGeometryShaders(); public static bool supportsTessellationShaders => SupportsTessellationShaders(); public static bool supportsRenderTargetArrayIndexFromVertexShader => SupportsRenderTargetArrayIndexFromVertexShader(); public static bool supportsInstancing => SupportsInstancing(); public static bool supportsHardwareQuadTopology => SupportsHardwareQuadTopology(); public static bool supports32bitsIndexBuffer => Supports32bitsIndexBuffer(); public static bool supportsSparseTextures => SupportsSparseTextures(); public static int supportedRenderTargetCount => SupportedRenderTargetCount(); public static bool supportsSeparatedRenderTargetsBlend => SupportsSeparatedRenderTargetsBlend(); public static int supportedRandomWriteTargetCount => SupportedRandomWriteTargetCount(); public static int supportsMultisampledTextures => SupportsMultisampledTextures(); public static bool supportsMultisampled2DArrayTextures => SupportsMultisampled2DArrayTextures(); public static bool supportsMultisampleAutoResolve => SupportsMultisampleAutoResolve(); public static int supportsTextureWrapMirrorOnce => SupportsTextureWrapMirrorOnce(); public static bool usesReversedZBuffer => UsesReversedZBuffer(); [Obsolete("supportsStencil always returns true, no need to call it")] public static int supportsStencil => 1; public static NPOTSupport npotSupport => GetNPOTSupport(); public static int maxTextureSize => GetMaxTextureSize(); public static int maxTexture3DSize => GetMaxTexture3DSize(); public static int maxTextureArraySlices => GetMaxTextureArraySlices(); public static int maxCubemapSize => GetMaxCubemapSize(); public static int maxAnisotropyLevel => GetMaxAnisotropyLevel(); internal static int maxRenderTextureSize => GetMaxRenderTextureSize(); public static int maxComputeBufferInputsVertex => MaxComputeBufferInputsVertex(); public static int maxComputeBufferInputsFragment => MaxComputeBufferInputsFragment(); public static int maxComputeBufferInputsGeometry => MaxComputeBufferInputsGeometry(); public static int maxComputeBufferInputsDomain => MaxComputeBufferInputsDomain(); public static int maxComputeBufferInputsHull => MaxComputeBufferInputsHull(); public static int maxComputeBufferInputsCompute => MaxComputeBufferInputsCompute(); public static int maxComputeWorkGroupSize => GetMaxComputeWorkGroupSize(); public static int maxComputeWorkGroupSizeX => GetMaxComputeWorkGroupSizeX(); public static int maxComputeWorkGroupSizeY => GetMaxComputeWorkGroupSizeY(); public static int maxComputeWorkGroupSizeZ => GetMaxComputeWorkGroupSizeZ(); public static int computeSubGroupSize => GetComputeSubGroupSize(); public static bool supportsAsyncCompute => SupportsAsyncCompute(); public static bool supportsGpuRecorder => SupportsGpuRecorder(); public static bool supportsGraphicsFence => SupportsGPUFence(); public static bool supportsAsyncGPUReadback => SupportsAsyncGPUReadback(); public static bool supportsRayTracing => SupportsRayTracing(); public static bool supportsSetConstantBuffer => SupportsSetConstantBuffer(); public static int constantBufferOffsetAlignment => MinConstantBufferOffsetAlignment(); public static long maxGraphicsBufferSize => MaxGraphicsBufferSize(); [Obsolete("Use SystemInfo.constantBufferOffsetAlignment instead.")] public static bool minConstantBufferOffsetAlignment => false; public static bool hasMipMaxLevel => HasMipMaxLevel(); public static bool supportsMipStreaming => SupportsMipStreaming(); [Obsolete("graphicsPixelFillrate is no longer supported in Unity 5.0+.")] public static int graphicsPixelFillrate => -1; public static bool usesLoadStoreActions => UsesLoadStoreActions(); public static HDRDisplaySupportFlags hdrDisplaySupportFlags => GetHDRDisplaySupportFlags(); public static bool supportsConservativeRaster => SupportsConservativeRaster(); public static bool supportsMultiview => SupportsMultiview(); public static bool supportsStoreAndResolveAction => SupportsStoreAndResolveAction(); public static bool supportsMultisampleResolveDepth => SupportsMultisampleResolveDepth(); [Obsolete("Vertex program support is required in Unity 5.0+")] public static bool supportsVertexPrograms => true; [Obsolete("SystemInfo.supportsGPUFence has been deprecated, use SystemInfo.supportsGraphicsFence instead (UnityUpgradable) -> supportsGraphicsFence", true)] public static bool supportsGPUFence => false; private static bool IsValidEnumValue(Enum value) { if (!Enum.IsDefined(value.GetType(), value)) { return false; } return true; } public static bool SupportsRenderTextureFormat(RenderTextureFormat format) { if (!IsValidEnumValue(format)) { throw new ArgumentException("Failed SupportsRenderTextureFormat; format is not a valid RenderTextureFormat"); } return HasRenderTextureNative(format); } public static bool SupportsBlendingOnRenderTextureFormat(RenderTextureFormat format) { if (!IsValidEnumValue(format)) { throw new ArgumentException("Failed SupportsBlendingOnRenderTextureFormat; format is not a valid RenderTextureFormat"); } return SupportsBlendingOnRenderTextureFormatNative(format); } public static bool SupportsRandomWriteOnRenderTextureFormat(RenderTextureFormat format) { if (!IsValidEnumValue(format)) { throw new ArgumentException("Failed SupportsRandomWriteOnRenderTextureFormat; format is not a valid RenderTextureFormat"); } return SupportsRandomWriteOnRenderTextureFormatNative(format); } public static bool SupportsTextureFormat(TextureFormat format) { if (!IsValidEnumValue(format)) { throw new ArgumentException("Failed SupportsTextureFormat; format is not a valid TextureFormat"); } return SupportsTextureFormatNative(format); } public static bool SupportsVertexAttributeFormat(VertexAttributeFormat format, int dimension) { if (!IsValidEnumValue(format)) { throw new ArgumentException("Failed SupportsVertexAttributeFormat; format is not a valid VertexAttributeFormat"); } if (dimension < 1 || dimension > 4) { throw new ArgumentException("Failed SupportsVertexAttributeFormat; dimension must be in 1..4 range"); } return SupportsVertexAttributeFormatNative(format, dimension); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::GetBatteryLevel")] private static extern float GetBatteryLevel(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::GetBatteryStatus")] private static extern BatteryStatus GetBatteryStatus(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::GetOperatingSystem")] private static extern string GetOperatingSystem(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::GetOperatingSystemFamily")] private static extern OperatingSystemFamily GetOperatingSystemFamily(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::GetProcessorType")] private static extern string GetProcessorType(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::GetProcessorFrequencyMHz")] private static extern int GetProcessorFrequencyMHz(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::GetProcessorCount")] private static extern int GetProcessorCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::GetPhysicalMemoryMB")] private static extern int GetPhysicalMemoryMB(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::GetDeviceUniqueIdentifier")] private static extern string GetDeviceUniqueIdentifier(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::GetDeviceName")] private static extern string GetDeviceName(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::GetDeviceModel")] private static extern string GetDeviceModel(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::SupportsAccelerometer")] private static extern bool SupportsAccelerometer(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern bool IsGyroAvailable(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::SupportsLocationService")] private static extern bool SupportsLocationService(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::SupportsVibration")] private static extern bool SupportsVibration(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::SupportsAudio")] private static extern bool SupportsAudio(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("systeminfo::GetDeviceType")] private static extern DeviceType GetDeviceType(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetGraphicsMemorySize")] private static extern int GetGraphicsMemorySize(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetGraphicsDeviceName")] private static extern string GetGraphicsDeviceName(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetGraphicsDeviceVendor")] private static extern string GetGraphicsDeviceVendor(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetGraphicsDeviceID")] private static extern int GetGraphicsDeviceID(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetGraphicsDeviceVendorID")] private static extern int GetGraphicsDeviceVendorID(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetGraphicsDeviceType")] private static extern GraphicsDeviceType GetGraphicsDeviceType(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetGraphicsUVStartsAtTop")] private static extern bool GetGraphicsUVStartsAtTop(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetGraphicsDeviceVersion")] private static extern string GetGraphicsDeviceVersion(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetGraphicsShaderLevel")] private static extern int GetGraphicsShaderLevel(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetGraphicsMultiThreaded")] private static extern bool GetGraphicsMultiThreaded(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetRenderingThreadingMode")] private static extern RenderingThreadingMode GetRenderingThreadingMode(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::HasHiddenSurfaceRemovalOnGPU")] private static extern bool HasHiddenSurfaceRemovalOnGPU(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::HasDynamicUniformArrayIndexingInFragmentShaders")] private static extern bool HasDynamicUniformArrayIndexingInFragmentShaders(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsShadows")] private static extern bool SupportsShadows(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsRawShadowDepthSampling")] private static extern bool SupportsRawShadowDepthSampling(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SupportsMotionVectors")] private static extern bool SupportsMotionVectors(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::Supports3DTextures")] private static extern bool Supports3DTextures(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsCompressed3DTextures")] private static extern bool SupportsCompressed3DTextures(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::Supports2DArrayTextures")] private static extern bool Supports2DArrayTextures(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::Supports3DRenderTextures")] private static extern bool Supports3DRenderTextures(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsCubemapArrayTextures")] private static extern bool SupportsCubemapArrayTextures(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsAnisotropicFilter")] private static extern bool SupportsAnisotropicFilter(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetCopyTextureSupport")] private static extern CopyTextureSupport GetCopyTextureSupport(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsComputeShaders")] private static extern bool SupportsComputeShaders(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsGeometryShaders")] private static extern bool SupportsGeometryShaders(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsTessellationShaders")] private static extern bool SupportsTessellationShaders(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsRenderTargetArrayIndexFromVertexShader")] private static extern bool SupportsRenderTargetArrayIndexFromVertexShader(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsInstancing")] private static extern bool SupportsInstancing(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsHardwareQuadTopology")] private static extern bool SupportsHardwareQuadTopology(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::Supports32bitsIndexBuffer")] private static extern bool Supports32bitsIndexBuffer(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsSparseTextures")] private static extern bool SupportsSparseTextures(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportedRenderTargetCount")] private static extern int SupportedRenderTargetCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsSeparatedRenderTargetsBlend")] private static extern bool SupportsSeparatedRenderTargetsBlend(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportedRandomWriteTargetCount")] private static extern int SupportedRandomWriteTargetCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::MaxComputeBufferInputsVertex")] private static extern int MaxComputeBufferInputsVertex(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::MaxComputeBufferInputsFragment")] private static extern int MaxComputeBufferInputsFragment(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::MaxComputeBufferInputsGeometry")] private static extern int MaxComputeBufferInputsGeometry(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::MaxComputeBufferInputsDomain")] private static extern int MaxComputeBufferInputsDomain(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::MaxComputeBufferInputsHull")] private static extern int MaxComputeBufferInputsHull(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::MaxComputeBufferInputsCompute")] private static extern int MaxComputeBufferInputsCompute(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsMultisampledTextures")] private static extern int SupportsMultisampledTextures(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsMultisampled2DArrayTextures")] private static extern bool SupportsMultisampled2DArrayTextures(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsMultisampleAutoResolve")] private static extern bool SupportsMultisampleAutoResolve(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsTextureWrapMirrorOnce")] private static extern int SupportsTextureWrapMirrorOnce(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::UsesReversedZBuffer")] private static extern bool UsesReversedZBuffer(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::HasRenderTexture")] private static extern bool HasRenderTextureNative(RenderTextureFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsBlendingOnRenderTextureFormat")] private static extern bool SupportsBlendingOnRenderTextureFormatNative(RenderTextureFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsRandomWriteOnRenderTextureFormat")] private static extern bool SupportsRandomWriteOnRenderTextureFormatNative(RenderTextureFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsTextureFormat")] private static extern bool SupportsTextureFormatNative(TextureFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsVertexAttributeFormat")] private static extern bool SupportsVertexAttributeFormatNative(VertexAttributeFormat format, int dimension); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetNPOTSupport")] private static extern NPOTSupport GetNPOTSupport(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetMaxTextureSize")] private static extern int GetMaxTextureSize(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetMaxTexture3DSize")] private static extern int GetMaxTexture3DSize(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetMaxTextureArraySlices")] private static extern int GetMaxTextureArraySlices(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetMaxCubemapSize")] private static extern int GetMaxCubemapSize(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetMaxAnisotropyLevel")] private static extern int GetMaxAnisotropyLevel(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetMaxRenderTextureSize")] private static extern int GetMaxRenderTextureSize(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetMaxComputeWorkGroupSize")] private static extern int GetMaxComputeWorkGroupSize(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetMaxComputeWorkGroupSizeX")] private static extern int GetMaxComputeWorkGroupSizeX(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetMaxComputeWorkGroupSizeY")] private static extern int GetMaxComputeWorkGroupSizeY(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetMaxComputeWorkGroupSizeZ")] private static extern int GetMaxComputeWorkGroupSizeZ(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetComputeSubGroupSize")] private static extern int GetComputeSubGroupSize(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsAsyncCompute")] private static extern bool SupportsAsyncCompute(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsGpuRecorder")] private static extern bool SupportsGpuRecorder(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsGPUFence")] private static extern bool SupportsGPUFence(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsAsyncGPUReadback")] private static extern bool SupportsAsyncGPUReadback(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsRayTracing")] private static extern bool SupportsRayTracing(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsSetConstantBuffer")] private static extern bool SupportsSetConstantBuffer(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::MinConstantBufferOffsetAlignment")] private static extern int MinConstantBufferOffsetAlignment(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::MaxGraphicsBufferSize")] private static extern long MaxGraphicsBufferSize(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::HasMipMaxLevel")] private static extern bool HasMipMaxLevel(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsMipStreaming")] private static extern bool SupportsMipStreaming(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::IsFormatSupported")] public static extern bool IsFormatSupported(GraphicsFormat format, FormatUsage usage); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetCompatibleFormat")] public static extern GraphicsFormat GetCompatibleFormat(GraphicsFormat format, FormatUsage usage); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetGraphicsFormat")] public static extern GraphicsFormat GetGraphicsFormat(DefaultFormat format); [FreeFunction("ScriptingGraphicsCaps::GetRenderTextureSupportedMSAASampleCount")] public static int GetRenderTextureSupportedMSAASampleCount(RenderTextureDescriptor desc) { return GetRenderTextureSupportedMSAASampleCount_Injected(ref desc); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::UsesLoadStoreActions")] private static extern bool UsesLoadStoreActions(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::GetHDRDisplaySupportFlags")] private static extern HDRDisplaySupportFlags GetHDRDisplaySupportFlags(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsConservativeRaster")] private static extern bool SupportsConservativeRaster(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsMultiview")] private static extern bool SupportsMultiview(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsStoreAndResolveAction")] private static extern bool SupportsStoreAndResolveAction(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingGraphicsCaps::SupportsMultisampleResolveDepth")] private static extern bool SupportsMultisampleResolveDepth(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetRenderTextureSupportedMSAASampleCount_Injected(ref RenderTextureDescriptor desc); } [VisibleToOtherModules] internal class SystemClock { private static readonly DateTime s_Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static DateTime now => DateTime.Now; public static long ToUnixTimeMilliseconds(DateTime date) { return Convert.ToInt64((date.ToUniversalTime() - s_Epoch).TotalMilliseconds); } public static long ToUnixTimeSeconds(DateTime date) { return Convert.ToInt64((date.ToUniversalTime() - s_Epoch).TotalSeconds); } } [NativeHeader("Runtime/Input/TimeManager.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public class Time { [NativeProperty("CurTime")] public static extern float time { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeProperty("CurTime")] public static extern double timeAsDouble { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeProperty("TimeSinceSceneLoad")] public static extern float timeSinceLevelLoad { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeProperty("TimeSinceSceneLoad")] public static extern double timeSinceLevelLoadAsDouble { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern float deltaTime { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern float fixedTime { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeProperty("FixedTime")] public static extern double fixedTimeAsDouble { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern float unscaledTime { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeProperty("UnscaledTime")] public static extern double unscaledTimeAsDouble { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern float fixedUnscaledTime { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeProperty("FixedUnscaledTime")] public static extern double fixedUnscaledTimeAsDouble { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern float unscaledDeltaTime { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern float fixedUnscaledDeltaTime { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern float fixedDeltaTime { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern float maximumDeltaTime { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern float smoothDeltaTime { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern float maximumParticleDeltaTime { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern float timeScale { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int frameCount { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeProperty("RenderFrameCount")] public static extern int renderedFrameCount { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeProperty("Realtime")] public static extern float realtimeSinceStartup { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeProperty("Realtime")] public static extern double realtimeSinceStartupAsDouble { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern float captureDeltaTime { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static int captureFramerate { get { return (captureDeltaTime != 0f) ? ((int)Mathf.Round(1f / captureDeltaTime)) : 0; } set { captureDeltaTime = ((value == 0) ? 0f : (1f / (float)value)); } } public static extern bool inFixedTimeStep { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("IsUsingFixedTimeStep")] get; } } internal struct TouchScreenKeyboard_InternalConstructorHelperArguments { public uint keyboardType; public uint autocorrection; public uint multiline; public uint secure; public uint alert; public int characterLimit; } [NativeHeader("Runtime/Export/TouchScreenKeyboard/TouchScreenKeyboard.bindings.h")] [NativeHeader("Runtime/Input/KeyboardOnScreen.h")] [NativeConditional("ENABLE_ONSCREEN_KEYBOARD")] public class TouchScreenKeyboard { public enum Status { Visible, Done, Canceled, LostFocus } public class Android { [Obsolete("TouchScreenKeyboard.Android.closeKeyboardOnOutsideTap is obsolete. Use TouchScreenKeyboard.Android.consumesOutsideTouches instead (UnityUpgradable) -> UnityEngine.TouchScreenKeyboard/Android.consumesOutsideTouches")] public static bool closeKeyboardOnOutsideTap { get { return consumesOutsideTouches; } set { consumesOutsideTouches = value; } } public static bool consumesOutsideTouches { get { return TouchScreenKeyboard_GetAndroidKeyboardConsumesOutsideTouches(); } set { TouchScreenKeyboard_SetAndroidKeyboardConsumesOutsideTouches(value); } } [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("PLATFORM_ANDROID")] [FreeFunction("TouchScreenKeyboard_SetAndroidKeyboardConsumesOutsideTouches")] private static extern void TouchScreenKeyboard_SetAndroidKeyboardConsumesOutsideTouches(bool enable); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("TouchScreenKeyboard_GetAndroidKeyboardConsumesOutsideTouches")] [NativeConditional("PLATFORM_ANDROID")] private static extern bool TouchScreenKeyboard_GetAndroidKeyboardConsumesOutsideTouches(); } [NonSerialized] internal IntPtr m_Ptr; public static bool isSupported { get { switch (Application.platform) { case RuntimePlatform.IPhonePlayer: case RuntimePlatform.Android: case RuntimePlatform.MetroPlayerX86: case RuntimePlatform.MetroPlayerX64: case RuntimePlatform.MetroPlayerARM: case RuntimePlatform.PS4: case RuntimePlatform.tvOS: case RuntimePlatform.Switch: case RuntimePlatform.Stadia: case RuntimePlatform.GameCoreXboxSeries: case RuntimePlatform.GameCoreXboxOne: case RuntimePlatform.PS5: return true; default: return false; } } } internal static bool disableInPlaceEditing { get; set; } public static bool isInPlaceEditingAllowed { get { if (disableInPlaceEditing) { return false; } return false; } } internal static bool isRequiredToForceOpen => IsRequiredToForceOpen(); public extern string text { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetText")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetText")] set; } public static extern bool hideInput { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("IsInputHidden")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetInputHidden")] set; } public extern bool active { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("IsActive")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetActive")] set; } [Obsolete("Property done is deprecated, use status instead")] public bool done => GetDone(m_Ptr); [Obsolete("Property wasCanceled is deprecated, use status instead.")] public bool wasCanceled => GetWasCanceled(m_Ptr); public extern Status status { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetKeyboardStatus")] get; } public extern int characterLimit { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetCharacterLimit")] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetCharacterLimit")] set; } public extern bool canGetSelection { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("CanGetSelection")] get; } public extern bool canSetSelection { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("CanSetSelection")] get; } public RangeInt selection { get { RangeInt result = default(RangeInt); GetSelection(out result.start, out result.length); return result; } set { if (value.start < 0 || value.length < 0 || value.start + value.length > text.Length) { throw new ArgumentOutOfRangeException("selection", "Selection is out of range."); } SetSelection(value.start, value.length); } } public extern TouchScreenKeyboardType type { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetKeyboardType")] get; } public int targetDisplay { get { return 0; } set { } } [NativeConditional("ENABLE_ONSCREEN_KEYBOARD", "RectT()")] public static Rect area { [NativeName("GetRect")] get { get_area_Injected(out var ret); return ret; } } public static extern bool visible { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("IsVisible")] get; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("TouchScreenKeyboard_Destroy", IsThreadSafe = true)] private static extern void Internal_Destroy(IntPtr ptr); private void Destroy() { if (m_Ptr != IntPtr.Zero) { Internal_Destroy(m_Ptr); m_Ptr = IntPtr.Zero; } GC.SuppressFinalize(this); } ~TouchScreenKeyboard() { Destroy(); } public TouchScreenKeyboard(string text, TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert, string textPlaceholder, int characterLimit) { TouchScreenKeyboard_InternalConstructorHelperArguments arguments = new TouchScreenKeyboard_InternalConstructorHelperArguments { keyboardType = Convert.ToUInt32(keyboardType), autocorrection = Convert.ToUInt32(autocorrection), multiline = Convert.ToUInt32(multiline), secure = Convert.ToUInt32(secure), alert = Convert.ToUInt32(alert), characterLimit = characterLimit }; m_Ptr = TouchScreenKeyboard_InternalConstructorHelper(ref arguments, text, textPlaceholder); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("TouchScreenKeyboard_InternalConstructorHelper")] private static extern IntPtr TouchScreenKeyboard_InternalConstructorHelper(ref TouchScreenKeyboard_InternalConstructorHelperArguments arguments, string text, string textPlaceholder); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("TouchScreenKeyboard_IsRequiredToForceOpen")] private static extern bool IsRequiredToForceOpen(); public static TouchScreenKeyboard Open(string text, [UnityEngine.Internal.DefaultValue("TouchScreenKeyboardType.Default")] TouchScreenKeyboardType keyboardType, [UnityEngine.Internal.DefaultValue("true")] bool autocorrection, [UnityEngine.Internal.DefaultValue("false")] bool multiline, [UnityEngine.Internal.DefaultValue("false")] bool secure, [UnityEngine.Internal.DefaultValue("false")] bool alert, [UnityEngine.Internal.DefaultValue("\"\"")] string textPlaceholder, [UnityEngine.Internal.DefaultValue("0")] int characterLimit) { return new TouchScreenKeyboard(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, characterLimit); } [ExcludeFromDocs] public static TouchScreenKeyboard Open(string text, TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert, string textPlaceholder) { int num = 0; return Open(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, num); } [ExcludeFromDocs] public static TouchScreenKeyboard Open(string text, TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert) { int num = 0; string textPlaceholder = ""; return Open(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, num); } [ExcludeFromDocs] public static TouchScreenKeyboard Open(string text, TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure) { int num = 0; string textPlaceholder = ""; bool alert = false; return Open(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, num); } [ExcludeFromDocs] public static TouchScreenKeyboard Open(string text, TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline) { int num = 0; string textPlaceholder = ""; bool alert = false; bool secure = false; return Open(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, num); } [ExcludeFromDocs] public static TouchScreenKeyboard Open(string text, TouchScreenKeyboardType keyboardType, bool autocorrection) { int num = 0; string textPlaceholder = ""; bool alert = false; bool secure = false; bool multiline = false; return Open(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, num); } [ExcludeFromDocs] public static TouchScreenKeyboard Open(string text, TouchScreenKeyboardType keyboardType) { int num = 0; string textPlaceholder = ""; bool alert = false; bool secure = false; bool multiline = false; bool autocorrection = true; return Open(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, num); } [ExcludeFromDocs] public static TouchScreenKeyboard Open(string text) { int num = 0; string textPlaceholder = ""; bool alert = false; bool secure = false; bool multiline = false; bool autocorrection = true; TouchScreenKeyboardType keyboardType = TouchScreenKeyboardType.Default; return Open(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, num); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("TouchScreenKeyboard_GetDone")] private static extern bool GetDone(IntPtr ptr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("TouchScreenKeyboard_GetWasCanceled")] private static extern bool GetWasCanceled(IntPtr ptr); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetSelection(out int start, out int length); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetSelection(int start, int length); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_area_Injected(out Rect ret); } public enum TouchScreenKeyboardType { Default, ASCIICapable, NumbersAndPunctuation, URL, NumberPad, PhonePad, NamePhonePad, EmailAddress, [Obsolete("Wii U is no longer supported as of Unity 2018.1.")] NintendoNetworkAccount, Social, Search, DecimalPad, OneTimeCode } [NativeHeader("Runtime/Export/UnityEvent/UnityEventQueueSystem.bindings.h")] public class UnityEventQueueSystem { public static string GenerateEventIdForPayload(string eventPayloadName) { byte[] array = Guid.NewGuid().ToByteArray(); return $"REGISTER_EVENT_ID(0x{array[0]:X2}{array[1]:X2}{array[2]:X2}{array[3]:X2}{array[4]:X2}{array[5]:X2}{array[6]:X2}{array[7]:X2}ULL,0x{array[8]:X2}{array[9]:X2}{array[10]:X2}{array[11]:X2}{array[12]:X2}{array[13]:X2}{array[14]:X2}{array[15]:X2}ULL,{eventPayloadName})"; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern IntPtr GetGlobalEventQueue(); } [Serializable] public struct Pose : IEquatable { public Vector3 position; public Quaternion rotation; private static readonly Pose k_Identity = new Pose(Vector3.zero, Quaternion.identity); public Vector3 forward => rotation * Vector3.forward; public Vector3 right => rotation * Vector3.right; public Vector3 up => rotation * Vector3.up; public static Pose identity => k_Identity; public Pose(Vector3 position, Quaternion rotation) { this.position = position; this.rotation = rotation; } public override string ToString() { return UnityString.Format("({0}, {1})", new object[2] { position.ToString(), rotation.ToString() }); } public string ToString(string format) { return UnityString.Format("({0}, {1})", new object[2] { position.ToString(format), rotation.ToString(format) }); } public Pose GetTransformedBy(Pose lhs) { return new Pose { position = lhs.position + lhs.rotation * position, rotation = lhs.rotation * rotation }; } public Pose GetTransformedBy(Transform lhs) { return new Pose { position = lhs.TransformPoint(position), rotation = lhs.rotation * rotation }; } public override bool Equals(object obj) { if (!(obj is Pose)) { return false; } return Equals((Pose)obj); } public bool Equals(Pose other) { return position == other.position && rotation == other.rotation; } public override int GetHashCode() { return position.GetHashCode() ^ (rotation.GetHashCode() << 1); } public static bool operator ==(Pose a, Pose b) { return a.Equals(b); } public static bool operator !=(Pose a, Pose b) { return !(a == b); } } [NativeHeader("Runtime/Profiler/PerformanceTools/FrameDebugger.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static class FrameDebugger { public static bool enabled => IsLocalEnabled() || IsRemoteEnabled(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsLocalEnabled(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsRemoteEnabled(); } [Flags] public enum DrivenTransformProperties { None = 0, All = -1, AnchoredPositionX = 2, AnchoredPositionY = 4, AnchoredPositionZ = 8, Rotation = 0x10, ScaleX = 0x20, ScaleY = 0x40, ScaleZ = 0x80, AnchorMinX = 0x100, AnchorMinY = 0x200, AnchorMaxX = 0x400, AnchorMaxY = 0x800, SizeDeltaX = 0x1000, SizeDeltaY = 0x2000, PivotX = 0x4000, PivotY = 0x8000, AnchoredPosition = 6, AnchoredPosition3D = 0xE, Scale = 0xE0, AnchorMin = 0x300, AnchorMax = 0xC00, Anchors = 0xF00, SizeDelta = 0x3000, Pivot = 0xC000 } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct DrivenRectTransformTracker { internal static bool CanRecordModifications() { return true; } public void Add(Object driver, RectTransform rectTransform, DrivenTransformProperties drivenProperties) { } [Obsolete("revertValues parameter is ignored. Please use Clear() instead.")] public void Clear(bool revertValues) { Clear(); } public void Clear() { } } [NativeHeader("Runtime/Transform/RectTransform.h")] [NativeClass("UI::RectTransform")] public sealed class RectTransform : Transform { public enum Edge { Left, Right, Top, Bottom } public enum Axis { Horizontal, Vertical } public delegate void ReapplyDrivenProperties(RectTransform driven); public Rect rect { get { get_rect_Injected(out var ret); return ret; } } public Vector2 anchorMin { get { get_anchorMin_Injected(out var ret); return ret; } set { set_anchorMin_Injected(ref value); } } public Vector2 anchorMax { get { get_anchorMax_Injected(out var ret); return ret; } set { set_anchorMax_Injected(ref value); } } public Vector2 anchoredPosition { get { get_anchoredPosition_Injected(out var ret); return ret; } set { set_anchoredPosition_Injected(ref value); } } public Vector2 sizeDelta { get { get_sizeDelta_Injected(out var ret); return ret; } set { set_sizeDelta_Injected(ref value); } } public Vector2 pivot { get { get_pivot_Injected(out var ret); return ret; } set { set_pivot_Injected(ref value); } } public Vector3 anchoredPosition3D { get { Vector2 vector = anchoredPosition; return new Vector3(vector.x, vector.y, base.localPosition.z); } set { anchoredPosition = new Vector2(value.x, value.y); Vector3 vector = base.localPosition; vector.z = value.z; base.localPosition = vector; } } public Vector2 offsetMin { get { return anchoredPosition - Vector2.Scale(sizeDelta, pivot); } set { Vector2 vector = value - (anchoredPosition - Vector2.Scale(sizeDelta, pivot)); sizeDelta -= vector; anchoredPosition += Vector2.Scale(vector, Vector2.one - pivot); } } public Vector2 offsetMax { get { return anchoredPosition + Vector2.Scale(sizeDelta, Vector2.one - pivot); } set { Vector2 vector = value - (anchoredPosition + Vector2.Scale(sizeDelta, Vector2.one - pivot)); sizeDelta += vector; anchoredPosition += Vector2.Scale(vector, pivot); } } public extern Object drivenByObject { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] internal set; } internal extern DrivenTransformProperties drivenProperties { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static event ReapplyDrivenProperties reapplyDrivenProperties; [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("UpdateIfTransformDispatchIsDirty")] public extern void ForceUpdateRectTransforms(); public void GetLocalCorners(Vector3[] fourCornersArray) { if (fourCornersArray == null || fourCornersArray.Length < 4) { Debug.LogError("Calling GetLocalCorners with an array that is null or has less than 4 elements."); return; } Rect rect = this.rect; float x = rect.x; float y = rect.y; float xMax = rect.xMax; float yMax = rect.yMax; fourCornersArray[0] = new Vector3(x, y, 0f); fourCornersArray[1] = new Vector3(x, yMax, 0f); fourCornersArray[2] = new Vector3(xMax, yMax, 0f); fourCornersArray[3] = new Vector3(xMax, y, 0f); } public void GetWorldCorners(Vector3[] fourCornersArray) { if (fourCornersArray == null || fourCornersArray.Length < 4) { Debug.LogError("Calling GetWorldCorners with an array that is null or has less than 4 elements."); return; } GetLocalCorners(fourCornersArray); Matrix4x4 matrix4x = base.transform.localToWorldMatrix; for (int i = 0; i < 4; i++) { fourCornersArray[i] = matrix4x.MultiplyPoint(fourCornersArray[i]); } } public void SetInsetAndSizeFromParentEdge(Edge edge, float inset, float size) { int index = ((edge == Edge.Top || edge == Edge.Bottom) ? 1 : 0); bool flag = edge == Edge.Top || edge == Edge.Right; float value = (flag ? 1 : 0); Vector2 vector = anchorMin; vector[index] = value; anchorMin = vector; vector = anchorMax; vector[index] = value; anchorMax = vector; Vector2 vector2 = sizeDelta; vector2[index] = size; sizeDelta = vector2; Vector2 vector3 = anchoredPosition; vector3[index] = (flag ? (0f - inset - size * (1f - pivot[index])) : (inset + size * pivot[index])); anchoredPosition = vector3; } public void SetSizeWithCurrentAnchors(Axis axis, float size) { Vector2 vector = sizeDelta; vector[(int)axis] = size - GetParentSize()[(int)axis] * (anchorMax[(int)axis] - anchorMin[(int)axis]); sizeDelta = vector; } [RequiredByNativeCode] internal static void SendReapplyDrivenProperties(RectTransform driven) { RectTransform.reapplyDrivenProperties?.Invoke(driven); } internal Rect GetRectInParentSpace() { Rect result = rect; Vector2 vector = offsetMin + Vector2.Scale(pivot, result.size); if ((bool)base.transform.parent) { RectTransform component = base.transform.parent.GetComponent(); if ((bool)component) { vector += Vector2.Scale(anchorMin, component.rect.size); } } result.x += vector.x; result.y += vector.y; return result; } private Vector2 GetParentSize() { RectTransform rectTransform = base.parent as RectTransform; if (!rectTransform) { return Vector2.zero; } return rectTransform.rect.size; } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_rect_Injected(out Rect ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_anchorMin_Injected(out Vector2 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_anchorMin_Injected(ref Vector2 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_anchorMax_Injected(out Vector2 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_anchorMax_Injected(ref Vector2 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_anchoredPosition_Injected(out Vector2 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_anchoredPosition_Injected(ref Vector2 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_sizeDelta_Injected(out Vector2 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_sizeDelta_Injected(ref Vector2 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_pivot_Injected(out Vector2 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_pivot_Injected(ref Vector2 value); } internal enum RotationOrder { OrderXYZ, OrderXZY, OrderYZX, OrderYXZ, OrderZXY, OrderZYX } [NativeHeader("Configuration/UnityConfigure.h")] [RequiredByNativeCode] [NativeHeader("Runtime/Transform/ScriptBindings/TransformScriptBindings.h")] [NativeHeader("Runtime/Transform/Transform.h")] public class Transform : Component, IEnumerable { private class Enumerator : IEnumerator { private Transform outer; private int currentIndex = -1; public object Current => outer.GetChild(currentIndex); internal Enumerator(Transform outer) { this.outer = outer; } public bool MoveNext() { int childCount = outer.childCount; return ++currentIndex < childCount; } public void Reset() { currentIndex = -1; } } public Vector3 position { get { get_position_Injected(out var ret); return ret; } set { set_position_Injected(ref value); } } public Vector3 localPosition { get { get_localPosition_Injected(out var ret); return ret; } set { set_localPosition_Injected(ref value); } } public Vector3 eulerAngles { get { return rotation.eulerAngles; } set { rotation = Quaternion.Euler(value); } } public Vector3 localEulerAngles { get { return localRotation.eulerAngles; } set { localRotation = Quaternion.Euler(value); } } public Vector3 right { get { return rotation * Vector3.right; } set { rotation = Quaternion.FromToRotation(Vector3.right, value); } } public Vector3 up { get { return rotation * Vector3.up; } set { rotation = Quaternion.FromToRotation(Vector3.up, value); } } public Vector3 forward { get { return rotation * Vector3.forward; } set { rotation = Quaternion.LookRotation(value); } } public Quaternion rotation { get { get_rotation_Injected(out var ret); return ret; } set { set_rotation_Injected(ref value); } } public Quaternion localRotation { get { get_localRotation_Injected(out var ret); return ret; } set { set_localRotation_Injected(ref value); } } [NativeConditional("UNITY_EDITOR")] internal RotationOrder rotationOrder { get { return (RotationOrder)GetRotationOrderInternal(); } set { SetRotationOrderInternal(value); } } public Vector3 localScale { get { get_localScale_Injected(out var ret); return ret; } set { set_localScale_Injected(ref value); } } public Transform parent { get { return parentInternal; } set { if (this is RectTransform) { Debug.LogWarning("Parent of RectTransform is being set with parent property. Consider using the SetParent method instead, with the worldPositionStays argument set to false. This will retain local orientation and scale rather than world orientation and scale, which can prevent common UI scaling issues.", this); } parentInternal = value; } } internal Transform parentInternal { get { return GetParent(); } set { SetParent(value); } } public Matrix4x4 worldToLocalMatrix { get { get_worldToLocalMatrix_Injected(out var ret); return ret; } } public Matrix4x4 localToWorldMatrix { get { get_localToWorldMatrix_Injected(out var ret); return ret; } } public Transform root => GetRoot(); public extern int childCount { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetChildrenCount")] get; } public Vector3 lossyScale { [NativeMethod("GetWorldScaleLossy")] get { get_lossyScale_Injected(out var ret); return ret; } } [NativeProperty("HasChangedDeprecated")] public extern bool hasChanged { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public int hierarchyCapacity { get { return internal_getHierarchyCapacity(); } set { internal_setHierarchyCapacity(value); } } public int hierarchyCount => internal_getHierarchyCount(); [NativeConditional("UNITY_EDITOR")] internal bool constrainProportionsScale { get { return IsConstrainProportionsScale(); } set { SetConstrainProportionsScale(value); } } protected Transform() { } internal Vector3 GetLocalEulerAngles(RotationOrder order) { GetLocalEulerAngles_Injected(order, out var ret); return ret; } internal void SetLocalEulerAngles(Vector3 euler, RotationOrder order) { SetLocalEulerAngles_Injected(ref euler, order); } [NativeConditional("UNITY_EDITOR")] internal void SetLocalEulerHint(Vector3 euler) { SetLocalEulerHint_Injected(ref euler); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("UNITY_EDITOR")] [NativeMethod("GetRotationOrder")] internal extern int GetRotationOrderInternal(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("UNITY_EDITOR")] [NativeMethod("SetRotationOrder")] internal extern void SetRotationOrderInternal(RotationOrder rotationOrder); [MethodImpl(MethodImplOptions.InternalCall)] private extern Transform GetParent(); public void SetParent(Transform p) { SetParent(p, worldPositionStays: true); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SetParent", HasExplicitThis = true)] public extern void SetParent(Transform parent, bool worldPositionStays); public void SetPositionAndRotation(Vector3 position, Quaternion rotation) { SetPositionAndRotation_Injected(ref position, ref rotation); } public void SetLocalPositionAndRotation(Vector3 localPosition, Quaternion localRotation) { SetLocalPositionAndRotation_Injected(ref localPosition, ref localRotation); } [MethodImpl(MethodImplOptions.InternalCall)] public extern void GetPositionAndRotation(out Vector3 position, out Quaternion rotation); [MethodImpl(MethodImplOptions.InternalCall)] public extern void GetLocalPositionAndRotation(out Vector3 localPosition, out Quaternion localRotation); public void Translate(Vector3 translation, [UnityEngine.Internal.DefaultValue("Space.Self")] Space relativeTo) { if (relativeTo == Space.World) { position += translation; } else { position += TransformDirection(translation); } } public void Translate(Vector3 translation) { Translate(translation, Space.Self); } public void Translate(float x, float y, float z, [UnityEngine.Internal.DefaultValue("Space.Self")] Space relativeTo) { Translate(new Vector3(x, y, z), relativeTo); } public void Translate(float x, float y, float z) { Translate(new Vector3(x, y, z), Space.Self); } public void Translate(Vector3 translation, Transform relativeTo) { if ((bool)relativeTo) { position += relativeTo.TransformDirection(translation); } else { position += translation; } } public void Translate(float x, float y, float z, Transform relativeTo) { Translate(new Vector3(x, y, z), relativeTo); } public void Rotate(Vector3 eulers, [UnityEngine.Internal.DefaultValue("Space.Self")] Space relativeTo) { Quaternion quaternion = Quaternion.Euler(eulers.x, eulers.y, eulers.z); if (relativeTo == Space.Self) { localRotation *= quaternion; } else { rotation *= Quaternion.Inverse(rotation) * quaternion * rotation; } } public void Rotate(Vector3 eulers) { Rotate(eulers, Space.Self); } public void Rotate(float xAngle, float yAngle, float zAngle, [UnityEngine.Internal.DefaultValue("Space.Self")] Space relativeTo) { Rotate(new Vector3(xAngle, yAngle, zAngle), relativeTo); } public void Rotate(float xAngle, float yAngle, float zAngle) { Rotate(new Vector3(xAngle, yAngle, zAngle), Space.Self); } [NativeMethod("RotateAround")] internal void RotateAroundInternal(Vector3 axis, float angle) { RotateAroundInternal_Injected(ref axis, angle); } public void Rotate(Vector3 axis, float angle, [UnityEngine.Internal.DefaultValue("Space.Self")] Space relativeTo) { if (relativeTo == Space.Self) { RotateAroundInternal(base.transform.TransformDirection(axis), angle * ((float)Math.PI / 180f)); } else { RotateAroundInternal(axis, angle * ((float)Math.PI / 180f)); } } public void Rotate(Vector3 axis, float angle) { Rotate(axis, angle, Space.Self); } public void RotateAround(Vector3 point, Vector3 axis, float angle) { Vector3 vector = position; Quaternion quaternion = Quaternion.AngleAxis(angle, axis); Vector3 vector2 = vector - point; vector2 = quaternion * vector2; vector = point + vector2; position = vector; RotateAroundInternal(axis, angle * ((float)Math.PI / 180f)); } public void LookAt(Transform target, [UnityEngine.Internal.DefaultValue("Vector3.up")] Vector3 worldUp) { if ((bool)target) { LookAt(target.position, worldUp); } } public void LookAt(Transform target) { if ((bool)target) { LookAt(target.position, Vector3.up); } } public void LookAt(Vector3 worldPosition, [UnityEngine.Internal.DefaultValue("Vector3.up")] Vector3 worldUp) { Internal_LookAt(worldPosition, worldUp); } public void LookAt(Vector3 worldPosition) { Internal_LookAt(worldPosition, Vector3.up); } [FreeFunction("Internal_LookAt", HasExplicitThis = true)] private void Internal_LookAt(Vector3 worldPosition, Vector3 worldUp) { Internal_LookAt_Injected(ref worldPosition, ref worldUp); } public Vector3 TransformDirection(Vector3 direction) { TransformDirection_Injected(ref direction, out var ret); return ret; } public Vector3 TransformDirection(float x, float y, float z) { return TransformDirection(new Vector3(x, y, z)); } public Vector3 InverseTransformDirection(Vector3 direction) { InverseTransformDirection_Injected(ref direction, out var ret); return ret; } public Vector3 InverseTransformDirection(float x, float y, float z) { return InverseTransformDirection(new Vector3(x, y, z)); } public Vector3 TransformVector(Vector3 vector) { TransformVector_Injected(ref vector, out var ret); return ret; } public Vector3 TransformVector(float x, float y, float z) { return TransformVector(new Vector3(x, y, z)); } public Vector3 InverseTransformVector(Vector3 vector) { InverseTransformVector_Injected(ref vector, out var ret); return ret; } public Vector3 InverseTransformVector(float x, float y, float z) { return InverseTransformVector(new Vector3(x, y, z)); } public Vector3 TransformPoint(Vector3 position) { TransformPoint_Injected(ref position, out var ret); return ret; } public Vector3 TransformPoint(float x, float y, float z) { return TransformPoint(new Vector3(x, y, z)); } public Vector3 InverseTransformPoint(Vector3 position) { InverseTransformPoint_Injected(ref position, out var ret); return ret; } public Vector3 InverseTransformPoint(float x, float y, float z) { return InverseTransformPoint(new Vector3(x, y, z)); } [MethodImpl(MethodImplOptions.InternalCall)] private extern Transform GetRoot(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("DetachChildren", HasExplicitThis = true)] public extern void DetachChildren(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetAsFirstSibling(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetAsLastSibling(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetSiblingIndex(int index); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("MoveAfterSiblingInternal")] internal extern void MoveAfterSibling(Transform transform, bool notifyEditorAndMarkDirty); [MethodImpl(MethodImplOptions.InternalCall)] public extern int GetSiblingIndex(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern Transform FindRelativeTransformWithPath([NotNull("NullExceptionObject")] Transform transform, string path, [UnityEngine.Internal.DefaultValue("false")] bool isActiveOnly); public Transform Find(string n) { if (n == null) { throw new ArgumentNullException("Name cannot be null"); } return FindRelativeTransformWithPath(this, n, isActiveOnly: false); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("UNITY_EDITOR")] internal extern void SendTransformChangedScale(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("Internal_IsChildOrSameTransform", HasExplicitThis = true)] public extern bool IsChildOf([NotNull("ArgumentNullException")] Transform parent); [Obsolete("FindChild has been deprecated. Use Find instead (UnityUpgradable) -> Find([mscorlib] System.String)", false)] public Transform FindChild(string n) { return Find(n); } public IEnumerator GetEnumerator() { return new Enumerator(this); } [Obsolete("warning use Transform.Rotate instead.")] public void RotateAround(Vector3 axis, float angle) { RotateAround_Injected(ref axis, angle); } [Obsolete("warning use Transform.Rotate instead.")] public void RotateAroundLocal(Vector3 axis, float angle) { RotateAroundLocal_Injected(ref axis, angle); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] [FreeFunction("GetChild", HasExplicitThis = true)] public extern Transform GetChild(int index); [MethodImpl(MethodImplOptions.InternalCall)] [Obsolete("warning use Transform.childCount instead (UnityUpgradable) -> Transform.childCount", false)] [NativeMethod("GetChildrenCount")] public extern int GetChildCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetHierarchyCapacity", HasExplicitThis = true)] private extern int internal_getHierarchyCapacity(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SetHierarchyCapacity", HasExplicitThis = true)] private extern void internal_setHierarchyCapacity(int value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetHierarchyCount", HasExplicitThis = true)] private extern int internal_getHierarchyCount(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("UNITY_EDITOR")] [FreeFunction("IsNonUniformScaleTransform", HasExplicitThis = true)] internal extern bool IsNonUniformScaleTransform(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("UNITY_EDITOR")] private extern void SetConstrainProportionsScale(bool isLinked); [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("UNITY_EDITOR")] private extern bool IsConstrainProportionsScale(); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_position_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_position_Injected(ref Vector3 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_localPosition_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_localPosition_Injected(ref Vector3 value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetLocalEulerAngles_Injected(RotationOrder order, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetLocalEulerAngles_Injected(ref Vector3 euler, RotationOrder order); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetLocalEulerHint_Injected(ref Vector3 euler); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_rotation_Injected(out Quaternion ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_rotation_Injected(ref Quaternion value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_localRotation_Injected(out Quaternion ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_localRotation_Injected(ref Quaternion value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_localScale_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_localScale_Injected(ref Vector3 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_worldToLocalMatrix_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_localToWorldMatrix_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetPositionAndRotation_Injected(ref Vector3 position, ref Quaternion rotation); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetLocalPositionAndRotation_Injected(ref Vector3 localPosition, ref Quaternion localRotation); [MethodImpl(MethodImplOptions.InternalCall)] private extern void RotateAroundInternal_Injected(ref Vector3 axis, float angle); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_LookAt_Injected(ref Vector3 worldPosition, ref Vector3 worldUp); [MethodImpl(MethodImplOptions.InternalCall)] private extern void TransformDirection_Injected(ref Vector3 direction, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void InverseTransformDirection_Injected(ref Vector3 direction, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void TransformVector_Injected(ref Vector3 vector, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void InverseTransformVector_Injected(ref Vector3 vector, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void TransformPoint_Injected(ref Vector3 position, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void InverseTransformPoint_Injected(ref Vector3 position, out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_lossyScale_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void RotateAround_Injected(ref Vector3 axis, float angle); [MethodImpl(MethodImplOptions.InternalCall)] private extern void RotateAroundLocal_Injected(ref Vector3 axis, float angle); } public enum SpriteDrawMode { Simple, Sliced, Tiled } public enum SpriteTileMode { Continuous, Adaptive } public enum SpriteMaskInteraction { None, VisibleInsideMask, VisibleOutsideMask } [RequireComponent(typeof(Transform))] [NativeType("Runtime/Graphics/Mesh/SpriteRenderer.h")] public sealed class SpriteRenderer : Renderer { private UnityEvent m_SpriteChangeEvent; internal extern bool shouldSupportTiling { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("ShouldSupportTiling")] get; } public extern Sprite sprite { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern SpriteDrawMode drawMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Vector2 size { get { get_size_Injected(out var ret); return ret; } set { set_size_Injected(ref value); } } public extern float adaptiveModeThreshold { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern SpriteTileMode tileMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public Color color { get { get_color_Injected(out var ret); return ret; } set { set_color_Injected(ref value); } } public extern SpriteMaskInteraction maskInteraction { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool flipX { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern bool flipY { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern SpriteSortPoint spriteSortPoint { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public void RegisterSpriteChangeCallback(UnityAction callback) { if (m_SpriteChangeEvent == null) { m_SpriteChangeEvent = new UnityEvent(); } m_SpriteChangeEvent.AddListener(callback); } public void UnregisterSpriteChangeCallback(UnityAction callback) { if (m_SpriteChangeEvent != null) { m_SpriteChangeEvent.RemoveListener(callback); } } [RequiredByNativeCode] private void InvokeSpriteChanged() { try { m_SpriteChangeEvent?.Invoke(this); } catch (Exception exception) { Debug.LogException(exception, this); } } [NativeMethod(Name = "GetSpriteBounds")] internal Bounds Internal_GetSpriteBounds(SpriteDrawMode mode) { Internal_GetSpriteBounds_Injected(mode, out var ret); return ret; } internal Bounds GetSpriteBounds() { return Internal_GetSpriteBounds(drawMode); } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_size_Injected(out Vector2 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_size_Injected(ref Vector2 value); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_color_Injected(out Color ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void set_color_Injected(ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_GetSpriteBounds_Injected(SpriteDrawMode mode, out Bounds ret); } public enum SpriteMeshType { FullRect, Tight } public enum SpriteAlignment { Center, TopLeft, TopCenter, TopRight, LeftCenter, RightCenter, BottomLeft, BottomCenter, BottomRight, Custom } public enum SpritePackingMode { Tight, Rectangle } public enum SpritePackingRotation { None = 0, FlipHorizontal = 1, FlipVertical = 2, Rotate180 = 3, Any = 15 } public enum SpriteSortPoint { Center, Pivot } [Serializable] public struct SecondarySpriteTexture { public string name; public Texture2D texture; } [NativeHeader("Runtime/Graphics/SpriteUtility.h")] [NativeType("Runtime/Graphics/SpriteFrame.h")] [NativeHeader("Runtime/2D/Common/ScriptBindings/SpritesMarshalling.h")] [NativeHeader("Runtime/2D/Common/SpriteDataAccess.h")] [ExcludeFromPreset] public sealed class Sprite : Object { public Bounds bounds { get { get_bounds_Injected(out var ret); return ret; } } public Rect rect { get { get_rect_Injected(out var ret); return ret; } } public Vector4 border { get { get_border_Injected(out var ret); return ret; } } public extern Texture2D texture { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern float pixelsPerUnit { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetPixelsToUnits")] get; } public extern float spriteAtlasTextureScale { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetSpriteAtlasTextureScale")] get; } public extern Texture2D associatedAlphaSplitTexture { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetAlphaTexture")] get; } public Vector2 pivot { [NativeMethod("GetPivotInPixels")] get { get_pivot_Injected(out var ret); return ret; } } public bool packed => GetPacked() == 1; public SpritePackingMode packingMode => (SpritePackingMode)GetPackingMode(); public SpritePackingRotation packingRotation => (SpritePackingRotation)GetPackingRotation(); public Rect textureRect { get { if (packed && packingMode != SpritePackingMode.Rectangle) { return Rect.zero; } return GetTextureRect(); } } public Vector2 textureRectOffset { get { if (packed && packingMode != SpritePackingMode.Rectangle) { return Vector2.zero; } return GetTextureRectOffset(); } } public extern Vector2[] vertices { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SpriteAccessLegacy::GetSpriteVertices", HasExplicitThis = true)] get; } public extern ushort[] triangles { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SpriteAccessLegacy::GetSpriteIndices", HasExplicitThis = true)] get; } public extern Vector2[] uv { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SpriteAccessLegacy::GetSpriteUVs", HasExplicitThis = true)] get; } [RequiredByNativeCode] private Sprite() { } [MethodImpl(MethodImplOptions.InternalCall)] internal extern int GetPackingMode(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern int GetPackingRotation(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern int GetPacked(); internal Rect GetTextureRect() { GetTextureRect_Injected(out var ret); return ret; } internal Vector2 GetTextureRectOffset() { GetTextureRectOffset_Injected(out var ret); return ret; } internal Vector4 GetInnerUVs() { GetInnerUVs_Injected(out var ret); return ret; } internal Vector4 GetOuterUVs() { GetOuterUVs_Injected(out var ret); return ret; } internal Vector4 GetPadding() { GetPadding_Injected(out var ret); return ret; } [FreeFunction("SpritesBindings::CreateSpriteWithoutTextureScripting")] internal static Sprite CreateSpriteWithoutTextureScripting(Rect rect, Vector2 pivot, float pixelsToUnits, Texture2D texture) { return CreateSpriteWithoutTextureScripting_Injected(ref rect, ref pivot, pixelsToUnits, texture); } [FreeFunction("SpritesBindings::CreateSprite")] internal static Sprite CreateSprite(Texture2D texture, Rect rect, Vector2 pivot, float pixelsPerUnit, uint extrude, SpriteMeshType meshType, Vector4 border, bool generateFallbackPhysicsShape) { return CreateSprite_Injected(texture, ref rect, ref pivot, pixelsPerUnit, extrude, meshType, ref border, generateFallbackPhysicsShape); } [MethodImpl(MethodImplOptions.InternalCall)] internal extern Texture2D GetSecondaryTexture(int index); [MethodImpl(MethodImplOptions.InternalCall)] public extern int GetPhysicsShapeCount(); public int GetPhysicsShapePointCount(int shapeIdx) { int physicsShapeCount = GetPhysicsShapeCount(); if (shapeIdx < 0 || shapeIdx >= physicsShapeCount) { throw new IndexOutOfRangeException($"Index({shapeIdx}) is out of bounds(0 - {physicsShapeCount - 1})"); } return Internal_GetPhysicsShapePointCount(shapeIdx); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetPhysicsShapePointCount")] private extern int Internal_GetPhysicsShapePointCount(int shapeIdx); public int GetPhysicsShape(int shapeIdx, List physicsShape) { int physicsShapeCount = GetPhysicsShapeCount(); if (shapeIdx < 0 || shapeIdx >= physicsShapeCount) { throw new IndexOutOfRangeException($"Index({shapeIdx}) is out of bounds(0 - {physicsShapeCount - 1})"); } GetPhysicsShapeImpl(this, shapeIdx, physicsShape); return physicsShape.Count; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SpritesBindings::GetPhysicsShape", ThrowsException = true)] private static extern void GetPhysicsShapeImpl(Sprite sprite, int shapeIdx, [NotNull("ArgumentNullException")] List physicsShape); public void OverridePhysicsShape(IList physicsShapes) { if (physicsShapes == null) { throw new ArgumentNullException("physicsShapes"); } for (int i = 0; i < physicsShapes.Count; i++) { Vector2[] array = physicsShapes[i]; if (array == null) { throw new ArgumentNullException("physicsShape", $"Physics Shape at {i} is null."); } if (array.Length < 3) { throw new ArgumentException($"Physics Shape at {i} has less than 3 vertices ({array.Length})."); } } OverridePhysicsShapeCount(this, physicsShapes.Count); for (int j = 0; j < physicsShapes.Count; j++) { OverridePhysicsShape(this, physicsShapes[j], j); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SpritesBindings::OverridePhysicsShapeCount")] private static extern void OverridePhysicsShapeCount(Sprite sprite, int physicsShapeCount); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SpritesBindings::OverridePhysicsShape", ThrowsException = true)] private static extern void OverridePhysicsShape(Sprite sprite, [Unmarshalled] Vector2[] physicsShape, int idx); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SpritesBindings::OverrideGeometry", HasExplicitThis = true)] public extern void OverrideGeometry([Unmarshalled][NotNull("ArgumentNullException")] Vector2[] vertices, [NotNull("ArgumentNullException")][Unmarshalled] ushort[] triangles); internal static Sprite Create(Rect rect, Vector2 pivot, float pixelsToUnits, Texture2D texture) { return CreateSpriteWithoutTextureScripting(rect, pivot, pixelsToUnits, texture); } internal static Sprite Create(Rect rect, Vector2 pivot, float pixelsToUnits) { return CreateSpriteWithoutTextureScripting(rect, pivot, pixelsToUnits, null); } public static Sprite Create(Texture2D texture, Rect rect, Vector2 pivot, float pixelsPerUnit, uint extrude, SpriteMeshType meshType, Vector4 border, bool generateFallbackPhysicsShape) { if (texture == null) { return null; } if (rect.xMax > (float)texture.width || rect.yMax > (float)texture.height) { throw new ArgumentException($"Could not create sprite ({rect.x}, {rect.y}, {rect.width}, {rect.height}) from a {texture.width}x{texture.height} texture."); } if (pixelsPerUnit <= 0f) { throw new ArgumentException("pixelsPerUnit must be set to a positive non-zero value."); } return CreateSprite(texture, rect, pivot, pixelsPerUnit, extrude, meshType, border, generateFallbackPhysicsShape); } public static Sprite Create(Texture2D texture, Rect rect, Vector2 pivot, float pixelsPerUnit, uint extrude, SpriteMeshType meshType, Vector4 border) { return Create(texture, rect, pivot, pixelsPerUnit, extrude, meshType, border, generateFallbackPhysicsShape: false); } public static Sprite Create(Texture2D texture, Rect rect, Vector2 pivot, float pixelsPerUnit, uint extrude, SpriteMeshType meshType) { return Create(texture, rect, pivot, pixelsPerUnit, extrude, meshType, Vector4.zero); } public static Sprite Create(Texture2D texture, Rect rect, Vector2 pivot, float pixelsPerUnit, uint extrude) { return Create(texture, rect, pivot, pixelsPerUnit, extrude, SpriteMeshType.Tight); } public static Sprite Create(Texture2D texture, Rect rect, Vector2 pivot, float pixelsPerUnit) { return Create(texture, rect, pivot, pixelsPerUnit, 0u); } public static Sprite Create(Texture2D texture, Rect rect, Vector2 pivot) { return Create(texture, rect, pivot, 100f); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetTextureRect_Injected(out Rect ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetTextureRectOffset_Injected(out Vector2 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetInnerUVs_Injected(out Vector4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetOuterUVs_Injected(out Vector4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetPadding_Injected(out Vector4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Sprite CreateSpriteWithoutTextureScripting_Injected(ref Rect rect, ref Vector2 pivot, float pixelsToUnits, Texture2D texture); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Sprite CreateSprite_Injected(Texture2D texture, ref Rect rect, ref Vector2 pivot, float pixelsPerUnit, uint extrude, SpriteMeshType meshType, ref Vector4 border, bool generateFallbackPhysicsShape); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_bounds_Injected(out Bounds ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_rect_Injected(out Rect ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_border_Injected(out Vector4 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private extern void get_pivot_Injected(out Vector2 ret); } } namespace UnityEngine._Scripting.APIUpdating { internal class APIUpdaterRuntimeHelpers { [RequiredByNativeCode] internal static bool GetMovedFromAttributeDataForType(Type sourceType, out string assembly, out string nsp, out string klass) { klass = null; nsp = null; assembly = null; object[] customAttributes = sourceType.GetCustomAttributes(typeof(MovedFromAttribute), inherit: false); if (customAttributes.Length != 1) { return false; } MovedFromAttribute movedFromAttribute = (MovedFromAttribute)customAttributes[0]; klass = movedFromAttribute.data.className; nsp = movedFromAttribute.data.nameSpace; assembly = movedFromAttribute.data.assembly; return true; } [RequiredByNativeCode] internal static bool GetObsoleteTypeRedirection(Type sourceType, out string assemblyName, out string nsp, out string className) { object[] customAttributes = sourceType.GetCustomAttributes(typeof(ObsoleteAttribute), inherit: false); assemblyName = null; nsp = null; className = null; if (customAttributes.Length != 1) { return false; } ObsoleteAttribute obsoleteAttribute = (ObsoleteAttribute)customAttributes[0]; string message = obsoleteAttribute.Message; if (string.IsNullOrEmpty(message)) { return false; } string text = "(UnityUpgradable) -> "; int num = message.IndexOf(text); if (num >= 0) { string text2 = message.Substring(num + text.Length).Trim(); if (text2.Length == 0) { return false; } int num2 = 0; if (text2[0] == '[') { num2 = text2.IndexOf(']'); if (num2 == -1) { return false; } assemblyName = text2.Substring(1, num2 - 1); text2 = text2.Substring(num2 + 1).Trim(); } else { assemblyName = sourceType.Assembly.GetName().Name; } num2 = text2.LastIndexOf('.'); if (num2 > -1) { className = text2.Substring(num2 + 1); text2 = text2.Substring(0, num2); } else { className = text2; text2 = ""; } if (text2.Length > 0) { nsp = text2; } else { nsp = sourceType.Namespace; } return true; } return false; } } } namespace UnityEngine.Sprites { public sealed class DataUtility { public static Vector4 GetInnerUV(Sprite sprite) { return sprite.GetInnerUVs(); } public static Vector4 GetOuterUV(Sprite sprite) { return sprite.GetOuterUVs(); } public static Vector4 GetPadding(Sprite sprite) { return sprite.GetPadding(); } public static Vector2 GetMinSize(Sprite sprite) { Vector2 result = default(Vector2); result.x = sprite.border.x + sprite.border.z; result.y = sprite.border.y + sprite.border.w; return result; } } } namespace UnityEngine.U2D { public abstract class Light2DBase : MonoBehaviour { } internal enum Light2DType { Parametric, Freeform, Sprite, Point, Global } [MovedFrom("UnityEngine.Experimental.U2D")] [NativeHeader("Runtime/2D/Common/PixelSnapping.h")] public static class PixelPerfectRendering { public static extern float pixelSnapSpacing { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetPixelSnapSpacing")] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SetPixelSnapSpacing")] set; } } [Serializable] [NativeHeader("Runtime/2D/Common/SpriteDataMarshalling.h")] [NativeHeader("Runtime/2D/Common/SpriteDataAccess.h")] [RequiredByNativeCode] [NativeType(/*Could not decode attribute arguments.*/)] [MovedFrom("UnityEngine.Experimental.U2D")] public struct SpriteBone { [NativeName("name")] [SerializeField] private string m_Name; [NativeName("guid")] [SerializeField] private string m_Guid; [NativeName("position")] [SerializeField] private Vector3 m_Position; [SerializeField] [NativeName("rotation")] private Quaternion m_Rotation; [NativeName("length")] [SerializeField] private float m_Length; [SerializeField] [NativeName("parentId")] private int m_ParentId; [NativeName("color")] [SerializeField] private Color32 m_Color; public string name { get { return m_Name; } set { m_Name = value; } } public string guid { get { return m_Guid; } set { m_Guid = value; } } public Vector3 position { get { return m_Position; } set { m_Position = value; } } public Quaternion rotation { get { return m_Rotation; } set { m_Rotation = value; } } public float length { get { return m_Length; } set { m_Length = value; } } public int parentId { get { return m_ParentId; } set { m_ParentId = value; } } public Color32 color { get { return m_Color; } set { m_Color = value; } } } [VisibleToOtherModules] internal struct SpriteChannelInfo { [NativeName("buffer")] private IntPtr m_Buffer; [NativeName("count")] private int m_Count; [NativeName("offset")] private int m_Offset; [NativeName("stride")] private int m_Stride; public unsafe void* buffer { get { return (void*)m_Buffer; } set { m_Buffer = (IntPtr)value; } } public int count { get { return m_Count; } set { m_Count = value; } } public int offset { get { return m_Offset; } set { m_Offset = value; } } public int stride { get { return m_Stride; } set { m_Stride = value; } } } [NativeHeader("Runtime/Graphics/SpriteFrame.h")] [NativeHeader("Runtime/2D/Common/SpriteDataAccess.h")] public static class SpriteDataAccessExtensions { private static void CheckAttributeTypeMatchesAndThrow(VertexAttribute channel) { bool flag = false; switch (channel) { case VertexAttribute.Position: case VertexAttribute.Normal: flag = (object)typeof(T) == typeof(Vector3); break; case VertexAttribute.Tangent: flag = (object)typeof(T) == typeof(Vector4); break; case VertexAttribute.Color: flag = (object)typeof(T) == typeof(Color32); break; case VertexAttribute.TexCoord0: case VertexAttribute.TexCoord1: case VertexAttribute.TexCoord2: case VertexAttribute.TexCoord3: case VertexAttribute.TexCoord4: case VertexAttribute.TexCoord5: case VertexAttribute.TexCoord6: case VertexAttribute.TexCoord7: flag = (object)typeof(T) == typeof(Vector2); break; case VertexAttribute.BlendWeight: flag = (object)typeof(T) == typeof(BoneWeight); break; default: throw new InvalidOperationException($"The requested channel '{channel}' is unknown."); } if (!flag) { throw new InvalidOperationException($"The requested channel '{channel}' does not match the return type {typeof(T).Name}."); } } public unsafe static NativeSlice GetVertexAttribute(this Sprite sprite, VertexAttribute channel) where T : struct { CheckAttributeTypeMatchesAndThrow(channel); SpriteChannelInfo channelInfo = GetChannelInfo(sprite, channel); byte* dataPointer = (byte*)channelInfo.buffer + channelInfo.offset; return NativeSliceUnsafeUtility.ConvertExistingDataToNativeSlice(dataPointer, channelInfo.stride, channelInfo.count); } public unsafe static void SetVertexAttribute(this Sprite sprite, VertexAttribute channel, NativeArray src) where T : struct { CheckAttributeTypeMatchesAndThrow(channel); SetChannelData(sprite, channel, src.GetUnsafeReadOnlyPtr()); } public unsafe static NativeArray GetBindPoses(this Sprite sprite) { SpriteChannelInfo bindPoseInfo = GetBindPoseInfo(sprite); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(bindPoseInfo.buffer, bindPoseInfo.count, Allocator.Invalid); } public unsafe static void SetBindPoses(this Sprite sprite, NativeArray src) { SetBindPoseData(sprite, src.GetUnsafeReadOnlyPtr(), src.Length); } public unsafe static NativeArray GetIndices(this Sprite sprite) { SpriteChannelInfo indicesInfo = GetIndicesInfo(sprite); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(indicesInfo.buffer, indicesInfo.count, Allocator.Invalid); } public unsafe static void SetIndices(this Sprite sprite, NativeArray src) { SetIndicesData(sprite, src.GetUnsafeReadOnlyPtr(), src.Length); } public static SpriteBone[] GetBones(this Sprite sprite) { return GetBoneInfo(sprite); } public static void SetBones(this Sprite sprite, SpriteBone[] src) { SetBoneData(sprite, src); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("HasChannel")] public static extern bool HasVertexAttribute([NotNull("ArgumentNullException")] this Sprite sprite, VertexAttribute channel); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void SetVertexCount([NotNull("ArgumentNullException")] this Sprite sprite, int count); [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetVertexCount([NotNull("ArgumentNullException")] this Sprite sprite); private static SpriteChannelInfo GetBindPoseInfo([NotNull("ArgumentNullException")] Sprite sprite) { GetBindPoseInfo_Injected(sprite, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void SetBindPoseData([NotNull("ArgumentNullException")] Sprite sprite, void* src, int count); private static SpriteChannelInfo GetIndicesInfo([NotNull("ArgumentNullException")] Sprite sprite) { GetIndicesInfo_Injected(sprite, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void SetIndicesData([NotNull("ArgumentNullException")] Sprite sprite, void* src, int count); private static SpriteChannelInfo GetChannelInfo([NotNull("ArgumentNullException")] Sprite sprite, VertexAttribute channel) { GetChannelInfo_Injected(sprite, channel, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void SetChannelData([NotNull("ArgumentNullException")] Sprite sprite, VertexAttribute channel, void* src); [MethodImpl(MethodImplOptions.InternalCall)] private static extern SpriteBone[] GetBoneInfo([NotNull("ArgumentNullException")] Sprite sprite); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetBoneData([NotNull("ArgumentNullException")] Sprite sprite, SpriteBone[] src); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetPrimaryVertexStreamSize(Sprite sprite); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetBindPoseInfo_Injected(Sprite sprite, out SpriteChannelInfo ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetIndicesInfo_Injected(Sprite sprite, out SpriteChannelInfo ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetChannelInfo_Injected(Sprite sprite, VertexAttribute channel, out SpriteChannelInfo ret); } [NativeHeader("Runtime/Graphics/Mesh/SpriteRenderer.h")] [NativeHeader("Runtime/2D/Common/SpriteDataAccess.h")] public static class SpriteRendererDataAccessExtensions { internal unsafe static void SetDeformableBuffer(this SpriteRenderer spriteRenderer, NativeArray src) { if (spriteRenderer.sprite == null) { throw new ArgumentException($"spriteRenderer does not have a valid sprite set."); } if (src.Length != SpriteDataAccessExtensions.GetPrimaryVertexStreamSize(spriteRenderer.sprite)) { throw new InvalidOperationException($"custom sprite vertex data size must match sprite asset's vertex data size {src.Length} {SpriteDataAccessExtensions.GetPrimaryVertexStreamSize(spriteRenderer.sprite)}"); } SetDeformableBuffer(spriteRenderer, src.GetUnsafeReadOnlyPtr(), src.Length); } internal unsafe static void SetDeformableBuffer(this SpriteRenderer spriteRenderer, NativeArray src) { if (spriteRenderer.sprite == null) { throw new InvalidOperationException("spriteRenderer does not have a valid sprite set."); } if (src.Length != spriteRenderer.sprite.GetVertexCount()) { throw new InvalidOperationException($"The src length {src.Length} must match the vertex count of source Sprite {spriteRenderer.sprite.GetVertexCount()}."); } SetDeformableBuffer(spriteRenderer, src.GetUnsafeReadOnlyPtr(), src.Length); } internal unsafe static void SetBatchDeformableBufferAndLocalAABBArray(SpriteRenderer[] spriteRenderers, NativeArray buffers, NativeArray bufferSizes, NativeArray bounds) { int num = spriteRenderers.Length; if (num != buffers.Length || num != bufferSizes.Length || num != bounds.Length) { throw new ArgumentException("Input array sizes are not the same."); } SetBatchDeformableBufferAndLocalAABBArray(spriteRenderers, buffers.GetUnsafeReadOnlyPtr(), bufferSizes.GetUnsafeReadOnlyPtr(), bounds.GetUnsafeReadOnlyPtr(), num); } internal unsafe static bool IsUsingDeformableBuffer(this SpriteRenderer spriteRenderer, IntPtr buffer) { return IsUsingDeformableBuffer(spriteRenderer, (void*)buffer); } [MethodImpl(MethodImplOptions.InternalCall)] public static extern void DeactivateDeformableBuffer([NotNull("ArgumentNullException")] this SpriteRenderer renderer); internal static void SetLocalAABB([NotNull("ArgumentNullException")] this SpriteRenderer renderer, Bounds aabb) { SetLocalAABB_Injected(renderer, ref aabb); } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void SetDeformableBuffer([NotNull("ArgumentNullException")] SpriteRenderer spriteRenderer, void* src, int count); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void SetBatchDeformableBufferAndLocalAABBArray(SpriteRenderer[] spriteRenderers, void* buffers, void* bufferSizes, void* bounds, int count); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern bool IsUsingDeformableBuffer([NotNull("ArgumentNullException")] SpriteRenderer spriteRenderer, void* buffer); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetLocalAABB_Injected(SpriteRenderer renderer, ref Bounds aabb); } [NativeHeader("Runtime/2D/SpriteAtlas/SpriteAtlas.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("Runtime/2D/SpriteAtlas/SpriteAtlasManager.h")] public class SpriteAtlasManager { public static event Action> atlasRequested; public static event Action atlasRegistered; [RequiredByNativeCode] private static bool RequestAtlas(string tag) { if (SpriteAtlasManager.atlasRequested != null) { SpriteAtlasManager.atlasRequested(tag, Register); return true; } return false; } [RequiredByNativeCode] private static void PostRegisteredAtlas(SpriteAtlas spriteAtlas) { SpriteAtlasManager.atlasRegistered?.Invoke(spriteAtlas); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void Register(SpriteAtlas spriteAtlas); } [NativeType(Header = "Runtime/2D/SpriteAtlas/SpriteAtlas.h")] [NativeHeader("Runtime/Graphics/SpriteFrame.h")] public class SpriteAtlas : Object { public extern bool isVariant { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("IsVariant")] get; } public extern string tag { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern int spriteCount { [MethodImpl(MethodImplOptions.InternalCall)] get; } [MethodImpl(MethodImplOptions.InternalCall)] public extern bool CanBindTo([NotNull("ArgumentNullException")] Sprite sprite); [MethodImpl(MethodImplOptions.InternalCall)] public extern Sprite GetSprite(string name); public int GetSprites(Sprite[] sprites) { return GetSpritesScripting(sprites); } public int GetSprites(Sprite[] sprites, string name) { return GetSpritesWithNameScripting(sprites, name); } [MethodImpl(MethodImplOptions.InternalCall)] private extern int GetSpritesScripting([Unmarshalled] Sprite[] sprites); [MethodImpl(MethodImplOptions.InternalCall)] private extern int GetSpritesWithNameScripting([Unmarshalled] Sprite[] sprites, string name); } } namespace UnityEngine.Profiling { public enum ProfilerArea { CPU, GPU, Rendering, Memory, Audio, Video, Physics, Physics2D, NetworkMessages, NetworkOperations, UI, UIDetails, GlobalIllumination, VirtualTexturing } [NativeHeader("Runtime/ScriptingBackend/ScriptingApi.h")] [NativeHeader("Runtime/Allocator/MemoryManager.h")] [NativeHeader("Runtime/Profiler/ScriptBindings/Profiler.bindings.h")] [NativeHeader("Runtime/Utilities/MemoryUtilities.h")] [UsedByNativeCode] [NativeHeader("Runtime/Profiler/Profiler.h")] [MovedFrom("UnityEngine")] public sealed class Profiler { internal const uint invalidProfilerArea = uint.MaxValue; public static extern bool supported { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "profiler_is_available", IsFreeFunction = true)] get; } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern string logFile { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool enableBinaryLog { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ProfilerBindings::IsBinaryLogEnabled", IsFreeFunction = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ProfilerBindings::SetBinaryLogEnabled", IsFreeFunction = true)] set; } public static extern int maxUsedMemory { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ProfilerBindings::GetMaxUsedMemory", IsFreeFunction = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ProfilerBindings::SetMaxUsedMemory", IsFreeFunction = true)] set; } public static extern bool enabled { [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("ENABLE_PROFILER")] [NativeMethod(Name = "profiler_is_enabled", IsFreeFunction = true, IsThreadSafe = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ProfilerBindings::SetProfilerEnabled", IsFreeFunction = true)] set; } public static extern bool enableAllocationCallstacks { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ProfilerBindings::IsAllocationCallstackCaptureEnabled", IsFreeFunction = true)] get; [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ProfilerBindings::SetAllocationCallstackCaptureEnabled", IsFreeFunction = true)] set; } public static int areaCount => Enum.GetNames(typeof(ProfilerArea)).Length; [Obsolete("maxNumberOfSamplesPerFrame has been depricated. Use maxUsedMemory instead")] public static int maxNumberOfSamplesPerFrame { get { return 0; } set { } } [Obsolete("usedHeapSize has been deprecated since it is limited to 4GB. Please use usedHeapSizeLong instead.")] public static uint usedHeapSize => (uint)usedHeapSizeLong; public static extern long usedHeapSizeLong { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GetUsedHeapSize", IsFreeFunction = true)] get; } private Profiler() { } [MethodImpl(MethodImplOptions.InternalCall)] [Conditional("ENABLE_PROFILER")] [FreeFunction("ProfilerBindings::profiler_set_area_enabled")] public static extern void SetAreaEnabled(ProfilerArea area, bool enabled); [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("ENABLE_PROFILER")] [FreeFunction("ProfilerBindings::profiler_is_area_enabled")] public static extern bool GetAreaEnabled(ProfilerArea area); [Conditional("UNITY_EDITOR")] public static void AddFramesFromFile(string file) { if (string.IsNullOrEmpty(file)) { Debug.LogError("AddFramesFromFile: Invalid or empty path"); } else { AddFramesFromFile_Internal(file, keepExistingFrames: true); } } [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("ENABLE_PROFILER && UNITY_EDITOR")] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeMethod(Name = "LoadFromFile")] [NativeHeader("Modules/ProfilerEditor/Public/ProfilerSession.h")] private static extern void AddFramesFromFile_Internal(string file, bool keepExistingFrames); [Conditional("ENABLE_PROFILER")] public static void BeginThreadProfiling(string threadGroupName, string threadName) { if (string.IsNullOrEmpty(threadGroupName)) { throw new ArgumentException("Argument should be a valid string", "threadGroupName"); } if (string.IsNullOrEmpty(threadName)) { throw new ArgumentException("Argument should be a valid string", "threadName"); } BeginThreadProfilingInternal(threadGroupName, threadName); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ProfilerBindings::BeginThreadProfiling", IsFreeFunction = true, IsThreadSafe = true)] [NativeConditional("ENABLE_PROFILER")] private static extern void BeginThreadProfilingInternal(string threadGroupName, string threadName); [NativeConditional("ENABLE_PROFILER")] public static void EndThreadProfiling() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("ENABLE_PROFILER")] public static void BeginSample(string name) { ValidateArguments(name); BeginSampleImpl(name, null); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("ENABLE_PROFILER")] public static void BeginSample(string name, Object targetObject) { ValidateArguments(name); BeginSampleImpl(name, targetObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void ValidateArguments(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("Argument should be a valid string.", "name"); } } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ProfilerBindings::BeginSample", IsFreeFunction = true, IsThreadSafe = true)] private static extern void BeginSampleImpl(string name, Object targetObject); [MethodImpl(MethodImplOptions.InternalCall)] [Conditional("ENABLE_PROFILER")] [NativeMethod(Name = "ProfilerBindings::EndSample", IsFreeFunction = true, IsThreadSafe = true)] public static extern void EndSample(); [Obsolete("GetRuntimeMemorySize has been deprecated since it is limited to 2GB. Please use GetRuntimeMemorySizeLong() instead.")] public static int GetRuntimeMemorySize(Object o) { return (int)GetRuntimeMemorySizeLong(o); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ProfilerBindings::GetRuntimeMemorySizeLong", IsFreeFunction = true)] public static extern long GetRuntimeMemorySizeLong([NotNull("ArgumentNullException")] Object o); [Obsolete("GetMonoHeapSize has been deprecated since it is limited to 4GB. Please use GetMonoHeapSizeLong() instead.")] public static uint GetMonoHeapSize() { return (uint)GetMonoHeapSizeLong(); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "scripting_gc_get_heap_size", IsFreeFunction = true)] public static extern long GetMonoHeapSizeLong(); [Obsolete("GetMonoUsedSize has been deprecated since it is limited to 4GB. Please use GetMonoUsedSizeLong() instead.")] public static uint GetMonoUsedSize() { return (uint)GetMonoUsedSizeLong(); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "scripting_gc_get_used_size", IsFreeFunction = true)] public static extern long GetMonoUsedSizeLong(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("ENABLE_MEMORY_MANAGER")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern bool SetTempAllocatorRequestedSize(uint size); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeConditional("ENABLE_MEMORY_MANAGER")] public static extern uint GetTempAllocatorSize(); [Obsolete("GetTotalAllocatedMemory has been deprecated since it is limited to 4GB. Please use GetTotalAllocatedMemoryLong() instead.")] public static uint GetTotalAllocatedMemory() { return (uint)GetTotalAllocatedMemoryLong(); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GetTotalAllocatedMemory")] [NativeConditional("ENABLE_MEMORY_MANAGER")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern long GetTotalAllocatedMemoryLong(); [Obsolete("GetTotalUnusedReservedMemory has been deprecated since it is limited to 4GB. Please use GetTotalUnusedReservedMemoryLong() instead.")] public static uint GetTotalUnusedReservedMemory() { return (uint)GetTotalUnusedReservedMemoryLong(); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GetTotalUnusedReservedMemory")] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeConditional("ENABLE_MEMORY_MANAGER")] public static extern long GetTotalUnusedReservedMemoryLong(); [Obsolete("GetTotalReservedMemory has been deprecated since it is limited to 4GB. Please use GetTotalReservedMemoryLong() instead.")] public static uint GetTotalReservedMemory() { return (uint)GetTotalReservedMemoryLong(); } [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeConditional("ENABLE_MEMORY_MANAGER")] [NativeMethod(Name = "GetTotalReservedMemory")] public static extern long GetTotalReservedMemoryLong(); [NativeConditional("ENABLE_MEMORY_MANAGER")] public unsafe static long GetTotalFragmentationInfo(NativeArray stats) { return InternalGetTotalFragmentationInfo((IntPtr)stats.GetUnsafePtr(), stats.Length); } [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeMethod(Name = "GetTotalFragmentationInfo")] [NativeConditional("ENABLE_MEMORY_MANAGER")] private static extern long InternalGetTotalFragmentationInfo(IntPtr pStats, int count); [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("ENABLE_PROFILER")] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeMethod(Name = "GetRegisteredGFXDriverMemory")] public static extern long GetAllocatedMemoryForGraphicsDriver(); [Conditional("ENABLE_PROFILER")] public unsafe static void EmitFrameMetaData(Guid id, int tag, Array data) { if (data == null) { throw new ArgumentNullException("data"); } Type elementType = data.GetType().GetElementType(); if (!UnsafeUtility.IsBlittable(elementType)) { throw new ArgumentException($"{elementType} type must be blittable"); } Internal_EmitGlobalMetaData_Array(&id, 16, tag, data, data.Length, UnsafeUtility.SizeOf(elementType), frameData: true); } [Conditional("ENABLE_PROFILER")] public unsafe static void EmitFrameMetaData(Guid id, int tag, List data) where T : struct { if (data == null) { throw new ArgumentNullException("data"); } Type typeFromHandle = typeof(T); if (!UnsafeUtility.IsBlittable(typeof(T))) { throw new ArgumentException($"{typeFromHandle} type must be blittable"); } Internal_EmitGlobalMetaData_Array(&id, 16, tag, NoAllocHelpers.ExtractArrayFromList(data), data.Count, UnsafeUtility.SizeOf(typeFromHandle), frameData: true); } [Conditional("ENABLE_PROFILER")] public unsafe static void EmitFrameMetaData(Guid id, int tag, NativeArray data) where T : struct { Internal_EmitGlobalMetaData_Native(&id, 16, tag, (IntPtr)data.GetUnsafeReadOnlyPtr(), data.Length, UnsafeUtility.SizeOf(), frameData: true); } [Conditional("ENABLE_PROFILER")] public unsafe static void EmitSessionMetaData(Guid id, int tag, Array data) { if (data == null) { throw new ArgumentNullException("data"); } Type elementType = data.GetType().GetElementType(); if (!UnsafeUtility.IsBlittable(elementType)) { throw new ArgumentException($"{elementType} type must be blittable"); } Internal_EmitGlobalMetaData_Array(&id, 16, tag, data, data.Length, UnsafeUtility.SizeOf(elementType), frameData: false); } [Conditional("ENABLE_PROFILER")] public unsafe static void EmitSessionMetaData(Guid id, int tag, List data) where T : struct { if (data == null) { throw new ArgumentNullException("data"); } Type typeFromHandle = typeof(T); if (!UnsafeUtility.IsBlittable(typeof(T))) { throw new ArgumentException($"{typeFromHandle} type must be blittable"); } Internal_EmitGlobalMetaData_Array(&id, 16, tag, NoAllocHelpers.ExtractArrayFromList(data), data.Count, UnsafeUtility.SizeOf(typeFromHandle), frameData: false); } [Conditional("ENABLE_PROFILER")] public unsafe static void EmitSessionMetaData(Guid id, int tag, NativeArray data) where T : struct { Internal_EmitGlobalMetaData_Native(&id, 16, tag, (IntPtr)data.GetUnsafeReadOnlyPtr(), data.Length, UnsafeUtility.SizeOf(), frameData: false); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "ProfilerBindings::Internal_EmitGlobalMetaData_Array", IsFreeFunction = true, IsThreadSafe = true)] [NativeConditional("ENABLE_PROFILER")] private unsafe static extern void Internal_EmitGlobalMetaData_Array(void* id, int idLen, int tag, Array data, int count, int elementSize, bool frameData); [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("ENABLE_PROFILER")] [NativeMethod(Name = "ProfilerBindings::Internal_EmitGlobalMetaData_Native", IsFreeFunction = true, IsThreadSafe = true)] private unsafe static extern void Internal_EmitGlobalMetaData_Native(void* id, int idLen, int tag, IntPtr data, int count, int elementSize, bool frameData); [Conditional("ENABLE_PROFILER")] public static void SetCategoryEnabled(ProfilerCategory category, bool enabled) { if ((ushort)category == (ushort)ProfilerCategory.Any) { throw new ArgumentException("Argument should be a valid category", "category"); } Internal_SetCategoryEnabled(category, enabled); } public static bool IsCategoryEnabled(ProfilerCategory category) { if ((ushort)category == (ushort)ProfilerCategory.Any) { throw new ArgumentException("Argument should be a valid category", "category"); } return Internal_IsCategoryEnabled(category); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "GetCategoriesCount")] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("Runtime/Profiler/ProfilerManager.h")] [NativeConditional("ENABLE_PROFILER")] public static extern uint GetCategoriesCount(); [Conditional("ENABLE_PROFILER")] public static void GetAllCategories(ProfilerCategory[] categories) { for (int i = 0; i < Math.Min(GetCategoriesCount(), categories.Length); i++) { categories[i] = new ProfilerCategory((ushort)i); } } [Conditional("ENABLE_PROFILER")] public static void GetAllCategories(NativeArray categories) { for (int i = 0; i < Math.Min(GetCategoriesCount(), categories.Length); i++) { categories[i] = new ProfilerCategory((ushort)i); } } [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("ENABLE_PROFILER")] [NativeMethod(Name = "profiler_set_category_enable", IsFreeFunction = true, IsThreadSafe = true)] private static extern void Internal_SetCategoryEnabled(ushort categoryId, bool enabled); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "profiler_is_category_enabled", IsFreeFunction = true, IsThreadSafe = true)] [NativeConditional("ENABLE_PROFILER")] private static extern bool Internal_IsCategoryEnabled(ushort categoryId); } [UsedByNativeCode] public sealed class Recorder { private const ProfilerRecorderOptions s_RecorderDefaultOptions = (ProfilerRecorderOptions)153; internal static Recorder s_InvalidRecorder = new Recorder(); private ProfilerRecorder m_RecorderCPU; private ProfilerRecorder m_RecorderGPU; public bool isValid => m_RecorderCPU.handle != 0; public bool enabled { get { return m_RecorderCPU.IsRunning; } set { SetEnabled(value); } } public long elapsedNanoseconds { get { if (!m_RecorderCPU.Valid) { return 0L; } return m_RecorderCPU.LastValue; } } public long gpuElapsedNanoseconds { get { if (!m_RecorderGPU.Valid) { return 0L; } return m_RecorderGPU.LastValue; } } public int sampleBlockCount { get { if (!m_RecorderCPU.Valid) { return 0; } if (m_RecorderCPU.Count != 1) { return 0; } return (int)m_RecorderCPU.GetSample(0).Count; } } public int gpuSampleBlockCount { get { if (!m_RecorderGPU.Valid) { return 0; } if (m_RecorderGPU.Count != 1) { return 0; } return (int)m_RecorderGPU.GetSample(0).Count; } } internal Recorder() { } internal Recorder(ProfilerRecorderHandle handle) { if (handle.Valid) { m_RecorderCPU = new ProfilerRecorder(handle, 1, (ProfilerRecorderOptions)153); if ((ProfilerRecorderHandle.GetDescription(handle).Flags & MarkerFlags.SampleGPU) != MarkerFlags.Default) { m_RecorderGPU = new ProfilerRecorder(handle, 1, (ProfilerRecorderOptions)217); } } } ~Recorder() { m_RecorderCPU.Dispose(); m_RecorderGPU.Dispose(); } public static Recorder Get(string samplerName) { ProfilerRecorderHandle handle = ProfilerRecorderHandle.Get(ProfilerCategory.Any, samplerName); if (!handle.Valid) { return s_InvalidRecorder; } return new Recorder(handle); } public void FilterToCurrentThread() { if (m_RecorderCPU.Valid) { m_RecorderCPU.FilterToCurrentThread(); } } public void CollectFromAllThreads() { if (m_RecorderCPU.Valid) { m_RecorderCPU.CollectFromAllThreads(); } } private void SetEnabled(bool state) { if (state) { m_RecorderCPU.Start(); if (m_RecorderGPU.Valid) { m_RecorderGPU.Start(); } } else { m_RecorderCPU.Stop(); if (m_RecorderGPU.Valid) { m_RecorderGPU.Stop(); } } } } [NativeHeader("Runtime/Profiler/ScriptBindings/Sampler.bindings.h")] [UsedByNativeCode] public class Sampler { internal IntPtr m_Ptr; internal static Sampler s_InvalidSampler = new Sampler(); public bool isValid => m_Ptr != IntPtr.Zero; public string name => ProfilerUnsafeUtility.Internal_GetName(m_Ptr); internal Sampler() { } internal Sampler(IntPtr ptr) { m_Ptr = ptr; } public Recorder GetRecorder() { ProfilerRecorderHandle handle = new ProfilerRecorderHandle((ulong)m_Ptr.ToInt64()); return new Recorder(handle); } public static Sampler Get(string name) { IntPtr marker = ProfilerUnsafeUtility.GetMarker(name); if (marker == IntPtr.Zero) { return s_InvalidSampler; } return new Sampler(marker); } public static int GetNames(List names) { List list = new List(); ProfilerRecorderHandle.GetAvailable(list); if (names != null) { if (names.Count < list.Count) { names.Capacity = list.Count; for (int i = names.Count; i < list.Count; i++) { names.Add(null); } } int num = 0; foreach (ProfilerRecorderHandle item in list) { names[num] = ProfilerRecorderHandle.GetDescription(item).Name; num++; } } return list.Count; } } [NativeHeader("Runtime/Profiler/Marker.h")] [UsedByNativeCode] [NativeHeader("Runtime/Profiler/ScriptBindings/Sampler.bindings.h")] public sealed class CustomSampler : Sampler { internal static CustomSampler s_InvalidCustomSampler = new CustomSampler(); internal CustomSampler() { } internal CustomSampler(IntPtr ptr) { m_Ptr = ptr; } public static CustomSampler Create(string name, bool collectGpuData = false) { IntPtr intPtr = ProfilerUnsafeUtility.CreateMarker(name, 1, (MarkerFlags)(8 | (collectGpuData ? 256 : 0)), 0); if (intPtr == IntPtr.Zero) { return s_InvalidCustomSampler; } return new CustomSampler(intPtr); } [Conditional("ENABLE_PROFILER")] public void Begin() { ProfilerUnsafeUtility.BeginSample(m_Ptr); } [Conditional("ENABLE_PROFILER")] public void Begin(Object targetObject) { ProfilerUnsafeUtility.Internal_BeginWithObject(m_Ptr, targetObject); } [Conditional("ENABLE_PROFILER")] public void End() { ProfilerUnsafeUtility.EndSample(m_Ptr); } } } namespace UnityEngine.Profiling.Experimental { public struct DebugScreenCapture { public NativeArray rawImageDataReference { get; set; } public TextureFormat imageFormat { get; set; } public int width { get; set; } public int height { get; set; } } } namespace UnityEngine.Profiling.Memory.Experimental { [Flags] public enum CaptureFlags : uint { ManagedObjects = 1u, NativeObjects = 2u, NativeAllocations = 4u, NativeAllocationSites = 8u, NativeStackTraces = 0x10u } public class MetaData { [NonSerialized] public string content; [NonSerialized] public string platform; } [NativeHeader("Modules/Profiler/Runtime/MemorySnapshotManager.h")] public sealed class MemoryProfiler { private static event Action m_SnapshotFinished; private static event Action m_SaveScreenshotToDisk; public static event Action createMetaData; [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeConditional("ENABLE_PROFILER")] [NativeMethod("StartOperation")] private static extern void StartOperation(uint captureFlag, bool requestScreenshot, string path, bool isRemote); public static void TakeSnapshot(string path, Action finishCallback, CaptureFlags captureFlags = CaptureFlags.ManagedObjects | CaptureFlags.NativeObjects) { TakeSnapshot(path, finishCallback, null, captureFlags); } public static void TakeSnapshot(string path, Action finishCallback, Action screenshotCallback, CaptureFlags captureFlags = CaptureFlags.ManagedObjects | CaptureFlags.NativeObjects) { if (MemoryProfiler.m_SnapshotFinished != null) { Debug.LogWarning("Canceling snapshot, there is another snapshot in progress."); finishCallback(path, arg2: false); } else { m_SnapshotFinished += finishCallback; m_SaveScreenshotToDisk += screenshotCallback; StartOperation((uint)captureFlags, MemoryProfiler.m_SaveScreenshotToDisk != null, path, isRemote: false); } } public static void TakeTempSnapshot(Action finishCallback, CaptureFlags captureFlags = CaptureFlags.ManagedObjects | CaptureFlags.NativeObjects) { string text = Application.dataPath.Split(new char[1] { '/' })[^2]; string path = Application.temporaryCachePath + "/" + text + ".snap"; TakeSnapshot(path, finishCallback, captureFlags); } [RequiredByNativeCode] private static byte[] PrepareMetadata() { if (MemoryProfiler.createMetaData == null) { return new byte[0]; } MetaData metaData = new MetaData(); MemoryProfiler.createMetaData(metaData); if (metaData.content == null) { metaData.content = ""; } if (metaData.platform == null) { metaData.platform = ""; } int num = 2 * metaData.content.Length; int num2 = 2 * metaData.platform.Length; int num3 = num + num2 + 12; byte[] array = new byte[num3]; int offset = 0; offset = WriteIntToByteArray(array, offset, metaData.content.Length); offset = WriteStringToByteArray(array, offset, metaData.content); offset = WriteIntToByteArray(array, offset, metaData.platform.Length); offset = WriteStringToByteArray(array, offset, metaData.platform); return array; } internal unsafe static int WriteIntToByteArray(byte[] array, int offset, int value) { byte* ptr = (byte*)(&value); array[offset++] = *ptr; array[offset++] = ptr[1]; array[offset++] = ptr[2]; array[offset++] = ptr[3]; return offset; } internal unsafe static int WriteStringToByteArray(byte[] array, int offset, string value) { if (value.Length != 0) { fixed (char* ptr = value) { char* ptr2 = ptr; for (char* ptr3 = ptr + value.Length; ptr2 != ptr3; ptr2++) { for (int i = 0; i < 2; i++) { array[offset++] = ((byte*)ptr2)[i]; } } } } return offset; } [RequiredByNativeCode] private static void FinalizeSnapshot(string path, bool result) { if (MemoryProfiler.m_SnapshotFinished != null) { Action snapshotFinished = MemoryProfiler.m_SnapshotFinished; MemoryProfiler.m_SnapshotFinished = null; snapshotFinished(path, result); } } [RequiredByNativeCode] private unsafe static void SaveScreenshotToDisk(string path, bool result, IntPtr pixelsPtr, int pixelsCount, TextureFormat format, int width, int height) { if (MemoryProfiler.m_SaveScreenshotToDisk != null) { Action saveScreenshotToDisk = MemoryProfiler.m_SaveScreenshotToDisk; MemoryProfiler.m_SaveScreenshotToDisk = null; DebugScreenCapture arg = default(DebugScreenCapture); if (result) { NativeArray rawImageDataReference = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(pixelsPtr.ToPointer(), pixelsCount, Allocator.Persistent); arg.rawImageDataReference = rawImageDataReference; arg.height = height; arg.width = width; arg.imageFormat = format; } saveScreenshotToDisk(path, result, arg); } } } } namespace UnityEngine.Jobs { [JobProducerType(typeof(IJobParallelForTransformExtensions.TransformParallelForLoopStruct<>))] public interface IJobParallelForTransform { void Execute(int index, TransformAccess transform); } public static class IJobParallelForTransformExtensions { [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct TransformParallelForLoopStruct where T : struct, IJobParallelForTransform { private struct TransformJobData { public IntPtr TransformAccessArray; public int IsReadOnly; } public delegate void ExecuteJobFunction(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); public static IntPtr jobReflectionData; public static IntPtr Initialize() { if (jobReflectionData == IntPtr.Zero) { jobReflectionData = JobsUtility.CreateJobReflectionData(typeof(T), new ExecuteJobFunction(Execute)); } return jobReflectionData; } public unsafe static void Execute(ref T jobData, IntPtr jobData2, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) { UnsafeUtility.CopyPtrToStructure((void*)jobData2, out var output); int* ptr = (int*)(void*)TransformAccessArray.GetSortedToUserIndex(output.TransformAccessArray); TransformAccess* ptr2 = (TransformAccess*)(void*)TransformAccessArray.GetSortedTransformAccess(output.TransformAccessArray); if (output.IsReadOnly == 1) { int beginIndex; int endIndex; while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out beginIndex, out endIndex)) { int num = endIndex; for (int i = beginIndex; i < num; i++) { int num2 = i; int index = ptr[num2]; TransformAccess transform = ptr2[num2]; jobData.Execute(index, transform); } } } else { JobsUtility.GetJobRange(ref ranges, jobIndex, out var beginIndex2, out var endIndex2); for (int j = beginIndex2; j < endIndex2; j++) { int num3 = j; int index2 = ptr[num3]; TransformAccess transform2 = ptr2[num3]; jobData.Execute(index2, transform2); } } } } public unsafe static JobHandle Schedule(this T jobData, TransformAccessArray transforms, JobHandle dependsOn = default(JobHandle)) where T : struct, IJobParallelForTransform { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), TransformParallelForLoopStruct.Initialize(), dependsOn, ScheduleMode.Batched); return JobsUtility.ScheduleParallelForTransform(ref parameters, transforms.GetTransformAccessArrayForSchedule()); } public unsafe static JobHandle ScheduleReadOnly(this T jobData, TransformAccessArray transforms, int batchSize, JobHandle dependsOn = default(JobHandle)) where T : struct, IJobParallelForTransform { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), TransformParallelForLoopStruct.Initialize(), dependsOn, ScheduleMode.Batched); return JobsUtility.ScheduleParallelForTransformReadOnly(ref parameters, transforms.GetTransformAccessArrayForSchedule(), batchSize); } public unsafe static void RunReadOnly(this T jobData, TransformAccessArray transforms) where T : struct, IJobParallelForTransform { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), TransformParallelForLoopStruct.Initialize(), default(JobHandle), ScheduleMode.Run); JobsUtility.ScheduleParallelForTransformReadOnly(ref parameters, transforms.GetTransformAccessArrayForSchedule(), transforms.length); } } [NativeHeader("Runtime/Transform/ScriptBindings/TransformAccess.bindings.h")] public struct TransformAccess { private IntPtr hierarchy; private int index; public Vector3 position { get { GetPosition(ref this, out var p); return p; } set { SetPosition(ref this, ref value); } } public Quaternion rotation { get { GetRotation(ref this, out var r); return r; } set { SetRotation(ref this, ref value); } } public Vector3 localPosition { get { GetLocalPosition(ref this, out var p); return p; } set { SetLocalPosition(ref this, ref value); } } public Quaternion localRotation { get { GetLocalRotation(ref this, out var r); return r; } set { SetLocalRotation(ref this, ref value); } } public Vector3 localScale { get { GetLocalScale(ref this, out var r); return r; } set { SetLocalScale(ref this, ref value); } } public Matrix4x4 localToWorldMatrix { get { GetLocalToWorldMatrix(ref this, out var m); return m; } } public Matrix4x4 worldToLocalMatrix { get { GetWorldToLocalMatrix(ref this, out var m); return m; } } public bool isValid => hierarchy != IntPtr.Zero; public void SetPositionAndRotation(Vector3 position, Quaternion rotation) { SetPositionAndRotation_Internal(ref this, ref position, ref rotation); } public void SetLocalPositionAndRotation(Vector3 localPosition, Quaternion localRotation) { SetLocalPositionAndRotation_Internal(ref this, ref localPosition, ref localRotation); } public void GetPositionAndRotation(out Vector3 position, out Quaternion rotation) { GetPositionAndRotation_Internal(ref this, out position, out rotation); } public void GetLocalPositionAndRotation(out Vector3 localPosition, out Quaternion localRotation) { GetLocalPositionAndRotation_Internal(ref this, out localPosition, out localRotation); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::SetPositionAndRotation", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void SetPositionAndRotation_Internal(ref TransformAccess access, ref Vector3 position, ref Quaternion rotation); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::SetLocalPositionAndRotation", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void SetLocalPositionAndRotation_Internal(ref TransformAccess access, ref Vector3 localPosition, ref Quaternion localRotation); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::GetPositionAndRotation", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void GetPositionAndRotation_Internal(ref TransformAccess access, out Vector3 position, out Quaternion rotation); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::GetLocalPositionAndRotation", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void GetLocalPositionAndRotation_Internal(ref TransformAccess access, out Vector3 localPosition, out Quaternion localRotation); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::GetPosition", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void GetPosition(ref TransformAccess access, out Vector3 p); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::SetPosition", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void SetPosition(ref TransformAccess access, ref Vector3 p); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::GetRotation", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void GetRotation(ref TransformAccess access, out Quaternion r); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::SetRotation", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void SetRotation(ref TransformAccess access, ref Quaternion r); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::GetLocalPosition", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void GetLocalPosition(ref TransformAccess access, out Vector3 p); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::SetLocalPosition", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void SetLocalPosition(ref TransformAccess access, ref Vector3 p); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::GetLocalRotation", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void GetLocalRotation(ref TransformAccess access, out Quaternion r); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::SetLocalRotation", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void SetLocalRotation(ref TransformAccess access, ref Quaternion r); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::GetLocalScale", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void GetLocalScale(ref TransformAccess access, out Vector3 r); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::SetLocalScale", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void SetLocalScale(ref TransformAccess access, ref Vector3 r); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::GetLocalToWorldMatrix", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void GetLocalToWorldMatrix(ref TransformAccess access, out Matrix4x4 m); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessBindings::GetWorldToLocalMatrix", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] private static extern void GetWorldToLocalMatrix(ref TransformAccess access, out Matrix4x4 m); [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] internal void CheckHierarchyValid() { if (!isValid) { throw new NullReferenceException("The TransformAccess is not valid and points to an invalid hierarchy"); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] internal void MarkReadWrite() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] internal void MarkReadOnly() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private void CheckWriteAccess() { } } [NativeType(/*Could not decode attribute arguments.*/)] public struct TransformAccessArray : IDisposable { private IntPtr m_TransformArray; public bool isCreated => m_TransformArray != IntPtr.Zero; public Transform this[int index] { get { return GetTransform(m_TransformArray, index); } set { SetTransform(m_TransformArray, index, value); } } public int capacity { get { return GetCapacity(m_TransformArray); } set { SetCapacity(m_TransformArray, value); } } public int length => GetLength(m_TransformArray); public TransformAccessArray(Transform[] transforms, int desiredJobCount = -1) { Allocate(transforms.Length, desiredJobCount, out this); SetTransforms(m_TransformArray, transforms); } public TransformAccessArray(int capacity, int desiredJobCount = -1) { Allocate(capacity, desiredJobCount, out this); } public static void Allocate(int capacity, int desiredJobCount, out TransformAccessArray array) { array.m_TransformArray = Create(capacity, desiredJobCount); } public void Dispose() { DestroyTransformAccessArray(m_TransformArray); m_TransformArray = IntPtr.Zero; } internal IntPtr GetTransformAccessArrayForSchedule() { return m_TransformArray; } public void Add(Transform transform) { Add(m_TransformArray, transform); } public void RemoveAtSwapBack(int index) { RemoveAtSwapBack(m_TransformArray, index); } public void SetTransforms(Transform[] transforms) { SetTransforms(m_TransformArray, transforms); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessArrayBindings::Create", IsFreeFunction = true)] private static extern IntPtr Create(int capacity, int desiredJobCount); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "DestroyTransformAccessArray", IsFreeFunction = true)] private static extern void DestroyTransformAccessArray(IntPtr transformArray); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessArrayBindings::SetTransforms", IsFreeFunction = true)] private static extern void SetTransforms(IntPtr transformArrayIntPtr, Transform[] transforms); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessArrayBindings::AddTransform", IsFreeFunction = true)] private static extern void Add(IntPtr transformArrayIntPtr, Transform transform); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessArrayBindings::RemoveAtSwapBack", IsFreeFunction = true, ThrowsException = true)] private static extern void RemoveAtSwapBack(IntPtr transformArrayIntPtr, int index); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessArrayBindings::GetSortedTransformAccess", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] internal static extern IntPtr GetSortedTransformAccess(IntPtr transformArrayIntPtr); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessArrayBindings::GetSortedToUserIndex", IsThreadSafe = true, IsFreeFunction = true, ThrowsException = true)] internal static extern IntPtr GetSortedToUserIndex(IntPtr transformArrayIntPtr); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessArrayBindings::GetLength", IsFreeFunction = true)] internal static extern int GetLength(IntPtr transformArrayIntPtr); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessArrayBindings::GetCapacity", IsFreeFunction = true)] internal static extern int GetCapacity(IntPtr transformArrayIntPtr); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessArrayBindings::SetCapacity", IsFreeFunction = true)] internal static extern void SetCapacity(IntPtr transformArrayIntPtr, int capacity); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessArrayBindings::GetTransform", IsFreeFunction = true, ThrowsException = true)] internal static extern Transform GetTransform(IntPtr transformArrayIntPtr, int index); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "TransformAccessArrayBindings::SetTransform", IsFreeFunction = true, ThrowsException = true)] internal static extern void SetTransform(IntPtr transformArrayIntPtr, int index, Transform transform); } } namespace UnityEngine.Windows { public static class CrashReporting { public static extern string crashReportFolder { [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeHeader("PlatformDependent/WinPlayer/Bindings/CrashReportingBindings.h")] get; } } [NativeHeader("PlatformDependent/Win/Bindings/InputBindings.h")] public static class Input { [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeName("ForwardRawInput")] [StaticAccessor(/*Could not decode attribute arguments.*/)] private unsafe static extern void ForwardRawInputImpl(uint* rawInputHeaderIndices, uint* rawInputDataIndices, uint indicesCount, byte* rawInputData, uint rawInputDataSize); public unsafe static void ForwardRawInput(IntPtr rawInputHeaderIndices, IntPtr rawInputDataIndices, uint indicesCount, IntPtr rawInputData, uint rawInputDataSize) { ForwardRawInput((uint*)(void*)rawInputHeaderIndices, (uint*)(void*)rawInputDataIndices, indicesCount, (byte*)(void*)rawInputData, rawInputDataSize); } public unsafe static void ForwardRawInput(uint* rawInputHeaderIndices, uint* rawInputDataIndices, uint indicesCount, byte* rawInputData, uint rawInputDataSize) { if (rawInputHeaderIndices == null) { throw new ArgumentNullException("rawInputHeaderIndices"); } if (rawInputDataIndices == null) { throw new ArgumentNullException("rawInputDataIndices"); } if (rawInputData == null) { throw new ArgumentNullException("rawInputData"); } ForwardRawInputImpl(rawInputHeaderIndices, rawInputDataIndices, indicesCount, rawInputData, rawInputDataSize); } } } namespace UnityEngine.Windows.Speech { public static class PhraseRecognitionSystem { public delegate void ErrorDelegate(SpeechError errorCode); public delegate void StatusDelegate(SpeechSystemStatus status); public static extern bool isSupported { [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] get; } public static extern SpeechSystemStatus Status { [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] get; } public static event ErrorDelegate OnError; public static event StatusDelegate OnStatusChanged; [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] [NativeThrows] public static extern void Restart(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] public static extern void Shutdown(); [RequiredByNativeCode] private static void PhraseRecognitionSystem_InvokeErrorEvent(SpeechError errorCode) { PhraseRecognitionSystem.OnError?.Invoke(errorCode); } [RequiredByNativeCode] private static void PhraseRecognitionSystem_InvokeStatusChangedEvent(SpeechSystemStatus status) { PhraseRecognitionSystem.OnStatusChanged?.Invoke(status); } } public abstract class PhraseRecognizer : IDisposable { public delegate void PhraseRecognizedDelegate(PhraseRecognizedEventArgs args); protected IntPtr m_Recognizer; public bool IsRunning => m_Recognizer != IntPtr.Zero && IsRunning_Internal(m_Recognizer); public event PhraseRecognizedDelegate OnPhraseRecognized; [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] protected static extern IntPtr CreateFromKeywords(object self, [Unmarshalled] string[] keywords, ConfidenceLevel minimumConfidence); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] protected static extern IntPtr CreateFromGrammarFile(object self, string grammarFilePath, ConfidenceLevel minimumConfidence); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] private static extern void Start_Internal(IntPtr recognizer); [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] private static extern void Stop_Internal(IntPtr recognizer); [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] private static extern bool IsRunning_Internal(IntPtr recognizer); [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] private static extern void Destroy(IntPtr recognizer); [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] [ThreadSafe] private static extern void DestroyThreaded(IntPtr recognizer); internal PhraseRecognizer() { } ~PhraseRecognizer() { if (m_Recognizer != IntPtr.Zero) { DestroyThreaded(m_Recognizer); m_Recognizer = IntPtr.Zero; GC.SuppressFinalize(this); } } public void Start() { if (!(m_Recognizer == IntPtr.Zero)) { Start_Internal(m_Recognizer); } } public void Stop() { if (!(m_Recognizer == IntPtr.Zero)) { Stop_Internal(m_Recognizer); } } public void Dispose() { if (m_Recognizer != IntPtr.Zero) { Destroy(m_Recognizer); m_Recognizer = IntPtr.Zero; } GC.SuppressFinalize(this); } [RequiredByNativeCode] private void InvokePhraseRecognizedEvent(string text, ConfidenceLevel confidence, SemanticMeaning[] semanticMeanings, long phraseStartFileTime, long phraseDurationTicks) { this.OnPhraseRecognized?.Invoke(new PhraseRecognizedEventArgs(text, confidence, semanticMeanings, DateTime.FromFileTime(phraseStartFileTime), TimeSpan.FromTicks(phraseDurationTicks))); } [RequiredByNativeCode] private unsafe static SemanticMeaning[] MarshalSemanticMeaning(IntPtr keys, IntPtr values, IntPtr valueSizes, int valueCount) { SemanticMeaning[] array = new SemanticMeaning[valueCount]; int num = 0; for (int i = 0; i < valueCount; i++) { uint num2 = ((uint*)(void*)valueSizes)[i]; SemanticMeaning semanticMeaning = new SemanticMeaning { key = new string(((char**)(void*)keys)[i]), values = new string[num2] }; for (int j = 0; j < num2; j++) { semanticMeaning.values[j] = new string(((char**)(void*)values)[num + j]); } array[i] = semanticMeaning; num += (int)num2; } return array; } } public sealed class DictationRecognizer : IDisposable { public delegate void DictationHypothesisDelegate(string text); public delegate void DictationResultDelegate(string text, ConfidenceLevel confidence); public delegate void DictationCompletedDelegate(DictationCompletionCause cause); public delegate void DictationErrorHandler(string error, int hresult); private IntPtr m_Recognizer; public SpeechSystemStatus Status => (m_Recognizer != IntPtr.Zero) ? GetStatus(m_Recognizer) : SpeechSystemStatus.Stopped; public float AutoSilenceTimeoutSeconds { get { if (m_Recognizer == IntPtr.Zero) { return 0f; } return GetAutoSilenceTimeoutSeconds(m_Recognizer); } set { if (!(m_Recognizer == IntPtr.Zero)) { SetAutoSilenceTimeoutSeconds(m_Recognizer, value); } } } public float InitialSilenceTimeoutSeconds { get { if (m_Recognizer == IntPtr.Zero) { return 0f; } return GetInitialSilenceTimeoutSeconds(m_Recognizer); } set { if (!(m_Recognizer == IntPtr.Zero)) { SetInitialSilenceTimeoutSeconds(m_Recognizer, value); } } } public event DictationHypothesisDelegate DictationHypothesis; public event DictationResultDelegate DictationResult; public event DictationCompletedDelegate DictationComplete; public event DictationErrorHandler DictationError; [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] [NativeThrows] private static extern IntPtr Create(object self, ConfidenceLevel minimumConfidence, DictationTopicConstraint topicConstraint); [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] [NativeThrows] private static extern void Start(IntPtr self); [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] private static extern void Stop(IntPtr self); [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] private static extern void Destroy(IntPtr self); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadSafe] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] private static extern void DestroyThreaded(IntPtr self); [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] private static extern SpeechSystemStatus GetStatus(IntPtr self); [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] private static extern float GetAutoSilenceTimeoutSeconds(IntPtr self); [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] private static extern void SetAutoSilenceTimeoutSeconds(IntPtr self, float value); [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] private static extern float GetInitialSilenceTimeoutSeconds(IntPtr self); [MethodImpl(MethodImplOptions.InternalCall)] [NativeHeader("PlatformDependent/Win/Bindings/SpeechBindings.h")] private static extern void SetInitialSilenceTimeoutSeconds(IntPtr self, float value); public DictationRecognizer() : this(ConfidenceLevel.Medium, DictationTopicConstraint.Dictation) { } public DictationRecognizer(ConfidenceLevel confidenceLevel) : this(confidenceLevel, DictationTopicConstraint.Dictation) { } public DictationRecognizer(DictationTopicConstraint topic) : this(ConfidenceLevel.Medium, topic) { } public DictationRecognizer(ConfidenceLevel minimumConfidence, DictationTopicConstraint topic) { m_Recognizer = Create(this, minimumConfidence, topic); } ~DictationRecognizer() { if (m_Recognizer != IntPtr.Zero) { DestroyThreaded(m_Recognizer); m_Recognizer = IntPtr.Zero; GC.SuppressFinalize(this); } } public void Start() { if (!(m_Recognizer == IntPtr.Zero)) { Start(m_Recognizer); } } public void Stop() { if (!(m_Recognizer == IntPtr.Zero)) { Stop(m_Recognizer); } } public void Dispose() { if (m_Recognizer != IntPtr.Zero) { Destroy(m_Recognizer); m_Recognizer = IntPtr.Zero; } GC.SuppressFinalize(this); } [RequiredByNativeCode] private void DictationRecognizer_InvokeHypothesisGeneratedEvent(string keyword) { this.DictationHypothesis?.Invoke(keyword); } [RequiredByNativeCode] private void DictationRecognizer_InvokeResultGeneratedEvent(string keyword, ConfidenceLevel minimumConfidence) { this.DictationResult?.Invoke(keyword, minimumConfidence); } [RequiredByNativeCode] private void DictationRecognizer_InvokeCompletedEvent(DictationCompletionCause cause) { this.DictationComplete?.Invoke(cause); } [RequiredByNativeCode] private void DictationRecognizer_InvokeErrorEvent(string error, int hresult) { this.DictationError?.Invoke(error, hresult); } } public enum ConfidenceLevel { High, Medium, Low, Rejected } public enum SpeechSystemStatus { Stopped, Running, Failed } public enum SpeechError { NoError, TopicLanguageNotSupported, GrammarLanguageMismatch, GrammarCompilationFailure, AudioQualityFailure, PauseLimitExceeded, TimeoutExceeded, NetworkFailure, MicrophoneUnavailable, UnknownError } public enum DictationTopicConstraint { WebSearch, Form, Dictation } public enum DictationCompletionCause { Complete, AudioQualityFailure, Canceled, TimeoutExceeded, PauseLimitExceeded, NetworkFailure, MicrophoneUnavailable, UnknownError } public struct SemanticMeaning { public string key; public string[] values; } public struct PhraseRecognizedEventArgs { public readonly ConfidenceLevel confidence; public readonly SemanticMeaning[] semanticMeanings; public readonly string text; public readonly DateTime phraseStartTime; public readonly TimeSpan phraseDuration; internal PhraseRecognizedEventArgs(string text, ConfidenceLevel confidence, SemanticMeaning[] semanticMeanings, DateTime phraseStartTime, TimeSpan phraseDuration) { this.text = text; this.confidence = confidence; this.semanticMeanings = semanticMeanings; this.phraseStartTime = phraseStartTime; this.phraseDuration = phraseDuration; } } public sealed class KeywordRecognizer : PhraseRecognizer { public IEnumerable Keywords { get; private set; } public KeywordRecognizer(string[] keywords) : this(keywords, ConfidenceLevel.Medium) { } public KeywordRecognizer(string[] keywords, ConfidenceLevel minimumConfidence) { if (keywords == null) { throw new ArgumentNullException("keywords"); } if (keywords.Length == 0) { throw new ArgumentException("At least one keyword must be specified.", "keywords"); } int num = keywords.Length; for (int i = 0; i < num; i++) { if (keywords[i] == null) { throw new ArgumentNullException($"Keyword at index {i} is null."); } } Keywords = keywords; m_Recognizer = PhraseRecognizer.CreateFromKeywords(this, keywords, minimumConfidence); } } public sealed class GrammarRecognizer : PhraseRecognizer { public string GrammarFilePath { get; private set; } public GrammarRecognizer(string grammarFilePath) : this(grammarFilePath, ConfidenceLevel.Medium) { } public GrammarRecognizer(string grammarFilePath, ConfidenceLevel minimumConfidence) { if (grammarFilePath == null) { throw new ArgumentNullException("grammarFilePath"); } if (grammarFilePath.Length == 0) { throw new ArgumentException("Grammar file path cannot be empty."); } GrammarFilePath = grammarFilePath; m_Recognizer = PhraseRecognizer.CreateFromGrammarFile(this, grammarFilePath, minimumConfidence); } } } namespace UnityEngine.Windows.WebCam { [MovedFrom("UnityEngine.XR.WSA.WebCam")] public enum PhotoCaptureFileOutputFormat { PNG, JPG } [StructLayout(LayoutKind.Sequential)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("PlatformDependent/Win/Webcam/PhotoCapture.h")] [MovedFrom("UnityEngine.XR.WSA.WebCam")] public class PhotoCapture : IDisposable { public enum CaptureResultType { Success, UnknownError } public struct PhotoCaptureResult { public CaptureResultType resultType; public long hResult; public bool success => resultType == CaptureResultType.Success; } public delegate void OnCaptureResourceCreatedCallback(PhotoCapture captureObject); public delegate void OnPhotoModeStartedCallback(PhotoCaptureResult result); public delegate void OnPhotoModeStoppedCallback(PhotoCaptureResult result); public delegate void OnCapturedToDiskCallback(PhotoCaptureResult result); public delegate void OnCapturedToMemoryCallback(PhotoCaptureResult result, PhotoCaptureFrame photoCaptureFrame); internal IntPtr m_NativePtr; private static Resolution[] s_SupportedResolutions; private static readonly long HR_SUCCESS; public static IEnumerable SupportedResolutions { get { if (s_SupportedResolutions == null) { s_SupportedResolutions = GetSupportedResolutions_Internal(); } return s_SupportedResolutions; } } private static PhotoCaptureResult MakeCaptureResult(CaptureResultType resultType, long hResult) { return new PhotoCaptureResult { resultType = resultType, hResult = hResult }; } private static PhotoCaptureResult MakeCaptureResult(long hResult) { PhotoCaptureResult result = default(PhotoCaptureResult); CaptureResultType resultType = ((hResult != HR_SUCCESS) ? CaptureResultType.UnknownError : CaptureResultType.Success); result.resultType = resultType; result.hResult = hResult; return result; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] [NativeName("GetSupportedResolutions")] private static extern Resolution[] GetSupportedResolutions_Internal(); public static void CreateAsync(bool showHolograms, OnCaptureResourceCreatedCallback onCreatedCallback) { if (onCreatedCallback == null) { throw new ArgumentNullException("onCreatedCallback"); } Instantiate_Internal(showHolograms, onCreatedCallback); } public static void CreateAsync(OnCaptureResourceCreatedCallback onCreatedCallback) { if (onCreatedCallback == null) { throw new ArgumentNullException("onCreatedCallback"); } Instantiate_Internal(showHolograms: false, onCreatedCallback); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("Instantiate")] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] private static extern IntPtr Instantiate_Internal(bool showHolograms, OnCaptureResourceCreatedCallback onCreatedCallback); [RequiredByNativeCode] private static void InvokeOnCreatedResourceDelegate(OnCaptureResourceCreatedCallback callback, IntPtr nativePtr) { if (nativePtr == IntPtr.Zero) { callback(null); } else { callback(new PhotoCapture(nativePtr)); } } private PhotoCapture(IntPtr nativeCaptureObject) { m_NativePtr = nativeCaptureObject; } public void StartPhotoModeAsync(CameraParameters setupParams, OnPhotoModeStartedCallback onPhotoModeStartedCallback) { if (onPhotoModeStartedCallback == null) { throw new ArgumentException("onPhotoModeStartedCallback"); } if (setupParams.cameraResolutionWidth == 0 || setupParams.cameraResolutionHeight == 0) { throw new ArgumentOutOfRangeException("setupParams", "The camera resolution must be set to a supported resolution."); } StartPhotoMode_Internal(setupParams, onPhotoModeStartedCallback); } [NativeName("StartPhotoMode")] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] private void StartPhotoMode_Internal(CameraParameters setupParams, OnPhotoModeStartedCallback onPhotoModeStartedCallback) { StartPhotoMode_Internal_Injected(ref setupParams, onPhotoModeStartedCallback); } [RequiredByNativeCode] private static void InvokeOnPhotoModeStartedDelegate(OnPhotoModeStartedCallback callback, long hResult) { callback(MakeCaptureResult(hResult)); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("StopPhotoMode")] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] public extern void StopPhotoModeAsync(OnPhotoModeStoppedCallback onPhotoModeStoppedCallback); [RequiredByNativeCode] private static void InvokeOnPhotoModeStoppedDelegate(OnPhotoModeStoppedCallback callback, long hResult) { callback(MakeCaptureResult(hResult)); } public void TakePhotoAsync(string filename, PhotoCaptureFileOutputFormat fileOutputFormat, OnCapturedToDiskCallback onCapturedPhotoToDiskCallback) { if (onCapturedPhotoToDiskCallback == null) { throw new ArgumentNullException("onCapturedPhotoToDiskCallback"); } if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename"); } filename = filename.Replace("/", "\\"); string directoryName = Path.GetDirectoryName(filename); if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName)) { throw new ArgumentException("The specified directory does not exist.", "filename"); } FileInfo fileInfo = new FileInfo(filename); if (fileInfo.Exists && fileInfo.IsReadOnly) { throw new ArgumentException("Cannot write to the file because it is read-only.", "filename"); } CapturePhotoToDisk_Internal(filename, fileOutputFormat, onCapturedPhotoToDiskCallback); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("CapturePhotoToDisk")] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] private extern void CapturePhotoToDisk_Internal(string filename, PhotoCaptureFileOutputFormat fileOutputFormat, OnCapturedToDiskCallback onCapturedPhotoToDiskCallback); [RequiredByNativeCode] private static void InvokeOnCapturedPhotoToDiskDelegate(OnCapturedToDiskCallback callback, long hResult) { callback(MakeCaptureResult(hResult)); } public void TakePhotoAsync(OnCapturedToMemoryCallback onCapturedPhotoToMemoryCallback) { if (onCapturedPhotoToMemoryCallback == null) { throw new ArgumentNullException("onCapturedPhotoToMemoryCallback"); } CapturePhotoToMemory_Internal(onCapturedPhotoToMemoryCallback); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] [NativeName("CapturePhotoToMemory")] private extern void CapturePhotoToMemory_Internal(OnCapturedToMemoryCallback onCapturedPhotoToMemoryCallback); [RequiredByNativeCode] private static void InvokeOnCapturedPhotoToMemoryDelegate(OnCapturedToMemoryCallback callback, long hResult, IntPtr photoCaptureFramePtr) { PhotoCaptureFrame photoCaptureFrame = null; if (photoCaptureFramePtr != IntPtr.Zero) { photoCaptureFrame = new PhotoCaptureFrame(photoCaptureFramePtr); } callback(MakeCaptureResult(hResult), photoCaptureFrame); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadAndSerializationSafe] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] [NativeName("GetUnsafePointerToVideoDeviceController")] public extern IntPtr GetUnsafePointerToVideoDeviceController(); public void Dispose() { if (m_NativePtr != IntPtr.Zero) { Dispose_Internal(); m_NativePtr = IntPtr.Zero; } GC.SuppressFinalize(this); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("Dispose")] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] private extern void Dispose_Internal(); ~PhotoCapture() { if (m_NativePtr != IntPtr.Zero) { DisposeThreaded_Internal(); m_NativePtr = IntPtr.Zero; } } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadAndSerializationSafe] [NativeName("DisposeThreaded")] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] private extern void DisposeThreaded_Internal(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void StartPhotoMode_Internal_Injected(ref CameraParameters setupParams, OnPhotoModeStartedCallback onPhotoModeStartedCallback); } [NativeHeader("PlatformDependent/Win/Webcam/PhotoCaptureFrame.h")] [MovedFrom("UnityEngine.XR.WSA.WebCam")] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] public sealed class PhotoCaptureFrame : IDisposable { private IntPtr m_NativePtr; public int dataLength { get; private set; } public bool hasLocationData { get; private set; } public CapturePixelFormat pixelFormat { get; private set; } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadAndSerializationSafe] private extern int GetDataLength(); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadAndSerializationSafe] private extern bool GetHasLocationData(); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadAndSerializationSafe] private extern CapturePixelFormat GetCapturePixelFormat(); public bool TryGetCameraToWorldMatrix(out Matrix4x4 cameraToWorldMatrix) { cameraToWorldMatrix = Matrix4x4.identity; if (hasLocationData) { cameraToWorldMatrix = GetCameraToWorldMatrix(); return true; } return false; } [NativeConditional("PLATFORM_WIN && !PLATFORM_XBOXONE", "Matrix4x4f()")] [NativeName("GetCameraToWorld")] [ThreadAndSerializationSafe] private Matrix4x4 GetCameraToWorldMatrix() { GetCameraToWorldMatrix_Injected(out var ret); return ret; } public bool TryGetProjectionMatrix(out Matrix4x4 projectionMatrix) { if (hasLocationData) { projectionMatrix = GetProjection(); return true; } projectionMatrix = Matrix4x4.identity; return false; } public bool TryGetProjectionMatrix(float nearClipPlane, float farClipPlane, out Matrix4x4 projectionMatrix) { if (hasLocationData) { float num = 0.01f; if (nearClipPlane < num) { nearClipPlane = num; } if (farClipPlane < nearClipPlane + num) { farClipPlane = nearClipPlane + num; } projectionMatrix = GetProjection(); float num2 = 1f / (farClipPlane - nearClipPlane); float m = (0f - (farClipPlane + nearClipPlane)) * num2; float m2 = (0f - 2f * farClipPlane * nearClipPlane) * num2; projectionMatrix.m22 = m; projectionMatrix.m23 = m2; return true; } projectionMatrix = Matrix4x4.identity; return false; } [ThreadAndSerializationSafe] [NativeConditional("PLATFORM_WIN && !PLATFORM_XBOXONE", "Matrix4x4f()")] private Matrix4x4 GetProjection() { GetProjection_Injected(out var ret); return ret; } public void UploadImageDataToTexture(Texture2D targetTexture) { if (targetTexture == null) { throw new ArgumentNullException("targetTexture"); } if (pixelFormat != CapturePixelFormat.BGRA32) { throw new ArgumentException("Uploading PhotoCaptureFrame to a texture is only supported with BGRA32 CameraFrameFormat!"); } UploadImageDataToTexture_Internal(targetTexture); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] [ThreadAndSerializationSafe] [NativeName("UploadImageDataToTexture")] private extern void UploadImageDataToTexture_Internal(Texture2D targetTexture); [MethodImpl(MethodImplOptions.InternalCall)] [ThreadAndSerializationSafe] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] public extern IntPtr GetUnsafePointerToBuffer(); public void CopyRawImageDataIntoBuffer(List byteBuffer) { if (byteBuffer == null) { throw new ArgumentNullException("byteBuffer"); } byte[] array = new byte[dataLength]; CopyRawImageDataIntoBuffer_Internal(array); if (byteBuffer.Capacity < array.Length) { byteBuffer.Capacity = array.Length; } byteBuffer.Clear(); byteBuffer.AddRange(array); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] [NativeName("CopyRawImageDataIntoBuffer")] [ThreadAndSerializationSafe] internal extern void CopyRawImageDataIntoBuffer_Internal([Out] byte[] byteArray); internal PhotoCaptureFrame(IntPtr nativePtr) { m_NativePtr = nativePtr; dataLength = GetDataLength(); hasLocationData = GetHasLocationData(); pixelFormat = GetCapturePixelFormat(); GC.AddMemoryPressure(dataLength); } private void Cleanup() { if (m_NativePtr != IntPtr.Zero) { GC.RemoveMemoryPressure(dataLength); Dispose_Internal(); m_NativePtr = IntPtr.Zero; } } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("Dispose")] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] [ThreadAndSerializationSafe] private extern void Dispose_Internal(); public void Dispose() { Cleanup(); GC.SuppressFinalize(this); } ~PhotoCaptureFrame() { Cleanup(); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetCameraToWorldMatrix_Injected(out Matrix4x4 ret); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetProjection_Injected(out Matrix4x4 ret); } [StructLayout(LayoutKind.Sequential)] [NativeHeader("PlatformDependent/Win/Webcam/VideoCaptureBindings.h")] [MovedFrom("UnityEngine.XR.WSA.WebCam")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public class VideoCapture : IDisposable { public enum CaptureResultType { Success, UnknownError } public enum AudioState { MicAudio, ApplicationAudio, ApplicationAndMicAudio, None } public struct VideoCaptureResult { public CaptureResultType resultType; public long hResult; public bool success => resultType == CaptureResultType.Success; } public delegate void OnVideoCaptureResourceCreatedCallback(VideoCapture captureObject); public delegate void OnVideoModeStartedCallback(VideoCaptureResult result); public delegate void OnVideoModeStoppedCallback(VideoCaptureResult result); public delegate void OnStartedRecordingVideoCallback(VideoCaptureResult result); public delegate void OnStoppedRecordingVideoCallback(VideoCaptureResult result); internal IntPtr m_NativePtr; private static Resolution[] s_SupportedResolutions; private static readonly long HR_SUCCESS; public static IEnumerable SupportedResolutions { get { if (s_SupportedResolutions == null) { s_SupportedResolutions = GetSupportedResolutions_Internal(); } return s_SupportedResolutions; } } public extern bool IsRecording { [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] [NativeMethod("VideoCaptureBindings::IsRecording", HasExplicitThis = true)] get; } private static VideoCaptureResult MakeCaptureResult(CaptureResultType resultType, long hResult) { return new VideoCaptureResult { resultType = resultType, hResult = hResult }; } private static VideoCaptureResult MakeCaptureResult(long hResult) { VideoCaptureResult result = default(VideoCaptureResult); CaptureResultType resultType = ((hResult != HR_SUCCESS) ? CaptureResultType.UnknownError : CaptureResultType.Success); result.resultType = resultType; result.hResult = hResult; return result; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] [NativeName("GetSupportedResolutions")] private static extern Resolution[] GetSupportedResolutions_Internal(); public static IEnumerable GetSupportedFrameRatesForResolution(Resolution resolution) { float[] array = null; return GetSupportedFrameRatesForResolution_Internal(resolution.width, resolution.height); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetSupportedFrameRatesForResolution")] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] private static extern float[] GetSupportedFrameRatesForResolution_Internal(int resolutionWidth, int resolutionHeight); public static void CreateAsync(bool showHolograms, OnVideoCaptureResourceCreatedCallback onCreatedCallback) { if (onCreatedCallback == null) { throw new ArgumentNullException("onCreatedCallback"); } Instantiate_Internal(showHolograms, onCreatedCallback); } public static void CreateAsync(OnVideoCaptureResourceCreatedCallback onCreatedCallback) { if (onCreatedCallback == null) { throw new ArgumentNullException("onCreatedCallback"); } Instantiate_Internal(showHolograms: false, onCreatedCallback); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("Instantiate")] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] private static extern void Instantiate_Internal(bool showHolograms, OnVideoCaptureResourceCreatedCallback onCreatedCallback); [RequiredByNativeCode] private static void InvokeOnCreatedVideoCaptureResourceDelegate(OnVideoCaptureResourceCreatedCallback callback, IntPtr nativePtr) { if (nativePtr == IntPtr.Zero) { callback(null); } else { callback(new VideoCapture(nativePtr)); } } private VideoCapture(IntPtr nativeCaptureObject) { m_NativePtr = nativeCaptureObject; } public void StartVideoModeAsync(CameraParameters setupParams, AudioState audioState, OnVideoModeStartedCallback onVideoModeStartedCallback) { if (onVideoModeStartedCallback == null) { throw new ArgumentNullException("onVideoModeStartedCallback"); } if (setupParams.cameraResolutionWidth == 0 || setupParams.cameraResolutionHeight == 0) { throw new ArgumentOutOfRangeException("setupParams", "The camera resolution must be set to a supported resolution."); } if (setupParams.frameRate == 0f) { throw new ArgumentOutOfRangeException("setupParams", "The camera frame rate must be set to a supported recording frame rate."); } StartVideoMode_Internal(setupParams, audioState, onVideoModeStartedCallback); } [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] [NativeMethod("VideoCaptureBindings::StartVideoMode", HasExplicitThis = true)] private void StartVideoMode_Internal(CameraParameters cameraParameters, AudioState audioState, OnVideoModeStartedCallback onVideoModeStartedCallback) { StartVideoMode_Internal_Injected(ref cameraParameters, audioState, onVideoModeStartedCallback); } [RequiredByNativeCode] private static void InvokeOnVideoModeStartedDelegate(OnVideoModeStartedCallback callback, long hResult) { callback(MakeCaptureResult(hResult)); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] [NativeMethod("VideoCaptureBindings::StopVideoMode", HasExplicitThis = true)] public extern void StopVideoModeAsync([NotNull("ArgumentNullException")] OnVideoModeStoppedCallback onVideoModeStoppedCallback); [RequiredByNativeCode] private static void InvokeOnVideoModeStoppedDelegate(OnVideoModeStoppedCallback callback, long hResult) { callback(MakeCaptureResult(hResult)); } public void StartRecordingAsync(string filename, OnStartedRecordingVideoCallback onStartedRecordingVideoCallback) { if (onStartedRecordingVideoCallback == null) { throw new ArgumentNullException("onStartedRecordingVideoCallback"); } if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException("filename"); } string directoryName = Path.GetDirectoryName(filename); if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName)) { throw new ArgumentException("The specified directory does not exist.", "filename"); } FileInfo fileInfo = new FileInfo(filename); if (fileInfo.Exists && fileInfo.IsReadOnly) { throw new ArgumentException("Cannot write to the file because it is read-only.", "filename"); } StartRecordingVideoToDisk_Internal(fileInfo.FullName, onStartedRecordingVideoCallback); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("VideoCaptureBindings::StartRecordingVideoToDisk", HasExplicitThis = true)] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] private extern void StartRecordingVideoToDisk_Internal(string filename, OnStartedRecordingVideoCallback onStartedRecordingVideoCallback); [RequiredByNativeCode] private static void InvokeOnStartedRecordingVideoToDiskDelegate(OnStartedRecordingVideoCallback callback, long hResult) { callback(MakeCaptureResult(hResult)); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("VideoCaptureBindings::StopRecordingVideoToDisk", HasExplicitThis = true)] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] public extern void StopRecordingAsync([NotNull("ArgumentNullException")] OnStoppedRecordingVideoCallback onStoppedRecordingVideoCallback); [RequiredByNativeCode] private static void InvokeOnStoppedRecordingVideoToDiskDelegate(OnStoppedRecordingVideoCallback callback, long hResult) { callback(MakeCaptureResult(hResult)); } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadAndSerializationSafe] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] [NativeMethod("VideoCaptureBindings::GetUnsafePointerToVideoDeviceController", HasExplicitThis = true)] public extern IntPtr GetUnsafePointerToVideoDeviceController(); public void Dispose() { if (m_NativePtr != IntPtr.Zero) { Dispose_Internal(); m_NativePtr = IntPtr.Zero; } GC.SuppressFinalize(this); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("VideoCaptureBindings::Dispose", HasExplicitThis = true)] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] private extern void Dispose_Internal(); ~VideoCapture() { if (m_NativePtr != IntPtr.Zero) { DisposeThreaded_Internal(); m_NativePtr = IntPtr.Zero; } } [MethodImpl(MethodImplOptions.InternalCall)] [ThreadAndSerializationSafe] [NativeMethod("VideoCaptureBindings::DisposeThreaded", HasExplicitThis = true)] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] private extern void DisposeThreaded_Internal(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void StartVideoMode_Internal_Injected(ref CameraParameters cameraParameters, AudioState audioState, OnVideoModeStartedCallback onVideoModeStartedCallback); } [MovedFrom("UnityEngine.XR.WSA.WebCam")] public enum CapturePixelFormat { BGRA32, NV12, JPEG, PNG } [MovedFrom("UnityEngine.XR.WSA.WebCam")] public enum WebCamMode { None, PhotoMode, VideoMode } [MovedFrom("UnityEngine.XR.WSA.WebCam")] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("PlatformDependent/Win/Webcam/WebCam.h")] public class WebCam { public static extern WebCamMode Mode { [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetWebCamMode")] [NativeConditional("(PLATFORM_WIN || PLATFORM_WINRT) && !PLATFORM_XBOXONE")] get; } } [NativeHeader("PlatformDependent/Win/Webcam/CameraParameters.h")] [MovedFrom("UnityEngine.XR.WSA.WebCam")] [UsedByNativeCode] public struct CameraParameters { private float m_HologramOpacity; private float m_FrameRate; private int m_CameraResolutionWidth; private int m_CameraResolutionHeight; private CapturePixelFormat m_PixelFormat; public float hologramOpacity { get { return m_HologramOpacity; } set { m_HologramOpacity = value; } } public float frameRate { get { return m_FrameRate; } set { m_FrameRate = value; } } public int cameraResolutionWidth { get { return m_CameraResolutionWidth; } set { m_CameraResolutionWidth = value; } } public int cameraResolutionHeight { get { return m_CameraResolutionHeight; } set { m_CameraResolutionHeight = value; } } public CapturePixelFormat pixelFormat { get { return m_PixelFormat; } set { m_PixelFormat = value; } } public CameraParameters(WebCamMode webCamMode) { m_HologramOpacity = 1f; m_PixelFormat = CapturePixelFormat.BGRA32; m_FrameRate = 0f; m_CameraResolutionWidth = 0; m_CameraResolutionHeight = 0; switch (webCamMode) { case WebCamMode.PhotoMode: { Resolution resolution2 = PhotoCapture.SupportedResolutions.OrderByDescending((Resolution res) => res.width * res.height).First(); m_CameraResolutionWidth = resolution2.width; m_CameraResolutionHeight = resolution2.height; break; } case WebCamMode.VideoMode: { Resolution resolution = VideoCapture.SupportedResolutions.OrderByDescending((Resolution res) => res.width * res.height).First(); float num = (from fps in VideoCapture.GetSupportedFrameRatesForResolution(resolution) orderby fps descending select fps).First(); m_CameraResolutionWidth = resolution.width; m_CameraResolutionHeight = resolution.height; m_FrameRate = num; break; } } } } } namespace UnityEngine.Events { [Serializable] public enum PersistentListenerMode { EventDefined, Void, Object, Int, Float, String, Bool } internal class UnityEventTools { internal static string TidyAssemblyTypeName(string assemblyTypeName) { if (string.IsNullOrEmpty(assemblyTypeName)) { return assemblyTypeName; } int num = int.MaxValue; int num2 = assemblyTypeName.IndexOf(", Version="); if (num2 != -1) { num = Math.Min(num2, num); } num2 = assemblyTypeName.IndexOf(", Culture="); if (num2 != -1) { num = Math.Min(num2, num); } num2 = assemblyTypeName.IndexOf(", PublicKeyToken="); if (num2 != -1) { num = Math.Min(num2, num); } if (num != int.MaxValue) { assemblyTypeName = assemblyTypeName.Substring(0, num); } num2 = assemblyTypeName.IndexOf(", UnityEngine."); if (num2 != -1 && assemblyTypeName.EndsWith("Module")) { assemblyTypeName = assemblyTypeName.Substring(0, num2) + ", UnityEngine"; } return assemblyTypeName; } } [Serializable] internal class ArgumentCache : ISerializationCallbackReceiver { [SerializeField] [FormerlySerializedAs("objectArgument")] private Object m_ObjectArgument; [FormerlySerializedAs("objectArgumentAssemblyTypeName")] [SerializeField] private string m_ObjectArgumentAssemblyTypeName; [SerializeField] [FormerlySerializedAs("intArgument")] private int m_IntArgument; [SerializeField] [FormerlySerializedAs("floatArgument")] private float m_FloatArgument; [SerializeField] [FormerlySerializedAs("stringArgument")] private string m_StringArgument; [SerializeField] private bool m_BoolArgument; public Object unityObjectArgument { get { return m_ObjectArgument; } set { m_ObjectArgument = value; m_ObjectArgumentAssemblyTypeName = ((value != null) ? value.GetType().AssemblyQualifiedName : string.Empty); } } public string unityObjectArgumentAssemblyTypeName => m_ObjectArgumentAssemblyTypeName; public int intArgument { get { return m_IntArgument; } set { m_IntArgument = value; } } public float floatArgument { get { return m_FloatArgument; } set { m_FloatArgument = value; } } public string stringArgument { get { return m_StringArgument; } set { m_StringArgument = value; } } public bool boolArgument { get { return m_BoolArgument; } set { m_BoolArgument = value; } } public void OnBeforeSerialize() { m_ObjectArgumentAssemblyTypeName = UnityEventTools.TidyAssemblyTypeName(m_ObjectArgumentAssemblyTypeName); } public void OnAfterDeserialize() { m_ObjectArgumentAssemblyTypeName = UnityEventTools.TidyAssemblyTypeName(m_ObjectArgumentAssemblyTypeName); } } internal abstract class BaseInvokableCall { protected BaseInvokableCall() { } protected BaseInvokableCall(object target, MethodInfo function) { if ((object)function == null) { throw new ArgumentNullException("function"); } if (function.IsStatic) { if (target != null) { throw new ArgumentException("target must be null"); } } else if (target == null) { throw new ArgumentNullException("target"); } } public abstract void Invoke(object[] args); protected static void ThrowOnInvalidArg(object arg) { if (arg != null && !(arg is T)) { throw new ArgumentException(UnityString.Format("Passed argument 'args[0]' is of the wrong type. Type:{0} Expected:{1}", new object[2] { arg.GetType(), typeof(T) })); } } protected static bool AllowInvoke(Delegate @delegate) { object target = @delegate.Target; if (target == null) { return true; } if (target is Object obj) { return obj != null; } return true; } public abstract bool Find(object targetObj, MethodInfo method); } internal class InvokableCall : BaseInvokableCall { private event UnityAction Delegate; public InvokableCall(object target, MethodInfo theFunction) : base(target, theFunction) { Delegate += (UnityAction)System.Delegate.CreateDelegate(typeof(UnityAction), target, theFunction); } public InvokableCall(UnityAction action) { Delegate += action; } public override void Invoke(object[] args) { if (BaseInvokableCall.AllowInvoke(this.Delegate)) { this.Delegate(); } } public void Invoke() { if (BaseInvokableCall.AllowInvoke(this.Delegate)) { this.Delegate(); } } public override bool Find(object targetObj, MethodInfo method) { return this.Delegate.Target == targetObj && this.Delegate.Method.Equals(method); } } internal class InvokableCall : BaseInvokableCall { protected event UnityAction Delegate; public InvokableCall(object target, MethodInfo theFunction) : base(target, theFunction) { Delegate += (UnityAction)System.Delegate.CreateDelegate(typeof(UnityAction), target, theFunction); } public InvokableCall(UnityAction action) { Delegate += action; } public override void Invoke(object[] args) { if (args.Length != 1) { throw new ArgumentException("Passed argument 'args' is invalid size. Expected size is 1"); } BaseInvokableCall.ThrowOnInvalidArg(args[0]); if (BaseInvokableCall.AllowInvoke(this.Delegate)) { this.Delegate((T1)args[0]); } } public virtual void Invoke(T1 args0) { if (BaseInvokableCall.AllowInvoke(this.Delegate)) { this.Delegate(args0); } } public override bool Find(object targetObj, MethodInfo method) { return this.Delegate.Target == targetObj && this.Delegate.Method.Equals(method); } } internal class InvokableCall : BaseInvokableCall { protected event UnityAction Delegate; public InvokableCall(object target, MethodInfo theFunction) : base(target, theFunction) { this.Delegate = (UnityAction)System.Delegate.CreateDelegate(typeof(UnityAction), target, theFunction); } public InvokableCall(UnityAction action) { Delegate += action; } public override void Invoke(object[] args) { if (args.Length != 2) { throw new ArgumentException("Passed argument 'args' is invalid size. Expected size is 1"); } BaseInvokableCall.ThrowOnInvalidArg(args[0]); BaseInvokableCall.ThrowOnInvalidArg(args[1]); if (BaseInvokableCall.AllowInvoke(this.Delegate)) { this.Delegate((T1)args[0], (T2)args[1]); } } public void Invoke(T1 args0, T2 args1) { if (BaseInvokableCall.AllowInvoke(this.Delegate)) { this.Delegate(args0, args1); } } public override bool Find(object targetObj, MethodInfo method) { return this.Delegate.Target == targetObj && this.Delegate.Method.Equals(method); } } internal class InvokableCall : BaseInvokableCall { protected event UnityAction Delegate; public InvokableCall(object target, MethodInfo theFunction) : base(target, theFunction) { this.Delegate = (UnityAction)System.Delegate.CreateDelegate(typeof(UnityAction), target, theFunction); } public InvokableCall(UnityAction action) { Delegate += action; } public override void Invoke(object[] args) { if (args.Length != 3) { throw new ArgumentException("Passed argument 'args' is invalid size. Expected size is 1"); } BaseInvokableCall.ThrowOnInvalidArg(args[0]); BaseInvokableCall.ThrowOnInvalidArg(args[1]); BaseInvokableCall.ThrowOnInvalidArg(args[2]); if (BaseInvokableCall.AllowInvoke(this.Delegate)) { this.Delegate((T1)args[0], (T2)args[1], (T3)args[2]); } } public void Invoke(T1 args0, T2 args1, T3 args2) { if (BaseInvokableCall.AllowInvoke(this.Delegate)) { this.Delegate(args0, args1, args2); } } public override bool Find(object targetObj, MethodInfo method) { return this.Delegate.Target == targetObj && this.Delegate.Method.Equals(method); } } internal class InvokableCall : BaseInvokableCall { protected event UnityAction Delegate; public InvokableCall(object target, MethodInfo theFunction) : base(target, theFunction) { this.Delegate = (UnityAction)System.Delegate.CreateDelegate(typeof(UnityAction), target, theFunction); } public InvokableCall(UnityAction action) { Delegate += action; } public override void Invoke(object[] args) { if (args.Length != 4) { throw new ArgumentException("Passed argument 'args' is invalid size. Expected size is 1"); } BaseInvokableCall.ThrowOnInvalidArg(args[0]); BaseInvokableCall.ThrowOnInvalidArg(args[1]); BaseInvokableCall.ThrowOnInvalidArg(args[2]); BaseInvokableCall.ThrowOnInvalidArg(args[3]); if (BaseInvokableCall.AllowInvoke(this.Delegate)) { this.Delegate((T1)args[0], (T2)args[1], (T3)args[2], (T4)args[3]); } } public void Invoke(T1 args0, T2 args1, T3 args2, T4 args3) { if (BaseInvokableCall.AllowInvoke(this.Delegate)) { this.Delegate(args0, args1, args2, args3); } } public override bool Find(object targetObj, MethodInfo method) { return this.Delegate.Target == targetObj && this.Delegate.Method.Equals(method); } } internal class CachedInvokableCall : InvokableCall { private readonly T m_Arg1; public CachedInvokableCall(Object target, MethodInfo theFunction, T argument) : base((object)target, theFunction) { m_Arg1 = argument; } public override void Invoke(object[] args) { base.Invoke(m_Arg1); } public override void Invoke(T arg0) { base.Invoke(m_Arg1); } } public enum UnityEventCallState { Off, EditorAndRuntime, RuntimeOnly } [Serializable] internal class PersistentCall : ISerializationCallbackReceiver { [SerializeField] [FormerlySerializedAs("instance")] private Object m_Target; [SerializeField] private string m_TargetAssemblyTypeName; [FormerlySerializedAs("methodName")] [SerializeField] private string m_MethodName; [FormerlySerializedAs("mode")] [SerializeField] private PersistentListenerMode m_Mode = PersistentListenerMode.EventDefined; [SerializeField] [FormerlySerializedAs("arguments")] private ArgumentCache m_Arguments = new ArgumentCache(); [SerializeField] [FormerlySerializedAs("m_Enabled")] [FormerlySerializedAs("enabled")] private UnityEventCallState m_CallState = UnityEventCallState.RuntimeOnly; public Object target => m_Target; public string targetAssemblyTypeName { get { if (string.IsNullOrEmpty(m_TargetAssemblyTypeName) && m_Target != null) { m_TargetAssemblyTypeName = UnityEventTools.TidyAssemblyTypeName(m_Target.GetType().AssemblyQualifiedName); } return m_TargetAssemblyTypeName; } } public string methodName => m_MethodName; public PersistentListenerMode mode { get { return m_Mode; } set { m_Mode = value; } } public ArgumentCache arguments => m_Arguments; public UnityEventCallState callState { get { return m_CallState; } set { m_CallState = value; } } public bool IsValid() { return !string.IsNullOrEmpty(targetAssemblyTypeName) && !string.IsNullOrEmpty(methodName); } public BaseInvokableCall GetRuntimeCall(UnityEventBase theEvent) { if (m_CallState == UnityEventCallState.Off || theEvent == null) { return null; } MethodInfo methodInfo = theEvent.FindMethod(this); if ((object)methodInfo == null) { return null; } if (!methodInfo.IsStatic && target == null) { return null; } Object obj = (methodInfo.IsStatic ? null : target); return m_Mode switch { PersistentListenerMode.EventDefined => theEvent.GetDelegate(obj, methodInfo), PersistentListenerMode.Object => GetObjectCall(obj, methodInfo, m_Arguments), PersistentListenerMode.Float => new CachedInvokableCall(obj, methodInfo, m_Arguments.floatArgument), PersistentListenerMode.Int => new CachedInvokableCall(obj, methodInfo, m_Arguments.intArgument), PersistentListenerMode.String => new CachedInvokableCall(obj, methodInfo, m_Arguments.stringArgument), PersistentListenerMode.Bool => new CachedInvokableCall(obj, methodInfo, m_Arguments.boolArgument), PersistentListenerMode.Void => new InvokableCall(obj, methodInfo), _ => null, }; } private static BaseInvokableCall GetObjectCall(Object target, MethodInfo method, ArgumentCache arguments) { Type type = typeof(Object); if (!string.IsNullOrEmpty(arguments.unityObjectArgumentAssemblyTypeName)) { type = Type.GetType(arguments.unityObjectArgumentAssemblyTypeName, throwOnError: false) ?? typeof(Object); } Type typeFromHandle = typeof(CachedInvokableCall<>); Type type2 = typeFromHandle.MakeGenericType(type); ConstructorInfo constructor = type2.GetConstructor(new Type[3] { typeof(Object), typeof(MethodInfo), type }); Object obj = arguments.unityObjectArgument; if (obj != null && !type.IsAssignableFrom(obj.GetType())) { obj = null; } return constructor.Invoke(new object[3] { target, method, obj }) as BaseInvokableCall; } public void RegisterPersistentListener(Object ttarget, Type targetType, string mmethodName) { m_Target = ttarget; m_TargetAssemblyTypeName = UnityEventTools.TidyAssemblyTypeName(targetType.AssemblyQualifiedName); m_MethodName = mmethodName; } public void UnregisterPersistentListener() { m_MethodName = string.Empty; m_Target = null; m_TargetAssemblyTypeName = string.Empty; } public void OnBeforeSerialize() { m_TargetAssemblyTypeName = UnityEventTools.TidyAssemblyTypeName(m_TargetAssemblyTypeName); } public void OnAfterDeserialize() { m_TargetAssemblyTypeName = UnityEventTools.TidyAssemblyTypeName(m_TargetAssemblyTypeName); } } [Serializable] internal class PersistentCallGroup { [FormerlySerializedAs("m_Listeners")] [SerializeField] private List m_Calls; public int Count => m_Calls.Count; public PersistentCallGroup() { m_Calls = new List(); } public PersistentCall GetListener(int index) { return m_Calls[index]; } public IEnumerable GetListeners() { return m_Calls; } public void AddListener() { m_Calls.Add(new PersistentCall()); } public void AddListener(PersistentCall call) { m_Calls.Add(call); } public void RemoveListener(int index) { m_Calls.RemoveAt(index); } public void Clear() { m_Calls.Clear(); } public void RegisterEventPersistentListener(int index, Object targetObj, Type targetObjType, string methodName) { PersistentCall listener = GetListener(index); listener.RegisterPersistentListener(targetObj, targetObjType, methodName); listener.mode = PersistentListenerMode.EventDefined; } public void RegisterVoidPersistentListener(int index, Object targetObj, Type targetObjType, string methodName) { PersistentCall listener = GetListener(index); listener.RegisterPersistentListener(targetObj, targetObjType, methodName); listener.mode = PersistentListenerMode.Void; } public void RegisterObjectPersistentListener(int index, Object targetObj, Type targetObjType, Object argument, string methodName) { PersistentCall listener = GetListener(index); listener.RegisterPersistentListener(targetObj, targetObjType, methodName); listener.mode = PersistentListenerMode.Object; listener.arguments.unityObjectArgument = argument; } public void RegisterIntPersistentListener(int index, Object targetObj, Type targetObjType, int argument, string methodName) { PersistentCall listener = GetListener(index); listener.RegisterPersistentListener(targetObj, targetObjType, methodName); listener.mode = PersistentListenerMode.Int; listener.arguments.intArgument = argument; } public void RegisterFloatPersistentListener(int index, Object targetObj, Type targetObjType, float argument, string methodName) { PersistentCall listener = GetListener(index); listener.RegisterPersistentListener(targetObj, targetObjType, methodName); listener.mode = PersistentListenerMode.Float; listener.arguments.floatArgument = argument; } public void RegisterStringPersistentListener(int index, Object targetObj, Type targetObjType, string argument, string methodName) { PersistentCall listener = GetListener(index); listener.RegisterPersistentListener(targetObj, targetObjType, methodName); listener.mode = PersistentListenerMode.String; listener.arguments.stringArgument = argument; } public void RegisterBoolPersistentListener(int index, Object targetObj, Type targetObjType, bool argument, string methodName) { PersistentCall listener = GetListener(index); listener.RegisterPersistentListener(targetObj, targetObjType, methodName); listener.mode = PersistentListenerMode.Bool; listener.arguments.boolArgument = argument; } public void UnregisterPersistentListener(int index) { PersistentCall listener = GetListener(index); listener.UnregisterPersistentListener(); } public void RemoveListeners(Object target, string methodName) { List list = new List(); for (int i = 0; i < m_Calls.Count; i++) { if (m_Calls[i].target == target && m_Calls[i].methodName == methodName) { list.Add(m_Calls[i]); } } m_Calls.RemoveAll(list.Contains); } public void Initialize(InvokableCallList invokableList, UnityEventBase unityEventBase) { foreach (PersistentCall call in m_Calls) { if (call.IsValid()) { BaseInvokableCall runtimeCall = call.GetRuntimeCall(unityEventBase); if (runtimeCall != null) { invokableList.AddPersistentInvokableCall(runtimeCall); } } } } } internal class InvokableCallList { private readonly List m_PersistentCalls = new List(); private readonly List m_RuntimeCalls = new List(); private List m_ExecutingCalls = new List(); private bool m_NeedsUpdate = true; public int Count => m_PersistentCalls.Count + m_RuntimeCalls.Count; public void AddPersistentInvokableCall(BaseInvokableCall call) { m_PersistentCalls.Add(call); m_NeedsUpdate = true; } public void AddListener(BaseInvokableCall call) { m_RuntimeCalls.Add(call); m_NeedsUpdate = true; } public void RemoveListener(object targetObj, MethodInfo method) { List list = new List(); for (int i = 0; i < m_RuntimeCalls.Count; i++) { if (m_RuntimeCalls[i].Find(targetObj, method)) { list.Add(m_RuntimeCalls[i]); } } m_RuntimeCalls.RemoveAll(list.Contains); List list2 = new List(m_PersistentCalls.Count + m_RuntimeCalls.Count); list2.AddRange(m_PersistentCalls); list2.AddRange(m_RuntimeCalls); m_ExecutingCalls = list2; m_NeedsUpdate = false; } public void Clear() { m_RuntimeCalls.Clear(); List executingCalls = new List(m_PersistentCalls); m_ExecutingCalls = executingCalls; m_NeedsUpdate = false; } public void ClearPersistent() { m_PersistentCalls.Clear(); List executingCalls = new List(m_RuntimeCalls); m_ExecutingCalls = executingCalls; m_NeedsUpdate = false; } public List PrepareInvoke() { if (m_NeedsUpdate) { m_ExecutingCalls.Clear(); m_ExecutingCalls.AddRange(m_PersistentCalls); m_ExecutingCalls.AddRange(m_RuntimeCalls); m_NeedsUpdate = false; } return m_ExecutingCalls; } } [Serializable] [UsedByNativeCode] public abstract class UnityEventBase : ISerializationCallbackReceiver { private InvokableCallList m_Calls; [SerializeField] [FormerlySerializedAs("m_PersistentListeners")] private PersistentCallGroup m_PersistentCalls; private bool m_CallsDirty = true; protected UnityEventBase() { m_Calls = new InvokableCallList(); m_PersistentCalls = new PersistentCallGroup(); } void ISerializationCallbackReceiver.OnBeforeSerialize() { DirtyPersistentCalls(); } void ISerializationCallbackReceiver.OnAfterDeserialize() { DirtyPersistentCalls(); } protected MethodInfo FindMethod_Impl(string name, object targetObj) { return FindMethod_Impl(name, targetObj.GetType()); } protected abstract MethodInfo FindMethod_Impl(string name, Type targetObjType); internal abstract BaseInvokableCall GetDelegate(object target, MethodInfo theFunction); internal MethodInfo FindMethod(PersistentCall call) { Type argumentType = typeof(Object); if (!string.IsNullOrEmpty(call.arguments.unityObjectArgumentAssemblyTypeName)) { argumentType = Type.GetType(call.arguments.unityObjectArgumentAssemblyTypeName, throwOnError: false) ?? typeof(Object); } Type listenerType = ((call.target != null) ? call.target.GetType() : Type.GetType(call.targetAssemblyTypeName, throwOnError: false)); return FindMethod(call.methodName, listenerType, call.mode, argumentType); } internal MethodInfo FindMethod(string name, Type listenerType, PersistentListenerMode mode, Type argumentType) { return mode switch { PersistentListenerMode.EventDefined => FindMethod_Impl(name, listenerType), PersistentListenerMode.Void => GetValidMethodInfo(listenerType, name, new Type[0]), PersistentListenerMode.Float => GetValidMethodInfo(listenerType, name, new Type[1] { typeof(float) }), PersistentListenerMode.Int => GetValidMethodInfo(listenerType, name, new Type[1] { typeof(int) }), PersistentListenerMode.Bool => GetValidMethodInfo(listenerType, name, new Type[1] { typeof(bool) }), PersistentListenerMode.String => GetValidMethodInfo(listenerType, name, new Type[1] { typeof(string) }), PersistentListenerMode.Object => GetValidMethodInfo(listenerType, name, new Type[1] { argumentType ?? typeof(Object) }), _ => null, }; } public int GetPersistentEventCount() { return m_PersistentCalls.Count; } public Object GetPersistentTarget(int index) { return m_PersistentCalls.GetListener(index)?.target; } public string GetPersistentMethodName(int index) { PersistentCall listener = m_PersistentCalls.GetListener(index); return (listener != null) ? listener.methodName : string.Empty; } private void DirtyPersistentCalls() { m_Calls.ClearPersistent(); m_CallsDirty = true; } private void RebuildPersistentCallsIfNeeded() { if (m_CallsDirty) { m_PersistentCalls.Initialize(m_Calls, this); m_CallsDirty = false; } } public void SetPersistentListenerState(int index, UnityEventCallState state) { PersistentCall listener = m_PersistentCalls.GetListener(index); if (listener != null) { listener.callState = state; } DirtyPersistentCalls(); } public UnityEventCallState GetPersistentListenerState(int index) { if (index < 0 || index > m_PersistentCalls.Count) { throw new IndexOutOfRangeException($"Index {index} is out of range of the {GetPersistentEventCount()} persistent listeners."); } return m_PersistentCalls.GetListener(index).callState; } protected void AddListener(object targetObj, MethodInfo method) { m_Calls.AddListener(GetDelegate(targetObj, method)); } internal void AddCall(BaseInvokableCall call) { m_Calls.AddListener(call); } protected void RemoveListener(object targetObj, MethodInfo method) { m_Calls.RemoveListener(targetObj, method); } public void RemoveAllListeners() { m_Calls.Clear(); } internal List PrepareInvoke() { RebuildPersistentCallsIfNeeded(); return m_Calls.PrepareInvoke(); } protected void Invoke(object[] parameters) { List list = PrepareInvoke(); for (int i = 0; i < list.Count; i++) { list[i].Invoke(parameters); } } public override string ToString() { return base.ToString() + " " + GetType().FullName; } public static MethodInfo GetValidMethodInfo(object obj, string functionName, Type[] argumentTypes) { return GetValidMethodInfo(obj.GetType(), functionName, argumentTypes); } public static MethodInfo GetValidMethodInfo(Type objectType, string functionName, Type[] argumentTypes) { while ((object)objectType != typeof(object) && (object)objectType != null) { MethodInfo method = objectType.GetMethod(functionName, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, argumentTypes, null); if ((object)method != null) { ParameterInfo[] parameters = method.GetParameters(); bool flag = true; int num = 0; ParameterInfo[] array = parameters; foreach (ParameterInfo parameterInfo in array) { Type type = argumentTypes[num]; Type parameterType = parameterInfo.ParameterType; flag = type.IsPrimitive == parameterType.IsPrimitive; if (!flag) { break; } num++; } if (flag) { return method; } } objectType = objectType.BaseType; } return null; } } public delegate void UnityAction(); [Serializable] public class UnityEvent : UnityEventBase { private object[] m_InvokeArray = null; [RequiredByNativeCode] public UnityEvent() { } public void AddListener(UnityAction call) { AddCall(GetDelegate(call)); } public void RemoveListener(UnityAction call) { RemoveListener(call.Target, call.Method); } protected override MethodInfo FindMethod_Impl(string name, Type targetObjType) { return UnityEventBase.GetValidMethodInfo(targetObjType, name, new Type[0]); } internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) { return new InvokableCall(target, theFunction); } private static BaseInvokableCall GetDelegate(UnityAction action) { return new InvokableCall(action); } public void Invoke() { List list = PrepareInvoke(); for (int i = 0; i < list.Count; i++) { if (list[i] is InvokableCall invokableCall) { invokableCall.Invoke(); continue; } if (list[i] is InvokableCall invokableCall2) { invokableCall2.Invoke(); continue; } BaseInvokableCall baseInvokableCall = list[i]; if (m_InvokeArray == null) { m_InvokeArray = new object[0]; } baseInvokableCall.Invoke(m_InvokeArray); } } } public delegate void UnityAction(T0 arg0); [Serializable] public class UnityEvent : UnityEventBase { private object[] m_InvokeArray = null; [RequiredByNativeCode] public UnityEvent() { } public void AddListener(UnityAction call) { AddCall(GetDelegate(call)); } public void RemoveListener(UnityAction call) { RemoveListener(call.Target, call.Method); } protected override MethodInfo FindMethod_Impl(string name, Type targetObjType) { return UnityEventBase.GetValidMethodInfo(targetObjType, name, new Type[1] { typeof(T0) }); } internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) { return new InvokableCall(target, theFunction); } private static BaseInvokableCall GetDelegate(UnityAction action) { return new InvokableCall(action); } public void Invoke(T0 arg0) { List list = PrepareInvoke(); for (int i = 0; i < list.Count; i++) { if (list[i] is InvokableCall invokableCall) { invokableCall.Invoke(arg0); continue; } if (list[i] is InvokableCall invokableCall2) { invokableCall2.Invoke(); continue; } BaseInvokableCall baseInvokableCall = list[i]; if (m_InvokeArray == null) { m_InvokeArray = new object[1]; } m_InvokeArray[0] = arg0; baseInvokableCall.Invoke(m_InvokeArray); } } } public delegate void UnityAction(T0 arg0, T1 arg1); [Serializable] public class UnityEvent : UnityEventBase { private object[] m_InvokeArray = null; [RequiredByNativeCode] public UnityEvent() { } public void AddListener(UnityAction call) { AddCall(GetDelegate(call)); } public void RemoveListener(UnityAction call) { RemoveListener(call.Target, call.Method); } protected override MethodInfo FindMethod_Impl(string name, Type targetObjType) { return UnityEventBase.GetValidMethodInfo(targetObjType, name, new Type[2] { typeof(T0), typeof(T1) }); } internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) { return new InvokableCall(target, theFunction); } private static BaseInvokableCall GetDelegate(UnityAction action) { return new InvokableCall(action); } public void Invoke(T0 arg0, T1 arg1) { List list = PrepareInvoke(); for (int i = 0; i < list.Count; i++) { if (list[i] is InvokableCall invokableCall) { invokableCall.Invoke(arg0, arg1); continue; } if (list[i] is InvokableCall invokableCall2) { invokableCall2.Invoke(); continue; } BaseInvokableCall baseInvokableCall = list[i]; if (m_InvokeArray == null) { m_InvokeArray = new object[2]; } m_InvokeArray[0] = arg0; m_InvokeArray[1] = arg1; baseInvokableCall.Invoke(m_InvokeArray); } } } public delegate void UnityAction(T0 arg0, T1 arg1, T2 arg2); [Serializable] public class UnityEvent : UnityEventBase { private object[] m_InvokeArray = null; [RequiredByNativeCode] public UnityEvent() { } public void AddListener(UnityAction call) { AddCall(GetDelegate(call)); } public void RemoveListener(UnityAction call) { RemoveListener(call.Target, call.Method); } protected override MethodInfo FindMethod_Impl(string name, Type targetObjType) { return UnityEventBase.GetValidMethodInfo(targetObjType, name, new Type[3] { typeof(T0), typeof(T1), typeof(T2) }); } internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) { return new InvokableCall(target, theFunction); } private static BaseInvokableCall GetDelegate(UnityAction action) { return new InvokableCall(action); } public void Invoke(T0 arg0, T1 arg1, T2 arg2) { List list = PrepareInvoke(); for (int i = 0; i < list.Count; i++) { if (list[i] is InvokableCall invokableCall) { invokableCall.Invoke(arg0, arg1, arg2); continue; } if (list[i] is InvokableCall invokableCall2) { invokableCall2.Invoke(); continue; } BaseInvokableCall baseInvokableCall = list[i]; if (m_InvokeArray == null) { m_InvokeArray = new object[3]; } m_InvokeArray[0] = arg0; m_InvokeArray[1] = arg1; m_InvokeArray[2] = arg2; baseInvokableCall.Invoke(m_InvokeArray); } } } public delegate void UnityAction(T0 arg0, T1 arg1, T2 arg2, T3 arg3); [Serializable] public class UnityEvent : UnityEventBase { private object[] m_InvokeArray = null; [RequiredByNativeCode] public UnityEvent() { } public void AddListener(UnityAction call) { AddCall(GetDelegate(call)); } public void RemoveListener(UnityAction call) { RemoveListener(call.Target, call.Method); } protected override MethodInfo FindMethod_Impl(string name, Type targetObjType) { return UnityEventBase.GetValidMethodInfo(targetObjType, name, new Type[4] { typeof(T0), typeof(T1), typeof(T2), typeof(T3) }); } internal override BaseInvokableCall GetDelegate(object target, MethodInfo theFunction) { return new InvokableCall(target, theFunction); } private static BaseInvokableCall GetDelegate(UnityAction action) { return new InvokableCall(action); } public void Invoke(T0 arg0, T1 arg1, T2 arg2, T3 arg3) { List list = PrepareInvoke(); for (int i = 0; i < list.Count; i++) { if (list[i] is InvokableCall invokableCall) { invokableCall.Invoke(arg0, arg1, arg2, arg3); continue; } if (list[i] is InvokableCall invokableCall2) { invokableCall2.Invoke(); continue; } BaseInvokableCall baseInvokableCall = list[i]; if (m_InvokeArray == null) { m_InvokeArray = new object[4]; } m_InvokeArray[0] = arg0; m_InvokeArray[1] = arg1; m_InvokeArray[2] = arg2; m_InvokeArray[3] = arg3; baseInvokableCall.Invoke(m_InvokeArray); } } } } namespace UnityEngine.Serialization { [RequiredByNativeCode] [AttributeUsage(AttributeTargets.Field, AllowMultiple = true, Inherited = false)] public class FormerlySerializedAsAttribute : Attribute { private string m_oldName; public string oldName => m_oldName; public FormerlySerializedAsAttribute(string oldName) { m_oldName = oldName; } } public class UnitySurrogateSelector : ISurrogateSelector { public ISerializationSurrogate GetSurrogate(Type type, StreamingContext context, out ISurrogateSelector selector) { if (type.IsGenericType) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if ((object)genericTypeDefinition == typeof(List<>)) { selector = this; return ListSerializationSurrogate.Default; } if ((object)genericTypeDefinition == typeof(Dictionary<, >)) { selector = this; Type type2 = typeof(DictionarySerializationSurrogate<, >).MakeGenericType(type.GetGenericArguments()); return (ISerializationSurrogate)Activator.CreateInstance(type2); } } selector = null; return null; } public void ChainSelector(ISurrogateSelector selector) { throw new NotImplementedException(); } public ISurrogateSelector GetNextSelector() { throw new NotImplementedException(); } } internal class ListSerializationSurrogate : ISerializationSurrogate { public static readonly ISerializationSurrogate Default = new ListSerializationSurrogate(); public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) { IList list = (IList)obj; info.AddValue("_size", list.Count); info.AddValue("_items", ArrayFromGenericList(list)); info.AddValue("_version", 0); } public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { IList list = (IList)Activator.CreateInstance(obj.GetType()); int @int = info.GetInt32("_size"); if (@int == 0) { return list; } IEnumerator enumerator = ((IEnumerable)info.GetValue("_items", typeof(IEnumerable))).GetEnumerator(); for (int i = 0; i < @int; i++) { if (!enumerator.MoveNext()) { throw new InvalidOperationException(); } list.Add(enumerator.Current); } return list; } private static Array ArrayFromGenericList(IList list) { Array array = Array.CreateInstance(list.GetType().GetGenericArguments()[0], list.Count); list.CopyTo(array, 0); return array; } } internal class DictionarySerializationSurrogate : ISerializationSurrogate { public void GetObjectData(object obj, SerializationInfo info, StreamingContext context) { Dictionary dictionary = (Dictionary)obj; dictionary.GetObjectData(info, context); } public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector) { IEqualityComparer comparer = (IEqualityComparer)info.GetValue("Comparer", typeof(IEqualityComparer)); Dictionary dictionary = new Dictionary(comparer); if (info.MemberCount > 3) { KeyValuePair[] array = (KeyValuePair[])info.GetValue("KeyValuePairs", typeof(KeyValuePair[])); if (array != null) { KeyValuePair[] array2 = array; for (int i = 0; i < array2.Length; i++) { KeyValuePair keyValuePair = array2[i]; dictionary.Add(keyValuePair.Key, keyValuePair.Value); } } } return dictionary; } } } namespace UnityEngine.Search { [Flags] public enum SearchViewFlags { None = 0, Debug = 0x10, NoIndexing = 0x20, Packages = 0x100, OpenLeftSidePanel = 0x800, OpenInspectorPreview = 0x1000, Centered = 0x2000, HideSearchBar = 0x4000, CompactView = 0x8000, ListView = 0x10000, GridView = 0x20000, TableView = 0x40000, EnableSearchQuery = 0x80000, DisableInspectorPreview = 0x100000, DisableSavedSearchQuery = 0x200000, OpenInBuilderMode = 0x400000, OpenInTextMode = 0x800000, DisableBuilderModeToggle = 0x1000000, Borderless = 0x2000000 } [AttributeUsage(AttributeTargets.Field)] public class SearchContextAttribute : PropertyAttribute { public string query { get; private set; } public string[] providerIds { get; private set; } public Type[] instantiableProviders { get; private set; } public SearchViewFlags flags { get; private set; } public SearchContextAttribute(string query) : this(query, null, SearchViewFlags.None) { } public SearchContextAttribute(string query, SearchViewFlags flags) : this(query, null, flags) { } public SearchContextAttribute(string query, string providerIdsCommaSeparated) : this(query, providerIdsCommaSeparated, SearchViewFlags.None) { } public SearchContextAttribute(string query, string providerIdsCommaSeparated, SearchViewFlags flags) : this(query, flags, providerIdsCommaSeparated, (Type[])null) { } public SearchContextAttribute(string query, params Type[] instantiableProviders) : this(query, SearchViewFlags.None, null, instantiableProviders) { } public SearchContextAttribute(string query, SearchViewFlags flags, params Type[] instantiableProviders) : this(query, flags, null, instantiableProviders) { } public SearchContextAttribute(string query, SearchViewFlags flags, string providerIdsCommaSeparated, params Type[] instantiableProviders) { this.query = ((string.IsNullOrEmpty(query) || query.EndsWith(" ")) ? query : (query + " ")); providerIds = providerIdsCommaSeparated?.Split(',', ';') ?? new string[0]; this.instantiableProviders = instantiableProviders ?? new Type[0]; this.flags = flags; } } } namespace UnityEngine.SearchService { [Obsolete("ObjectSelectorHandlerWithLabelsAttribute has been deprecated. Use SearchContextAttribute instead.")] [AttributeUsage(AttributeTargets.Field)] public class ObjectSelectorHandlerWithLabelsAttribute : Attribute { public string[] labels { get; } public bool matchAll { get; } public ObjectSelectorHandlerWithLabelsAttribute(params string[] labels) { this.labels = labels; matchAll = true; } public ObjectSelectorHandlerWithLabelsAttribute(bool matchAll, params string[] labels) { this.labels = labels; this.matchAll = matchAll; } } [AttributeUsage(AttributeTargets.Field)] [Obsolete("ObjectSelectorHandlerWithTagsAttribute has been deprecated. Use SearchContextAttribute instead.")] public class ObjectSelectorHandlerWithTagsAttribute : Attribute { public string[] tags { get; } public ObjectSelectorHandlerWithTagsAttribute(params string[] tags) { this.tags = tags; } } } namespace UnityEngine.Scripting { [AttributeUsage(AttributeTargets.Assembly)] public class AlwaysLinkAssemblyAttribute : Attribute { } [NativeHeader("Runtime/Scripting/GarbageCollector.h")] public static class GarbageCollector { public enum Mode { Disabled, Enabled, Manual } public static Mode GCMode { get { return GetMode(); } set { if (value != GetMode()) { SetMode(value); if (GarbageCollector.GCModeChanged != null) { GarbageCollector.GCModeChanged(value); } } } } public static extern bool isIncremental { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetIncrementalEnabled")] get; } public static extern ulong incrementalTimeSliceNanoseconds { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static event Action GCModeChanged; [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern void SetMode(Mode mode); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Mode GetMode(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] [NativeMethod("CollectIncrementalWrapper")] public static extern bool CollectIncremental(ulong nanoseconds = 0uL); } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] [RequiredByNativeCode] public class PreserveAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class RequireAttributeUsagesAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class RequireDerivedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = true)] public class RequiredInterfaceAttribute : Attribute { public RequiredInterfaceAttribute(Type interfaceType) { } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event)] public class RequiredMemberAttribute : Attribute { } [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false)] public class RequireImplementorsAttribute : Attribute { } } namespace UnityEngine.Scripting.APIUpdating { internal struct MovedFromAttributeData { public string className; public string nameSpace; public string assembly; public bool classHasChanged; public bool nameSpaceHasChanged; public bool assemblyHasChanged; public bool autoUdpateAPI; public void Set(bool autoUpdateAPI, string sourceNamespace = null, string sourceAssembly = null, string sourceClassName = null) { className = sourceClassName; classHasChanged = className != null; nameSpace = sourceNamespace; nameSpaceHasChanged = nameSpace != null; assembly = sourceAssembly; assemblyHasChanged = assembly != null; autoUdpateAPI = autoUpdateAPI; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate)] public class MovedFromAttribute : Attribute { internal MovedFromAttributeData data; internal bool AffectsAPIUpdater => !data.classHasChanged && !data.assemblyHasChanged; public bool IsInDifferentAssembly => data.assemblyHasChanged; public MovedFromAttribute(bool autoUpdateAPI, string sourceNamespace = null, string sourceAssembly = null, string sourceClassName = null) { data.Set(autoUpdateAPI, sourceNamespace, sourceAssembly, sourceClassName); } public MovedFromAttribute(string sourceNamespace) { data.Set(autoUpdateAPI: true, sourceNamespace); } } } namespace UnityEngine.SceneManagement { [Serializable] [NativeHeader("Runtime/Export/SceneManager/Scene.bindings.h")] public struct Scene { internal enum LoadingState { NotLoaded, Loading, Loaded, Unloading } [HideInInspector] [SerializeField] private int m_Handle; public int handle => m_Handle; internal LoadingState loadingState => GetLoadingStateInternal(handle); internal string guid => GetGUIDInternal(handle); public string path => GetPathInternal(handle); public string name { get { return GetNameInternal(handle); } set { SetNameInternal(handle, value); } } public bool isLoaded => GetIsLoadedInternal(handle); public int buildIndex => GetBuildIndexInternal(handle); public bool isDirty => GetIsDirtyInternal(handle); internal int dirtyID => GetDirtyID(handle); public int rootCount => GetRootCountInternal(handle); public bool isSubScene { get { return IsSubScene(handle); } set { SetIsSubScene(handle, value); } } [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern bool IsValidInternal(int sceneHandle); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern string GetPathInternal(int sceneHandle); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern string GetNameInternal(int sceneHandle); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeThrows] private static extern void SetNameInternal(int sceneHandle, string name); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern string GetGUIDInternal(int sceneHandle); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern bool IsSubScene(int sceneHandle); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern void SetIsSubScene(int sceneHandle, bool value); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern bool GetIsLoadedInternal(int sceneHandle); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern LoadingState GetLoadingStateInternal(int sceneHandle); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern bool GetIsDirtyInternal(int sceneHandle); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern int GetDirtyID(int sceneHandle); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern int GetBuildIndexInternal(int sceneHandle); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern int GetRootCountInternal(int sceneHandle); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern void GetRootGameObjectsInternal(int sceneHandle, object resultRootList); internal Scene(int handle) { m_Handle = handle; } public bool IsValid() { return IsValidInternal(handle); } public GameObject[] GetRootGameObjects() { List list = new List(rootCount); GetRootGameObjects(list); return list.ToArray(); } public void GetRootGameObjects(List rootGameObjects) { if (rootGameObjects.Capacity < rootCount) { rootGameObjects.Capacity = rootCount; } rootGameObjects.Clear(); if (!IsValid()) { throw new ArgumentException("The scene is invalid."); } if (!Application.isPlaying && !isLoaded) { throw new ArgumentException("The scene is not loaded."); } if (rootCount != 0) { GetRootGameObjectsInternal(handle, rootGameObjects); } } public static bool operator ==(Scene lhs, Scene rhs) { return lhs.handle == rhs.handle; } public static bool operator !=(Scene lhs, Scene rhs) { return lhs.handle != rhs.handle; } public override int GetHashCode() { return m_Handle; } public override bool Equals(object other) { if (!(other is Scene scene)) { return false; } return handle == scene.handle; } } [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("Runtime/Export/SceneManager/SceneManager.bindings.h")] [NativeHeader("Runtime/SceneManager/SceneManager.h")] internal static class SceneManagerAPIInternal { [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetNumScenesInBuildSettings(); [NativeThrows] public static Scene GetSceneByBuildIndex(int buildIndex) { GetSceneByBuildIndex_Injected(buildIndex, out var ret); return ret; } [NativeThrows] public static AsyncOperation LoadSceneAsyncNameIndexInternal(string sceneName, int sceneBuildIndex, LoadSceneParameters parameters, bool mustCompleteNextFrame) { return LoadSceneAsyncNameIndexInternal_Injected(sceneName, sceneBuildIndex, ref parameters, mustCompleteNextFrame); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] public static extern AsyncOperation UnloadSceneNameIndexInternal(string sceneName, int sceneBuildIndex, bool immediately, UnloadSceneOptions options, out bool outSuccess); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetSceneByBuildIndex_Injected(int buildIndex, out Scene ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern AsyncOperation LoadSceneAsyncNameIndexInternal_Injected(string sceneName, int sceneBuildIndex, ref LoadSceneParameters parameters, bool mustCompleteNextFrame); } public class SceneManagerAPI { private static SceneManagerAPI s_DefaultAPI = new SceneManagerAPI(); internal static SceneManagerAPI ActiveAPI => overrideAPI ?? s_DefaultAPI; public static SceneManagerAPI overrideAPI { get; set; } protected internal SceneManagerAPI() { } protected internal virtual int GetNumScenesInBuildSettings() { return SceneManagerAPIInternal.GetNumScenesInBuildSettings(); } protected internal virtual Scene GetSceneByBuildIndex(int buildIndex) { return SceneManagerAPIInternal.GetSceneByBuildIndex(buildIndex); } protected internal virtual AsyncOperation LoadSceneAsyncByNameOrIndex(string sceneName, int sceneBuildIndex, LoadSceneParameters parameters, bool mustCompleteNextFrame) { return SceneManagerAPIInternal.LoadSceneAsyncNameIndexInternal(sceneName, sceneBuildIndex, parameters, mustCompleteNextFrame); } protected internal virtual AsyncOperation UnloadSceneAsyncByNameOrIndex(string sceneName, int sceneBuildIndex, bool immediately, UnloadSceneOptions options, out bool outSuccess) { return SceneManagerAPIInternal.UnloadSceneNameIndexInternal(sceneName, sceneBuildIndex, immediately, options, out outSuccess); } protected internal virtual AsyncOperation LoadFirstScene(bool mustLoadAsync) { return null; } } [NativeHeader("Runtime/Export/SceneManager/SceneManager.bindings.h")] [RequiredByNativeCode] public class SceneManager { internal static bool s_AllowLoadScene = true; public static extern int sceneCount { [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeMethod("GetSceneCount")] [NativeHeader("Runtime/SceneManager/SceneManager.h")] get; } public static int sceneCountInBuildSettings => SceneManagerAPI.ActiveAPI.GetNumScenesInBuildSettings(); public static event UnityAction sceneLoaded; public static event UnityAction sceneUnloaded; public static event UnityAction activeSceneChanged; [StaticAccessor(/*Could not decode attribute arguments.*/)] public static Scene GetActiveScene() { GetActiveScene_Injected(out var ret); return ret; } [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeThrows] public static bool SetActiveScene(Scene scene) { return SetActiveScene_Injected(ref scene); } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static Scene GetSceneByPath(string scenePath) { GetSceneByPath_Injected(scenePath, out var ret); return ret; } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static Scene GetSceneByName(string name) { GetSceneByName_Injected(name, out var ret); return ret; } public static Scene GetSceneByBuildIndex(int buildIndex) { return SceneManagerAPI.ActiveAPI.GetSceneByBuildIndex(buildIndex); } [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeThrows] public static Scene GetSceneAt(int index) { GetSceneAt_Injected(index, out var ret); return ret; } [NativeThrows] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static Scene CreateScene([NotNull("ArgumentNullException")] string sceneName, CreateSceneParameters parameters) { CreateScene_Injected(sceneName, ref parameters, out var ret); return ret; } [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeThrows] private static bool UnloadSceneInternal(Scene scene, UnloadSceneOptions options) { return UnloadSceneInternal_Injected(ref scene, options); } [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeThrows] private static AsyncOperation UnloadSceneAsyncInternal(Scene scene, UnloadSceneOptions options) { return UnloadSceneAsyncInternal_Injected(ref scene, options); } private static AsyncOperation LoadSceneAsyncNameIndexInternal(string sceneName, int sceneBuildIndex, LoadSceneParameters parameters, bool mustCompleteNextFrame) { if (!s_AllowLoadScene) { return null; } return SceneManagerAPI.ActiveAPI.LoadSceneAsyncByNameOrIndex(sceneName, sceneBuildIndex, parameters, mustCompleteNextFrame); } private static AsyncOperation UnloadSceneNameIndexInternal(string sceneName, int sceneBuildIndex, bool immediately, UnloadSceneOptions options, out bool outSuccess) { if (!s_AllowLoadScene) { outSuccess = false; return null; } return SceneManagerAPI.ActiveAPI.UnloadSceneAsyncByNameOrIndex(sceneName, sceneBuildIndex, immediately, options, out outSuccess); } [NativeThrows] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static void MergeScenes(Scene sourceScene, Scene destinationScene) { MergeScenes_Injected(ref sourceScene, ref destinationScene); } [NativeThrows] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static void MoveGameObjectToScene([NotNull("ArgumentNullException")] GameObject go, Scene scene) { MoveGameObjectToScene_Injected(go, ref scene); } [RequiredByNativeCode] internal static AsyncOperation LoadFirstScene_Internal(bool async) { return SceneManagerAPI.ActiveAPI.LoadFirstScene(async); } [Obsolete("Use SceneManager.sceneCount and SceneManager.GetSceneAt(int index) to loop the all scenes instead.")] public static Scene[] GetAllScenes() { Scene[] array = new Scene[sceneCount]; for (int i = 0; i < sceneCount; i++) { array[i] = GetSceneAt(i); } return array; } public static Scene CreateScene(string sceneName) { CreateSceneParameters parameters = new CreateSceneParameters(LocalPhysicsMode.None); return CreateScene(sceneName, parameters); } public static void LoadScene(string sceneName, [UnityEngine.Internal.DefaultValue("LoadSceneMode.Single")] LoadSceneMode mode) { LoadSceneParameters parameters = new LoadSceneParameters(mode); LoadScene(sceneName, parameters); } [ExcludeFromDocs] public static void LoadScene(string sceneName) { LoadSceneParameters parameters = new LoadSceneParameters(LoadSceneMode.Single); LoadScene(sceneName, parameters); } public static Scene LoadScene(string sceneName, LoadSceneParameters parameters) { LoadSceneAsyncNameIndexInternal(sceneName, -1, parameters, mustCompleteNextFrame: true); return GetSceneAt(sceneCount - 1); } public static void LoadScene(int sceneBuildIndex, [UnityEngine.Internal.DefaultValue("LoadSceneMode.Single")] LoadSceneMode mode) { LoadSceneParameters parameters = new LoadSceneParameters(mode); LoadScene(sceneBuildIndex, parameters); } [ExcludeFromDocs] public static void LoadScene(int sceneBuildIndex) { LoadSceneParameters parameters = new LoadSceneParameters(LoadSceneMode.Single); LoadScene(sceneBuildIndex, parameters); } public static Scene LoadScene(int sceneBuildIndex, LoadSceneParameters parameters) { LoadSceneAsyncNameIndexInternal(null, sceneBuildIndex, parameters, mustCompleteNextFrame: true); return GetSceneAt(sceneCount - 1); } public static AsyncOperation LoadSceneAsync(int sceneBuildIndex, [UnityEngine.Internal.DefaultValue("LoadSceneMode.Single")] LoadSceneMode mode) { LoadSceneParameters parameters = new LoadSceneParameters(mode); return LoadSceneAsync(sceneBuildIndex, parameters); } [ExcludeFromDocs] public static AsyncOperation LoadSceneAsync(int sceneBuildIndex) { LoadSceneParameters parameters = new LoadSceneParameters(LoadSceneMode.Single); return LoadSceneAsync(sceneBuildIndex, parameters); } public static AsyncOperation LoadSceneAsync(int sceneBuildIndex, LoadSceneParameters parameters) { return LoadSceneAsyncNameIndexInternal(null, sceneBuildIndex, parameters, mustCompleteNextFrame: false); } public static AsyncOperation LoadSceneAsync(string sceneName, [UnityEngine.Internal.DefaultValue("LoadSceneMode.Single")] LoadSceneMode mode) { LoadSceneParameters parameters = new LoadSceneParameters(mode); return LoadSceneAsync(sceneName, parameters); } [ExcludeFromDocs] public static AsyncOperation LoadSceneAsync(string sceneName) { LoadSceneParameters parameters = new LoadSceneParameters(LoadSceneMode.Single); return LoadSceneAsync(sceneName, parameters); } public static AsyncOperation LoadSceneAsync(string sceneName, LoadSceneParameters parameters) { return LoadSceneAsyncNameIndexInternal(sceneName, -1, parameters, mustCompleteNextFrame: false); } [Obsolete("Use SceneManager.UnloadSceneAsync. This function is not safe to use during triggers and under other circumstances. See Scripting reference for more details.")] public static bool UnloadScene(Scene scene) { return UnloadSceneInternal(scene, UnloadSceneOptions.None); } [Obsolete("Use SceneManager.UnloadSceneAsync. This function is not safe to use during triggers and under other circumstances. See Scripting reference for more details.")] public static bool UnloadScene(int sceneBuildIndex) { UnloadSceneNameIndexInternal("", sceneBuildIndex, immediately: true, UnloadSceneOptions.None, out var outSuccess); return outSuccess; } [Obsolete("Use SceneManager.UnloadSceneAsync. This function is not safe to use during triggers and under other circumstances. See Scripting reference for more details.")] public static bool UnloadScene(string sceneName) { UnloadSceneNameIndexInternal(sceneName, -1, immediately: true, UnloadSceneOptions.None, out var outSuccess); return outSuccess; } public static AsyncOperation UnloadSceneAsync(int sceneBuildIndex) { bool outSuccess; return UnloadSceneNameIndexInternal("", sceneBuildIndex, immediately: false, UnloadSceneOptions.None, out outSuccess); } public static AsyncOperation UnloadSceneAsync(string sceneName) { bool outSuccess; return UnloadSceneNameIndexInternal(sceneName, -1, immediately: false, UnloadSceneOptions.None, out outSuccess); } public static AsyncOperation UnloadSceneAsync(Scene scene) { return UnloadSceneAsyncInternal(scene, UnloadSceneOptions.None); } public static AsyncOperation UnloadSceneAsync(int sceneBuildIndex, UnloadSceneOptions options) { bool outSuccess; return UnloadSceneNameIndexInternal("", sceneBuildIndex, immediately: false, options, out outSuccess); } public static AsyncOperation UnloadSceneAsync(string sceneName, UnloadSceneOptions options) { bool outSuccess; return UnloadSceneNameIndexInternal(sceneName, -1, immediately: false, options, out outSuccess); } public static AsyncOperation UnloadSceneAsync(Scene scene, UnloadSceneOptions options) { return UnloadSceneAsyncInternal(scene, options); } [RequiredByNativeCode] private static void Internal_SceneLoaded(Scene scene, LoadSceneMode mode) { if (SceneManager.sceneLoaded != null) { SceneManager.sceneLoaded(scene, mode); } } [RequiredByNativeCode] private static void Internal_SceneUnloaded(Scene scene) { if (SceneManager.sceneUnloaded != null) { SceneManager.sceneUnloaded(scene); } } [RequiredByNativeCode] private static void Internal_ActiveSceneChanged(Scene previousActiveScene, Scene newActiveScene) { if (SceneManager.activeSceneChanged != null) { SceneManager.activeSceneChanged(previousActiveScene, newActiveScene); } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetActiveScene_Injected(out Scene ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool SetActiveScene_Injected(ref Scene scene); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetSceneByPath_Injected(string scenePath, out Scene ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetSceneByName_Injected(string name, out Scene ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetSceneAt_Injected(int index, out Scene ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CreateScene_Injected(string sceneName, ref CreateSceneParameters parameters, out Scene ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool UnloadSceneInternal_Injected(ref Scene scene, UnloadSceneOptions options); [MethodImpl(MethodImplOptions.InternalCall)] private static extern AsyncOperation UnloadSceneAsyncInternal_Injected(ref Scene scene, UnloadSceneOptions options); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void MergeScenes_Injected(ref Scene sourceScene, ref Scene destinationScene); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void MoveGameObjectToScene_Injected(GameObject go, ref Scene scene); } public enum LoadSceneMode { Single, Additive } [Flags] public enum LocalPhysicsMode { None = 0, Physics2D = 1, Physics3D = 2 } [Serializable] public struct LoadSceneParameters { [SerializeField] private LoadSceneMode m_LoadSceneMode; [SerializeField] private LocalPhysicsMode m_LocalPhysicsMode; public LoadSceneMode loadSceneMode { get { return m_LoadSceneMode; } set { m_LoadSceneMode = value; } } public LocalPhysicsMode localPhysicsMode { get { return m_LocalPhysicsMode; } set { m_LocalPhysicsMode = value; } } public LoadSceneParameters(LoadSceneMode mode) { m_LoadSceneMode = mode; m_LocalPhysicsMode = LocalPhysicsMode.None; } public LoadSceneParameters(LoadSceneMode mode, LocalPhysicsMode physicsMode) { m_LoadSceneMode = mode; m_LocalPhysicsMode = physicsMode; } } [Serializable] public struct CreateSceneParameters { [SerializeField] private LocalPhysicsMode m_LocalPhysicsMode; public LocalPhysicsMode localPhysicsMode { get { return m_LocalPhysicsMode; } set { m_LocalPhysicsMode = value; } } public CreateSceneParameters(LocalPhysicsMode physicsMode) { m_LocalPhysicsMode = physicsMode; } } [Flags] public enum UnloadSceneOptions { None = 0, UnloadAllEmbeddedSceneObjects = 1 } [NativeHeader("Runtime/Export/SceneManager/SceneUtility.bindings.h")] public static class SceneUtility { [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern string GetScenePathByBuildIndex(int buildIndex); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern int GetBuildIndexByScenePath(string scenePath); } } namespace UnityEngine.LowLevel { [NativeType(Header = "Runtime/Misc/PlayerLoop.h")] [MovedFrom("UnityEngine.Experimental.LowLevel")] [RequiredByNativeCode] internal struct PlayerLoopSystemInternal { public Type type; public PlayerLoopSystem.UpdateFunction updateDelegate; public IntPtr updateFunction; public IntPtr loopConditionFunction; public int numSubSystems; } [MovedFrom("UnityEngine.Experimental.LowLevel")] public struct PlayerLoopSystem { public delegate void UpdateFunction(); public Type type; public PlayerLoopSystem[] subSystemList; public UpdateFunction updateDelegate; public IntPtr updateFunction; public IntPtr loopConditionFunction; public override string ToString() { return type.Name; } } [MovedFrom("UnityEngine.Experimental.LowLevel")] public class PlayerLoop { public static PlayerLoopSystem GetDefaultPlayerLoop() { PlayerLoopSystemInternal[] defaultPlayerLoopInternal = GetDefaultPlayerLoopInternal(); int offset = 0; return InternalToPlayerLoopSystem(defaultPlayerLoopInternal, ref offset); } public static PlayerLoopSystem GetCurrentPlayerLoop() { PlayerLoopSystemInternal[] currentPlayerLoopInternal = GetCurrentPlayerLoopInternal(); int offset = 0; return InternalToPlayerLoopSystem(currentPlayerLoopInternal, ref offset); } public static void SetPlayerLoop(PlayerLoopSystem loop) { List internalSys = new List(); PlayerLoopSystemToInternal(loop, ref internalSys); SetPlayerLoopInternal(internalSys.ToArray()); } private static int PlayerLoopSystemToInternal(PlayerLoopSystem sys, ref List internalSys) { int count = internalSys.Count; PlayerLoopSystemInternal playerLoopSystemInternal = new PlayerLoopSystemInternal { type = sys.type, updateDelegate = sys.updateDelegate, updateFunction = sys.updateFunction, loopConditionFunction = sys.loopConditionFunction, numSubSystems = 0 }; internalSys.Add(playerLoopSystemInternal); if (sys.subSystemList != null) { for (int i = 0; i < sys.subSystemList.Length; i++) { playerLoopSystemInternal.numSubSystems += PlayerLoopSystemToInternal(sys.subSystemList[i], ref internalSys); } } internalSys[count] = playerLoopSystemInternal; return playerLoopSystemInternal.numSubSystems + 1; } private static PlayerLoopSystem InternalToPlayerLoopSystem(PlayerLoopSystemInternal[] internalSys, ref int offset) { PlayerLoopSystem result = new PlayerLoopSystem { type = internalSys[offset].type, updateDelegate = internalSys[offset].updateDelegate, updateFunction = internalSys[offset].updateFunction, loopConditionFunction = internalSys[offset].loopConditionFunction, subSystemList = null }; int num = offset++; if (internalSys[num].numSubSystems > 0) { List list = new List(); while (offset <= num + internalSys[num].numSubSystems) { list.Add(InternalToPlayerLoopSystem(internalSys, ref offset)); } result.subSystemList = list.ToArray(); } return result; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsFreeFunction = true)] private static extern PlayerLoopSystemInternal[] GetDefaultPlayerLoopInternal(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsFreeFunction = true)] private static extern PlayerLoopSystemInternal[] GetCurrentPlayerLoopInternal(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsFreeFunction = true)] private static extern void SetPlayerLoopInternal(PlayerLoopSystemInternal[] loop); } } namespace UnityEngine.PlayerLoop { [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct TimeUpdate { [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct WaitForLastPresentationAndUpdateTime { } [StructLayout(LayoutKind.Sequential, Size = 1)] [Obsolete("ProfilerStartFrame player loop component has been moved to the Initialization category. (UnityUpgradable) -> UnityEngine.PlayerLoop.Initialization/ProfilerStartFrame", true)] public struct ProfilerStartFrame { } } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] [MovedFrom("UnityEngine.Experimental.PlayerLoop")] public struct Initialization { [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ProfilerStartFrame { } [StructLayout(LayoutKind.Sequential, Size = 1)] [Obsolete("PlayerUpdateTime player loop component has been moved to its own category called TimeUpdate. (UnityUpgradable) -> UnityEngine.PlayerLoop.TimeUpdate/WaitForLastPresentationAndUpdateTime", true)] public struct PlayerUpdateTime { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateCameraMotionVectors { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct DirectorSampleTime { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct AsyncUploadTimeSlicedUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct SynchronizeState { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct SynchronizeInputs { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct XREarlyUpdate { } } [StructLayout(LayoutKind.Sequential, Size = 1)] [MovedFrom("UnityEngine.Experimental.PlayerLoop")] [RequiredByNativeCode] public struct EarlyUpdate { [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PollPlayerConnection { } [StructLayout(LayoutKind.Sequential, Size = 1)] [Obsolete("ProfilerStartFrame player loop component has been moved to the Initialization category. (UnityUpgradable) -> UnityEngine.PlayerLoop.Initialization/ProfilerStartFrame", true)] public struct ProfilerStartFrame { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PollHtcsPlayerConnection { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct GpuTimestamp { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct AnalyticsCoreStatsUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UnityWebRequestUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateStreamingManager { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ExecuteMainThreadJobs { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ProcessMouseInWindow { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ClearIntermediateRenderers { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ClearLines { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PresentBeforeUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ResetFrameStatsAfterPresent { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateAsyncReadbackManager { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateTextureStreamingManager { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdatePreloading { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct RendererNotifyInvisible { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PlayerCleanupCachedData { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateMainGameViewRect { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateCanvasRectTransform { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateInputManager { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ProcessRemoteInput { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct XRUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ScriptRunDelayedStartupFrame { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateKinect { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct DeliverIosPlatformEvents { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct DispatchEventQueueEvents { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PhysicsResetInterpolatedTransformPosition { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct SpriteAtlasManagerUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [Obsolete("TangoUpdate has been deprecated. Use ARCoreUpdate instead (UnityUpgradable) -> UnityEngine.PlayerLoop.EarlyUpdate/ARCoreUpdate", false)] [RequiredByNativeCode] public struct TangoUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ARCoreUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PerformanceAnalyticsUpdate { } } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] [MovedFrom("UnityEngine.Experimental.PlayerLoop")] public struct FixedUpdate { [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ClearLines { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct DirectorFixedSampleTime { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct AudioFixedUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ScriptRunBehaviourFixedUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct DirectorFixedUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct LegacyFixedAnimationUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct XRFixedUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PhysicsFixedUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct Physics2DFixedUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] private struct PhysicsClothFixedUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct DirectorFixedUpdatePostPhysics { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ScriptRunDelayedFixedFrameRate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct NewInputFixedUpdate { } } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] [MovedFrom("UnityEngine.Experimental.PlayerLoop")] public struct PreUpdate { [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PhysicsUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct Physics2DUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct CheckTexFieldInput { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct IMGUISendQueuedEvents { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct SendMouseEvents { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct AIUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct WindUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateVideo { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct NewInputUpdate { } } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] [MovedFrom("UnityEngine.Experimental.PlayerLoop")] public struct Update { [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ScriptRunBehaviourUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct DirectorUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ScriptRunDelayedDynamicFrameRate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ScriptRunDelayedTasks { } } [StructLayout(LayoutKind.Sequential, Size = 1)] [MovedFrom("UnityEngine.Experimental.PlayerLoop")] [RequiredByNativeCode] public struct PreLateUpdate { [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct Physics2DLateUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct AIUpdatePostScript { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct DirectorUpdateAnimationBegin { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct LegacyAnimationUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct DirectorUpdateAnimationEnd { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct DirectorDeferredEvaluate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UIElementsUpdatePanels { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateNetworkManager { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateMasterServerInterface { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UNetUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct EndGraphicsJobsAfterScriptUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ParticleSystemBeginUpdateAll { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ScriptRunBehaviourLateUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ConstraintManagerUpdate { } } [StructLayout(LayoutKind.Sequential, Size = 1)] [MovedFrom("UnityEngine.Experimental.PlayerLoop")] [RequiredByNativeCode] public struct PostLateUpdate { [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PlayerSendFrameStarted { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateRectTransform { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateCanvasRectTransform { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PlayerUpdateCanvases { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateAudio { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateVideo { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct DirectorLateUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ScriptRunDelayedDynamicFrameRate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct VFXUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ParticleSystemEndUpdateAll { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct EndGraphicsJobsAfterScriptLateUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateSubstance { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateCustomRenderTextures { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct XRPostLateUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateAllRenderers { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateLightProbeProxyVolumes { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct EnlightenRuntimeUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateAllSkinnedMeshes { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ProcessWebSendMessages { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct SortingGroupsUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateVideoTextures { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct DirectorRenderImage { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PlayerEmitCanvasGeometry { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] internal struct PlayerRenderUIEBatchModeOffscreen { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct FinishFrameRendering { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct BatchModeUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PlayerSendFrameComplete { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateCaptureScreenshot { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PresentAfterDraw { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ClearImmediateRenderers { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct XRPostPresent { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct UpdateResolution { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct InputEndFrame { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct GUIClearEvents { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ShaderHandleErrors { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ResetInputAxis { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ThreadedLoadingDebug { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ProfilerSynchronizeStats { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct MemoryFrameMaintenance { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ExecuteGameCenterCallbacks { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct XRPreEndFrame { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct ProfilerEndFrame { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct GraphicsWarmupPreloadedShaders { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PlayerSendFramePostPresent { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PhysicsSkinnedClothBeginUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct PhysicsSkinnedClothFinishUpdate { } [StructLayout(LayoutKind.Sequential, Size = 1)] [RequiredByNativeCode] public struct TriggerEndOfFrameCallbacks { } } } namespace UnityEngine.Pool { public class CollectionPool where TCollection : class, ICollection, new() { internal static readonly ObjectPool s_Pool = new ObjectPool(() => new TCollection(), null, delegate(TCollection l) { l.Clear(); }); public static TCollection Get() { return s_Pool.Get(); } public static PooledObject Get(out TCollection value) { return s_Pool.Get(out value); } public static void Release(TCollection toRelease) { s_Pool.Release(toRelease); } } public class ListPool : CollectionPool, T> { } public class HashSetPool : CollectionPool, T> { } public class DictionaryPool : CollectionPool, KeyValuePair> { } public class GenericPool where T : class, new() { internal static readonly ObjectPool s_Pool = new ObjectPool(() => new T()); public static T Get() { return s_Pool.Get(); } public static PooledObject Get(out T value) { return s_Pool.Get(out value); } public static void Release(T toRelease) { s_Pool.Release(toRelease); } } public interface IObjectPool where T : class { int CountInactive { get; } T Get(); PooledObject Get(out T v); void Release(T element); void Clear(); } public class LinkedPool : IDisposable, IObjectPool where T : class { internal class LinkedPoolItem { internal LinkedPoolItem poolNext; internal T value; } private readonly Func m_CreateFunc; private readonly Action m_ActionOnGet; private readonly Action m_ActionOnRelease; private readonly Action m_ActionOnDestroy; private readonly int m_Limit; internal LinkedPoolItem m_PoolFirst; internal LinkedPoolItem m_NextAvailableListItem; private bool m_CollectionCheck; public int CountInactive { get; private set; } public LinkedPool(Func createFunc, Action actionOnGet = null, Action actionOnRelease = null, Action actionOnDestroy = null, bool collectionCheck = true, int maxSize = 10000) { if (createFunc == null) { throw new ArgumentNullException("createFunc"); } if (maxSize <= 0) { throw new ArgumentException("maxSize", "Max size must be greater than 0"); } m_CreateFunc = createFunc; m_ActionOnGet = actionOnGet; m_ActionOnRelease = actionOnRelease; m_ActionOnDestroy = actionOnDestroy; m_Limit = maxSize; m_CollectionCheck = collectionCheck; } public T Get() { T val = null; if (m_PoolFirst == null) { val = m_CreateFunc(); } else { LinkedPoolItem poolFirst = m_PoolFirst; val = poolFirst.value; m_PoolFirst = poolFirst.poolNext; poolFirst.poolNext = m_NextAvailableListItem; m_NextAvailableListItem = poolFirst; m_NextAvailableListItem.value = null; int countInactive = CountInactive - 1; CountInactive = countInactive; } m_ActionOnGet?.Invoke(val); return val; } public PooledObject Get(out T v) { return new PooledObject(v = Get(), this); } public void Release(T item) { m_ActionOnRelease?.Invoke(item); if (CountInactive < m_Limit) { LinkedPoolItem linkedPoolItem = m_NextAvailableListItem; if (linkedPoolItem == null) { linkedPoolItem = new LinkedPoolItem(); } else { m_NextAvailableListItem = linkedPoolItem.poolNext; } linkedPoolItem.value = item; linkedPoolItem.poolNext = m_PoolFirst; m_PoolFirst = linkedPoolItem; int countInactive = CountInactive + 1; CountInactive = countInactive; } else { m_ActionOnDestroy?.Invoke(item); } } public void Clear() { if (m_ActionOnDestroy != null) { for (LinkedPoolItem linkedPoolItem = m_PoolFirst; linkedPoolItem != null; linkedPoolItem = linkedPoolItem.poolNext) { m_ActionOnDestroy(linkedPoolItem.value); } } m_PoolFirst = null; m_NextAvailableListItem = null; CountInactive = 0; } public void Dispose() { Clear(); } } public class ObjectPool : IDisposable, IObjectPool where T : class { internal readonly List m_List; private readonly Func m_CreateFunc; private readonly Action m_ActionOnGet; private readonly Action m_ActionOnRelease; private readonly Action m_ActionOnDestroy; private readonly int m_MaxSize; internal bool m_CollectionCheck; public int CountAll { get; private set; } public int CountActive => CountAll - CountInactive; public int CountInactive => m_List.Count; public ObjectPool(Func createFunc, Action actionOnGet = null, Action actionOnRelease = null, Action actionOnDestroy = null, bool collectionCheck = true, int defaultCapacity = 10, int maxSize = 10000) { if (createFunc == null) { throw new ArgumentNullException("createFunc"); } if (maxSize <= 0) { throw new ArgumentException("Max Size must be greater than 0", "maxSize"); } m_List = new List(defaultCapacity); m_CreateFunc = createFunc; m_MaxSize = maxSize; m_ActionOnGet = actionOnGet; m_ActionOnRelease = actionOnRelease; m_ActionOnDestroy = actionOnDestroy; m_CollectionCheck = collectionCheck; } public T Get() { T val; if (m_List.Count == 0) { val = m_CreateFunc(); CountAll++; } else { int index = m_List.Count - 1; val = m_List[index]; m_List.RemoveAt(index); } m_ActionOnGet?.Invoke(val); return val; } public PooledObject Get(out T v) { return new PooledObject(v = Get(), this); } public void Release(T element) { m_ActionOnRelease?.Invoke(element); if (CountInactive < m_MaxSize) { m_List.Add(element); } else { m_ActionOnDestroy?.Invoke(element); } } public void Clear() { if (m_ActionOnDestroy != null) { foreach (T item in m_List) { m_ActionOnDestroy(item); } } m_List.Clear(); CountAll = 0; } public void Dispose() { Clear(); } } public struct PooledObject : IDisposable where T : class { private readonly T m_ToReturn; private readonly IObjectPool m_Pool; internal PooledObject(T value, IObjectPool pool) { m_ToReturn = value; m_Pool = pool; } void IDisposable.Dispose() { m_Pool.Release(m_ToReturn); } } public static class UnsafeGenericPool where T : class, new() { internal static readonly ObjectPool s_Pool = new ObjectPool(() => new T(), null, null, null, collectionCheck: false); public static T Get() { return s_Pool.Get(); } public static PooledObject Get(out T value) { return s_Pool.Get(out value); } public static void Release(T toRelease) { s_Pool.Release(toRelease); } } } namespace UnityEngine.Networking.PlayerConnection { [MovedFrom("UnityEngine.Experimental.Networking.PlayerConnection")] public enum ConnectionTarget { None, Player, Editor } [MovedFrom("UnityEngine.Experimental.Networking.PlayerConnection")] public interface IConnectionState : IDisposable { ConnectionTarget connectedToTarget { get; } string connectionName { get; } } [Serializable] public class MessageEventArgs { public int playerId; public byte[] data; } public interface IEditorPlayerConnection { void Register(Guid messageId, UnityAction callback); void Unregister(Guid messageId, UnityAction callback); void DisconnectAll(); void RegisterConnection(UnityAction callback); void RegisterDisconnection(UnityAction callback); void UnregisterConnection(UnityAction callback); void UnregisterDisconnection(UnityAction callback); void Send(Guid messageId, byte[] data); bool TrySend(Guid messageId, byte[] data); } [Serializable] public class PlayerConnection : ScriptableObject, IEditorPlayerConnection { internal static IPlayerEditorConnectionNative connectionNative; [SerializeField] private PlayerEditorConnectionEvents m_PlayerEditorConnectionEvents = new PlayerEditorConnectionEvents(); [SerializeField] private List m_connectedPlayers = new List(); private bool m_IsInitilized; private static PlayerConnection s_Instance; public static PlayerConnection instance { get { if (s_Instance == null) { return CreateInstance(); } return s_Instance; } } public bool isConnected => GetConnectionNativeApi().IsConnected(); private static PlayerConnection CreateInstance() { s_Instance = ScriptableObject.CreateInstance(); s_Instance.hideFlags = HideFlags.HideAndDontSave; return s_Instance; } public void OnEnable() { if (!m_IsInitilized) { m_IsInitilized = true; GetConnectionNativeApi().Initialize(); } } private IPlayerEditorConnectionNative GetConnectionNativeApi() { return connectionNative ?? new PlayerConnectionInternal(); } public void Register(Guid messageId, UnityAction callback) { if (messageId == Guid.Empty) { throw new ArgumentException("Cant be Guid.Empty", "messageId"); } if (!m_PlayerEditorConnectionEvents.messageTypeSubscribers.Any((PlayerEditorConnectionEvents.MessageTypeSubscribers x) => x.MessageTypeId == messageId)) { GetConnectionNativeApi().RegisterInternal(messageId); } m_PlayerEditorConnectionEvents.AddAndCreate(messageId).AddListener(callback); } public void Unregister(Guid messageId, UnityAction callback) { m_PlayerEditorConnectionEvents.UnregisterManagedCallback(messageId, callback); if (!m_PlayerEditorConnectionEvents.messageTypeSubscribers.Any((PlayerEditorConnectionEvents.MessageTypeSubscribers x) => x.MessageTypeId == messageId)) { GetConnectionNativeApi().UnregisterInternal(messageId); } } public void RegisterConnection(UnityAction callback) { foreach (int connectedPlayer in m_connectedPlayers) { callback(connectedPlayer); } m_PlayerEditorConnectionEvents.connectionEvent.AddListener(callback); } public void RegisterDisconnection(UnityAction callback) { m_PlayerEditorConnectionEvents.disconnectionEvent.AddListener(callback); } public void UnregisterConnection(UnityAction callback) { m_PlayerEditorConnectionEvents.connectionEvent.RemoveListener(callback); } public void UnregisterDisconnection(UnityAction callback) { m_PlayerEditorConnectionEvents.disconnectionEvent.RemoveListener(callback); } public void Send(Guid messageId, byte[] data) { if (messageId == Guid.Empty) { throw new ArgumentException("Cant be Guid.Empty", "messageId"); } GetConnectionNativeApi().SendMessage(messageId, data, 0); } public bool TrySend(Guid messageId, byte[] data) { if (messageId == Guid.Empty) { throw new ArgumentException("Cant be Guid.Empty", "messageId"); } return GetConnectionNativeApi().TrySendMessage(messageId, data, 0); } public bool BlockUntilRecvMsg(Guid messageId, int timeout) { bool msgReceived = false; UnityAction callback = delegate { msgReceived = true; }; DateTime now = DateTime.Now; Register(messageId, callback); while ((DateTime.Now - now).TotalMilliseconds < (double)timeout && !msgReceived) { GetConnectionNativeApi().Poll(); } Unregister(messageId, callback); return msgReceived; } public void DisconnectAll() { GetConnectionNativeApi().DisconnectAll(); } [RequiredByNativeCode] private static void MessageCallbackInternal(IntPtr data, ulong size, ulong guid, string messageId) { byte[] array = null; if (size != 0) { array = new byte[size]; Marshal.Copy(data, array, 0, (int)size); } instance.m_PlayerEditorConnectionEvents.InvokeMessageIdSubscribers(new Guid(messageId), array, (int)guid); } [RequiredByNativeCode] private static void ConnectedCallbackInternal(int playerId) { instance.m_connectedPlayers.Add(playerId); instance.m_PlayerEditorConnectionEvents.connectionEvent.Invoke(playerId); } [RequiredByNativeCode] private static void DisconnectedCallback(int playerId) { instance.m_connectedPlayers.Remove(playerId); instance.m_PlayerEditorConnectionEvents.disconnectionEvent.Invoke(playerId); } } [Serializable] internal class PlayerEditorConnectionEvents { [Serializable] public class MessageEvent : UnityEvent { } [Serializable] public class ConnectionChangeEvent : UnityEvent { } [Serializable] public class MessageTypeSubscribers { [SerializeField] private string m_messageTypeId; public int subscriberCount = 0; public MessageEvent messageCallback = new MessageEvent(); public Guid MessageTypeId { get { return new Guid(m_messageTypeId); } set { m_messageTypeId = value.ToString(); } } } [SerializeField] public List messageTypeSubscribers = new List(); [SerializeField] public ConnectionChangeEvent connectionEvent = new ConnectionChangeEvent(); [SerializeField] public ConnectionChangeEvent disconnectionEvent = new ConnectionChangeEvent(); public void InvokeMessageIdSubscribers(Guid messageId, byte[] data, int playerId) { IEnumerable enumerable = messageTypeSubscribers.Where((MessageTypeSubscribers x) => x.MessageTypeId == messageId); if (!enumerable.Any()) { Guid guid = messageId; Debug.LogError("No actions found for messageId: " + guid); return; } MessageEventArgs arg = new MessageEventArgs { playerId = playerId, data = data }; foreach (MessageTypeSubscribers item in enumerable) { item.messageCallback.Invoke(arg); } } public UnityEvent AddAndCreate(Guid messageId) { MessageTypeSubscribers messageTypeSubscribers = this.messageTypeSubscribers.SingleOrDefault((MessageTypeSubscribers x) => x.MessageTypeId == messageId); if (messageTypeSubscribers == null) { messageTypeSubscribers = new MessageTypeSubscribers { MessageTypeId = messageId, messageCallback = new MessageEvent() }; this.messageTypeSubscribers.Add(messageTypeSubscribers); } messageTypeSubscribers.subscriberCount++; return messageTypeSubscribers.messageCallback; } public void UnregisterManagedCallback(Guid messageId, UnityAction callback) { MessageTypeSubscribers messageTypeSubscribers = this.messageTypeSubscribers.SingleOrDefault((MessageTypeSubscribers x) => x.MessageTypeId == messageId); if (messageTypeSubscribers != null) { messageTypeSubscribers.subscriberCount--; messageTypeSubscribers.messageCallback.RemoveListener(callback); if (messageTypeSubscribers.subscriberCount <= 0) { this.messageTypeSubscribers.Remove(messageTypeSubscribers); } } } } } namespace UnityEngine.Lumin { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public sealed class UsesLuminPlatformLevelAttribute : Attribute { private readonly uint m_PlatformLevel; public uint platformLevel => m_PlatformLevel; public UsesLuminPlatformLevelAttribute(uint platformLevel) { m_PlatformLevel = platformLevel; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class UsesLuminPrivilegeAttribute : Attribute { private readonly string m_Privilege; public string privilege => m_Privilege; public UsesLuminPrivilegeAttribute(string privilege) { m_Privilege = privilege; } } } namespace UnityEngine.Internal { [Serializable] [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.GenericParameter)] public class DefaultValueAttribute : Attribute { private object DefaultValue; public object Value => DefaultValue; public DefaultValueAttribute(string value) { DefaultValue = value; } public override bool Equals(object obj) { if (!(obj is DefaultValueAttribute defaultValueAttribute)) { return false; } if (DefaultValue == null) { return defaultValueAttribute.Value == null; } return DefaultValue.Equals(defaultValueAttribute.Value); } public override int GetHashCode() { if (DefaultValue == null) { return base.GetHashCode(); } return DefaultValue.GetHashCode(); } } [Serializable] public class ExcludeFromDocsAttribute : Attribute { } [VisibleToOtherModules] internal interface ISubAssetNotDuplicatable { } } namespace UnityEngine.Rendering { [NativeHeader("Runtime/Graphics/AsyncGPUReadbackManaged.h")] [UsedByNativeCode] [NativeHeader("Runtime/Shaders/ComputeShader.h")] [NativeHeader("Runtime/Graphics/Texture.h")] public struct AsyncGPUReadbackRequest { internal IntPtr m_Ptr; internal int m_Version; public bool done => IsDone(); public bool hasError => HasError(); public int layerCount => GetLayerCount(); public int layerDataSize => GetLayerDataSize(); public int width => GetWidth(); public int height => GetHeight(); public int depth => GetDepth(); public void Update() { Update_Injected(ref this); } public void WaitForCompletion() { WaitForCompletion_Injected(ref this); } public unsafe NativeArray GetData(int layer = 0) where T : struct { if (!done || hasError) { throw new InvalidOperationException("Cannot access the data as it is not available"); } if (layer < 0 || layer >= layerCount) { throw new ArgumentException($"Layer index is out of range {layer} / {layerCount}"); } int num = UnsafeUtility.SizeOf(); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)GetDataRaw(layer), layerDataSize / num, Allocator.None); } private bool IsDone() { return IsDone_Injected(ref this); } private bool HasError() { return HasError_Injected(ref this); } private int GetLayerCount() { return GetLayerCount_Injected(ref this); } private int GetLayerDataSize() { return GetLayerDataSize_Injected(ref this); } private int GetWidth() { return GetWidth_Injected(ref this); } private int GetHeight() { return GetHeight_Injected(ref this); } private int GetDepth() { return GetDepth_Injected(ref this); } internal void SetScriptingCallback(Action callback) { SetScriptingCallback_Injected(ref this, callback); } private IntPtr GetDataRaw(int layer) { return GetDataRaw_Injected(ref this, layer); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Update_Injected(ref AsyncGPUReadbackRequest _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void WaitForCompletion_Injected(ref AsyncGPUReadbackRequest _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsDone_Injected(ref AsyncGPUReadbackRequest _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool HasError_Injected(ref AsyncGPUReadbackRequest _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetLayerCount_Injected(ref AsyncGPUReadbackRequest _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetLayerDataSize_Injected(ref AsyncGPUReadbackRequest _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetWidth_Injected(ref AsyncGPUReadbackRequest _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetHeight_Injected(ref AsyncGPUReadbackRequest _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetDepth_Injected(ref AsyncGPUReadbackRequest _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetScriptingCallback_Injected(ref AsyncGPUReadbackRequest _unity_self, Action callback); [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr GetDataRaw_Injected(ref AsyncGPUReadbackRequest _unity_self, int layer); } [UsedByNativeCode] [NativeHeader("Runtime/Graphics/AsyncGPUReadbackManaged.h")] internal struct AsyncRequestNativeArrayData { public unsafe void* nativeArrayBuffer; public long lengthInBytes; public unsafe static AsyncRequestNativeArrayData CreateAndCheckAccess(NativeArray array) where T : struct { if (array.m_AllocatorLabel == Allocator.Temp || array.m_AllocatorLabel == Allocator.TempJob) { throw new ArgumentException("AsyncGPUReadback cannot use Temp memory as input since the result may only become available at an unspecified point in the future."); } return new AsyncRequestNativeArrayData { nativeArrayBuffer = array.GetUnsafePtr(), lengthInBytes = (long)array.Length * (long)UnsafeUtility.SizeOf() }; } public unsafe static AsyncRequestNativeArrayData CreateAndCheckAccess(NativeSlice array) where T : struct { return new AsyncRequestNativeArrayData { nativeArrayBuffer = array.GetUnsafePtr(), lengthInBytes = (long)array.Length * (long)UnsafeUtility.SizeOf() }; } } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static class AsyncGPUReadback { internal static void ValidateFormat(Texture src, GraphicsFormat dstformat) { GraphicsFormat format = GraphicsFormatUtility.GetFormat(src); if (!SystemInfo.IsFormatSupported(format, FormatUsage.ReadPixels)) { Debug.LogError($"'{format}' doesn't support ReadPixels usage on this platform. Async GPU readback failed."); } } [MethodImpl(MethodImplOptions.InternalCall)] public static extern void WaitAllRequests(); public unsafe static AsyncGPUReadbackRequest Request(ComputeBuffer src, Action callback = null) { AsyncGPUReadbackRequest result = Request_Internal_ComputeBuffer_1(src, null); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest Request(ComputeBuffer src, int size, int offset, Action callback = null) { AsyncGPUReadbackRequest result = Request_Internal_ComputeBuffer_2(src, size, offset, null); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest Request(GraphicsBuffer src, Action callback = null) { AsyncGPUReadbackRequest result = Request_Internal_GraphicsBuffer_1(src, null); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest Request(GraphicsBuffer src, int size, int offset, Action callback = null) { AsyncGPUReadbackRequest result = Request_Internal_GraphicsBuffer_2(src, size, offset, null); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest Request(Texture src, int mipIndex = 0, Action callback = null) { AsyncGPUReadbackRequest result = Request_Internal_Texture_1(src, mipIndex, null); result.SetScriptingCallback(callback); return result; } public static AsyncGPUReadbackRequest Request(Texture src, int mipIndex, TextureFormat dstFormat, Action callback = null) { return Request(src, mipIndex, GraphicsFormatUtility.GetGraphicsFormat(dstFormat, QualitySettings.activeColorSpace == ColorSpace.Linear), callback); } public unsafe static AsyncGPUReadbackRequest Request(Texture src, int mipIndex, GraphicsFormat dstFormat, Action callback = null) { ValidateFormat(src, dstFormat); AsyncGPUReadbackRequest result = Request_Internal_Texture_2(src, mipIndex, dstFormat, null); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest Request(Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, Action callback = null) { AsyncGPUReadbackRequest result = Request_Internal_Texture_3(src, mipIndex, x, width, y, height, z, depth, null); result.SetScriptingCallback(callback); return result; } public static AsyncGPUReadbackRequest Request(Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, TextureFormat dstFormat, Action callback = null) { return Request(src, mipIndex, x, width, y, height, z, depth, GraphicsFormatUtility.GetGraphicsFormat(dstFormat, QualitySettings.activeColorSpace == ColorSpace.Linear), callback); } public unsafe static AsyncGPUReadbackRequest Request(Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, GraphicsFormat dstFormat, Action callback = null) { ValidateFormat(src, dstFormat); AsyncGPUReadbackRequest result = Request_Internal_Texture_4(src, mipIndex, x, width, y, height, z, depth, dstFormat, null); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeArray(ref NativeArray output, ComputeBuffer src, Action callback = null) where T : struct { AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_ComputeBuffer_1(src, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeArray(ref NativeArray output, ComputeBuffer src, int size, int offset, Action callback = null) where T : struct { AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_ComputeBuffer_2(src, size, offset, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeArray(ref NativeArray output, GraphicsBuffer src, Action callback = null) where T : struct { AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_GraphicsBuffer_1(src, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeArray(ref NativeArray output, GraphicsBuffer src, int size, int offset, Action callback = null) where T : struct { AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_GraphicsBuffer_2(src, size, offset, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeArray(ref NativeArray output, Texture src, int mipIndex = 0, Action callback = null) where T : struct { AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_Texture_1(src, mipIndex, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } public static AsyncGPUReadbackRequest RequestIntoNativeArray(ref NativeArray output, Texture src, int mipIndex, TextureFormat dstFormat, Action callback = null) where T : struct { return RequestIntoNativeArray(ref output, src, mipIndex, GraphicsFormatUtility.GetGraphicsFormat(dstFormat, QualitySettings.activeColorSpace == ColorSpace.Linear), callback); } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeArray(ref NativeArray output, Texture src, int mipIndex, GraphicsFormat dstFormat, Action callback = null) where T : struct { ValidateFormat(src, dstFormat); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_Texture_2(src, mipIndex, dstFormat, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } public static AsyncGPUReadbackRequest RequestIntoNativeArray(ref NativeArray output, Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, TextureFormat dstFormat, Action callback = null) where T : struct { return RequestIntoNativeArray(ref output, src, mipIndex, x, width, y, height, z, depth, GraphicsFormatUtility.GetGraphicsFormat(dstFormat, QualitySettings.activeColorSpace == ColorSpace.Linear), callback); } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeArray(ref NativeArray output, Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, GraphicsFormat dstFormat, Action callback = null) where T : struct { ValidateFormat(src, dstFormat); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_Texture_4(src, mipIndex, x, width, y, height, z, depth, dstFormat, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeSlice(ref NativeSlice output, ComputeBuffer src, Action callback = null) where T : struct { AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_ComputeBuffer_1(src, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeSlice(ref NativeSlice output, ComputeBuffer src, int size, int offset, Action callback = null) where T : struct { AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_ComputeBuffer_2(src, size, offset, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeSlice(ref NativeSlice output, GraphicsBuffer src, Action callback = null) where T : struct { AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_GraphicsBuffer_1(src, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeSlice(ref NativeSlice output, GraphicsBuffer src, int size, int offset, Action callback = null) where T : struct { AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_GraphicsBuffer_2(src, size, offset, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeSlice(ref NativeSlice output, Texture src, int mipIndex = 0, Action callback = null) where T : struct { AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_Texture_1(src, mipIndex, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } public static AsyncGPUReadbackRequest RequestIntoNativeSlice(ref NativeSlice output, Texture src, int mipIndex, TextureFormat dstFormat, Action callback = null) where T : struct { return RequestIntoNativeSlice(ref output, src, mipIndex, GraphicsFormatUtility.GetGraphicsFormat(dstFormat, QualitySettings.activeColorSpace == ColorSpace.Linear), callback); } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeSlice(ref NativeSlice output, Texture src, int mipIndex, GraphicsFormat dstFormat, Action callback = null) where T : struct { ValidateFormat(src, dstFormat); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_Texture_2(src, mipIndex, dstFormat, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } public static AsyncGPUReadbackRequest RequestIntoNativeSlice(ref NativeSlice output, Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, TextureFormat dstFormat, Action callback = null) where T : struct { return RequestIntoNativeSlice(ref output, src, mipIndex, x, width, y, height, z, depth, GraphicsFormatUtility.GetGraphicsFormat(dstFormat, QualitySettings.activeColorSpace == ColorSpace.Linear), callback); } public unsafe static AsyncGPUReadbackRequest RequestIntoNativeSlice(ref NativeSlice output, Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, GraphicsFormat dstFormat, Action callback = null) where T : struct { ValidateFormat(src, dstFormat); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); AsyncGPUReadbackRequest result = Request_Internal_Texture_4(src, mipIndex, x, width, y, height, z, depth, dstFormat, &asyncRequestNativeArrayData); result.SetScriptingCallback(callback); return result; } [NativeMethod("Request")] private unsafe static AsyncGPUReadbackRequest Request_Internal_ComputeBuffer_1([NotNull("ArgumentNullException")] ComputeBuffer buffer, AsyncRequestNativeArrayData* data) { Request_Internal_ComputeBuffer_1_Injected(buffer, data, out var ret); return ret; } [NativeMethod("Request")] private unsafe static AsyncGPUReadbackRequest Request_Internal_ComputeBuffer_2([NotNull("ArgumentNullException")] ComputeBuffer src, int size, int offset, AsyncRequestNativeArrayData* data) { Request_Internal_ComputeBuffer_2_Injected(src, size, offset, data, out var ret); return ret; } [NativeMethod("Request")] private unsafe static AsyncGPUReadbackRequest Request_Internal_GraphicsBuffer_1([NotNull("ArgumentNullException")] GraphicsBuffer buffer, AsyncRequestNativeArrayData* data) { Request_Internal_GraphicsBuffer_1_Injected(buffer, data, out var ret); return ret; } [NativeMethod("Request")] private unsafe static AsyncGPUReadbackRequest Request_Internal_GraphicsBuffer_2([NotNull("ArgumentNullException")] GraphicsBuffer src, int size, int offset, AsyncRequestNativeArrayData* data) { Request_Internal_GraphicsBuffer_2_Injected(src, size, offset, data, out var ret); return ret; } [NativeMethod("Request")] private unsafe static AsyncGPUReadbackRequest Request_Internal_Texture_1([NotNull("ArgumentNullException")] Texture src, int mipIndex, AsyncRequestNativeArrayData* data) { Request_Internal_Texture_1_Injected(src, mipIndex, data, out var ret); return ret; } [NativeMethod("Request")] private unsafe static AsyncGPUReadbackRequest Request_Internal_Texture_2([NotNull("ArgumentNullException")] Texture src, int mipIndex, GraphicsFormat dstFormat, AsyncRequestNativeArrayData* data) { Request_Internal_Texture_2_Injected(src, mipIndex, dstFormat, data, out var ret); return ret; } [NativeMethod("Request")] private unsafe static AsyncGPUReadbackRequest Request_Internal_Texture_3([NotNull("ArgumentNullException")] Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, AsyncRequestNativeArrayData* data) { Request_Internal_Texture_3_Injected(src, mipIndex, x, width, y, height, z, depth, data, out var ret); return ret; } [NativeMethod("Request")] private unsafe static AsyncGPUReadbackRequest Request_Internal_Texture_4([NotNull("ArgumentNullException")] Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, GraphicsFormat dstFormat, AsyncRequestNativeArrayData* data) { Request_Internal_Texture_4_Injected(src, mipIndex, x, width, y, height, z, depth, dstFormat, data, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Request_Internal_ComputeBuffer_1_Injected(ComputeBuffer buffer, AsyncRequestNativeArrayData* data, out AsyncGPUReadbackRequest ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Request_Internal_ComputeBuffer_2_Injected(ComputeBuffer src, int size, int offset, AsyncRequestNativeArrayData* data, out AsyncGPUReadbackRequest ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Request_Internal_GraphicsBuffer_1_Injected(GraphicsBuffer buffer, AsyncRequestNativeArrayData* data, out AsyncGPUReadbackRequest ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Request_Internal_GraphicsBuffer_2_Injected(GraphicsBuffer src, int size, int offset, AsyncRequestNativeArrayData* data, out AsyncGPUReadbackRequest ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Request_Internal_Texture_1_Injected(Texture src, int mipIndex, AsyncRequestNativeArrayData* data, out AsyncGPUReadbackRequest ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Request_Internal_Texture_2_Injected(Texture src, int mipIndex, GraphicsFormat dstFormat, AsyncRequestNativeArrayData* data, out AsyncGPUReadbackRequest ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Request_Internal_Texture_3_Injected(Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, AsyncRequestNativeArrayData* data, out AsyncGPUReadbackRequest ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Request_Internal_Texture_4_Injected(Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, GraphicsFormat dstFormat, AsyncRequestNativeArrayData* data, out AsyncGPUReadbackRequest ret); } public enum SynchronisationStage { VertexProcessing, PixelProcessing } [StructLayout(LayoutKind.Sequential, Size = 1)] [Obsolete("GPUFence has been deprecated. Use GraphicsFence instead (UnityUpgradable) -> GraphicsFence", false)] public struct GPUFence { public bool passed => true; } [NativeHeader("Runtime/Graphics/GraphicsScriptBindings.h")] public class PIX { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PIX::BeginGPUCapture")] public static extern void BeginGPUCapture(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PIX::EndGPUCapture")] public static extern void EndGPUCapture(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PIX::IsAttached")] public static extern bool IsAttached(); } [Obsolete("ShaderHardwareTier was renamed to GraphicsTier (UnityUpgradable) -> GraphicsTier", false)] public enum ShaderHardwareTier { Tier1, Tier2, Tier3 } public enum IndexFormat { UInt16, UInt32 } [Flags] public enum MeshUpdateFlags { Default = 0, DontValidateIndices = 1, DontResetBoneBounds = 2, DontNotifyMeshUsers = 4, DontRecalculateBounds = 8 } public enum VertexAttributeFormat { Float32, Float16, UNorm8, SNorm8, UNorm16, SNorm16, UInt8, SInt8, UInt16, SInt16, UInt32, SInt32 } [MovedFrom("UnityEngine.Experimental.Rendering")] public enum VertexAttribute { Position, Normal, Tangent, Color, TexCoord0, TexCoord1, TexCoord2, TexCoord3, TexCoord4, TexCoord5, TexCoord6, TexCoord7, BlendWeight, BlendIndices } public enum ShaderParamType { Float, Int, Bool, Half, Short, UInt } public enum ShaderConstantType { Vector, Matrix, Struct } public enum OpaqueSortMode { Default, FrontToBack, NoDistanceSort } public enum RenderQueue { Background = 1000, Geometry = 2000, AlphaTest = 2450, GeometryLast = 2500, Transparent = 3000, Overlay = 4000 } public enum RenderBufferLoadAction { Load, Clear, DontCare } public enum RenderBufferStoreAction { Store, Resolve, StoreAndResolve, DontCare } [Flags] public enum FastMemoryFlags { None = 0, SpillTop = 1, SpillBottom = 2 } [NativeHeader("Runtime/GfxDevice/GfxDeviceTypes.h")] public enum BlendMode { Zero, One, DstColor, SrcColor, OneMinusDstColor, SrcAlpha, OneMinusSrcColor, DstAlpha, OneMinusDstAlpha, SrcAlphaSaturate, OneMinusSrcAlpha } [NativeHeader("Runtime/GfxDevice/GfxDeviceTypes.h")] public enum BlendOp { Add, Subtract, ReverseSubtract, Min, Max, LogicalClear, LogicalSet, LogicalCopy, LogicalCopyInverted, LogicalNoop, LogicalInvert, LogicalAnd, LogicalNand, LogicalOr, LogicalNor, LogicalXor, LogicalEquivalence, LogicalAndReverse, LogicalAndInverted, LogicalOrReverse, LogicalOrInverted, Multiply, Screen, Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, HSLHue, HSLSaturation, HSLColor, HSLLuminosity } [NativeHeader("Runtime/GfxDevice/GfxDeviceTypes.h")] public enum CompareFunction { Disabled, Never, Less, Equal, LessEqual, Greater, NotEqual, GreaterEqual, Always } [NativeHeader("Runtime/GfxDevice/GfxDeviceTypes.h")] public enum CullMode { Off, Front, Back } [Flags] public enum ColorWriteMask { Alpha = 1, Blue = 2, Green = 4, Red = 8, All = 0xF } [NativeHeader("Runtime/GfxDevice/GfxDeviceTypes.h")] public enum StencilOp { Keep, Zero, Replace, IncrementSaturate, DecrementSaturate, Invert, IncrementWrap, DecrementWrap } public enum AmbientMode { Skybox = 0, Trilight = 1, Flat = 3, Custom = 4 } public enum DefaultReflectionMode { Skybox, Custom } public enum ReflectionCubemapCompression { Uncompressed, Compressed, Auto } public enum CameraEvent { BeforeDepthTexture, AfterDepthTexture, BeforeDepthNormalsTexture, AfterDepthNormalsTexture, BeforeGBuffer, AfterGBuffer, BeforeLighting, AfterLighting, BeforeFinalPass, AfterFinalPass, BeforeForwardOpaque, AfterForwardOpaque, BeforeImageEffectsOpaque, AfterImageEffectsOpaque, BeforeSkybox, AfterSkybox, BeforeForwardAlpha, AfterForwardAlpha, BeforeImageEffects, AfterImageEffects, AfterEverything, BeforeReflections, AfterReflections, BeforeHaloAndLensFlares, AfterHaloAndLensFlares } internal static class CameraEventUtils { private const CameraEvent k_MinimumValue = CameraEvent.BeforeDepthTexture; private const CameraEvent k_MaximumValue = CameraEvent.AfterHaloAndLensFlares; public static bool IsValid(CameraEvent value) { return value >= CameraEvent.BeforeDepthTexture && value <= CameraEvent.AfterHaloAndLensFlares; } } public enum LightEvent { BeforeShadowMap, AfterShadowMap, BeforeScreenspaceMask, AfterScreenspaceMask, BeforeShadowMapPass, AfterShadowMapPass } [Flags] public enum ShadowMapPass { PointlightPositiveX = 1, PointlightNegativeX = 2, PointlightPositiveY = 4, PointlightNegativeY = 8, PointlightPositiveZ = 0x10, PointlightNegativeZ = 0x20, DirectionalCascade0 = 0x40, DirectionalCascade1 = 0x80, DirectionalCascade2 = 0x100, DirectionalCascade3 = 0x200, Spotlight = 0x400, Pointlight = 0x3F, Directional = 0x3C0, All = 0x7FF } public enum BuiltinRenderTextureType { PropertyName = -4, BufferPtr = -3, RenderTexture = -2, BindableTexture = -1, None = 0, CurrentActive = 1, CameraTarget = 2, Depth = 3, DepthNormals = 4, ResolvedDepth = 5, PrepassNormalsSpec = 7, PrepassLight = 8, PrepassLightSpec = 9, GBuffer0 = 10, GBuffer1 = 11, GBuffer2 = 12, GBuffer3 = 13, Reflections = 14, MotionVectors = 15, GBuffer4 = 16, GBuffer5 = 17, GBuffer6 = 18, GBuffer7 = 19 } public enum PassType { Normal = 0, Vertex = 1, VertexLM = 2, [Obsolete("VertexLMRGBM PassType is obsolete. Please use VertexLM PassType together with DecodeLightmap shader function.")] VertexLMRGBM = 3, ForwardBase = 4, ForwardAdd = 5, LightPrePassBase = 6, LightPrePassFinal = 7, ShadowCaster = 8, Deferred = 10, Meta = 11, MotionVectors = 12, ScriptableRenderPipeline = 13, ScriptableRenderPipelineDefaultUnlit = 14, GrabPass = 15 } public enum ShadowCastingMode { Off, On, TwoSided, ShadowsOnly } public enum LightShadowResolution { FromQualitySettings = -1, Low, Medium, High, VeryHigh } [UsedByNativeCode] public enum GraphicsDeviceType { [Obsolete("OpenGL2 is no longer supported in Unity 5.5+")] OpenGL2 = 0, [Obsolete("Direct3D 9 is no longer supported in Unity 2017.2+")] Direct3D9 = 1, Direct3D11 = 2, [Obsolete("PS3 is no longer supported in Unity 5.5+")] PlayStation3 = 3, Null = 4, [Obsolete("Xbox360 is no longer supported in Unity 5.5+")] Xbox360 = 6, OpenGLES2 = 8, OpenGLES3 = 11, [Obsolete("PVita is no longer supported as of Unity 2018")] PlayStationVita = 12, PlayStation4 = 13, XboxOne = 14, [Obsolete("PlayStationMobile is no longer supported in Unity 5.3+")] PlayStationMobile = 15, Metal = 16, OpenGLCore = 17, Direct3D12 = 18, [Obsolete("Nintendo 3DS support is unavailable since 2018.1")] N3DS = 19, Vulkan = 21, Switch = 22, XboxOneD3D12 = 23, GameCoreXboxOne = 24, [Obsolete("GameCoreScarlett is deprecated, please use GameCoreXboxSeries (UnityUpgradable) -> GameCoreXboxSeries", false)] GameCoreScarlett = -1, GameCoreXboxSeries = 25, PlayStation5 = 26, PlayStation5NGGC = 27 } public enum GraphicsTier { Tier1, Tier2, Tier3 } public struct SubMeshDescriptor { public Bounds bounds { get; set; } public MeshTopology topology { get; set; } public int indexStart { get; set; } public int indexCount { get; set; } public int baseVertex { get; set; } public int firstVertex { get; set; } public int vertexCount { get; set; } public SubMeshDescriptor(int indexStart, int indexCount, MeshTopology topology = MeshTopology.Triangles) { this.indexStart = indexStart; this.indexCount = indexCount; this.topology = topology; bounds = default(Bounds); baseVertex = 0; firstVertex = 0; vertexCount = 0; } public override string ToString() { return $"(topo={topology} indices={indexStart},{indexCount} vertices={firstVertex},{vertexCount} basevtx={baseVertex} bounds={bounds})"; } } [UsedByNativeCode] public struct VertexAttributeDescriptor : IEquatable { public VertexAttribute attribute { get; set; } public VertexAttributeFormat format { get; set; } public int dimension { get; set; } public int stream { get; set; } public VertexAttributeDescriptor(VertexAttribute attribute = VertexAttribute.Position, VertexAttributeFormat format = VertexAttributeFormat.Float32, int dimension = 3, int stream = 0) { this.attribute = attribute; this.format = format; this.dimension = dimension; this.stream = stream; } public override string ToString() { return $"(attr={attribute} fmt={format} dim={dimension} stream={stream})"; } public override int GetHashCode() { int num = 17; num = (int)(num * 23 + attribute); num = (int)(num * 23 + format); num = num * 23 + dimension; return num * 23 + stream; } public override bool Equals(object other) { if (!(other is VertexAttributeDescriptor)) { return false; } return Equals((VertexAttributeDescriptor)other); } public bool Equals(VertexAttributeDescriptor other) { return attribute == other.attribute && format == other.format && dimension == other.dimension && stream == other.stream; } public static bool operator ==(VertexAttributeDescriptor lhs, VertexAttributeDescriptor rhs) { return lhs.Equals(rhs); } public static bool operator !=(VertexAttributeDescriptor lhs, VertexAttributeDescriptor rhs) { return !lhs.Equals(rhs); } } public enum FormatSwizzle { FormatSwizzleR, FormatSwizzleG, FormatSwizzleB, FormatSwizzleA, FormatSwizzle0, FormatSwizzle1 } public struct RenderTargetIdentifier : IEquatable { public const int AllDepthSlices = -1; private BuiltinRenderTextureType m_Type; private int m_NameID; private int m_InstanceID; private IntPtr m_BufferPointer; private int m_MipLevel; private CubemapFace m_CubeFace; private int m_DepthSlice; public RenderTargetIdentifier(BuiltinRenderTextureType type) { m_Type = type; m_NameID = -1; m_InstanceID = 0; m_BufferPointer = IntPtr.Zero; m_MipLevel = 0; m_CubeFace = CubemapFace.Unknown; m_DepthSlice = 0; } public RenderTargetIdentifier(BuiltinRenderTextureType type, int mipLevel = 0, CubemapFace cubeFace = CubemapFace.Unknown, int depthSlice = 0) { m_Type = type; m_NameID = -1; m_InstanceID = 0; m_BufferPointer = IntPtr.Zero; m_MipLevel = mipLevel; m_CubeFace = cubeFace; m_DepthSlice = depthSlice; } public RenderTargetIdentifier(string name) { m_Type = BuiltinRenderTextureType.PropertyName; m_NameID = Shader.PropertyToID(name); m_InstanceID = 0; m_BufferPointer = IntPtr.Zero; m_MipLevel = 0; m_CubeFace = CubemapFace.Unknown; m_DepthSlice = 0; } public RenderTargetIdentifier(string name, int mipLevel = 0, CubemapFace cubeFace = CubemapFace.Unknown, int depthSlice = 0) { m_Type = BuiltinRenderTextureType.PropertyName; m_NameID = Shader.PropertyToID(name); m_InstanceID = 0; m_BufferPointer = IntPtr.Zero; m_MipLevel = mipLevel; m_CubeFace = cubeFace; m_DepthSlice = depthSlice; } public RenderTargetIdentifier(int nameID) { m_Type = BuiltinRenderTextureType.PropertyName; m_NameID = nameID; m_InstanceID = 0; m_BufferPointer = IntPtr.Zero; m_MipLevel = 0; m_CubeFace = CubemapFace.Unknown; m_DepthSlice = 0; } public RenderTargetIdentifier(int nameID, int mipLevel = 0, CubemapFace cubeFace = CubemapFace.Unknown, int depthSlice = 0) { m_Type = BuiltinRenderTextureType.PropertyName; m_NameID = nameID; m_InstanceID = 0; m_BufferPointer = IntPtr.Zero; m_MipLevel = mipLevel; m_CubeFace = cubeFace; m_DepthSlice = depthSlice; } public RenderTargetIdentifier(RenderTargetIdentifier renderTargetIdentifier, int mipLevel, CubemapFace cubeFace = CubemapFace.Unknown, int depthSlice = 0) { m_Type = renderTargetIdentifier.m_Type; m_NameID = renderTargetIdentifier.m_NameID; m_InstanceID = renderTargetIdentifier.m_InstanceID; m_BufferPointer = renderTargetIdentifier.m_BufferPointer; m_MipLevel = mipLevel; m_CubeFace = cubeFace; m_DepthSlice = depthSlice; } public RenderTargetIdentifier(Texture tex) { if (tex == null) { m_Type = BuiltinRenderTextureType.None; } else if (tex is RenderTexture) { m_Type = BuiltinRenderTextureType.RenderTexture; } else { m_Type = BuiltinRenderTextureType.BindableTexture; } m_BufferPointer = IntPtr.Zero; m_NameID = -1; m_InstanceID = (tex ? tex.GetInstanceID() : 0); m_MipLevel = 0; m_CubeFace = CubemapFace.Unknown; m_DepthSlice = 0; } public RenderTargetIdentifier(Texture tex, int mipLevel = 0, CubemapFace cubeFace = CubemapFace.Unknown, int depthSlice = 0) { if (tex == null) { m_Type = BuiltinRenderTextureType.None; } else if (tex is RenderTexture) { m_Type = BuiltinRenderTextureType.RenderTexture; } else { m_Type = BuiltinRenderTextureType.BindableTexture; } m_BufferPointer = IntPtr.Zero; m_NameID = -1; m_InstanceID = (tex ? tex.GetInstanceID() : 0); m_MipLevel = mipLevel; m_CubeFace = cubeFace; m_DepthSlice = depthSlice; } public RenderTargetIdentifier(RenderBuffer buf, int mipLevel = 0, CubemapFace cubeFace = CubemapFace.Unknown, int depthSlice = 0) { m_Type = BuiltinRenderTextureType.BufferPtr; m_NameID = -1; m_InstanceID = buf.m_RenderTextureInstanceID; m_BufferPointer = buf.m_BufferPtr; m_MipLevel = mipLevel; m_CubeFace = cubeFace; m_DepthSlice = depthSlice; } public static implicit operator RenderTargetIdentifier(BuiltinRenderTextureType type) { return new RenderTargetIdentifier(type); } public static implicit operator RenderTargetIdentifier(string name) { return new RenderTargetIdentifier(name); } public static implicit operator RenderTargetIdentifier(int nameID) { return new RenderTargetIdentifier(nameID); } public static implicit operator RenderTargetIdentifier(Texture tex) { return new RenderTargetIdentifier(tex); } public static implicit operator RenderTargetIdentifier(RenderBuffer buf) { return new RenderTargetIdentifier(buf); } public override string ToString() { return UnityString.Format("Type {0} NameID {1} InstanceID {2} BufferPointer {3} MipLevel {4} CubeFace {5} DepthSlice {6}", new object[7] { m_Type, m_NameID, m_InstanceID, m_BufferPointer, m_MipLevel, m_CubeFace, m_DepthSlice }); } public override int GetHashCode() { return (m_Type.GetHashCode() * 23 + m_NameID.GetHashCode()) * 23 + m_InstanceID.GetHashCode(); } public bool Equals(RenderTargetIdentifier rhs) { return m_Type == rhs.m_Type && m_NameID == rhs.m_NameID && m_InstanceID == rhs.m_InstanceID && m_BufferPointer == rhs.m_BufferPointer && m_MipLevel == rhs.m_MipLevel && m_CubeFace == rhs.m_CubeFace && m_DepthSlice == rhs.m_DepthSlice; } public override bool Equals(object obj) { if (!(obj is RenderTargetIdentifier rhs)) { return false; } return Equals(rhs); } public static bool operator ==(RenderTargetIdentifier lhs, RenderTargetIdentifier rhs) { return lhs.Equals(rhs); } public static bool operator !=(RenderTargetIdentifier lhs, RenderTargetIdentifier rhs) { return !lhs.Equals(rhs); } } [Flags] public enum RenderTargetFlags { None = 0, ReadOnlyDepth = 1, ReadOnlyStencil = 2, ReadOnlyDepthStencil = 3 } public struct RenderTargetBinding { private RenderTargetIdentifier[] m_ColorRenderTargets; private RenderTargetIdentifier m_DepthRenderTarget; private RenderBufferLoadAction[] m_ColorLoadActions; private RenderBufferStoreAction[] m_ColorStoreActions; private RenderBufferLoadAction m_DepthLoadAction; private RenderBufferStoreAction m_DepthStoreAction; private RenderTargetFlags m_Flags; public RenderTargetIdentifier[] colorRenderTargets { get { return m_ColorRenderTargets; } set { m_ColorRenderTargets = value; } } public RenderTargetIdentifier depthRenderTarget { get { return m_DepthRenderTarget; } set { m_DepthRenderTarget = value; } } public RenderBufferLoadAction[] colorLoadActions { get { return m_ColorLoadActions; } set { m_ColorLoadActions = value; } } public RenderBufferStoreAction[] colorStoreActions { get { return m_ColorStoreActions; } set { m_ColorStoreActions = value; } } public RenderBufferLoadAction depthLoadAction { get { return m_DepthLoadAction; } set { m_DepthLoadAction = value; } } public RenderBufferStoreAction depthStoreAction { get { return m_DepthStoreAction; } set { m_DepthStoreAction = value; } } public RenderTargetFlags flags { get { return m_Flags; } set { m_Flags = value; } } public RenderTargetBinding(RenderTargetIdentifier[] colorRenderTargets, RenderBufferLoadAction[] colorLoadActions, RenderBufferStoreAction[] colorStoreActions, RenderTargetIdentifier depthRenderTarget, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction) { m_ColorRenderTargets = colorRenderTargets; m_DepthRenderTarget = depthRenderTarget; m_ColorLoadActions = colorLoadActions; m_ColorStoreActions = colorStoreActions; m_DepthLoadAction = depthLoadAction; m_DepthStoreAction = depthStoreAction; m_Flags = RenderTargetFlags.None; } public RenderTargetBinding(RenderTargetIdentifier colorRenderTarget, RenderBufferLoadAction colorLoadAction, RenderBufferStoreAction colorStoreAction, RenderTargetIdentifier depthRenderTarget, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction) : this(new RenderTargetIdentifier[1] { colorRenderTarget }, new RenderBufferLoadAction[1] { colorLoadAction }, new RenderBufferStoreAction[1] { colorStoreAction }, depthRenderTarget, depthLoadAction, depthStoreAction) { } public RenderTargetBinding(RenderTargetSetup setup) { m_ColorRenderTargets = new RenderTargetIdentifier[setup.color.Length]; for (int i = 0; i < m_ColorRenderTargets.Length; i++) { m_ColorRenderTargets[i] = new RenderTargetIdentifier(setup.color[i], setup.mipLevel, setup.cubemapFace, setup.depthSlice); } m_DepthRenderTarget = setup.depth; m_ColorLoadActions = (RenderBufferLoadAction[])setup.colorLoad.Clone(); m_ColorStoreActions = (RenderBufferStoreAction[])setup.colorStore.Clone(); m_DepthLoadAction = setup.depthLoad; m_DepthStoreAction = setup.depthStore; m_Flags = RenderTargetFlags.None; } } public enum ReflectionProbeUsage { Off, BlendProbes, BlendProbesAndSkybox, Simple } public enum ReflectionProbeType { Cube, Card } public enum ReflectionProbeClearFlags { Skybox = 1, SolidColor } public enum ReflectionProbeMode { Baked, Realtime, Custom } [UsedByNativeCode] public struct ReflectionProbeBlendInfo { public ReflectionProbe probe; public float weight; } public enum ReflectionProbeRefreshMode { OnAwake, EveryFrame, ViaScripting } public enum ReflectionProbeTimeSlicingMode { AllFacesAtOnce, IndividualFaces, NoTimeSlicing } public enum ShadowSamplingMode { CompareDepths, RawDepth, None } public enum LightProbeUsage { Off = 0, BlendProbes = 1, UseProxyVolume = 2, CustomProvided = 4 } public enum BuiltinShaderType { DeferredShading, DeferredReflections, LegacyDeferredLighting, ScreenSpaceShadows, DepthNormals, MotionVectors, LightHalo, LensFlare } public enum BuiltinShaderMode { Disabled, UseBuiltin, UseCustom } public enum BuiltinShaderDefine { UNITY_NO_DXT5nm, UNITY_NO_RGBM, UNITY_USE_NATIVE_HDR, UNITY_ENABLE_REFLECTION_BUFFERS, UNITY_FRAMEBUFFER_FETCH_AVAILABLE, UNITY_ENABLE_NATIVE_SHADOW_LOOKUPS, UNITY_METAL_SHADOWS_USE_POINT_FILTERING, UNITY_NO_CUBEMAP_ARRAY, UNITY_NO_SCREENSPACE_SHADOWS, UNITY_USE_DITHER_MASK_FOR_ALPHABLENDED_SHADOWS, UNITY_PBS_USE_BRDF1, UNITY_PBS_USE_BRDF2, UNITY_PBS_USE_BRDF3, UNITY_NO_FULL_STANDARD_SHADER, UNITY_SPECCUBE_BOX_PROJECTION, UNITY_SPECCUBE_BLENDING, UNITY_ENABLE_DETAIL_NORMALMAP, SHADER_API_MOBILE, SHADER_API_DESKTOP, UNITY_HARDWARE_TIER1, UNITY_HARDWARE_TIER2, UNITY_HARDWARE_TIER3, UNITY_COLORSPACE_GAMMA, UNITY_LIGHT_PROBE_PROXY_VOLUME, UNITY_HALF_PRECISION_FRAGMENT_SHADER_REGISTERS, UNITY_LIGHTMAP_DLDR_ENCODING, UNITY_LIGHTMAP_RGBM_ENCODING, UNITY_LIGHTMAP_FULL_HDR, UNITY_VIRTUAL_TEXTURING, UNITY_PRETRANSFORM_TO_DISPLAY_ORIENTATION, UNITY_ASTC_NORMALMAP_ENCODING, SHADER_API_GLES30, UNITY_UNIFIED_SHADER_PRECISION_MODEL } public enum VideoShadersIncludeMode { Never, Referenced, Always } public enum TextureDimension { Unknown = -1, None, Any, Tex2D, Tex3D, Cube, Tex2DArray, CubeArray } [Flags] public enum CopyTextureSupport { None = 0, Basic = 1, Copy3D = 2, DifferentTypes = 4, TextureToRT = 8, RTToTexture = 0x10 } public enum CameraHDRMode { FP16 = 1, R11G11B10 } public enum RealtimeGICPUUsage { Low = 25, Medium = 50, High = 75, Unlimited = 100 } public enum ComputeQueueType { Default, Background, Urgent } public enum SinglePassStereoMode { None, SideBySide, Instancing, Multiview } public enum CommandBufferExecutionFlags { None = 0, AsyncCompute = 2 } [Flags] public enum RTClearFlags { None = 0, Color = 1, Depth = 2, Stencil = 4, All = 7, DepthStencil = 6, ColorDepth = 3, ColorStencil = 5 } public enum RenderTextureSubElement { Color, Depth, Stencil, Default } [MovedFrom("UnityEngine.Experimental.Rendering")] public enum RenderingThreadingMode { Direct, SingleThreaded, MultiThreaded, LegacyJobified, NativeGraphicsJobs, NativeGraphicsJobsWithoutRenderThread } public enum CameraLateLatchMatrixType { View, InverseView, ViewProjection, InverseViewProjection } public enum OpenGLESVersion { None, OpenGLES20, OpenGLES30, OpenGLES31, OpenGLES31AEP, OpenGLES32 } public enum SynchronisationStageFlags { VertexProcessing = 1, PixelProcessing = 2, ComputeProcessing = 4, AllGPUOperations = 7 } public enum GraphicsFenceType { AsyncQueueSynchronisation, CPUSynchronisation } [NativeHeader("Runtime/Graphics/GPUFence.h")] [UsedByNativeCode] public struct GraphicsFence { internal IntPtr m_Ptr; internal int m_Version; internal GraphicsFenceType m_FenceType; public bool passed { get { Validate(); if (!SystemInfo.supportsGraphicsFence || (m_FenceType == GraphicsFenceType.AsyncQueueSynchronisation && !SystemInfo.supportsAsyncCompute)) { throw new NotSupportedException("Cannot determine if this GraphicsFence has passed as this platform has not implemented GraphicsFences."); } if (!IsFencePending()) { return true; } return HasFencePassed_Internal(m_Ptr); } } internal static SynchronisationStageFlags TranslateSynchronizationStageToFlags(SynchronisationStage s) { return (s == SynchronisationStage.VertexProcessing) ? SynchronisationStageFlags.VertexProcessing : SynchronisationStageFlags.PixelProcessing; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GPUFenceInternals::HasFencePassed_Internal")] private static extern bool HasFencePassed_Internal(IntPtr fencePtr); internal void InitPostAllocation() { if (m_Ptr == IntPtr.Zero) { if (SystemInfo.supportsGraphicsFence) { throw new NullReferenceException("The internal fence ptr is null, this should not be possible for fences that have been correctly constructed using Graphics.CreateGraphicsFence() or CommandBuffer.CreateGraphicsFence()"); } m_Version = GetPlatformNotSupportedVersion(); } else { m_Version = GetVersionNumber(m_Ptr); } } internal bool IsFencePending() { if (m_Ptr == IntPtr.Zero) { return false; } return m_Version == GetVersionNumber(m_Ptr); } internal void Validate() { if (m_Version == 0 || (SystemInfo.supportsGraphicsFence && m_Version == GetPlatformNotSupportedVersion())) { throw new InvalidOperationException("This GraphicsFence object has not been correctly constructed see Graphics.CreateGraphicsFence() or CommandBuffer.CreateGraphicsFence()"); } } private int GetPlatformNotSupportedVersion() { return -1; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] [FreeFunction("GPUFenceInternals::GetVersionNumber")] private static extern int GetVersionNumber(IntPtr fencePtr); } [NativeHeader("Runtime/Camera/GraphicsSettings.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public sealed class GraphicsSettings : Object { public static extern TransparencySortMode transparencySortMode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static Vector3 transparencySortAxis { get { get_transparencySortAxis_Injected(out var ret); return ret; } set { set_transparencySortAxis_Injected(ref value); } } public static extern bool realtimeDirectRectangularAreaLights { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool lightsUseLinearIntensity { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool lightsUseColorTemperature { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern uint defaultRenderingLayerMask { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool useScriptableRenderPipelineBatching { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool logWhenShaderIsCompiled { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool disableBuiltinCustomRenderTextureUpdate { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern VideoShadersIncludeMode videoShadersIncludeMode { [MethodImpl(MethodImplOptions.InternalCall)] get; } [NativeName("CurrentRenderPipeline")] private static extern ScriptableObject INTERNAL_currentRenderPipeline { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static RenderPipelineAsset currentRenderPipeline => INTERNAL_currentRenderPipeline as RenderPipelineAsset; public static RenderPipelineAsset renderPipelineAsset { get { return defaultRenderPipeline; } set { defaultRenderPipeline = value; } } [NativeName("DefaultRenderPipeline")] private static extern ScriptableObject INTERNAL_defaultRenderPipeline { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static RenderPipelineAsset defaultRenderPipeline { get { return INTERNAL_defaultRenderPipeline as RenderPipelineAsset; } set { INTERNAL_defaultRenderPipeline = value; } } public static RenderPipelineAsset[] allConfiguredRenderPipelines => GetAllConfiguredRenderPipelines().Cast().ToArray(); public static extern bool cameraRelativeLightCulling { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern bool cameraRelativeShadowCulling { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } private GraphicsSettings() { } [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool HasShaderDefine(GraphicsTier tier, BuiltinShaderDefine defineHash); public static bool HasShaderDefine(BuiltinShaderDefine defineHash) { return HasShaderDefine(Graphics.activeTier, defineHash); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetAllConfiguredRenderPipelinesForScript")] private static extern ScriptableObject[] GetAllConfiguredRenderPipelines(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern Object GetGraphicsSettings(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetShaderModeScript")] public static extern void SetShaderMode(BuiltinShaderType type, BuiltinShaderMode mode); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetShaderModeScript")] public static extern BuiltinShaderMode GetShaderMode(BuiltinShaderType type); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("SetCustomShaderScript")] public static extern void SetCustomShader(BuiltinShaderType type, Shader shader); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetCustomShaderScript")] public static extern Shader GetCustomShader(BuiltinShaderType type); public static void RegisterRenderPipelineSettings(RenderPipelineGlobalSettings settings) where T : RenderPipeline { RegisterRenderPipeline(typeof(T).FullName, settings); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("RegisterRenderPipelineSettings")] private static extern void RegisterRenderPipeline(string renderpipelineName, Object settings); public static void UnregisterRenderPipelineSettings() where T : RenderPipeline { UnregisterRenderPipeline(typeof(T).FullName); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("UnregisterRenderPipelineSettings")] private static extern void UnregisterRenderPipeline(string renderpipelineName); public static RenderPipelineGlobalSettings GetSettingsForRenderPipeline() where T : RenderPipeline { return GetSettingsForRenderPipeline(typeof(T).FullName) as RenderPipelineGlobalSettings; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetSettingsForRenderPipeline")] private static extern Object GetSettingsForRenderPipeline(string renderpipelineName); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_transparencySortAxis_Injected(out Vector3 ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_transparencySortAxis_Injected(ref Vector3 value); } [RequiredByNativeCode] public class OnDemandRendering { private static int m_RenderFrameInterval = 1; public static bool willCurrentFrameRender => Time.frameCount % renderFrameInterval == 0; public static int renderFrameInterval { get { return m_RenderFrameInterval; } set { m_RenderFrameInterval = Math.Max(1, value); } } public static int effectiveRenderFrameRate { get { float num = GetEffectiveRenderFrameRate(); if ((double)num <= 0.0) { return (int)num; } return (int)(num + 0.5f); } } [RequiredByNativeCode] internal static void GetRenderFrameInterval(out int frameInterval) { frameInterval = renderFrameInterval; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] internal static extern float GetEffectiveRenderFrameRate(); } [UsedByNativeCode] [NativeType("Runtime/Graphics/CommandBuffer/RenderingCommandBuffer.h")] [NativeHeader("Runtime/Export/Graphics/RenderingCommandBuffer.bindings.h")] [NativeHeader("Runtime/Shaders/ComputeShader.h")] [NativeHeader("Runtime/Shaders/RayTracingShader.h")] public class CommandBuffer : IDisposable { internal IntPtr m_Ptr; public extern string name { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int sizeInBytes { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("GetBufferSize")] get; } public void ConvertTexture(RenderTargetIdentifier src, RenderTargetIdentifier dst) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); ConvertTexture_Internal(src, 0, dst, 0); } public void ConvertTexture(RenderTargetIdentifier src, int srcElement, RenderTargetIdentifier dst, int dstElement) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); ConvertTexture_Internal(src, srcElement, dst, dstElement); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddWaitAllAsyncReadbackRequests")] public extern void WaitAllAsyncReadbackRequests(); public unsafe void RequestAsyncReadback(ComputeBuffer src, Action callback) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_RequestAsyncReadback_1(src, callback, null); } public unsafe void RequestAsyncReadback(GraphicsBuffer src, Action callback) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_RequestAsyncReadback_8(src, callback, null); } public unsafe void RequestAsyncReadback(ComputeBuffer src, int size, int offset, Action callback) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_RequestAsyncReadback_2(src, size, offset, callback, null); } public unsafe void RequestAsyncReadback(GraphicsBuffer src, int size, int offset, Action callback) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_RequestAsyncReadback_9(src, size, offset, callback, null); } public unsafe void RequestAsyncReadback(Texture src, Action callback) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_RequestAsyncReadback_3(src, callback, null); } public unsafe void RequestAsyncReadback(Texture src, int mipIndex, Action callback) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_RequestAsyncReadback_4(src, mipIndex, callback, null); } public unsafe void RequestAsyncReadback(Texture src, int mipIndex, TextureFormat dstFormat, Action callback) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_RequestAsyncReadback_5(src, mipIndex, GraphicsFormatUtility.GetGraphicsFormat(dstFormat, QualitySettings.activeColorSpace == ColorSpace.Linear), callback, null); } public unsafe void RequestAsyncReadback(Texture src, int mipIndex, GraphicsFormat dstFormat, Action callback) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_RequestAsyncReadback_5(src, mipIndex, dstFormat, callback, null); } public unsafe void RequestAsyncReadback(Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, Action callback) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_RequestAsyncReadback_6(src, mipIndex, x, width, y, height, z, depth, callback, null); } public unsafe void RequestAsyncReadback(Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, TextureFormat dstFormat, Action callback) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_RequestAsyncReadback_7(src, mipIndex, x, width, y, height, z, depth, GraphicsFormatUtility.GetGraphicsFormat(dstFormat, QualitySettings.activeColorSpace == ColorSpace.Linear), callback, null); } public unsafe void RequestAsyncReadback(Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, GraphicsFormat dstFormat, Action callback) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_RequestAsyncReadback_7(src, mipIndex, x, width, y, height, z, depth, dstFormat, callback, null); } public unsafe void RequestAsyncReadbackIntoNativeArray(ref NativeArray output, ComputeBuffer src, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_1(src, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeArray(ref NativeArray output, ComputeBuffer src, int size, int offset, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_2(src, size, offset, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeArray(ref NativeArray output, GraphicsBuffer src, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_8(src, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeArray(ref NativeArray output, GraphicsBuffer src, int size, int offset, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_9(src, size, offset, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeArray(ref NativeArray output, Texture src, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_3(src, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeArray(ref NativeArray output, Texture src, int mipIndex, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_4(src, mipIndex, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeArray(ref NativeArray output, Texture src, int mipIndex, TextureFormat dstFormat, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_5(src, mipIndex, GraphicsFormatUtility.GetGraphicsFormat(dstFormat, QualitySettings.activeColorSpace == ColorSpace.Linear), callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeArray(ref NativeArray output, Texture src, int mipIndex, GraphicsFormat dstFormat, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_5(src, mipIndex, dstFormat, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeArray(ref NativeArray output, Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_6(src, mipIndex, x, width, y, height, z, depth, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeArray(ref NativeArray output, Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, TextureFormat dstFormat, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_7(src, mipIndex, x, width, y, height, z, depth, GraphicsFormatUtility.GetGraphicsFormat(dstFormat, QualitySettings.activeColorSpace == ColorSpace.Linear), callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeArray(ref NativeArray output, Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, GraphicsFormat dstFormat, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_7(src, mipIndex, x, width, y, height, z, depth, dstFormat, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeSlice(ref NativeSlice output, ComputeBuffer src, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_1(src, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeSlice(ref NativeSlice output, ComputeBuffer src, int size, int offset, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_2(src, size, offset, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeSlice(ref NativeSlice output, GraphicsBuffer src, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_8(src, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeSlice(ref NativeSlice output, GraphicsBuffer src, int size, int offset, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_9(src, size, offset, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeSlice(ref NativeSlice output, Texture src, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_3(src, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeSlice(ref NativeSlice output, Texture src, int mipIndex, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_4(src, mipIndex, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeSlice(ref NativeSlice output, Texture src, int mipIndex, TextureFormat dstFormat, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_5(src, mipIndex, GraphicsFormatUtility.GetGraphicsFormat(dstFormat, QualitySettings.activeColorSpace == ColorSpace.Linear), callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeSlice(ref NativeSlice output, Texture src, int mipIndex, GraphicsFormat dstFormat, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_5(src, mipIndex, dstFormat, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeSlice(ref NativeSlice output, Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_6(src, mipIndex, x, width, y, height, z, depth, callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeSlice(ref NativeSlice output, Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, TextureFormat dstFormat, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_7(src, mipIndex, x, width, y, height, z, depth, GraphicsFormatUtility.GetGraphicsFormat(dstFormat, QualitySettings.activeColorSpace == ColorSpace.Linear), callback, &asyncRequestNativeArrayData); } public unsafe void RequestAsyncReadbackIntoNativeSlice(ref NativeSlice output, Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, GraphicsFormat dstFormat, Action callback) where T : struct { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); AsyncRequestNativeArrayData asyncRequestNativeArrayData = AsyncRequestNativeArrayData.CreateAndCheckAccess(output); Internal_RequestAsyncReadback_7(src, mipIndex, x, width, y, height, z, depth, dstFormat, callback, &asyncRequestNativeArrayData); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddRequestAsyncReadback")] private unsafe extern void Internal_RequestAsyncReadback_1([NotNull("ArgumentNullException")] ComputeBuffer src, [NotNull("ArgumentNullException")] Action callback, AsyncRequestNativeArrayData* nativeArrayData = null); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddRequestAsyncReadback")] private unsafe extern void Internal_RequestAsyncReadback_2([NotNull("ArgumentNullException")] ComputeBuffer src, int size, int offset, [NotNull("ArgumentNullException")] Action callback, AsyncRequestNativeArrayData* nativeArrayData = null); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddRequestAsyncReadback")] private unsafe extern void Internal_RequestAsyncReadback_3([NotNull("ArgumentNullException")] Texture src, [NotNull("ArgumentNullException")] Action callback, AsyncRequestNativeArrayData* nativeArrayData = null); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddRequestAsyncReadback")] private unsafe extern void Internal_RequestAsyncReadback_4([NotNull("ArgumentNullException")] Texture src, int mipIndex, [NotNull("ArgumentNullException")] Action callback, AsyncRequestNativeArrayData* nativeArrayData = null); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddRequestAsyncReadback")] private unsafe extern void Internal_RequestAsyncReadback_5([NotNull("ArgumentNullException")] Texture src, int mipIndex, GraphicsFormat dstFormat, [NotNull("ArgumentNullException")] Action callback, AsyncRequestNativeArrayData* nativeArrayData = null); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddRequestAsyncReadback")] private unsafe extern void Internal_RequestAsyncReadback_6([NotNull("ArgumentNullException")] Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, [NotNull("ArgumentNullException")] Action callback, AsyncRequestNativeArrayData* nativeArrayData = null); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddRequestAsyncReadback")] private unsafe extern void Internal_RequestAsyncReadback_7([NotNull("ArgumentNullException")] Texture src, int mipIndex, int x, int width, int y, int height, int z, int depth, GraphicsFormat dstFormat, [NotNull("ArgumentNullException")] Action callback, AsyncRequestNativeArrayData* nativeArrayData = null); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddRequestAsyncReadback")] private unsafe extern void Internal_RequestAsyncReadback_8([NotNull("ArgumentNullException")] GraphicsBuffer src, [NotNull("ArgumentNullException")] Action callback, AsyncRequestNativeArrayData* nativeArrayData = null); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddRequestAsyncReadback")] private unsafe extern void Internal_RequestAsyncReadback_9([NotNull("ArgumentNullException")] GraphicsBuffer src, int size, int offset, [NotNull("ArgumentNullException")] Action callback, AsyncRequestNativeArrayData* nativeArrayData = null); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddSetInvertCulling")] public extern void SetInvertCulling(bool invertCulling); private void ConvertTexture_Internal(RenderTargetIdentifier src, int srcElement, RenderTargetIdentifier dst, int dstElement) { ConvertTexture_Internal_Injected(ref src, srcElement, ref dst, dstElement); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetSinglePassStereo", HasExplicitThis = true)] private extern void Internal_SetSinglePassStereo(SinglePassStereoMode mode); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::InitBuffer")] private static extern IntPtr InitBuffer(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::CreateGPUFence_Internal", HasExplicitThis = true)] private extern IntPtr CreateGPUFence_Internal(GraphicsFenceType fenceType, SynchronisationStageFlags stage); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::WaitOnGPUFence_Internal", HasExplicitThis = true)] private extern void WaitOnGPUFence_Internal(IntPtr fencePtr, SynchronisationStageFlags stage); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::ReleaseBuffer", HasExplicitThis = true, IsThreadSafe = true)] private extern void ReleaseBuffer(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetComputeFloatParam", HasExplicitThis = true)] public extern void SetComputeFloatParam([NotNull("ArgumentNullException")] ComputeShader computeShader, int nameID, float val); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetComputeIntParam", HasExplicitThis = true)] public extern void SetComputeIntParam([NotNull("ArgumentNullException")] ComputeShader computeShader, int nameID, int val); [FreeFunction("RenderingCommandBuffer_Bindings::SetComputeVectorParam", HasExplicitThis = true)] public void SetComputeVectorParam([NotNull("ArgumentNullException")] ComputeShader computeShader, int nameID, Vector4 val) { SetComputeVectorParam_Injected(computeShader, nameID, ref val); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetComputeVectorArrayParam", HasExplicitThis = true)] public extern void SetComputeVectorArrayParam([NotNull("ArgumentNullException")] ComputeShader computeShader, int nameID, [Unmarshalled] Vector4[] values); [FreeFunction("RenderingCommandBuffer_Bindings::SetComputeMatrixParam", HasExplicitThis = true)] public void SetComputeMatrixParam([NotNull("ArgumentNullException")] ComputeShader computeShader, int nameID, Matrix4x4 val) { SetComputeMatrixParam_Injected(computeShader, nameID, ref val); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetComputeMatrixArrayParam", HasExplicitThis = true)] public extern void SetComputeMatrixArrayParam([NotNull("ArgumentNullException")] ComputeShader computeShader, int nameID, [Unmarshalled] Matrix4x4[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetComputeFloats", HasExplicitThis = true)] private extern void Internal_SetComputeFloats([NotNull("ArgumentNullException")] ComputeShader computeShader, int nameID, [Unmarshalled] float[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetComputeInts", HasExplicitThis = true)] private extern void Internal_SetComputeInts([NotNull("ArgumentNullException")] ComputeShader computeShader, int nameID, [Unmarshalled] int[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetComputeTextureParam", HasExplicitThis = true)] private extern void Internal_SetComputeTextureParam([NotNull("ArgumentNullException")] ComputeShader computeShader, int kernelIndex, int nameID, ref RenderTargetIdentifier rt, int mipLevel, RenderTextureSubElement element); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetComputeBufferParam", HasExplicitThis = true)] private extern void Internal_SetComputeBufferParam([NotNull("ArgumentNullException")] ComputeShader computeShader, int kernelIndex, int nameID, ComputeBuffer buffer); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetComputeBufferParam", HasExplicitThis = true)] private extern void Internal_SetComputeGraphicsBufferParam([NotNull("ArgumentNullException")] ComputeShader computeShader, int kernelIndex, int nameID, GraphicsBuffer buffer); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetComputeConstantBufferParam", HasExplicitThis = true)] private extern void Internal_SetComputeConstantComputeBufferParam([NotNull("ArgumentNullException")] ComputeShader computeShader, int nameID, ComputeBuffer buffer, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetComputeConstantBufferParam", HasExplicitThis = true)] private extern void Internal_SetComputeConstantGraphicsBufferParam([NotNull("ArgumentNullException")] ComputeShader computeShader, int nameID, GraphicsBuffer buffer, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DispatchCompute", HasExplicitThis = true, ThrowsException = true)] private extern void Internal_DispatchCompute([NotNull("ArgumentNullException")] ComputeShader computeShader, int kernelIndex, int threadGroupsX, int threadGroupsY, int threadGroupsZ); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DispatchComputeIndirect", HasExplicitThis = true, ThrowsException = true)] private extern void Internal_DispatchComputeIndirect([NotNull("ArgumentNullException")] ComputeShader computeShader, int kernelIndex, ComputeBuffer indirectBuffer, uint argsOffset); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DispatchComputeIndirect", HasExplicitThis = true, ThrowsException = true)] private extern void Internal_DispatchComputeIndirectGraphicsBuffer([NotNull("ArgumentNullException")] ComputeShader computeShader, int kernelIndex, GraphicsBuffer indirectBuffer, uint argsOffset); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetRayTracingBufferParam", HasExplicitThis = true)] private extern void Internal_SetRayTracingBufferParam([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, int nameID, ComputeBuffer buffer); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetRayTracingConstantBufferParam", HasExplicitThis = true)] private extern void Internal_SetRayTracingConstantComputeBufferParam([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, int nameID, ComputeBuffer buffer, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetRayTracingConstantBufferParam", HasExplicitThis = true)] private extern void Internal_SetRayTracingConstantGraphicsBufferParam([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, int nameID, GraphicsBuffer buffer, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetRayTracingTextureParam", HasExplicitThis = true)] private extern void Internal_SetRayTracingTextureParam([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, int nameID, ref RenderTargetIdentifier rt); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetRayTracingFloatParam", HasExplicitThis = true)] private extern void Internal_SetRayTracingFloatParam([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, int nameID, float val); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetRayTracingIntParam", HasExplicitThis = true)] private extern void Internal_SetRayTracingIntParam([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, int nameID, int val); [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetRayTracingVectorParam", HasExplicitThis = true)] private void Internal_SetRayTracingVectorParam([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, int nameID, Vector4 val) { Internal_SetRayTracingVectorParam_Injected(rayTracingShader, nameID, ref val); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetRayTracingVectorArrayParam", HasExplicitThis = true)] private extern void Internal_SetRayTracingVectorArrayParam([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, int nameID, [Unmarshalled] Vector4[] values); [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetRayTracingMatrixParam", HasExplicitThis = true)] private void Internal_SetRayTracingMatrixParam([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, int nameID, Matrix4x4 val) { Internal_SetRayTracingMatrixParam_Injected(rayTracingShader, nameID, ref val); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetRayTracingMatrixArrayParam", HasExplicitThis = true)] private extern void Internal_SetRayTracingMatrixArrayParam([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, int nameID, [Unmarshalled] Matrix4x4[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetRayTracingFloats", HasExplicitThis = true)] private extern void Internal_SetRayTracingFloats([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, int nameID, [Unmarshalled] float[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetRayTracingInts", HasExplicitThis = true)] private extern void Internal_SetRayTracingInts([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, int nameID, [Unmarshalled] int[] values); [FreeFunction("RenderingCommandBuffer_Bindings::Internal_BuildRayTracingAccelerationStructure", HasExplicitThis = true)] private void Internal_BuildRayTracingAccelerationStructure([NotNull("ArgumentNullException")] RayTracingAccelerationStructure accelerationStructure, Vector3 relativeOrigin) { Internal_BuildRayTracingAccelerationStructure_Injected(accelerationStructure, ref relativeOrigin); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_SetRayTracingAccelerationStructure", HasExplicitThis = true)] private extern void Internal_SetRayTracingAccelerationStructure([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, int nameID, RayTracingAccelerationStructure accelerationStructure); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddSetRayTracingShaderPass")] public extern void SetRayTracingShaderPass([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, string passName); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DispatchRays", HasExplicitThis = true, ThrowsException = true)] private extern void Internal_DispatchRays([NotNull("ArgumentNullException")] RayTracingShader rayTracingShader, string rayGenShaderName, uint width, uint height, uint depth, Camera camera = null); [NativeMethod("AddGenerateMips")] private void Internal_GenerateMips(RenderTargetIdentifier rt) { Internal_GenerateMips_Injected(ref rt); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddResolveAntiAliasedSurface")] private extern void Internal_ResolveAntiAliasedSurface(RenderTexture rt, RenderTexture target); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddCopyCounterValue")] private extern void CopyCounterValueCC(ComputeBuffer src, ComputeBuffer dst, uint dstOffsetBytes); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddCopyCounterValue")] private extern void CopyCounterValueGC(GraphicsBuffer src, ComputeBuffer dst, uint dstOffsetBytes); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddCopyCounterValue")] private extern void CopyCounterValueCG(ComputeBuffer src, GraphicsBuffer dst, uint dstOffsetBytes); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddCopyCounterValue")] private extern void CopyCounterValueGG(GraphicsBuffer src, GraphicsBuffer dst, uint dstOffsetBytes); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("ClearCommands")] public extern void Clear(); [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DrawMesh", HasExplicitThis = true)] private void Internal_DrawMesh([NotNull("ArgumentNullException")] Mesh mesh, Matrix4x4 matrix, Material material, int submeshIndex, int shaderPass, MaterialPropertyBlock properties) { Internal_DrawMesh_Injected(mesh, ref matrix, material, submeshIndex, shaderPass, properties); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddDrawRenderer")] private extern void Internal_DrawRenderer([NotNull("ArgumentNullException")] Renderer renderer, Material material, int submeshIndex, int shaderPass); [NativeMethod("AddDrawRendererList")] private void Internal_DrawRendererList(RendererList rendererList) { Internal_DrawRendererList_Injected(ref rendererList); } private void Internal_DrawRenderer(Renderer renderer, Material material, int submeshIndex) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_DrawRenderer(renderer, material, submeshIndex, -1); } private void Internal_DrawRenderer(Renderer renderer, Material material) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_DrawRenderer(renderer, material, 0); } [NativeMethod("AddDrawProcedural")] private void Internal_DrawProcedural(Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, int vertexCount, int instanceCount, MaterialPropertyBlock properties) { Internal_DrawProcedural_Injected(ref matrix, material, shaderPass, topology, vertexCount, instanceCount, properties); } [NativeMethod("AddDrawProceduralIndexed")] private void Internal_DrawProceduralIndexed(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, int indexCount, int instanceCount, MaterialPropertyBlock properties) { Internal_DrawProceduralIndexed_Injected(indexBuffer, ref matrix, material, shaderPass, topology, indexCount, instanceCount, properties); } [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DrawProceduralIndirect", HasExplicitThis = true)] private void Internal_DrawProceduralIndirect(Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, ComputeBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties) { Internal_DrawProceduralIndirect_Injected(ref matrix, material, shaderPass, topology, bufferWithArgs, argsOffset, properties); } [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DrawProceduralIndexedIndirect", HasExplicitThis = true)] private void Internal_DrawProceduralIndexedIndirect(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, ComputeBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties) { Internal_DrawProceduralIndexedIndirect_Injected(indexBuffer, ref matrix, material, shaderPass, topology, bufferWithArgs, argsOffset, properties); } [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DrawProceduralIndirect", HasExplicitThis = true)] private void Internal_DrawProceduralIndirectGraphicsBuffer(Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, GraphicsBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties) { Internal_DrawProceduralIndirectGraphicsBuffer_Injected(ref matrix, material, shaderPass, topology, bufferWithArgs, argsOffset, properties); } [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DrawProceduralIndexedIndirect", HasExplicitThis = true)] private void Internal_DrawProceduralIndexedIndirectGraphicsBuffer(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, GraphicsBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties) { Internal_DrawProceduralIndexedIndirectGraphicsBuffer_Injected(indexBuffer, ref matrix, material, shaderPass, topology, bufferWithArgs, argsOffset, properties); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DrawMeshInstanced", HasExplicitThis = true)] private extern void Internal_DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, int shaderPass, [Unmarshalled] Matrix4x4[] matrices, int count, MaterialPropertyBlock properties); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DrawMeshInstancedProcedural", HasExplicitThis = true)] private extern void Internal_DrawMeshInstancedProcedural(Mesh mesh, int submeshIndex, Material material, int shaderPass, int count, MaterialPropertyBlock properties); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DrawMeshInstancedIndirect", HasExplicitThis = true)] private extern void Internal_DrawMeshInstancedIndirect(Mesh mesh, int submeshIndex, Material material, int shaderPass, ComputeBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DrawMeshInstancedIndirect", HasExplicitThis = true)] private extern void Internal_DrawMeshInstancedIndirectGraphicsBuffer(Mesh mesh, int submeshIndex, Material material, int shaderPass, GraphicsBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties); [FreeFunction("RenderingCommandBuffer_Bindings::Internal_DrawOcclusionMesh", HasExplicitThis = true)] private void Internal_DrawOcclusionMesh(RectInt normalizedCamViewport) { Internal_DrawOcclusionMesh_Injected(ref normalizedCamViewport); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetRandomWriteTarget_Texture", HasExplicitThis = true, ThrowsException = true)] private extern void SetRandomWriteTarget_Texture(int index, ref RenderTargetIdentifier rt); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetRandomWriteTarget_Buffer", HasExplicitThis = true, ThrowsException = true)] private extern void SetRandomWriteTarget_Buffer(int index, ComputeBuffer uav, bool preserveCounterValue); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetRandomWriteTarget_Buffer", HasExplicitThis = true, ThrowsException = true)] private extern void SetRandomWriteTarget_GraphicsBuffer(int index, GraphicsBuffer uav, bool preserveCounterValue); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::ClearRandomWriteTargets", HasExplicitThis = true, ThrowsException = true)] public extern void ClearRandomWriteTargets(); [FreeFunction("RenderingCommandBuffer_Bindings::SetViewport", HasExplicitThis = true, ThrowsException = true)] public void SetViewport(Rect pixelRect) { SetViewport_Injected(ref pixelRect); } [FreeFunction("RenderingCommandBuffer_Bindings::EnableScissorRect", HasExplicitThis = true, ThrowsException = true)] public void EnableScissorRect(Rect scissor) { EnableScissorRect_Injected(ref scissor); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::DisableScissorRect", HasExplicitThis = true, ThrowsException = true)] public extern void DisableScissorRect(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::CopyTexture_Internal", HasExplicitThis = true)] private extern void CopyTexture_Internal(ref RenderTargetIdentifier src, int srcElement, int srcMip, int srcX, int srcY, int srcWidth, int srcHeight, ref RenderTargetIdentifier dst, int dstElement, int dstMip, int dstX, int dstY, int mode); [FreeFunction("RenderingCommandBuffer_Bindings::Blit_Texture", HasExplicitThis = true)] private void Blit_Texture(Texture source, ref RenderTargetIdentifier dest, Material mat, int pass, Vector2 scale, Vector2 offset, int sourceDepthSlice, int destDepthSlice) { Blit_Texture_Injected(source, ref dest, mat, pass, ref scale, ref offset, sourceDepthSlice, destDepthSlice); } [FreeFunction("RenderingCommandBuffer_Bindings::Blit_Identifier", HasExplicitThis = true)] private void Blit_Identifier(ref RenderTargetIdentifier source, ref RenderTargetIdentifier dest, Material mat, int pass, Vector2 scale, Vector2 offset, int sourceDepthSlice, int destDepthSlice) { Blit_Identifier_Injected(ref source, ref dest, mat, pass, ref scale, ref offset, sourceDepthSlice, destDepthSlice); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::GetTemporaryRT", HasExplicitThis = true)] public extern void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, GraphicsFormat format, int antiAliasing, bool enableRandomWrite, RenderTextureMemoryless memorylessMode, bool useDynamicScale); public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, GraphicsFormat format, int antiAliasing, bool enableRandomWrite, RenderTextureMemoryless memorylessMode) { GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, antiAliasing, enableRandomWrite, memorylessMode, useDynamicScale: false); } public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, GraphicsFormat format, int antiAliasing, bool enableRandomWrite) { GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, antiAliasing, enableRandomWrite, RenderTextureMemoryless.None); } public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, GraphicsFormat format, int antiAliasing) { GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, antiAliasing, enableRandomWrite: false, RenderTextureMemoryless.None); } public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, GraphicsFormat format) { GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, 1); } public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, RenderTextureFormat format, RenderTextureReadWrite readWrite, int antiAliasing, bool enableRandomWrite, RenderTextureMemoryless memorylessMode, bool useDynamicScale) { GetTemporaryRT(nameID, width, height, depthBuffer, filter, GraphicsFormatUtility.GetGraphicsFormat(format, readWrite), antiAliasing, enableRandomWrite, memorylessMode, useDynamicScale); } public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, RenderTextureFormat format, RenderTextureReadWrite readWrite, int antiAliasing, bool enableRandomWrite, RenderTextureMemoryless memorylessMode) { GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, readWrite, antiAliasing, enableRandomWrite, memorylessMode, useDynamicScale: false); } public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, RenderTextureFormat format, RenderTextureReadWrite readWrite, int antiAliasing, bool enableRandomWrite) { GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, readWrite, antiAliasing, enableRandomWrite, RenderTextureMemoryless.None); } public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, RenderTextureFormat format, RenderTextureReadWrite readWrite, int antiAliasing) { GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, readWrite, antiAliasing, enableRandomWrite: false); } public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, RenderTextureFormat format, RenderTextureReadWrite readWrite) { GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, readWrite, 1); } public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, RenderTextureFormat format) { GetTemporaryRT(nameID, width, height, depthBuffer, filter, GraphicsFormatUtility.GetGraphicsFormat(format, RenderTextureReadWrite.Default)); } public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter) { GetTemporaryRT(nameID, width, height, depthBuffer, filter, SystemInfo.GetGraphicsFormat(DefaultFormat.LDR)); } public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer) { GetTemporaryRT(nameID, width, height, depthBuffer, FilterMode.Point); } public void GetTemporaryRT(int nameID, int width, int height) { GetTemporaryRT(nameID, width, height, 0); } [FreeFunction("RenderingCommandBuffer_Bindings::GetTemporaryRTWithDescriptor", HasExplicitThis = true)] private void GetTemporaryRTWithDescriptor(int nameID, RenderTextureDescriptor desc, FilterMode filter) { GetTemporaryRTWithDescriptor_Injected(nameID, ref desc, filter); } public void GetTemporaryRT(int nameID, RenderTextureDescriptor desc, FilterMode filter) { GetTemporaryRTWithDescriptor(nameID, desc, filter); } public void GetTemporaryRT(int nameID, RenderTextureDescriptor desc) { GetTemporaryRT(nameID, desc, FilterMode.Point); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::GetTemporaryRTArray", HasExplicitThis = true)] public extern void GetTemporaryRTArray(int nameID, int width, int height, int slices, int depthBuffer, FilterMode filter, GraphicsFormat format, int antiAliasing, bool enableRandomWrite, bool useDynamicScale); public void GetTemporaryRTArray(int nameID, int width, int height, int slices, int depthBuffer, FilterMode filter, GraphicsFormat format, int antiAliasing, bool enableRandomWrite) { GetTemporaryRTArray(nameID, width, height, slices, depthBuffer, filter, format, antiAliasing, enableRandomWrite, useDynamicScale: false); } public void GetTemporaryRTArray(int nameID, int width, int height, int slices, int depthBuffer, FilterMode filter, GraphicsFormat format, int antiAliasing) { GetTemporaryRTArray(nameID, width, height, slices, depthBuffer, filter, format, antiAliasing, enableRandomWrite: false); } public void GetTemporaryRTArray(int nameID, int width, int height, int slices, int depthBuffer, FilterMode filter, GraphicsFormat format) { GetTemporaryRTArray(nameID, width, height, slices, depthBuffer, filter, format, 1); } public void GetTemporaryRTArray(int nameID, int width, int height, int slices, int depthBuffer, FilterMode filter, RenderTextureFormat format, RenderTextureReadWrite readWrite, int antiAliasing, bool enableRandomWrite) { GetTemporaryRTArray(nameID, width, height, slices, depthBuffer, filter, GraphicsFormatUtility.GetGraphicsFormat(format, readWrite), antiAliasing, enableRandomWrite, useDynamicScale: false); } public void GetTemporaryRTArray(int nameID, int width, int height, int slices, int depthBuffer, FilterMode filter, RenderTextureFormat format, RenderTextureReadWrite readWrite, int antiAliasing) { GetTemporaryRTArray(nameID, width, height, slices, depthBuffer, filter, GraphicsFormatUtility.GetGraphicsFormat(format, readWrite), antiAliasing, enableRandomWrite: false); } public void GetTemporaryRTArray(int nameID, int width, int height, int slices, int depthBuffer, FilterMode filter, RenderTextureFormat format, RenderTextureReadWrite readWrite) { GetTemporaryRTArray(nameID, width, height, slices, depthBuffer, filter, GraphicsFormatUtility.GetGraphicsFormat(format, readWrite), 1, enableRandomWrite: false); } public void GetTemporaryRTArray(int nameID, int width, int height, int slices, int depthBuffer, FilterMode filter, RenderTextureFormat format) { GetTemporaryRTArray(nameID, width, height, slices, depthBuffer, filter, GraphicsFormatUtility.GetGraphicsFormat(format, RenderTextureReadWrite.Default), 1, enableRandomWrite: false); } public void GetTemporaryRTArray(int nameID, int width, int height, int slices, int depthBuffer, FilterMode filter) { GetTemporaryRTArray(nameID, width, height, slices, depthBuffer, filter, SystemInfo.GetGraphicsFormat(DefaultFormat.LDR), 1, enableRandomWrite: false); } public void GetTemporaryRTArray(int nameID, int width, int height, int slices, int depthBuffer) { GetTemporaryRTArray(nameID, width, height, slices, depthBuffer, FilterMode.Point); } public void GetTemporaryRTArray(int nameID, int width, int height, int slices) { GetTemporaryRTArray(nameID, width, height, slices, 0); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::ReleaseTemporaryRT", HasExplicitThis = true)] public extern void ReleaseTemporaryRT(int nameID); [FreeFunction("RenderingCommandBuffer_Bindings::ClearRenderTarget", HasExplicitThis = true)] public void ClearRenderTarget(RTClearFlags clearFlags, Color backgroundColor, float depth, uint stencil) { ClearRenderTarget_Injected(clearFlags, ref backgroundColor, depth, stencil); } public void ClearRenderTarget(bool clearDepth, bool clearColor, Color backgroundColor) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); ClearRenderTarget((RTClearFlags)((clearColor ? 1 : 0) | (clearDepth ? 6 : 0)), backgroundColor, 1f, 0u); } public void ClearRenderTarget(bool clearDepth, bool clearColor, Color backgroundColor, float depth) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); ClearRenderTarget((RTClearFlags)((clearColor ? 1 : 0) | (clearDepth ? 6 : 0)), backgroundColor, depth, 0u); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalFloat", HasExplicitThis = true)] public extern void SetGlobalFloat(int nameID, float value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalInt", HasExplicitThis = true)] public extern void SetGlobalInt(int nameID, int value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalInteger", HasExplicitThis = true)] public extern void SetGlobalInteger(int nameID, int value); [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalVector", HasExplicitThis = true)] public void SetGlobalVector(int nameID, Vector4 value) { SetGlobalVector_Injected(nameID, ref value); } [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalColor", HasExplicitThis = true)] public void SetGlobalColor(int nameID, Color value) { SetGlobalColor_Injected(nameID, ref value); } [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalMatrix", HasExplicitThis = true)] public void SetGlobalMatrix(int nameID, Matrix4x4 value) { SetGlobalMatrix_Injected(nameID, ref value); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::EnableShaderKeyword", HasExplicitThis = true)] public extern void EnableShaderKeyword(string keyword); [FreeFunction("RenderingCommandBuffer_Bindings::EnableShaderKeyword", HasExplicitThis = true)] private void EnableGlobalKeyword(GlobalKeyword keyword) { EnableGlobalKeyword_Injected(ref keyword); } [FreeFunction("RenderingCommandBuffer_Bindings::EnableMaterialKeyword", HasExplicitThis = true)] private void EnableMaterialKeyword(Material material, LocalKeyword keyword) { EnableMaterialKeyword_Injected(material, ref keyword); } [FreeFunction("RenderingCommandBuffer_Bindings::EnableComputeKeyword", HasExplicitThis = true)] private void EnableComputeKeyword(ComputeShader computeShader, LocalKeyword keyword) { EnableComputeKeyword_Injected(computeShader, ref keyword); } public void EnableKeyword(in GlobalKeyword keyword) { EnableGlobalKeyword(keyword); } public void EnableKeyword(Material material, in LocalKeyword keyword) { EnableMaterialKeyword(material, keyword); } public void EnableKeyword(ComputeShader computeShader, in LocalKeyword keyword) { EnableComputeKeyword(computeShader, keyword); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::DisableShaderKeyword", HasExplicitThis = true)] public extern void DisableShaderKeyword(string keyword); [FreeFunction("RenderingCommandBuffer_Bindings::DisableShaderKeyword", HasExplicitThis = true)] private void DisableGlobalKeyword(GlobalKeyword keyword) { DisableGlobalKeyword_Injected(ref keyword); } [FreeFunction("RenderingCommandBuffer_Bindings::DisableMaterialKeyword", HasExplicitThis = true)] private void DisableMaterialKeyword(Material material, LocalKeyword keyword) { DisableMaterialKeyword_Injected(material, ref keyword); } [FreeFunction("RenderingCommandBuffer_Bindings::DisableComputeKeyword", HasExplicitThis = true)] private void DisableComputeKeyword(ComputeShader computeShader, LocalKeyword keyword) { DisableComputeKeyword_Injected(computeShader, ref keyword); } public void DisableKeyword(in GlobalKeyword keyword) { DisableGlobalKeyword(keyword); } public void DisableKeyword(Material material, in LocalKeyword keyword) { DisableMaterialKeyword(material, keyword); } public void DisableKeyword(ComputeShader computeShader, in LocalKeyword keyword) { DisableComputeKeyword(computeShader, keyword); } [FreeFunction("RenderingCommandBuffer_Bindings::SetShaderKeyword", HasExplicitThis = true)] private void SetGlobalKeyword(GlobalKeyword keyword, bool value) { SetGlobalKeyword_Injected(ref keyword, value); } [FreeFunction("RenderingCommandBuffer_Bindings::SetMaterialKeyword", HasExplicitThis = true)] private void SetMaterialKeyword(Material material, LocalKeyword keyword, bool value) { SetMaterialKeyword_Injected(material, ref keyword, value); } [FreeFunction("RenderingCommandBuffer_Bindings::SetComputeKeyword", HasExplicitThis = true)] private void SetComputeKeyword(ComputeShader computeShader, LocalKeyword keyword, bool value) { SetComputeKeyword_Injected(computeShader, ref keyword, value); } public void SetKeyword(in GlobalKeyword keyword, bool value) { SetGlobalKeyword(keyword, value); } public void SetKeyword(Material material, in LocalKeyword keyword, bool value) { SetMaterialKeyword(material, keyword, value); } public void SetKeyword(ComputeShader computeShader, in LocalKeyword keyword, bool value) { SetComputeKeyword(computeShader, keyword, value); } [FreeFunction("RenderingCommandBuffer_Bindings::SetViewMatrix", HasExplicitThis = true, ThrowsException = true)] public void SetViewMatrix(Matrix4x4 view) { SetViewMatrix_Injected(ref view); } [FreeFunction("RenderingCommandBuffer_Bindings::SetProjectionMatrix", HasExplicitThis = true, ThrowsException = true)] public void SetProjectionMatrix(Matrix4x4 proj) { SetProjectionMatrix_Injected(ref proj); } [FreeFunction("RenderingCommandBuffer_Bindings::SetViewProjectionMatrices", HasExplicitThis = true, ThrowsException = true)] public void SetViewProjectionMatrices(Matrix4x4 view, Matrix4x4 proj) { SetViewProjectionMatrices_Injected(ref view, ref proj); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("AddSetGlobalDepthBias")] public extern void SetGlobalDepthBias(float bias, float slopeBias); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetExecutionFlags", HasExplicitThis = true, ThrowsException = true)] public extern void SetExecutionFlags(CommandBufferExecutionFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::ValidateAgainstExecutionFlags", HasExplicitThis = true, ThrowsException = true)] private extern bool ValidateAgainstExecutionFlags(CommandBufferExecutionFlags requiredFlags, CommandBufferExecutionFlags invalidFlags); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalFloatArrayListImpl", HasExplicitThis = true)] private extern void SetGlobalFloatArrayListImpl(int nameID, object values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalVectorArrayListImpl", HasExplicitThis = true)] private extern void SetGlobalVectorArrayListImpl(int nameID, object values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalMatrixArrayListImpl", HasExplicitThis = true)] private extern void SetGlobalMatrixArrayListImpl(int nameID, object values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalFloatArray", HasExplicitThis = true, ThrowsException = true)] public extern void SetGlobalFloatArray(int nameID, [Unmarshalled] float[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalVectorArray", HasExplicitThis = true, ThrowsException = true)] public extern void SetGlobalVectorArray(int nameID, [Unmarshalled] Vector4[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalMatrixArray", HasExplicitThis = true, ThrowsException = true)] public extern void SetGlobalMatrixArray(int nameID, [Unmarshalled] Matrix4x4[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetLateLatchProjectionMatrices", HasExplicitThis = true, ThrowsException = true)] public extern void SetLateLatchProjectionMatrices([Unmarshalled] Matrix4x4[] projectionMat); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::MarkLateLatchMatrixShaderPropertyID", HasExplicitThis = true)] public extern void MarkLateLatchMatrixShaderPropertyID(CameraLateLatchMatrixType matrixPropertyType, int shaderPropertyID); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::UnmarkLateLatchMatrix", HasExplicitThis = true)] public extern void UnmarkLateLatchMatrix(CameraLateLatchMatrixType matrixPropertyType); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalTexture_Impl", HasExplicitThis = true)] private extern void SetGlobalTexture_Impl(int nameID, ref RenderTargetIdentifier rt, RenderTextureSubElement element); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalBuffer", HasExplicitThis = true)] private extern void SetGlobalBufferInternal(int nameID, ComputeBuffer value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalBuffer", HasExplicitThis = true)] private extern void SetGlobalGraphicsBufferInternal(int nameID, GraphicsBuffer value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetShadowSamplingMode_Impl", HasExplicitThis = true)] private extern void SetShadowSamplingMode_Impl(ref RenderTargetIdentifier shadowmap, ShadowSamplingMode mode); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::IssuePluginEventInternal", HasExplicitThis = true)] private extern void IssuePluginEventInternal(IntPtr callback, int eventID); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::BeginSample", HasExplicitThis = true)] public extern void BeginSample(string name); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::EndSample", HasExplicitThis = true)] public extern void EndSample(string name); public void BeginSample(CustomSampler sampler) { BeginSample_CustomSampler(sampler); } public void EndSample(CustomSampler sampler) { EndSample_CustomSampler(sampler); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::BeginSample_CustomSampler", HasExplicitThis = true)] private extern void BeginSample_CustomSampler([NotNull("ArgumentNullException")] CustomSampler sampler); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::EndSample_CustomSampler", HasExplicitThis = true)] private extern void EndSample_CustomSampler([NotNull("ArgumentNullException")] CustomSampler sampler); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::IssuePluginEventAndDataInternal", HasExplicitThis = true)] private extern void IssuePluginEventAndDataInternal(IntPtr callback, int eventID, IntPtr data); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::IssuePluginCustomBlitInternal", HasExplicitThis = true)] private extern void IssuePluginCustomBlitInternal(IntPtr callback, uint command, ref RenderTargetIdentifier source, ref RenderTargetIdentifier dest, uint commandParam, uint commandFlags); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::IssuePluginCustomTextureUpdateInternal", HasExplicitThis = true)] private extern void IssuePluginCustomTextureUpdateInternal(IntPtr callback, Texture targetTexture, uint userData, bool useNewUnityRenderingExtTextureUpdateParamsV2); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalConstantBuffer", HasExplicitThis = true)] private extern void SetGlobalConstantBufferInternal(ComputeBuffer buffer, int nameID, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetGlobalConstantBuffer", HasExplicitThis = true)] private extern void SetGlobalConstantGraphicsBufferInternal(GraphicsBuffer buffer, int nameID, int offset, int size); [FreeFunction("RenderingCommandBuffer_Bindings::IncrementUpdateCount", HasExplicitThis = true)] public void IncrementUpdateCount(RenderTargetIdentifier dest) { IncrementUpdateCount_Injected(ref dest); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBuffer_Bindings::SetInstanceMultiplier", HasExplicitThis = true)] public extern void SetInstanceMultiplier(uint multiplier); public void SetRenderTarget(RenderTargetIdentifier rt) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); SetRenderTargetSingle_Internal(rt, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store); } public void SetRenderTarget(RenderTargetIdentifier rt, RenderBufferLoadAction loadAction, RenderBufferStoreAction storeAction) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (loadAction == RenderBufferLoadAction.Clear) { throw new ArgumentException("RenderBufferLoadAction.Clear is not supported"); } SetRenderTargetSingle_Internal(rt, loadAction, storeAction, loadAction, storeAction); } public void SetRenderTarget(RenderTargetIdentifier rt, RenderBufferLoadAction colorLoadAction, RenderBufferStoreAction colorStoreAction, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (colorLoadAction == RenderBufferLoadAction.Clear || depthLoadAction == RenderBufferLoadAction.Clear) { throw new ArgumentException("RenderBufferLoadAction.Clear is not supported"); } SetRenderTargetSingle_Internal(rt, colorLoadAction, colorStoreAction, depthLoadAction, depthStoreAction); } public void SetRenderTarget(RenderTargetIdentifier rt, int mipLevel) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (mipLevel < 0) { throw new ArgumentException($"Invalid value for mipLevel ({mipLevel})"); } SetRenderTargetSingle_Internal(new RenderTargetIdentifier(rt, mipLevel), RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store); } public void SetRenderTarget(RenderTargetIdentifier rt, int mipLevel, CubemapFace cubemapFace) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (mipLevel < 0) { throw new ArgumentException($"Invalid value for mipLevel ({mipLevel})"); } SetRenderTargetSingle_Internal(new RenderTargetIdentifier(rt, mipLevel, cubemapFace), RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store); } public void SetRenderTarget(RenderTargetIdentifier rt, int mipLevel, CubemapFace cubemapFace, int depthSlice) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (depthSlice < -1) { throw new ArgumentException($"Invalid value for depthSlice ({depthSlice})"); } if (mipLevel < 0) { throw new ArgumentException($"Invalid value for mipLevel ({mipLevel})"); } SetRenderTargetSingle_Internal(new RenderTargetIdentifier(rt, mipLevel, cubemapFace, depthSlice), RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store); } public void SetRenderTarget(RenderTargetIdentifier color, RenderTargetIdentifier depth) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); SetRenderTargetColorDepth_Internal(color, depth, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, RenderTargetFlags.None); } public void SetRenderTarget(RenderTargetIdentifier color, RenderTargetIdentifier depth, int mipLevel) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (mipLevel < 0) { throw new ArgumentException($"Invalid value for mipLevel ({mipLevel})"); } SetRenderTargetColorDepth_Internal(new RenderTargetIdentifier(color, mipLevel), depth, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, RenderTargetFlags.None); } public void SetRenderTarget(RenderTargetIdentifier color, RenderTargetIdentifier depth, int mipLevel, CubemapFace cubemapFace) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (mipLevel < 0) { throw new ArgumentException($"Invalid value for mipLevel ({mipLevel})"); } SetRenderTargetColorDepth_Internal(new RenderTargetIdentifier(color, mipLevel, cubemapFace), depth, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, RenderTargetFlags.None); } public void SetRenderTarget(RenderTargetIdentifier color, RenderTargetIdentifier depth, int mipLevel, CubemapFace cubemapFace, int depthSlice) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (depthSlice < -1) { throw new ArgumentException($"Invalid value for depthSlice ({depthSlice})"); } if (mipLevel < 0) { throw new ArgumentException($"Invalid value for mipLevel ({mipLevel})"); } SetRenderTargetColorDepth_Internal(new RenderTargetIdentifier(color, mipLevel, cubemapFace, depthSlice), depth, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, RenderTargetFlags.None); } public void SetRenderTarget(RenderTargetIdentifier color, RenderBufferLoadAction colorLoadAction, RenderBufferStoreAction colorStoreAction, RenderTargetIdentifier depth, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (colorLoadAction == RenderBufferLoadAction.Clear || depthLoadAction == RenderBufferLoadAction.Clear) { throw new ArgumentException("RenderBufferLoadAction.Clear is not supported"); } SetRenderTargetColorDepth_Internal(color, depth, colorLoadAction, colorStoreAction, depthLoadAction, depthStoreAction, RenderTargetFlags.None); } public void SetRenderTarget(RenderTargetIdentifier[] colors, RenderTargetIdentifier depth) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (colors.Length < 1) { throw new ArgumentException($"colors.Length must be at least 1, but was {colors.Length}"); } if (colors.Length > SystemInfo.supportedRenderTargetCount) { throw new ArgumentException($"colors.Length is {colors.Length} and exceeds the maximum number of supported render targets ({SystemInfo.supportedRenderTargetCount})"); } SetRenderTargetMulti_Internal(colors, depth, null, null, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, RenderTargetFlags.None); } public void SetRenderTarget(RenderTargetIdentifier[] colors, RenderTargetIdentifier depth, int mipLevel, CubemapFace cubemapFace, int depthSlice) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (colors.Length < 1) { throw new ArgumentException($"colors.Length must be at least 1, but was {colors.Length}"); } if (colors.Length > SystemInfo.supportedRenderTargetCount) { throw new ArgumentException($"colors.Length is {colors.Length} and exceeds the maximum number of supported render targets ({SystemInfo.supportedRenderTargetCount})"); } SetRenderTargetMultiSubtarget(colors, depth, null, null, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store, mipLevel, cubemapFace, depthSlice); } public void SetRenderTarget(RenderTargetBinding binding, int mipLevel, CubemapFace cubemapFace, int depthSlice) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (binding.colorRenderTargets.Length < 1) { throw new ArgumentException($"The number of color render targets must be at least 1, but was {binding.colorRenderTargets.Length}"); } if (binding.colorRenderTargets.Length > SystemInfo.supportedRenderTargetCount) { throw new ArgumentException($"The number of color render targets ({binding.colorRenderTargets.Length}) and exceeds the maximum supported number of render targets ({SystemInfo.supportedRenderTargetCount})"); } if (binding.colorLoadActions.Length != binding.colorRenderTargets.Length) { throw new ArgumentException($"The number of color load actions provided ({binding.colorLoadActions.Length}) does not match the number of color render targets ({binding.colorRenderTargets.Length})"); } if (binding.colorStoreActions.Length != binding.colorRenderTargets.Length) { throw new ArgumentException($"The number of color store actions provided ({binding.colorLoadActions.Length}) does not match the number of color render targets ({binding.colorRenderTargets.Length})"); } if (binding.depthLoadAction == RenderBufferLoadAction.Clear || Array.IndexOf(binding.colorLoadActions, RenderBufferLoadAction.Clear) > -1) { throw new ArgumentException("RenderBufferLoadAction.Clear is not supported"); } if (binding.colorRenderTargets.Length == 1) { SetRenderTargetColorDepthSubtarget(binding.colorRenderTargets[0], binding.depthRenderTarget, binding.colorLoadActions[0], binding.colorStoreActions[0], binding.depthLoadAction, binding.depthStoreAction, mipLevel, cubemapFace, depthSlice); } else { SetRenderTargetMultiSubtarget(binding.colorRenderTargets, binding.depthRenderTarget, binding.colorLoadActions, binding.colorStoreActions, binding.depthLoadAction, binding.depthStoreAction, mipLevel, cubemapFace, depthSlice); } } public void SetRenderTarget(RenderTargetBinding binding) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (binding.colorRenderTargets.Length < 1) { throw new ArgumentException($"The number of color render targets must be at least 1, but was {binding.colorRenderTargets.Length}"); } if (binding.colorRenderTargets.Length > SystemInfo.supportedRenderTargetCount) { throw new ArgumentException($"The number of color render targets ({binding.colorRenderTargets.Length}) and exceeds the maximum supported number of render targets ({SystemInfo.supportedRenderTargetCount})"); } if (binding.colorLoadActions.Length != binding.colorRenderTargets.Length) { throw new ArgumentException($"The number of color load actions provided ({binding.colorLoadActions.Length}) does not match the number of color render targets ({binding.colorRenderTargets.Length})"); } if (binding.colorStoreActions.Length != binding.colorRenderTargets.Length) { throw new ArgumentException($"The number of color store actions provided ({binding.colorLoadActions.Length}) does not match the number of color render targets ({binding.colorRenderTargets.Length})"); } if (binding.depthLoadAction == RenderBufferLoadAction.Clear || Array.IndexOf(binding.colorLoadActions, RenderBufferLoadAction.Clear) > -1) { throw new ArgumentException("RenderBufferLoadAction.Clear is not supported"); } if (binding.colorRenderTargets.Length == 1) { SetRenderTargetColorDepth_Internal(binding.colorRenderTargets[0], binding.depthRenderTarget, binding.colorLoadActions[0], binding.colorStoreActions[0], binding.depthLoadAction, binding.depthStoreAction, binding.flags); } else { SetRenderTargetMulti_Internal(binding.colorRenderTargets, binding.depthRenderTarget, binding.colorLoadActions, binding.colorStoreActions, binding.depthLoadAction, binding.depthStoreAction, binding.flags); } } private void SetRenderTargetSingle_Internal(RenderTargetIdentifier rt, RenderBufferLoadAction colorLoadAction, RenderBufferStoreAction colorStoreAction, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction) { SetRenderTargetSingle_Internal_Injected(ref rt, colorLoadAction, colorStoreAction, depthLoadAction, depthStoreAction); } private void SetRenderTargetColorDepth_Internal(RenderTargetIdentifier color, RenderTargetIdentifier depth, RenderBufferLoadAction colorLoadAction, RenderBufferStoreAction colorStoreAction, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction, RenderTargetFlags flags) { SetRenderTargetColorDepth_Internal_Injected(ref color, ref depth, colorLoadAction, colorStoreAction, depthLoadAction, depthStoreAction, flags); } private void SetRenderTargetMulti_Internal(RenderTargetIdentifier[] colors, RenderTargetIdentifier depth, RenderBufferLoadAction[] colorLoadActions, RenderBufferStoreAction[] colorStoreActions, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction, RenderTargetFlags flags) { SetRenderTargetMulti_Internal_Injected(colors, ref depth, colorLoadActions, colorStoreActions, depthLoadAction, depthStoreAction, flags); } private void SetRenderTargetColorDepthSubtarget(RenderTargetIdentifier color, RenderTargetIdentifier depth, RenderBufferLoadAction colorLoadAction, RenderBufferStoreAction colorStoreAction, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction, int mipLevel, CubemapFace cubemapFace, int depthSlice) { SetRenderTargetColorDepthSubtarget_Injected(ref color, ref depth, colorLoadAction, colorStoreAction, depthLoadAction, depthStoreAction, mipLevel, cubemapFace, depthSlice); } private void SetRenderTargetMultiSubtarget(RenderTargetIdentifier[] colors, RenderTargetIdentifier depth, RenderBufferLoadAction[] colorLoadActions, RenderBufferStoreAction[] colorStoreActions, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction, int mipLevel, CubemapFace cubemapFace, int depthSlice) { SetRenderTargetMultiSubtarget_Injected(colors, ref depth, colorLoadActions, colorStoreActions, depthLoadAction, depthStoreAction, mipLevel, cubemapFace, depthSlice); } [NativeMethod("ProcessVTFeedback")] private void Internal_ProcessVTFeedback(RenderTargetIdentifier rt, IntPtr resolver, int slice, int x, int width, int y, int height, int mip) { Internal_ProcessVTFeedback_Injected(ref rt, resolver, slice, x, width, y, height, mip); } [SecuritySafeCritical] public void SetBufferData(ComputeBuffer buffer, Array data) { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException($"Array passed to RenderingCommandBuffer.SetBufferData(array) must be blittable.\n{UnsafeUtility.GetReasonForArrayNonBlittable(data)}"); } InternalSetComputeBufferData(buffer, data, 0, 0, data.Length, UnsafeUtility.SizeOf(data.GetType().GetElementType())); } [SecuritySafeCritical] public void SetBufferData(ComputeBuffer buffer, List data) where T : struct { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException($"List<{typeof(T)}> passed to RenderingCommandBuffer.SetBufferData(List<>) must be blittable.\n{UnsafeUtility.GetReasonForGenericListNonBlittable()}"); } InternalSetComputeBufferData(buffer, NoAllocHelpers.ExtractArrayFromList(data), 0, 0, NoAllocHelpers.SafeLength(data), Marshal.SizeOf(typeof(T))); } [SecuritySafeCritical] public unsafe void SetBufferData(ComputeBuffer buffer, NativeArray data) where T : struct { InternalSetComputeBufferNativeData(buffer, (IntPtr)data.GetUnsafeReadOnlyPtr(), 0, 0, data.Length, UnsafeUtility.SizeOf()); } [SecuritySafeCritical] public void SetBufferData(ComputeBuffer buffer, Array data, int managedBufferStartIndex, int graphicsBufferStartIndex, int count) { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException($"Array passed to RenderingCommandBuffer.SetBufferData(array) must be blittable.\n{UnsafeUtility.GetReasonForArrayNonBlittable(data)}"); } if (managedBufferStartIndex < 0 || graphicsBufferStartIndex < 0 || count < 0 || managedBufferStartIndex + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (managedBufferStartIndex:{managedBufferStartIndex} graphicsBufferStartIndex:{graphicsBufferStartIndex} count:{count})"); } InternalSetComputeBufferData(buffer, data, managedBufferStartIndex, graphicsBufferStartIndex, count, Marshal.SizeOf(data.GetType().GetElementType())); } [SecuritySafeCritical] public void SetBufferData(ComputeBuffer buffer, List data, int managedBufferStartIndex, int graphicsBufferStartIndex, int count) where T : struct { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException($"List<{typeof(T)}> passed to RenderingCommandBuffer.SetBufferData(List<>) must be blittable.\n{UnsafeUtility.GetReasonForGenericListNonBlittable()}"); } if (managedBufferStartIndex < 0 || graphicsBufferStartIndex < 0 || count < 0 || managedBufferStartIndex + count > data.Count) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (managedBufferStartIndex:{managedBufferStartIndex} graphicsBufferStartIndex:{graphicsBufferStartIndex} count:{count})"); } InternalSetComputeBufferData(buffer, NoAllocHelpers.ExtractArrayFromList(data), managedBufferStartIndex, graphicsBufferStartIndex, count, Marshal.SizeOf(typeof(T))); } [SecuritySafeCritical] public unsafe void SetBufferData(ComputeBuffer buffer, NativeArray data, int nativeBufferStartIndex, int graphicsBufferStartIndex, int count) where T : struct { if (nativeBufferStartIndex < 0 || graphicsBufferStartIndex < 0 || count < 0 || nativeBufferStartIndex + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (nativeBufferStartIndex:{nativeBufferStartIndex} graphicsBufferStartIndex:{graphicsBufferStartIndex} count:{count})"); } InternalSetComputeBufferNativeData(buffer, (IntPtr)data.GetUnsafeReadOnlyPtr(), nativeBufferStartIndex, graphicsBufferStartIndex, count, UnsafeUtility.SizeOf()); } public void SetBufferCounterValue(ComputeBuffer buffer, uint counterValue) { InternalSetComputeBufferCounterValue(buffer, counterValue); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RenderingCommandBuffer_Bindings::InternalSetGraphicsBufferNativeData", HasExplicitThis = true, ThrowsException = true)] private extern void InternalSetComputeBufferNativeData([NotNull("ArgumentNullException")] ComputeBuffer buffer, IntPtr data, int nativeBufferStartIndex, int graphicsBufferStartIndex, int count, int elemSize); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RenderingCommandBuffer_Bindings::InternalSetGraphicsBufferData", HasExplicitThis = true, ThrowsException = true)] private extern void InternalSetComputeBufferData([NotNull("ArgumentNullException")] ComputeBuffer buffer, Array data, int managedBufferStartIndex, int graphicsBufferStartIndex, int count, int elemSize); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RenderingCommandBuffer_Bindings::InternalSetGraphicsBufferCounterValue", HasExplicitThis = true)] private extern void InternalSetComputeBufferCounterValue([NotNull("ArgumentNullException")] ComputeBuffer buffer, uint counterValue); [SecuritySafeCritical] public void SetBufferData(GraphicsBuffer buffer, Array data) { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException($"Array passed to RenderingCommandBuffer.SetBufferData(array) must be blittable.\n{UnsafeUtility.GetReasonForArrayNonBlittable(data)}"); } InternalSetGraphicsBufferData(buffer, data, 0, 0, data.Length, UnsafeUtility.SizeOf(data.GetType().GetElementType())); } [SecuritySafeCritical] public void SetBufferData(GraphicsBuffer buffer, List data) where T : struct { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException($"List<{typeof(T)}> passed to RenderingCommandBuffer.SetBufferData(List<>) must be blittable.\n{UnsafeUtility.GetReasonForGenericListNonBlittable()}"); } InternalSetGraphicsBufferData(buffer, NoAllocHelpers.ExtractArrayFromList(data), 0, 0, NoAllocHelpers.SafeLength(data), Marshal.SizeOf(typeof(T))); } [SecuritySafeCritical] public unsafe void SetBufferData(GraphicsBuffer buffer, NativeArray data) where T : struct { InternalSetGraphicsBufferNativeData(buffer, (IntPtr)data.GetUnsafeReadOnlyPtr(), 0, 0, data.Length, UnsafeUtility.SizeOf()); } [SecuritySafeCritical] public void SetBufferData(GraphicsBuffer buffer, Array data, int managedBufferStartIndex, int graphicsBufferStartIndex, int count) { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsArrayBlittable(data)) { throw new ArgumentException($"Array passed to RenderingCommandBuffer.SetBufferData(array) must be blittable.\n{UnsafeUtility.GetReasonForArrayNonBlittable(data)}"); } if (managedBufferStartIndex < 0 || graphicsBufferStartIndex < 0 || count < 0 || managedBufferStartIndex + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (managedBufferStartIndex:{managedBufferStartIndex} graphicsBufferStartIndex:{graphicsBufferStartIndex} count:{count})"); } InternalSetGraphicsBufferData(buffer, data, managedBufferStartIndex, graphicsBufferStartIndex, count, Marshal.SizeOf(data.GetType().GetElementType())); } [SecuritySafeCritical] public void SetBufferData(GraphicsBuffer buffer, List data, int managedBufferStartIndex, int graphicsBufferStartIndex, int count) where T : struct { if (data == null) { throw new ArgumentNullException("data"); } if (!UnsafeUtility.IsGenericListBlittable()) { throw new ArgumentException($"List<{typeof(T)}> passed to RenderingCommandBuffer.SetBufferData(List<>) must be blittable.\n{UnsafeUtility.GetReasonForGenericListNonBlittable()}"); } if (managedBufferStartIndex < 0 || graphicsBufferStartIndex < 0 || count < 0 || managedBufferStartIndex + count > data.Count) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (managedBufferStartIndex:{managedBufferStartIndex} graphicsBufferStartIndex:{graphicsBufferStartIndex} count:{count})"); } InternalSetGraphicsBufferData(buffer, NoAllocHelpers.ExtractArrayFromList(data), managedBufferStartIndex, graphicsBufferStartIndex, count, Marshal.SizeOf(typeof(T))); } [SecuritySafeCritical] public unsafe void SetBufferData(GraphicsBuffer buffer, NativeArray data, int nativeBufferStartIndex, int graphicsBufferStartIndex, int count) where T : struct { if (nativeBufferStartIndex < 0 || graphicsBufferStartIndex < 0 || count < 0 || nativeBufferStartIndex + count > data.Length) { throw new ArgumentOutOfRangeException($"Bad indices/count arguments (nativeBufferStartIndex:{nativeBufferStartIndex} graphicsBufferStartIndex:{graphicsBufferStartIndex} count:{count})"); } InternalSetGraphicsBufferNativeData(buffer, (IntPtr)data.GetUnsafeReadOnlyPtr(), nativeBufferStartIndex, graphicsBufferStartIndex, count, UnsafeUtility.SizeOf()); } public void SetBufferCounterValue(GraphicsBuffer buffer, uint counterValue) { InternalSetGraphicsBufferCounterValue(buffer, counterValue); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RenderingCommandBuffer_Bindings::InternalSetGraphicsBufferNativeData", HasExplicitThis = true, ThrowsException = true)] private extern void InternalSetGraphicsBufferNativeData([NotNull("ArgumentNullException")] GraphicsBuffer buffer, IntPtr data, int nativeBufferStartIndex, int graphicsBufferStartIndex, int count, int elemSize); [MethodImpl(MethodImplOptions.InternalCall)] [SecurityCritical] [FreeFunction(Name = "RenderingCommandBuffer_Bindings::InternalSetGraphicsBufferData", HasExplicitThis = true, ThrowsException = true)] private extern void InternalSetGraphicsBufferData([NotNull("ArgumentNullException")] GraphicsBuffer buffer, Array data, int managedBufferStartIndex, int graphicsBufferStartIndex, int count, int elemSize); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RenderingCommandBuffer_Bindings::InternalSetGraphicsBufferCounterValue", HasExplicitThis = true)] private extern void InternalSetGraphicsBufferCounterValue([NotNull("ArgumentNullException")] GraphicsBuffer buffer, uint counterValue); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RenderingCommandBuffer_Bindings::CopyBuffer", HasExplicitThis = true, ThrowsException = true)] private extern void CopyBufferImpl([NotNull("ArgumentNullException")] GraphicsBuffer source, [NotNull("ArgumentNullException")] GraphicsBuffer dest); ~CommandBuffer() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { ReleaseBuffer(); m_Ptr = IntPtr.Zero; } public CommandBuffer() { m_Ptr = InitBuffer(); } public void Release() { Dispose(); } public GraphicsFence CreateAsyncGraphicsFence() { return CreateGraphicsFence(GraphicsFenceType.AsyncQueueSynchronisation, SynchronisationStageFlags.PixelProcessing); } public GraphicsFence CreateAsyncGraphicsFence(SynchronisationStage stage) { return CreateGraphicsFence(GraphicsFenceType.AsyncQueueSynchronisation, GraphicsFence.TranslateSynchronizationStageToFlags(stage)); } public GraphicsFence CreateGraphicsFence(GraphicsFenceType fenceType, SynchronisationStageFlags stage) { GraphicsFence result = default(GraphicsFence); result.m_FenceType = fenceType; result.m_Ptr = CreateGPUFence_Internal(fenceType, stage); result.InitPostAllocation(); result.Validate(); return result; } public void WaitOnAsyncGraphicsFence(GraphicsFence fence) { WaitOnAsyncGraphicsFence(fence, SynchronisationStage.VertexProcessing); } public void WaitOnAsyncGraphicsFence(GraphicsFence fence, SynchronisationStage stage) { WaitOnAsyncGraphicsFence(fence, GraphicsFence.TranslateSynchronizationStageToFlags(stage)); } public void WaitOnAsyncGraphicsFence(GraphicsFence fence, SynchronisationStageFlags stage) { if (fence.m_FenceType != GraphicsFenceType.AsyncQueueSynchronisation) { throw new ArgumentException("Attempting to call WaitOnAsyncGPUFence on a fence that is not of GraphicsFenceType.AsyncQueueSynchronization"); } fence.Validate(); if (fence.IsFencePending()) { WaitOnGPUFence_Internal(fence.m_Ptr, stage); } } public void SetComputeFloatParam(ComputeShader computeShader, string name, float val) { SetComputeFloatParam(computeShader, Shader.PropertyToID(name), val); } public void SetComputeIntParam(ComputeShader computeShader, string name, int val) { SetComputeIntParam(computeShader, Shader.PropertyToID(name), val); } public void SetComputeVectorParam(ComputeShader computeShader, string name, Vector4 val) { SetComputeVectorParam(computeShader, Shader.PropertyToID(name), val); } public void SetComputeVectorArrayParam(ComputeShader computeShader, string name, Vector4[] values) { SetComputeVectorArrayParam(computeShader, Shader.PropertyToID(name), values); } public void SetComputeMatrixParam(ComputeShader computeShader, string name, Matrix4x4 val) { SetComputeMatrixParam(computeShader, Shader.PropertyToID(name), val); } public void SetComputeMatrixArrayParam(ComputeShader computeShader, string name, Matrix4x4[] values) { SetComputeMatrixArrayParam(computeShader, Shader.PropertyToID(name), values); } public void SetComputeFloatParams(ComputeShader computeShader, string name, params float[] values) { Internal_SetComputeFloats(computeShader, Shader.PropertyToID(name), values); } public void SetComputeFloatParams(ComputeShader computeShader, int nameID, params float[] values) { Internal_SetComputeFloats(computeShader, nameID, values); } public void SetComputeIntParams(ComputeShader computeShader, string name, params int[] values) { Internal_SetComputeInts(computeShader, Shader.PropertyToID(name), values); } public void SetComputeIntParams(ComputeShader computeShader, int nameID, params int[] values) { Internal_SetComputeInts(computeShader, nameID, values); } public void SetComputeTextureParam(ComputeShader computeShader, int kernelIndex, string name, RenderTargetIdentifier rt) { Internal_SetComputeTextureParam(computeShader, kernelIndex, Shader.PropertyToID(name), ref rt, 0, RenderTextureSubElement.Default); } public void SetComputeTextureParam(ComputeShader computeShader, int kernelIndex, int nameID, RenderTargetIdentifier rt) { Internal_SetComputeTextureParam(computeShader, kernelIndex, nameID, ref rt, 0, RenderTextureSubElement.Default); } public void SetComputeTextureParam(ComputeShader computeShader, int kernelIndex, string name, RenderTargetIdentifier rt, int mipLevel) { Internal_SetComputeTextureParam(computeShader, kernelIndex, Shader.PropertyToID(name), ref rt, mipLevel, RenderTextureSubElement.Default); } public void SetComputeTextureParam(ComputeShader computeShader, int kernelIndex, int nameID, RenderTargetIdentifier rt, int mipLevel) { Internal_SetComputeTextureParam(computeShader, kernelIndex, nameID, ref rt, mipLevel, RenderTextureSubElement.Default); } public void SetComputeTextureParam(ComputeShader computeShader, int kernelIndex, string name, RenderTargetIdentifier rt, int mipLevel, RenderTextureSubElement element) { Internal_SetComputeTextureParam(computeShader, kernelIndex, Shader.PropertyToID(name), ref rt, mipLevel, element); } public void SetComputeTextureParam(ComputeShader computeShader, int kernelIndex, int nameID, RenderTargetIdentifier rt, int mipLevel, RenderTextureSubElement element) { Internal_SetComputeTextureParam(computeShader, kernelIndex, nameID, ref rt, mipLevel, element); } public void SetComputeBufferParam(ComputeShader computeShader, int kernelIndex, int nameID, ComputeBuffer buffer) { Internal_SetComputeBufferParam(computeShader, kernelIndex, nameID, buffer); } public void SetComputeBufferParam(ComputeShader computeShader, int kernelIndex, string name, ComputeBuffer buffer) { Internal_SetComputeBufferParam(computeShader, kernelIndex, Shader.PropertyToID(name), buffer); } public void SetComputeBufferParam(ComputeShader computeShader, int kernelIndex, int nameID, GraphicsBuffer buffer) { Internal_SetComputeGraphicsBufferParam(computeShader, kernelIndex, nameID, buffer); } public void SetComputeBufferParam(ComputeShader computeShader, int kernelIndex, string name, GraphicsBuffer buffer) { Internal_SetComputeGraphicsBufferParam(computeShader, kernelIndex, Shader.PropertyToID(name), buffer); } public void SetComputeConstantBufferParam(ComputeShader computeShader, int nameID, ComputeBuffer buffer, int offset, int size) { Internal_SetComputeConstantComputeBufferParam(computeShader, nameID, buffer, offset, size); } public void SetComputeConstantBufferParam(ComputeShader computeShader, string name, ComputeBuffer buffer, int offset, int size) { Internal_SetComputeConstantComputeBufferParam(computeShader, Shader.PropertyToID(name), buffer, offset, size); } public void SetComputeConstantBufferParam(ComputeShader computeShader, int nameID, GraphicsBuffer buffer, int offset, int size) { Internal_SetComputeConstantGraphicsBufferParam(computeShader, nameID, buffer, offset, size); } public void SetComputeConstantBufferParam(ComputeShader computeShader, string name, GraphicsBuffer buffer, int offset, int size) { Internal_SetComputeConstantGraphicsBufferParam(computeShader, Shader.PropertyToID(name), buffer, offset, size); } public void DispatchCompute(ComputeShader computeShader, int kernelIndex, int threadGroupsX, int threadGroupsY, int threadGroupsZ) { Internal_DispatchCompute(computeShader, kernelIndex, threadGroupsX, threadGroupsY, threadGroupsZ); } public void DispatchCompute(ComputeShader computeShader, int kernelIndex, ComputeBuffer indirectBuffer, uint argsOffset) { Internal_DispatchComputeIndirect(computeShader, kernelIndex, indirectBuffer, argsOffset); } public void DispatchCompute(ComputeShader computeShader, int kernelIndex, GraphicsBuffer indirectBuffer, uint argsOffset) { Internal_DispatchComputeIndirectGraphicsBuffer(computeShader, kernelIndex, indirectBuffer, argsOffset); } public void BuildRayTracingAccelerationStructure(RayTracingAccelerationStructure accelerationStructure) { Vector3 relativeOrigin = new Vector3(0f, 0f, 0f); Internal_BuildRayTracingAccelerationStructure(accelerationStructure, relativeOrigin); } public void BuildRayTracingAccelerationStructure(RayTracingAccelerationStructure accelerationStructure, Vector3 relativeOrigin) { Internal_BuildRayTracingAccelerationStructure(accelerationStructure, relativeOrigin); } public void SetRayTracingAccelerationStructure(RayTracingShader rayTracingShader, string name, RayTracingAccelerationStructure rayTracingAccelerationStructure) { Internal_SetRayTracingAccelerationStructure(rayTracingShader, Shader.PropertyToID(name), rayTracingAccelerationStructure); } public void SetRayTracingAccelerationStructure(RayTracingShader rayTracingShader, int nameID, RayTracingAccelerationStructure rayTracingAccelerationStructure) { Internal_SetRayTracingAccelerationStructure(rayTracingShader, nameID, rayTracingAccelerationStructure); } public void SetRayTracingBufferParam(RayTracingShader rayTracingShader, string name, ComputeBuffer buffer) { Internal_SetRayTracingBufferParam(rayTracingShader, Shader.PropertyToID(name), buffer); } public void SetRayTracingBufferParam(RayTracingShader rayTracingShader, int nameID, ComputeBuffer buffer) { Internal_SetRayTracingBufferParam(rayTracingShader, nameID, buffer); } public void SetRayTracingConstantBufferParam(RayTracingShader rayTracingShader, int nameID, ComputeBuffer buffer, int offset, int size) { Internal_SetRayTracingConstantComputeBufferParam(rayTracingShader, nameID, buffer, offset, size); } public void SetRayTracingConstantBufferParam(RayTracingShader rayTracingShader, string name, ComputeBuffer buffer, int offset, int size) { Internal_SetRayTracingConstantComputeBufferParam(rayTracingShader, Shader.PropertyToID(name), buffer, offset, size); } public void SetRayTracingConstantBufferParam(RayTracingShader rayTracingShader, int nameID, GraphicsBuffer buffer, int offset, int size) { Internal_SetRayTracingConstantGraphicsBufferParam(rayTracingShader, nameID, buffer, offset, size); } public void SetRayTracingConstantBufferParam(RayTracingShader rayTracingShader, string name, GraphicsBuffer buffer, int offset, int size) { Internal_SetRayTracingConstantGraphicsBufferParam(rayTracingShader, Shader.PropertyToID(name), buffer, offset, size); } public void SetRayTracingTextureParam(RayTracingShader rayTracingShader, string name, RenderTargetIdentifier rt) { Internal_SetRayTracingTextureParam(rayTracingShader, Shader.PropertyToID(name), ref rt); } public void SetRayTracingTextureParam(RayTracingShader rayTracingShader, int nameID, RenderTargetIdentifier rt) { Internal_SetRayTracingTextureParam(rayTracingShader, nameID, ref rt); } public void SetRayTracingFloatParam(RayTracingShader rayTracingShader, string name, float val) { Internal_SetRayTracingFloatParam(rayTracingShader, Shader.PropertyToID(name), val); } public void SetRayTracingFloatParam(RayTracingShader rayTracingShader, int nameID, float val) { Internal_SetRayTracingFloatParam(rayTracingShader, nameID, val); } public void SetRayTracingFloatParams(RayTracingShader rayTracingShader, string name, params float[] values) { Internal_SetRayTracingFloats(rayTracingShader, Shader.PropertyToID(name), values); } public void SetRayTracingFloatParams(RayTracingShader rayTracingShader, int nameID, params float[] values) { Internal_SetRayTracingFloats(rayTracingShader, nameID, values); } public void SetRayTracingIntParam(RayTracingShader rayTracingShader, string name, int val) { Internal_SetRayTracingIntParam(rayTracingShader, Shader.PropertyToID(name), val); } public void SetRayTracingIntParam(RayTracingShader rayTracingShader, int nameID, int val) { Internal_SetRayTracingIntParam(rayTracingShader, nameID, val); } public void SetRayTracingIntParams(RayTracingShader rayTracingShader, string name, params int[] values) { Internal_SetRayTracingInts(rayTracingShader, Shader.PropertyToID(name), values); } public void SetRayTracingIntParams(RayTracingShader rayTracingShader, int nameID, params int[] values) { Internal_SetRayTracingInts(rayTracingShader, nameID, values); } public void SetRayTracingVectorParam(RayTracingShader rayTracingShader, string name, Vector4 val) { Internal_SetRayTracingVectorParam(rayTracingShader, Shader.PropertyToID(name), val); } public void SetRayTracingVectorParam(RayTracingShader rayTracingShader, int nameID, Vector4 val) { Internal_SetRayTracingVectorParam(rayTracingShader, nameID, val); } public void SetRayTracingVectorArrayParam(RayTracingShader rayTracingShader, string name, params Vector4[] values) { Internal_SetRayTracingVectorArrayParam(rayTracingShader, Shader.PropertyToID(name), values); } public void SetRayTracingVectorArrayParam(RayTracingShader rayTracingShader, int nameID, params Vector4[] values) { Internal_SetRayTracingVectorArrayParam(rayTracingShader, nameID, values); } public void SetRayTracingMatrixParam(RayTracingShader rayTracingShader, string name, Matrix4x4 val) { Internal_SetRayTracingMatrixParam(rayTracingShader, Shader.PropertyToID(name), val); } public void SetRayTracingMatrixParam(RayTracingShader rayTracingShader, int nameID, Matrix4x4 val) { Internal_SetRayTracingMatrixParam(rayTracingShader, nameID, val); } public void SetRayTracingMatrixArrayParam(RayTracingShader rayTracingShader, string name, params Matrix4x4[] values) { Internal_SetRayTracingMatrixArrayParam(rayTracingShader, Shader.PropertyToID(name), values); } public void SetRayTracingMatrixArrayParam(RayTracingShader rayTracingShader, int nameID, params Matrix4x4[] values) { Internal_SetRayTracingMatrixArrayParam(rayTracingShader, nameID, values); } public void DispatchRays(RayTracingShader rayTracingShader, string rayGenName, uint width, uint height, uint depth, Camera camera = null) { Internal_DispatchRays(rayTracingShader, rayGenName, width, height, depth, camera); } public void GenerateMips(RenderTargetIdentifier rt) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_GenerateMips(rt); } public void GenerateMips(RenderTexture rt) { if (rt == null) { throw new ArgumentNullException("rt"); } GenerateMips(new RenderTargetIdentifier(rt)); } public void ResolveAntiAliasedSurface(RenderTexture rt, RenderTexture target = null) { if (rt == null) { throw new ArgumentNullException("rt"); } Internal_ResolveAntiAliasedSurface(rt, target); } public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int submeshIndex, int shaderPass, MaterialPropertyBlock properties) { if (mesh == null) { throw new ArgumentNullException("mesh"); } ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (submeshIndex < 0 || submeshIndex >= mesh.subMeshCount) { submeshIndex = Mathf.Clamp(submeshIndex, 0, mesh.subMeshCount - 1); Debug.LogWarning($"submeshIndex out of range. Clampped to {submeshIndex}."); } if (material == null) { throw new ArgumentNullException("material"); } Internal_DrawMesh(mesh, matrix, material, submeshIndex, shaderPass, properties); } public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int submeshIndex, int shaderPass) { DrawMesh(mesh, matrix, material, submeshIndex, shaderPass, null); } public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material, int submeshIndex) { DrawMesh(mesh, matrix, material, submeshIndex, -1); } public void DrawMesh(Mesh mesh, Matrix4x4 matrix, Material material) { DrawMesh(mesh, matrix, material, 0); } public void DrawRenderer(Renderer renderer, Material material, int submeshIndex, int shaderPass) { if (renderer == null) { throw new ArgumentNullException("renderer"); } ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (submeshIndex < 0) { submeshIndex = Mathf.Max(submeshIndex, 0); Debug.LogWarning($"submeshIndex out of range. Clampped to {submeshIndex}."); } if (material == null) { throw new ArgumentNullException("material"); } Internal_DrawRenderer(renderer, material, submeshIndex, shaderPass); } public void DrawRenderer(Renderer renderer, Material material, int submeshIndex) { DrawRenderer(renderer, material, submeshIndex, -1); } public void DrawRenderer(Renderer renderer, Material material) { DrawRenderer(renderer, material, 0); } public void DrawRendererList(RendererList rendererList) { Internal_DrawRendererList(rendererList); } public void DrawProcedural(Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, int vertexCount, int instanceCount, MaterialPropertyBlock properties) { if (material == null) { throw new ArgumentNullException("material"); } ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_DrawProcedural(matrix, material, shaderPass, topology, vertexCount, instanceCount, properties); } public void DrawProcedural(Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, int vertexCount, int instanceCount) { DrawProcedural(matrix, material, shaderPass, topology, vertexCount, instanceCount, null); } public void DrawProcedural(Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, int vertexCount) { DrawProcedural(matrix, material, shaderPass, topology, vertexCount, 1); } public void DrawProcedural(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, int indexCount, int instanceCount, MaterialPropertyBlock properties) { if (indexBuffer == null) { throw new ArgumentNullException("indexBuffer"); } if (material == null) { throw new ArgumentNullException("material"); } Internal_DrawProceduralIndexed(indexBuffer, matrix, material, shaderPass, topology, indexCount, instanceCount, properties); } public void DrawProcedural(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, int indexCount, int instanceCount) { DrawProcedural(indexBuffer, matrix, material, shaderPass, topology, indexCount, instanceCount, null); } public void DrawProcedural(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, int indexCount) { DrawProcedural(indexBuffer, matrix, material, shaderPass, topology, indexCount, 1); } public void DrawProceduralIndirect(Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, ComputeBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties) { if (material == null) { throw new ArgumentNullException("material"); } if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_DrawProceduralIndirect(matrix, material, shaderPass, topology, bufferWithArgs, argsOffset, properties); } public void DrawProceduralIndirect(Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, ComputeBuffer bufferWithArgs, int argsOffset) { DrawProceduralIndirect(matrix, material, shaderPass, topology, bufferWithArgs, argsOffset, null); } public void DrawProceduralIndirect(Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, ComputeBuffer bufferWithArgs) { DrawProceduralIndirect(matrix, material, shaderPass, topology, bufferWithArgs, 0); } public void DrawProceduralIndirect(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, ComputeBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties) { if (indexBuffer == null) { throw new ArgumentNullException("indexBuffer"); } if (material == null) { throw new ArgumentNullException("material"); } if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } Internal_DrawProceduralIndexedIndirect(indexBuffer, matrix, material, shaderPass, topology, bufferWithArgs, argsOffset, properties); } public void DrawProceduralIndirect(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, ComputeBuffer bufferWithArgs, int argsOffset) { DrawProceduralIndirect(indexBuffer, matrix, material, shaderPass, topology, bufferWithArgs, argsOffset, null); } public void DrawProceduralIndirect(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, ComputeBuffer bufferWithArgs) { DrawProceduralIndirect(indexBuffer, matrix, material, shaderPass, topology, bufferWithArgs, 0); } public void DrawProceduralIndirect(Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, GraphicsBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties) { if (material == null) { throw new ArgumentNullException("material"); } if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_DrawProceduralIndirectGraphicsBuffer(matrix, material, shaderPass, topology, bufferWithArgs, argsOffset, properties); } public void DrawProceduralIndirect(Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, GraphicsBuffer bufferWithArgs, int argsOffset) { DrawProceduralIndirect(matrix, material, shaderPass, topology, bufferWithArgs, argsOffset, null); } public void DrawProceduralIndirect(Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, GraphicsBuffer bufferWithArgs) { DrawProceduralIndirect(matrix, material, shaderPass, topology, bufferWithArgs, 0); } public void DrawProceduralIndirect(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, GraphicsBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties) { if (indexBuffer == null) { throw new ArgumentNullException("indexBuffer"); } if (material == null) { throw new ArgumentNullException("material"); } if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } Internal_DrawProceduralIndexedIndirectGraphicsBuffer(indexBuffer, matrix, material, shaderPass, topology, bufferWithArgs, argsOffset, properties); } public void DrawProceduralIndirect(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, GraphicsBuffer bufferWithArgs, int argsOffset) { DrawProceduralIndirect(indexBuffer, matrix, material, shaderPass, topology, bufferWithArgs, argsOffset, null); } public void DrawProceduralIndirect(GraphicsBuffer indexBuffer, Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, GraphicsBuffer bufferWithArgs) { DrawProceduralIndirect(indexBuffer, matrix, material, shaderPass, topology, bufferWithArgs, 0); } public void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, int shaderPass, Matrix4x4[] matrices, int count, MaterialPropertyBlock properties) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("DrawMeshInstanced is not supported."); } if (mesh == null) { throw new ArgumentNullException("mesh"); } if (submeshIndex < 0 || submeshIndex >= mesh.subMeshCount) { throw new ArgumentOutOfRangeException("submeshIndex", "submeshIndex out of range."); } if (material == null) { throw new ArgumentNullException("material"); } if (matrices == null) { throw new ArgumentNullException("matrices"); } if (count < 0 || count > Mathf.Min(Graphics.kMaxDrawMeshInstanceCount, matrices.Length)) { throw new ArgumentOutOfRangeException("count", $"Count must be in the range of 0 to {Mathf.Min(Graphics.kMaxDrawMeshInstanceCount, matrices.Length)}."); } ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (count > 0) { Internal_DrawMeshInstanced(mesh, submeshIndex, material, shaderPass, matrices, count, properties); } } public void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, int shaderPass, Matrix4x4[] matrices, int count) { DrawMeshInstanced(mesh, submeshIndex, material, shaderPass, matrices, count, null); } public void DrawMeshInstanced(Mesh mesh, int submeshIndex, Material material, int shaderPass, Matrix4x4[] matrices) { DrawMeshInstanced(mesh, submeshIndex, material, shaderPass, matrices, matrices.Length); } public void DrawMeshInstancedProcedural(Mesh mesh, int submeshIndex, Material material, int shaderPass, int count, MaterialPropertyBlock properties = null) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("DrawMeshInstancedProcedural is not supported."); } if (mesh == null) { throw new ArgumentNullException("mesh"); } if (submeshIndex < 0 || submeshIndex >= mesh.subMeshCount) { throw new ArgumentOutOfRangeException("submeshIndex", "submeshIndex out of range."); } if (material == null) { throw new ArgumentNullException("material"); } if (count <= 0) { throw new ArgumentOutOfRangeException("count"); } ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); if (count > 0) { Internal_DrawMeshInstancedProcedural(mesh, submeshIndex, material, shaderPass, count, properties); } } public void DrawMeshInstancedIndirect(Mesh mesh, int submeshIndex, Material material, int shaderPass, ComputeBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } if (mesh == null) { throw new ArgumentNullException("mesh"); } if (submeshIndex < 0 || submeshIndex >= mesh.subMeshCount) { throw new ArgumentOutOfRangeException("submeshIndex", "submeshIndex out of range."); } if (material == null) { throw new ArgumentNullException("material"); } if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } Internal_DrawMeshInstancedIndirect(mesh, submeshIndex, material, shaderPass, bufferWithArgs, argsOffset, properties); } public void DrawMeshInstancedIndirect(Mesh mesh, int submeshIndex, Material material, int shaderPass, ComputeBuffer bufferWithArgs, int argsOffset) { DrawMeshInstancedIndirect(mesh, submeshIndex, material, shaderPass, bufferWithArgs, argsOffset, null); } public void DrawMeshInstancedIndirect(Mesh mesh, int submeshIndex, Material material, int shaderPass, ComputeBuffer bufferWithArgs) { DrawMeshInstancedIndirect(mesh, submeshIndex, material, shaderPass, bufferWithArgs, 0, null); } public void DrawMeshInstancedIndirect(Mesh mesh, int submeshIndex, Material material, int shaderPass, GraphicsBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties) { if (!SystemInfo.supportsInstancing) { throw new InvalidOperationException("Instancing is not supported."); } if (mesh == null) { throw new ArgumentNullException("mesh"); } if (submeshIndex < 0 || submeshIndex >= mesh.subMeshCount) { throw new ArgumentOutOfRangeException("submeshIndex", "submeshIndex out of range."); } if (material == null) { throw new ArgumentNullException("material"); } if (bufferWithArgs == null) { throw new ArgumentNullException("bufferWithArgs"); } Internal_DrawMeshInstancedIndirectGraphicsBuffer(mesh, submeshIndex, material, shaderPass, bufferWithArgs, argsOffset, properties); } public void DrawMeshInstancedIndirect(Mesh mesh, int submeshIndex, Material material, int shaderPass, GraphicsBuffer bufferWithArgs, int argsOffset) { DrawMeshInstancedIndirect(mesh, submeshIndex, material, shaderPass, bufferWithArgs, argsOffset, null); } public void DrawMeshInstancedIndirect(Mesh mesh, int submeshIndex, Material material, int shaderPass, GraphicsBuffer bufferWithArgs) { DrawMeshInstancedIndirect(mesh, submeshIndex, material, shaderPass, bufferWithArgs, 0, null); } public void DrawOcclusionMesh(RectInt normalizedCamViewport) { Internal_DrawOcclusionMesh(normalizedCamViewport); } public void SetRandomWriteTarget(int index, RenderTargetIdentifier rt) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); SetRandomWriteTarget_Texture(index, ref rt); } public void SetRandomWriteTarget(int index, ComputeBuffer buffer, bool preserveCounterValue) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); SetRandomWriteTarget_Buffer(index, buffer, preserveCounterValue); } public void SetRandomWriteTarget(int index, ComputeBuffer buffer) { SetRandomWriteTarget(index, buffer, preserveCounterValue: false); } public void SetRandomWriteTarget(int index, GraphicsBuffer buffer, bool preserveCounterValue) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); SetRandomWriteTarget_GraphicsBuffer(index, buffer, preserveCounterValue); } public void SetRandomWriteTarget(int index, GraphicsBuffer buffer) { SetRandomWriteTarget(index, buffer, preserveCounterValue: false); } public void CopyCounterValue(ComputeBuffer src, ComputeBuffer dst, uint dstOffsetBytes) { CopyCounterValueCC(src, dst, dstOffsetBytes); } public void CopyCounterValue(GraphicsBuffer src, ComputeBuffer dst, uint dstOffsetBytes) { CopyCounterValueGC(src, dst, dstOffsetBytes); } public void CopyCounterValue(ComputeBuffer src, GraphicsBuffer dst, uint dstOffsetBytes) { CopyCounterValueCG(src, dst, dstOffsetBytes); } public void CopyCounterValue(GraphicsBuffer src, GraphicsBuffer dst, uint dstOffsetBytes) { CopyCounterValueGG(src, dst, dstOffsetBytes); } public void CopyTexture(RenderTargetIdentifier src, RenderTargetIdentifier dst) { CopyTexture_Internal(ref src, -1, -1, -1, -1, -1, -1, ref dst, -1, -1, -1, -1, 1); } public void CopyTexture(RenderTargetIdentifier src, int srcElement, RenderTargetIdentifier dst, int dstElement) { CopyTexture_Internal(ref src, srcElement, -1, -1, -1, -1, -1, ref dst, dstElement, -1, -1, -1, 2); } public void CopyTexture(RenderTargetIdentifier src, int srcElement, int srcMip, RenderTargetIdentifier dst, int dstElement, int dstMip) { CopyTexture_Internal(ref src, srcElement, srcMip, -1, -1, -1, -1, ref dst, dstElement, dstMip, -1, -1, 3); } public void CopyTexture(RenderTargetIdentifier src, int srcElement, int srcMip, int srcX, int srcY, int srcWidth, int srcHeight, RenderTargetIdentifier dst, int dstElement, int dstMip, int dstX, int dstY) { CopyTexture_Internal(ref src, srcElement, srcMip, srcX, srcY, srcWidth, srcHeight, ref dst, dstElement, dstMip, dstX, dstY, 4); } public void Blit(Texture source, RenderTargetIdentifier dest) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Blit_Texture(source, ref dest, null, -1, new Vector2(1f, 1f), new Vector2(0f, 0f), Texture2DArray.allSlices, 0); } public void Blit(Texture source, RenderTargetIdentifier dest, Vector2 scale, Vector2 offset) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Blit_Texture(source, ref dest, null, -1, scale, offset, Texture2DArray.allSlices, 0); } public void Blit(Texture source, RenderTargetIdentifier dest, Material mat) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Blit_Texture(source, ref dest, mat, -1, new Vector2(1f, 1f), new Vector2(0f, 0f), Texture2DArray.allSlices, 0); } public void Blit(Texture source, RenderTargetIdentifier dest, Material mat, int pass) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Blit_Texture(source, ref dest, mat, pass, new Vector2(1f, 1f), new Vector2(0f, 0f), Texture2DArray.allSlices, 0); } public void Blit(RenderTargetIdentifier source, RenderTargetIdentifier dest) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Blit_Identifier(ref source, ref dest, null, -1, new Vector2(1f, 1f), new Vector2(0f, 0f), Texture2DArray.allSlices, 0); } public void Blit(RenderTargetIdentifier source, RenderTargetIdentifier dest, Vector2 scale, Vector2 offset) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Blit_Identifier(ref source, ref dest, null, -1, scale, offset, Texture2DArray.allSlices, 0); } public void Blit(RenderTargetIdentifier source, RenderTargetIdentifier dest, Material mat) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Blit_Identifier(ref source, ref dest, mat, -1, new Vector2(1f, 1f), new Vector2(0f, 0f), Texture2DArray.allSlices, 0); } public void Blit(RenderTargetIdentifier source, RenderTargetIdentifier dest, Material mat, int pass) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Blit_Identifier(ref source, ref dest, mat, pass, new Vector2(1f, 1f), new Vector2(0f, 0f), Texture2DArray.allSlices, 0); } public void Blit(RenderTargetIdentifier source, RenderTargetIdentifier dest, int sourceDepthSlice, int destDepthSlice) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Blit_Identifier(ref source, ref dest, null, -1, new Vector2(1f, 1f), new Vector2(0f, 0f), sourceDepthSlice, destDepthSlice); } public void Blit(RenderTargetIdentifier source, RenderTargetIdentifier dest, Vector2 scale, Vector2 offset, int sourceDepthSlice, int destDepthSlice) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Blit_Identifier(ref source, ref dest, null, -1, scale, offset, sourceDepthSlice, destDepthSlice); } public void Blit(RenderTargetIdentifier source, RenderTargetIdentifier dest, Material mat, int pass, int destDepthSlice) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Blit_Identifier(ref source, ref dest, mat, pass, new Vector2(1f, 1f), new Vector2(0f, 0f), Texture2DArray.allSlices, destDepthSlice); } public void SetGlobalFloat(string name, float value) { SetGlobalFloat(Shader.PropertyToID(name), value); } public void SetGlobalInt(string name, int value) { SetGlobalInt(Shader.PropertyToID(name), value); } public void SetGlobalInteger(string name, int value) { SetGlobalInteger(Shader.PropertyToID(name), value); } public void SetGlobalVector(string name, Vector4 value) { SetGlobalVector(Shader.PropertyToID(name), value); } public void SetGlobalColor(string name, Color value) { SetGlobalColor(Shader.PropertyToID(name), value); } public void SetGlobalMatrix(string name, Matrix4x4 value) { SetGlobalMatrix(Shader.PropertyToID(name), value); } public void SetGlobalFloatArray(string propertyName, List values) { SetGlobalFloatArray(Shader.PropertyToID(propertyName), values); } public void SetGlobalFloatArray(int nameID, List values) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Count == 0) { throw new ArgumentException("Zero-sized array is not allowed."); } SetGlobalFloatArrayListImpl(nameID, values); } public void SetGlobalFloatArray(string propertyName, float[] values) { SetGlobalFloatArray(Shader.PropertyToID(propertyName), values); } public void SetGlobalVectorArray(string propertyName, List values) { SetGlobalVectorArray(Shader.PropertyToID(propertyName), values); } public void SetGlobalVectorArray(int nameID, List values) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Count == 0) { throw new ArgumentException("Zero-sized array is not allowed."); } SetGlobalVectorArrayListImpl(nameID, values); } public void SetGlobalVectorArray(string propertyName, Vector4[] values) { SetGlobalVectorArray(Shader.PropertyToID(propertyName), values); } public void SetGlobalMatrixArray(string propertyName, List values) { SetGlobalMatrixArray(Shader.PropertyToID(propertyName), values); } public void SetGlobalMatrixArray(int nameID, List values) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Count == 0) { throw new ArgumentException("Zero-sized array is not allowed."); } SetGlobalMatrixArrayListImpl(nameID, values); } public void SetGlobalMatrixArray(string propertyName, Matrix4x4[] values) { SetGlobalMatrixArray(Shader.PropertyToID(propertyName), values); } public void SetGlobalTexture(string name, RenderTargetIdentifier value) { SetGlobalTexture(Shader.PropertyToID(name), value, RenderTextureSubElement.Default); } public void SetGlobalTexture(int nameID, RenderTargetIdentifier value) { SetGlobalTexture_Impl(nameID, ref value, RenderTextureSubElement.Default); } public void SetGlobalTexture(string name, RenderTargetIdentifier value, RenderTextureSubElement element) { SetGlobalTexture(Shader.PropertyToID(name), value, element); } public void SetGlobalTexture(int nameID, RenderTargetIdentifier value, RenderTextureSubElement element) { SetGlobalTexture_Impl(nameID, ref value, element); } public void SetGlobalBuffer(string name, ComputeBuffer value) { SetGlobalBufferInternal(Shader.PropertyToID(name), value); } public void SetGlobalBuffer(int nameID, ComputeBuffer value) { SetGlobalBufferInternal(nameID, value); } public void SetGlobalBuffer(string name, GraphicsBuffer value) { SetGlobalGraphicsBufferInternal(Shader.PropertyToID(name), value); } public void SetGlobalBuffer(int nameID, GraphicsBuffer value) { SetGlobalGraphicsBufferInternal(nameID, value); } public void SetGlobalConstantBuffer(ComputeBuffer buffer, int nameID, int offset, int size) { SetGlobalConstantBufferInternal(buffer, nameID, offset, size); } public void SetGlobalConstantBuffer(ComputeBuffer buffer, string name, int offset, int size) { SetGlobalConstantBufferInternal(buffer, Shader.PropertyToID(name), offset, size); } public void SetGlobalConstantBuffer(GraphicsBuffer buffer, int nameID, int offset, int size) { SetGlobalConstantGraphicsBufferInternal(buffer, nameID, offset, size); } public void SetGlobalConstantBuffer(GraphicsBuffer buffer, string name, int offset, int size) { SetGlobalConstantGraphicsBufferInternal(buffer, Shader.PropertyToID(name), offset, size); } public void SetShadowSamplingMode(RenderTargetIdentifier shadowmap, ShadowSamplingMode mode) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); SetShadowSamplingMode_Impl(ref shadowmap, mode); } public void SetSinglePassStereo(SinglePassStereoMode mode) { Internal_SetSinglePassStereo(mode); } public void IssuePluginEvent(IntPtr callback, int eventID) { if (callback == IntPtr.Zero) { throw new ArgumentException("Null callback specified."); } IssuePluginEventInternal(callback, eventID); } public void IssuePluginEventAndData(IntPtr callback, int eventID, IntPtr data) { if (callback == IntPtr.Zero) { throw new ArgumentException("Null callback specified."); } ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); IssuePluginEventAndDataInternal(callback, eventID, data); } public void IssuePluginCustomBlit(IntPtr callback, uint command, RenderTargetIdentifier source, RenderTargetIdentifier dest, uint commandParam, uint commandFlags) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); IssuePluginCustomBlitInternal(callback, command, ref source, ref dest, commandParam, commandFlags); } [Obsolete("Use IssuePluginCustomTextureUpdateV2 to register TextureUpdate callbacks instead. Callbacks will be passed event IDs kUnityRenderingExtEventUpdateTextureBeginV2 or kUnityRenderingExtEventUpdateTextureEndV2, and data parameter of type UnityRenderingExtTextureUpdateParamsV2.", false)] public void IssuePluginCustomTextureUpdate(IntPtr callback, Texture targetTexture, uint userData) { IssuePluginCustomTextureUpdateInternal(callback, targetTexture, userData, useNewUnityRenderingExtTextureUpdateParamsV2: false); } [Obsolete("Use IssuePluginCustomTextureUpdateV2 to register TextureUpdate callbacks instead. Callbacks will be passed event IDs kUnityRenderingExtEventUpdateTextureBeginV2 or kUnityRenderingExtEventUpdateTextureEndV2, and data parameter of type UnityRenderingExtTextureUpdateParamsV2.", false)] public void IssuePluginCustomTextureUpdateV1(IntPtr callback, Texture targetTexture, uint userData) { IssuePluginCustomTextureUpdateInternal(callback, targetTexture, userData, useNewUnityRenderingExtTextureUpdateParamsV2: false); } public void IssuePluginCustomTextureUpdateV2(IntPtr callback, Texture targetTexture, uint userData) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); IssuePluginCustomTextureUpdateInternal(callback, targetTexture, userData, useNewUnityRenderingExtTextureUpdateParamsV2: true); } public void ProcessVTFeedback(RenderTargetIdentifier rt, IntPtr resolver, int slice, int x, int width, int y, int height, int mip) { ValidateAgainstExecutionFlags(CommandBufferExecutionFlags.None, CommandBufferExecutionFlags.AsyncCompute); Internal_ProcessVTFeedback(rt, resolver, slice, x, width, y, height, mip); } public void CopyBuffer(GraphicsBuffer source, GraphicsBuffer dest) { Graphics.ValidateCopyBuffer(source, dest); CopyBufferImpl(source, dest); } [Obsolete("CommandBuffer.CreateGPUFence has been deprecated. Use CreateGraphicsFence instead (UnityUpgradable) -> CreateAsyncGraphicsFence(*)", false)] public GPUFence CreateGPUFence(SynchronisationStage stage) { return default(GPUFence); } [Obsolete("CommandBuffer.CreateGPUFence has been deprecated. Use CreateGraphicsFence instead (UnityUpgradable) -> CreateAsyncGraphicsFence()", false)] public GPUFence CreateGPUFence() { return default(GPUFence); } [Obsolete("CommandBuffer.WaitOnGPUFence has been deprecated. Use WaitOnGraphicsFence instead (UnityUpgradable) -> WaitOnAsyncGraphicsFence(*)", false)] public void WaitOnGPUFence(GPUFence fence, SynchronisationStage stage) { } [Obsolete("CommandBuffer.WaitOnGPUFence has been deprecated. Use WaitOnGraphicsFence instead (UnityUpgradable) -> WaitOnAsyncGraphicsFence(*)", false)] public void WaitOnGPUFence(GPUFence fence) { } [Obsolete("CommandBuffer.SetComputeBufferData has been deprecated. Use SetBufferData instead (UnityUpgradable) -> SetBufferData(*)", false)] public void SetComputeBufferData(ComputeBuffer buffer, Array data) { SetBufferData(buffer, data); } [Obsolete("CommandBuffer.SetComputeBufferData has been deprecated. Use SetBufferData instead (UnityUpgradable) -> SetBufferData(*)", false)] public void SetComputeBufferData(ComputeBuffer buffer, List data) where T : struct { SetBufferData(buffer, data); } [Obsolete("CommandBuffer.SetComputeBufferData has been deprecated. Use SetBufferData instead (UnityUpgradable) -> SetBufferData(*)", false)] public void SetComputeBufferData(ComputeBuffer buffer, NativeArray data) where T : struct { SetBufferData(buffer, data); } [Obsolete("CommandBuffer.SetComputeBufferData has been deprecated. Use SetBufferData instead (UnityUpgradable) -> SetBufferData(*)", false)] public void SetComputeBufferData(ComputeBuffer buffer, Array data, int managedBufferStartIndex, int graphicsBufferStartIndex, int count) { SetBufferData(buffer, data, managedBufferStartIndex, graphicsBufferStartIndex, count); } [Obsolete("CommandBuffer.SetComputeBufferData has been deprecated. Use SetBufferData instead (UnityUpgradable) -> SetBufferData(*)", false)] public void SetComputeBufferData(ComputeBuffer buffer, List data, int managedBufferStartIndex, int graphicsBufferStartIndex, int count) where T : struct { SetBufferData(buffer, data, managedBufferStartIndex, graphicsBufferStartIndex, count); } [Obsolete("CommandBuffer.SetComputeBufferData has been deprecated. Use SetBufferData instead (UnityUpgradable) -> SetBufferData(*)", false)] public void SetComputeBufferData(ComputeBuffer buffer, NativeArray data, int nativeBufferStartIndex, int graphicsBufferStartIndex, int count) where T : struct { SetBufferData(buffer, data, nativeBufferStartIndex, graphicsBufferStartIndex, count); } [Obsolete("CommandBuffer.SetComputeBufferCounterValue has been deprecated. Use SetBufferCounterValue instead (UnityUpgradable) -> SetBufferCounterValue(*)", false)] public void SetComputeBufferCounterValue(ComputeBuffer buffer, uint counterValue) { SetBufferCounterValue(buffer, counterValue); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void ConvertTexture_Internal_Injected(ref RenderTargetIdentifier src, int srcElement, ref RenderTargetIdentifier dst, int dstElement); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetComputeVectorParam_Injected(ComputeShader computeShader, int nameID, ref Vector4 val); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetComputeMatrixParam_Injected(ComputeShader computeShader, int nameID, ref Matrix4x4 val); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_SetRayTracingVectorParam_Injected(RayTracingShader rayTracingShader, int nameID, ref Vector4 val); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_SetRayTracingMatrixParam_Injected(RayTracingShader rayTracingShader, int nameID, ref Matrix4x4 val); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_BuildRayTracingAccelerationStructure_Injected(RayTracingAccelerationStructure accelerationStructure, ref Vector3 relativeOrigin); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_GenerateMips_Injected(ref RenderTargetIdentifier rt); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_DrawMesh_Injected(Mesh mesh, ref Matrix4x4 matrix, Material material, int submeshIndex, int shaderPass, MaterialPropertyBlock properties); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_DrawRendererList_Injected(ref RendererList rendererList); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_DrawProcedural_Injected(ref Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, int vertexCount, int instanceCount, MaterialPropertyBlock properties); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_DrawProceduralIndexed_Injected(GraphicsBuffer indexBuffer, ref Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, int indexCount, int instanceCount, MaterialPropertyBlock properties); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_DrawProceduralIndirect_Injected(ref Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, ComputeBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_DrawProceduralIndexedIndirect_Injected(GraphicsBuffer indexBuffer, ref Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, ComputeBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_DrawProceduralIndirectGraphicsBuffer_Injected(ref Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, GraphicsBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_DrawProceduralIndexedIndirectGraphicsBuffer_Injected(GraphicsBuffer indexBuffer, ref Matrix4x4 matrix, Material material, int shaderPass, MeshTopology topology, GraphicsBuffer bufferWithArgs, int argsOffset, MaterialPropertyBlock properties); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_DrawOcclusionMesh_Injected(ref RectInt normalizedCamViewport); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetViewport_Injected(ref Rect pixelRect); [MethodImpl(MethodImplOptions.InternalCall)] private extern void EnableScissorRect_Injected(ref Rect scissor); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Blit_Texture_Injected(Texture source, ref RenderTargetIdentifier dest, Material mat, int pass, ref Vector2 scale, ref Vector2 offset, int sourceDepthSlice, int destDepthSlice); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Blit_Identifier_Injected(ref RenderTargetIdentifier source, ref RenderTargetIdentifier dest, Material mat, int pass, ref Vector2 scale, ref Vector2 offset, int sourceDepthSlice, int destDepthSlice); [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetTemporaryRTWithDescriptor_Injected(int nameID, ref RenderTextureDescriptor desc, FilterMode filter); [MethodImpl(MethodImplOptions.InternalCall)] private extern void ClearRenderTarget_Injected(RTClearFlags clearFlags, ref Color backgroundColor, float depth, uint stencil); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetGlobalVector_Injected(int nameID, ref Vector4 value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetGlobalColor_Injected(int nameID, ref Color value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetGlobalMatrix_Injected(int nameID, ref Matrix4x4 value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void EnableGlobalKeyword_Injected(ref GlobalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private extern void EnableMaterialKeyword_Injected(Material material, ref LocalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private extern void EnableComputeKeyword_Injected(ComputeShader computeShader, ref LocalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private extern void DisableGlobalKeyword_Injected(ref GlobalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private extern void DisableMaterialKeyword_Injected(Material material, ref LocalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private extern void DisableComputeKeyword_Injected(ComputeShader computeShader, ref LocalKeyword keyword); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetGlobalKeyword_Injected(ref GlobalKeyword keyword, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetMaterialKeyword_Injected(Material material, ref LocalKeyword keyword, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetComputeKeyword_Injected(ComputeShader computeShader, ref LocalKeyword keyword, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetViewMatrix_Injected(ref Matrix4x4 view); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetProjectionMatrix_Injected(ref Matrix4x4 proj); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetViewProjectionMatrices_Injected(ref Matrix4x4 view, ref Matrix4x4 proj); [MethodImpl(MethodImplOptions.InternalCall)] private extern void IncrementUpdateCount_Injected(ref RenderTargetIdentifier dest); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetRenderTargetSingle_Internal_Injected(ref RenderTargetIdentifier rt, RenderBufferLoadAction colorLoadAction, RenderBufferStoreAction colorStoreAction, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetRenderTargetColorDepth_Internal_Injected(ref RenderTargetIdentifier color, ref RenderTargetIdentifier depth, RenderBufferLoadAction colorLoadAction, RenderBufferStoreAction colorStoreAction, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction, RenderTargetFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetRenderTargetMulti_Internal_Injected(RenderTargetIdentifier[] colors, ref RenderTargetIdentifier depth, RenderBufferLoadAction[] colorLoadActions, RenderBufferStoreAction[] colorStoreActions, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction, RenderTargetFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetRenderTargetColorDepthSubtarget_Injected(ref RenderTargetIdentifier color, ref RenderTargetIdentifier depth, RenderBufferLoadAction colorLoadAction, RenderBufferStoreAction colorStoreAction, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction, int mipLevel, CubemapFace cubemapFace, int depthSlice); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetRenderTargetMultiSubtarget_Injected(RenderTargetIdentifier[] colors, ref RenderTargetIdentifier depth, RenderBufferLoadAction[] colorLoadActions, RenderBufferStoreAction[] colorStoreActions, RenderBufferLoadAction depthLoadAction, RenderBufferStoreAction depthStoreAction, int mipLevel, CubemapFace cubemapFace, int depthSlice); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Internal_ProcessVTFeedback_Injected(ref RenderTargetIdentifier rt, IntPtr resolver, int slice, int x, int width, int y, int height, int mip); } [UsedByNativeCode] [NativeHeader("Runtime/Export/Graphics/RenderingCommandBufferExtensions.bindings.h")] public static class CommandBufferExtensions { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBufferExtensions_Bindings::Internal_SwitchIntoFastMemory")] private static extern void Internal_SwitchIntoFastMemory([NotNull("NullExceptionObject")] CommandBuffer cmd, ref RenderTargetIdentifier rt, FastMemoryFlags fastMemoryFlags, float residency, bool copyContents); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RenderingCommandBufferExtensions_Bindings::Internal_SwitchOutOfFastMemory")] private static extern void Internal_SwitchOutOfFastMemory([NotNull("NullExceptionObject")] CommandBuffer cmd, ref RenderTargetIdentifier rt, bool copyContents); [NativeConditional("UNITY_XBOXONE || UNITY_GAMECORE_XBOXONE")] public static void SwitchIntoFastMemory(this CommandBuffer cmd, RenderTargetIdentifier rid, FastMemoryFlags fastMemoryFlags, float residency, bool copyContents) { Internal_SwitchIntoFastMemory(cmd, ref rid, fastMemoryFlags, residency, copyContents); } [NativeConditional("UNITY_XBOXONE || UNITY_GAMECORE_XBOXONE")] public static void SwitchOutOfFastMemory(this CommandBuffer cmd, RenderTargetIdentifier rid, bool copyContents) { Internal_SwitchOutOfFastMemory(cmd, ref rid, copyContents); } } [NativeHeader("Runtime/Graphics/DrawSplashScreenAndWatermarks.h")] public class SplashScreen { public enum StopBehavior { StopImmediate, FadeOut } public static extern bool isFinished { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("IsSplashScreenFinished")] get; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern void CancelSplashScreen(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern void BeginSplashScreenFade(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("BeginSplashScreen_Binding")] public static extern void Begin(); public static void Stop(StopBehavior stopBehavior) { if (stopBehavior == StopBehavior.FadeOut) { BeginSplashScreenFade(); } else { CancelSplashScreen(); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("DrawSplashScreen_Binding")] public static extern void Draw(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SetSplashScreenTime")] internal static extern void SetTime(float time); } [NativeHeader("Runtime/Export/Math/SphericalHarmonicsL2.bindings.h")] [UsedByNativeCode] public struct SphericalHarmonicsL2 : IEquatable { private float shr0; private float shr1; private float shr2; private float shr3; private float shr4; private float shr5; private float shr6; private float shr7; private float shr8; private float shg0; private float shg1; private float shg2; private float shg3; private float shg4; private float shg5; private float shg6; private float shg7; private float shg8; private float shb0; private float shb1; private float shb2; private float shb3; private float shb4; private float shb5; private float shb6; private float shb7; private float shb8; public float this[int rgb, int coefficient] { get { return (rgb * 9 + coefficient) switch { 0 => shr0, 1 => shr1, 2 => shr2, 3 => shr3, 4 => shr4, 5 => shr5, 6 => shr6, 7 => shr7, 8 => shr8, 9 => shg0, 10 => shg1, 11 => shg2, 12 => shg3, 13 => shg4, 14 => shg5, 15 => shg6, 16 => shg7, 17 => shg8, 18 => shb0, 19 => shb1, 20 => shb2, 21 => shb3, 22 => shb4, 23 => shb5, 24 => shb6, 25 => shb7, 26 => shb8, _ => throw new IndexOutOfRangeException("Invalid index!"), }; } set { switch (rgb * 9 + coefficient) { case 0: shr0 = value; break; case 1: shr1 = value; break; case 2: shr2 = value; break; case 3: shr3 = value; break; case 4: shr4 = value; break; case 5: shr5 = value; break; case 6: shr6 = value; break; case 7: shr7 = value; break; case 8: shr8 = value; break; case 9: shg0 = value; break; case 10: shg1 = value; break; case 11: shg2 = value; break; case 12: shg3 = value; break; case 13: shg4 = value; break; case 14: shg5 = value; break; case 15: shg6 = value; break; case 16: shg7 = value; break; case 17: shg8 = value; break; case 18: shb0 = value; break; case 19: shb1 = value; break; case 20: shb2 = value; break; case 21: shb3 = value; break; case 22: shb4 = value; break; case 23: shb5 = value; break; case 24: shb6 = value; break; case 25: shb7 = value; break; case 26: shb8 = value; break; default: throw new IndexOutOfRangeException("Invalid index!"); } } } public void Clear() { SetZero(); } private void SetZero() { SetZero_Injected(ref this); } public void AddAmbientLight(Color color) { AddAmbientLight_Injected(ref this, ref color); } public void AddDirectionalLight(Vector3 direction, Color color, float intensity) { Color color2 = color * (2f * intensity); AddDirectionalLightInternal(ref this, direction, color2); } [FreeFunction] private static void AddDirectionalLightInternal(ref SphericalHarmonicsL2 sh, Vector3 direction, Color color) { AddDirectionalLightInternal_Injected(ref sh, ref direction, ref color); } public void Evaluate(Vector3[] directions, Color[] results) { if (directions == null) { throw new ArgumentNullException("directions"); } if (results == null) { throw new ArgumentNullException("results"); } if (directions.Length != 0) { if (directions.Length != results.Length) { throw new ArgumentException("Length of the directions array and the results array must match."); } EvaluateInternal(ref this, directions, results); } } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern void EvaluateInternal(ref SphericalHarmonicsL2 sh, Vector3[] directions, [Out] Color[] results); public override int GetHashCode() { int num = 17; num = num * 23 + shr0.GetHashCode(); num = num * 23 + shr1.GetHashCode(); num = num * 23 + shr2.GetHashCode(); num = num * 23 + shr3.GetHashCode(); num = num * 23 + shr4.GetHashCode(); num = num * 23 + shr5.GetHashCode(); num = num * 23 + shr6.GetHashCode(); num = num * 23 + shr7.GetHashCode(); num = num * 23 + shr8.GetHashCode(); num = num * 23 + shg0.GetHashCode(); num = num * 23 + shg1.GetHashCode(); num = num * 23 + shg2.GetHashCode(); num = num * 23 + shg3.GetHashCode(); num = num * 23 + shg4.GetHashCode(); num = num * 23 + shg5.GetHashCode(); num = num * 23 + shg6.GetHashCode(); num = num * 23 + shg7.GetHashCode(); num = num * 23 + shg8.GetHashCode(); num = num * 23 + shb0.GetHashCode(); num = num * 23 + shb1.GetHashCode(); num = num * 23 + shb2.GetHashCode(); num = num * 23 + shb3.GetHashCode(); num = num * 23 + shb4.GetHashCode(); num = num * 23 + shb5.GetHashCode(); num = num * 23 + shb6.GetHashCode(); num = num * 23 + shb7.GetHashCode(); return num * 23 + shb8.GetHashCode(); } public override bool Equals(object other) { return other is SphericalHarmonicsL2 && Equals((SphericalHarmonicsL2)other); } public bool Equals(SphericalHarmonicsL2 other) { return this == other; } public static SphericalHarmonicsL2 operator *(SphericalHarmonicsL2 lhs, float rhs) { return new SphericalHarmonicsL2 { shr0 = lhs.shr0 * rhs, shr1 = lhs.shr1 * rhs, shr2 = lhs.shr2 * rhs, shr3 = lhs.shr3 * rhs, shr4 = lhs.shr4 * rhs, shr5 = lhs.shr5 * rhs, shr6 = lhs.shr6 * rhs, shr7 = lhs.shr7 * rhs, shr8 = lhs.shr8 * rhs, shg0 = lhs.shg0 * rhs, shg1 = lhs.shg1 * rhs, shg2 = lhs.shg2 * rhs, shg3 = lhs.shg3 * rhs, shg4 = lhs.shg4 * rhs, shg5 = lhs.shg5 * rhs, shg6 = lhs.shg6 * rhs, shg7 = lhs.shg7 * rhs, shg8 = lhs.shg8 * rhs, shb0 = lhs.shb0 * rhs, shb1 = lhs.shb1 * rhs, shb2 = lhs.shb2 * rhs, shb3 = lhs.shb3 * rhs, shb4 = lhs.shb4 * rhs, shb5 = lhs.shb5 * rhs, shb6 = lhs.shb6 * rhs, shb7 = lhs.shb7 * rhs, shb8 = lhs.shb8 * rhs }; } public static SphericalHarmonicsL2 operator *(float lhs, SphericalHarmonicsL2 rhs) { return new SphericalHarmonicsL2 { shr0 = rhs.shr0 * lhs, shr1 = rhs.shr1 * lhs, shr2 = rhs.shr2 * lhs, shr3 = rhs.shr3 * lhs, shr4 = rhs.shr4 * lhs, shr5 = rhs.shr5 * lhs, shr6 = rhs.shr6 * lhs, shr7 = rhs.shr7 * lhs, shr8 = rhs.shr8 * lhs, shg0 = rhs.shg0 * lhs, shg1 = rhs.shg1 * lhs, shg2 = rhs.shg2 * lhs, shg3 = rhs.shg3 * lhs, shg4 = rhs.shg4 * lhs, shg5 = rhs.shg5 * lhs, shg6 = rhs.shg6 * lhs, shg7 = rhs.shg7 * lhs, shg8 = rhs.shg8 * lhs, shb0 = rhs.shb0 * lhs, shb1 = rhs.shb1 * lhs, shb2 = rhs.shb2 * lhs, shb3 = rhs.shb3 * lhs, shb4 = rhs.shb4 * lhs, shb5 = rhs.shb5 * lhs, shb6 = rhs.shb6 * lhs, shb7 = rhs.shb7 * lhs, shb8 = rhs.shb8 * lhs }; } public static SphericalHarmonicsL2 operator +(SphericalHarmonicsL2 lhs, SphericalHarmonicsL2 rhs) { return new SphericalHarmonicsL2 { shr0 = lhs.shr0 + rhs.shr0, shr1 = lhs.shr1 + rhs.shr1, shr2 = lhs.shr2 + rhs.shr2, shr3 = lhs.shr3 + rhs.shr3, shr4 = lhs.shr4 + rhs.shr4, shr5 = lhs.shr5 + rhs.shr5, shr6 = lhs.shr6 + rhs.shr6, shr7 = lhs.shr7 + rhs.shr7, shr8 = lhs.shr8 + rhs.shr8, shg0 = lhs.shg0 + rhs.shg0, shg1 = lhs.shg1 + rhs.shg1, shg2 = lhs.shg2 + rhs.shg2, shg3 = lhs.shg3 + rhs.shg3, shg4 = lhs.shg4 + rhs.shg4, shg5 = lhs.shg5 + rhs.shg5, shg6 = lhs.shg6 + rhs.shg6, shg7 = lhs.shg7 + rhs.shg7, shg8 = lhs.shg8 + rhs.shg8, shb0 = lhs.shb0 + rhs.shb0, shb1 = lhs.shb1 + rhs.shb1, shb2 = lhs.shb2 + rhs.shb2, shb3 = lhs.shb3 + rhs.shb3, shb4 = lhs.shb4 + rhs.shb4, shb5 = lhs.shb5 + rhs.shb5, shb6 = lhs.shb6 + rhs.shb6, shb7 = lhs.shb7 + rhs.shb7, shb8 = lhs.shb8 + rhs.shb8 }; } public static bool operator ==(SphericalHarmonicsL2 lhs, SphericalHarmonicsL2 rhs) { return lhs.shr0 == rhs.shr0 && lhs.shr1 == rhs.shr1 && lhs.shr2 == rhs.shr2 && lhs.shr3 == rhs.shr3 && lhs.shr4 == rhs.shr4 && lhs.shr5 == rhs.shr5 && lhs.shr6 == rhs.shr6 && lhs.shr7 == rhs.shr7 && lhs.shr8 == rhs.shr8 && lhs.shg0 == rhs.shg0 && lhs.shg1 == rhs.shg1 && lhs.shg2 == rhs.shg2 && lhs.shg3 == rhs.shg3 && lhs.shg4 == rhs.shg4 && lhs.shg5 == rhs.shg5 && lhs.shg6 == rhs.shg6 && lhs.shg7 == rhs.shg7 && lhs.shg8 == rhs.shg8 && lhs.shb0 == rhs.shb0 && lhs.shb1 == rhs.shb1 && lhs.shb2 == rhs.shb2 && lhs.shb3 == rhs.shb3 && lhs.shb4 == rhs.shb4 && lhs.shb5 == rhs.shb5 && lhs.shb6 == rhs.shb6 && lhs.shb7 == rhs.shb7 && lhs.shb8 == rhs.shb8; } public static bool operator !=(SphericalHarmonicsL2 lhs, SphericalHarmonicsL2 rhs) { return !(lhs == rhs); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetZero_Injected(ref SphericalHarmonicsL2 _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void AddAmbientLight_Injected(ref SphericalHarmonicsL2 _unity_self, ref Color color); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void AddDirectionalLightInternal_Injected(ref SphericalHarmonicsL2 sh, ref Vector3 direction, ref Color color); } public struct BatchVisibility { public readonly int offset; public readonly int instancesCount; public int visibleCount; } [NativeHeader("Runtime/Camera/BatchRendererGroup.h")] [UsedByNativeCode] public struct BatchCullingContext { public readonly NativeArray cullingPlanes; public NativeArray batchVisibility; public NativeArray visibleIndices; public NativeArray visibleIndicesY; public readonly LODParameters lodParameters; public readonly Matrix4x4 cullingMatrix; public readonly float nearPlane; [Obsolete("For internal BatchRendererGroup use only")] public unsafe BatchCullingContext(NativeArray inCullingPlanes, NativeArray inOutBatchVisibility, NativeArray outVisibleIndices, LODParameters inLodParameters) { cullingPlanes = inCullingPlanes; batchVisibility = inOutBatchVisibility; visibleIndices = outVisibleIndices; visibleIndicesY = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(null, 0, Allocator.Invalid); lodParameters = inLodParameters; cullingMatrix = Matrix4x4.identity; nearPlane = 0f; } [Obsolete("For internal BatchRendererGroup use only")] public unsafe BatchCullingContext(NativeArray inCullingPlanes, NativeArray inOutBatchVisibility, NativeArray outVisibleIndices, LODParameters inLodParameters, Matrix4x4 inCullingMatrix, float inNearPlane) { cullingPlanes = inCullingPlanes; batchVisibility = inOutBatchVisibility; visibleIndices = outVisibleIndices; visibleIndicesY = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(null, 0, Allocator.Invalid); lodParameters = inLodParameters; cullingMatrix = inCullingMatrix; nearPlane = inNearPlane; } internal BatchCullingContext(NativeArray inCullingPlanes, NativeArray inOutBatchVisibility, NativeArray outVisibleIndices, NativeArray outVisibleIndicesY, LODParameters inLodParameters, Matrix4x4 inCullingMatrix, float inNearPlane) { cullingPlanes = inCullingPlanes; batchVisibility = inOutBatchVisibility; visibleIndices = outVisibleIndices; visibleIndicesY = outVisibleIndicesY; lodParameters = inLodParameters; cullingMatrix = inCullingMatrix; nearPlane = inNearPlane; } } [NativeHeader("Runtime/Camera/BatchRendererGroup.h")] [UsedByNativeCode] internal struct BatchRendererCullingOutput { public JobHandle cullingJobsFence; public Matrix4x4 cullingMatrix; public unsafe Plane* cullingPlanes; public unsafe BatchVisibility* batchVisibility; public unsafe int* visibleIndices; public unsafe int* visibleIndicesY; public int cullingPlanesCount; public int batchVisibilityCount; public int visibleIndicesCount; public float nearPlane; } [StructLayout(LayoutKind.Sequential)] [NativeHeader("Runtime/Math/Matrix4x4.h")] [NativeHeader("Runtime/Camera/BatchRendererGroup.h")] [RequiredByNativeCode] public class BatchRendererGroup : IDisposable { public delegate JobHandle OnPerformCulling(BatchRendererGroup rendererGroup, BatchCullingContext cullingContext); private IntPtr m_GroupHandle = IntPtr.Zero; private OnPerformCulling m_PerformCulling; public BatchRendererGroup(OnPerformCulling cullingCallback) { m_PerformCulling = cullingCallback; m_GroupHandle = Create(this); } public void Dispose() { Destroy(m_GroupHandle); m_GroupHandle = IntPtr.Zero; } public int AddBatch(Mesh mesh, int subMeshIndex, Material material, int layer, ShadowCastingMode castShadows, bool receiveShadows, bool invertCulling, Bounds bounds, int instanceCount, MaterialPropertyBlock customProps, GameObject associatedSceneObject, ulong sceneCullingMask = 9223372036854775808uL, uint renderingLayerMask = uint.MaxValue) { return AddBatch_Injected(mesh, subMeshIndex, material, layer, castShadows, receiveShadows, invertCulling, ref bounds, instanceCount, customProps, associatedSceneObject, sceneCullingMask, renderingLayerMask); } [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetBatchFlags(int batchIndex, ulong flags); public unsafe void SetBatchPropertyMetadata(int batchIndex, NativeArray cbufferLengths, NativeArray cbufferMetadata) { InternalSetBatchPropertyMetadata(batchIndex, (IntPtr)cbufferLengths.GetUnsafeReadOnlyPtr(), cbufferLengths.Length, (IntPtr)cbufferMetadata.GetUnsafeReadOnlyPtr(), cbufferMetadata.Length); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void InternalSetBatchPropertyMetadata(int batchIndex, IntPtr cbufferLengths, int cbufferLengthsCount, IntPtr cbufferMetadata, int cbufferMetadataCount); [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetInstancingData(int batchIndex, int instanceCount, MaterialPropertyBlock customProps); public unsafe NativeArray GetBatchMatrices(int batchIndex) { int matrixCount = 0; void* batchMatrices = GetBatchMatrices(batchIndex, out matrixCount); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(batchMatrices, matrixCount, Allocator.Invalid); } public unsafe NativeArray GetBatchScalarArrayInt(int batchIndex, string propertyName) { int elementCount = 0; void* batchScalarArray = GetBatchScalarArray(batchIndex, propertyName, out elementCount); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(batchScalarArray, elementCount, Allocator.Invalid); } public unsafe NativeArray GetBatchScalarArray(int batchIndex, string propertyName) { int elementCount = 0; void* batchScalarArray = GetBatchScalarArray(batchIndex, propertyName, out elementCount); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(batchScalarArray, elementCount, Allocator.Invalid); } public unsafe NativeArray GetBatchVectorArrayInt(int batchIndex, string propertyName) { int elementCount = 0; void* batchVectorArray = GetBatchVectorArray(batchIndex, propertyName, out elementCount); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(batchVectorArray, elementCount, Allocator.Invalid); } public unsafe NativeArray GetBatchVectorArray(int batchIndex, string propertyName) { int elementCount = 0; void* batchVectorArray = GetBatchVectorArray(batchIndex, propertyName, out elementCount); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(batchVectorArray, elementCount, Allocator.Invalid); } public unsafe NativeArray GetBatchMatrixArray(int batchIndex, string propertyName) { int elementCount = 0; void* batchMatrixArray = GetBatchMatrixArray(batchIndex, propertyName, out elementCount); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(batchMatrixArray, elementCount, Allocator.Invalid); } public unsafe NativeArray GetBatchScalarArrayInt(int batchIndex, int propertyName) { int elementCount = 0; void* batchScalarArray_Internal = GetBatchScalarArray_Internal(batchIndex, propertyName, out elementCount); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(batchScalarArray_Internal, elementCount, Allocator.Invalid); } public unsafe NativeArray GetBatchScalarArray(int batchIndex, int propertyName) { int elementCount = 0; void* batchScalarArray_Internal = GetBatchScalarArray_Internal(batchIndex, propertyName, out elementCount); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(batchScalarArray_Internal, elementCount, Allocator.Invalid); } public unsafe NativeArray GetBatchVectorArrayInt(int batchIndex, int propertyName) { int elementCount = 0; void* batchVectorArray_Internal = GetBatchVectorArray_Internal(batchIndex, propertyName, out elementCount); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(batchVectorArray_Internal, elementCount, Allocator.Invalid); } public unsafe NativeArray GetBatchVectorArray(int batchIndex, int propertyName) { int elementCount = 0; void* batchVectorArray_Internal = GetBatchVectorArray_Internal(batchIndex, propertyName, out elementCount); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(batchVectorArray_Internal, elementCount, Allocator.Invalid); } public unsafe NativeArray GetBatchMatrixArray(int batchIndex, int propertyName) { int elementCount = 0; void* batchMatrixArray_Internal = GetBatchMatrixArray_Internal(batchIndex, propertyName, out elementCount); return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(batchMatrixArray_Internal, elementCount, Allocator.Invalid); } public void SetBatchBounds(int batchIndex, Bounds bounds) { SetBatchBounds_Injected(batchIndex, ref bounds); } [MethodImpl(MethodImplOptions.InternalCall)] public extern int GetNumBatches(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void RemoveBatch(int index); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe extern void* GetBatchMatrices(int batchIndex, out int matrixCount); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe extern void* GetBatchScalarArray(int batchIndex, string propertyName, out int elementCount); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe extern void* GetBatchVectorArray(int batchIndex, string propertyName, out int elementCount); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe extern void* GetBatchMatrixArray(int batchIndex, string propertyName, out int elementCount); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetBatchScalarArray")] private unsafe extern void* GetBatchScalarArray_Internal(int batchIndex, int propertyName, out int elementCount); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetBatchVectorArray")] private unsafe extern void* GetBatchVectorArray_Internal(int batchIndex, int propertyName, out int elementCount); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("GetBatchMatrixArray")] private unsafe extern void* GetBatchMatrixArray_Internal(int batchIndex, int propertyName, out int elementCount); [MethodImpl(MethodImplOptions.InternalCall)] public extern void EnableVisibleIndicesYArray(bool enabled); [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr Create(BatchRendererGroup group); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Destroy(IntPtr groupHandle); [RequiredByNativeCode] private unsafe static void InvokeOnPerformCulling(BatchRendererGroup group, ref BatchRendererCullingOutput context, ref LODParameters lodParameters) { NativeArray inCullingPlanes = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(context.cullingPlanes, context.cullingPlanesCount, Allocator.Invalid); NativeArray inOutBatchVisibility = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(context.batchVisibility, context.batchVisibilityCount, Allocator.Invalid); NativeArray outVisibleIndices = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(context.visibleIndices, context.visibleIndicesCount, Allocator.Invalid); NativeArray outVisibleIndicesY = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(context.visibleIndicesY, context.visibleIndicesCount, Allocator.Invalid); try { context.cullingJobsFence = group.m_PerformCulling(group, new BatchCullingContext(inCullingPlanes, inOutBatchVisibility, outVisibleIndices, outVisibleIndicesY, lodParameters, context.cullingMatrix, context.nearPlane)); } finally { JobHandle.ScheduleBatchedJobs(); } } [MethodImpl(MethodImplOptions.InternalCall)] private extern int AddBatch_Injected(Mesh mesh, int subMeshIndex, Material material, int layer, ShadowCastingMode castShadows, bool receiveShadows, bool invertCulling, ref Bounds bounds, int instanceCount, MaterialPropertyBlock customProps, GameObject associatedSceneObject, ulong sceneCullingMask = 9223372036854775808uL, uint renderingLayerMask = uint.MaxValue); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetBatchBounds_Injected(int batchIndex, ref Bounds bounds); } public struct AttachmentDescriptor : IEquatable { private RenderBufferLoadAction m_LoadAction; private RenderBufferStoreAction m_StoreAction; private GraphicsFormat m_Format; private RenderTargetIdentifier m_LoadStoreTarget; private RenderTargetIdentifier m_ResolveTarget; private Color m_ClearColor; private float m_ClearDepth; private uint m_ClearStencil; public RenderBufferLoadAction loadAction { get { return m_LoadAction; } set { m_LoadAction = value; } } public RenderBufferStoreAction storeAction { get { return m_StoreAction; } set { m_StoreAction = value; } } public GraphicsFormat graphicsFormat { get { return m_Format; } set { m_Format = value; } } public RenderTextureFormat format { get { if ((GraphicsFormatUtility.IsDepthFormat(m_Format) || GraphicsFormatUtility.IsStencilFormat(m_Format)) && m_Format != GraphicsFormat.ShadowAuto) { return RenderTextureFormat.Depth; } return GraphicsFormatUtility.GetRenderTextureFormat(m_Format); } set { m_Format = GraphicsFormatUtility.GetGraphicsFormat(value, RenderTextureReadWrite.Default); } } public RenderTargetIdentifier loadStoreTarget { get { return m_LoadStoreTarget; } set { m_LoadStoreTarget = value; } } public RenderTargetIdentifier resolveTarget { get { return m_ResolveTarget; } set { m_ResolveTarget = value; } } public Color clearColor { get { return m_ClearColor; } set { m_ClearColor = value; } } public float clearDepth { get { return m_ClearDepth; } set { m_ClearDepth = value; } } public uint clearStencil { get { return m_ClearStencil; } set { m_ClearStencil = value; } } public void ConfigureTarget(RenderTargetIdentifier target, bool loadExistingContents, bool storeResults) { m_LoadStoreTarget = target; if (loadExistingContents && m_LoadAction != RenderBufferLoadAction.Clear) { m_LoadAction = RenderBufferLoadAction.Load; } if (storeResults) { if (m_StoreAction == RenderBufferStoreAction.StoreAndResolve || m_StoreAction == RenderBufferStoreAction.Resolve) { m_StoreAction = RenderBufferStoreAction.StoreAndResolve; } else { m_StoreAction = RenderBufferStoreAction.Store; } } } public void ConfigureResolveTarget(RenderTargetIdentifier target) { m_ResolveTarget = target; if (m_StoreAction == RenderBufferStoreAction.StoreAndResolve || m_StoreAction == RenderBufferStoreAction.Store) { m_StoreAction = RenderBufferStoreAction.StoreAndResolve; } else { m_StoreAction = RenderBufferStoreAction.Resolve; } } public void ConfigureClear(Color clearColor, float clearDepth = 1f, uint clearStencil = 0u) { m_ClearColor = clearColor; m_ClearDepth = clearDepth; m_ClearStencil = clearStencil; m_LoadAction = RenderBufferLoadAction.Clear; } public AttachmentDescriptor(GraphicsFormat format) { this = default(AttachmentDescriptor); m_LoadAction = RenderBufferLoadAction.DontCare; m_StoreAction = RenderBufferStoreAction.DontCare; m_Format = format; m_LoadStoreTarget = new RenderTargetIdentifier(BuiltinRenderTextureType.None); m_ResolveTarget = new RenderTargetIdentifier(BuiltinRenderTextureType.None); m_ClearColor = new Color(0f, 0f, 0f, 0f); m_ClearDepth = 1f; } public AttachmentDescriptor(RenderTextureFormat format) : this(GraphicsFormatUtility.GetGraphicsFormat(format, RenderTextureReadWrite.Default)) { } public AttachmentDescriptor(RenderTextureFormat format, RenderTargetIdentifier target, bool loadExistingContents = false, bool storeResults = false, bool resolve = false) : this(GraphicsFormatUtility.GetGraphicsFormat(format, RenderTextureReadWrite.Default)) { } public bool Equals(AttachmentDescriptor other) { return m_LoadAction == other.m_LoadAction && m_StoreAction == other.m_StoreAction && m_Format == other.m_Format && m_LoadStoreTarget.Equals(other.m_LoadStoreTarget) && m_ResolveTarget.Equals(other.m_ResolveTarget) && m_ClearColor.Equals(other.m_ClearColor) && m_ClearDepth.Equals(other.m_ClearDepth) && m_ClearStencil == other.m_ClearStencil; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is AttachmentDescriptor && Equals((AttachmentDescriptor)obj); } public override int GetHashCode() { int num = (int)m_LoadAction; num = (num * 397) ^ (int)m_StoreAction; num = (num * 397) ^ (int)m_Format; num = (num * 397) ^ m_LoadStoreTarget.GetHashCode(); num = (num * 397) ^ m_ResolveTarget.GetHashCode(); num = (num * 397) ^ m_ClearColor.GetHashCode(); num = (num * 397) ^ m_ClearDepth.GetHashCode(); return (num * 397) ^ (int)m_ClearStencil; } public static bool operator ==(AttachmentDescriptor left, AttachmentDescriptor right) { return left.Equals(right); } public static bool operator !=(AttachmentDescriptor left, AttachmentDescriptor right) { return !left.Equals(right); } } public struct BlendState : IEquatable { private RenderTargetBlendState m_BlendState0; private RenderTargetBlendState m_BlendState1; private RenderTargetBlendState m_BlendState2; private RenderTargetBlendState m_BlendState3; private RenderTargetBlendState m_BlendState4; private RenderTargetBlendState m_BlendState5; private RenderTargetBlendState m_BlendState6; private RenderTargetBlendState m_BlendState7; private byte m_SeparateMRTBlendStates; private byte m_AlphaToMask; private short m_Padding; public static BlendState defaultValue => new BlendState(separateMRTBlend: false, alphaToMask: false); public bool separateMRTBlendStates { get { return Convert.ToBoolean(m_SeparateMRTBlendStates); } set { m_SeparateMRTBlendStates = Convert.ToByte(value); } } public bool alphaToMask { get { return Convert.ToBoolean(m_AlphaToMask); } set { m_AlphaToMask = Convert.ToByte(value); } } public RenderTargetBlendState blendState0 { get { return m_BlendState0; } set { m_BlendState0 = value; } } public RenderTargetBlendState blendState1 { get { return m_BlendState1; } set { m_BlendState1 = value; } } public RenderTargetBlendState blendState2 { get { return m_BlendState2; } set { m_BlendState2 = value; } } public RenderTargetBlendState blendState3 { get { return m_BlendState3; } set { m_BlendState3 = value; } } public RenderTargetBlendState blendState4 { get { return m_BlendState4; } set { m_BlendState4 = value; } } public RenderTargetBlendState blendState5 { get { return m_BlendState5; } set { m_BlendState5 = value; } } public RenderTargetBlendState blendState6 { get { return m_BlendState6; } set { m_BlendState6 = value; } } public RenderTargetBlendState blendState7 { get { return m_BlendState7; } set { m_BlendState7 = value; } } public BlendState(bool separateMRTBlend = false, bool alphaToMask = false) { m_BlendState0 = RenderTargetBlendState.defaultValue; m_BlendState1 = RenderTargetBlendState.defaultValue; m_BlendState2 = RenderTargetBlendState.defaultValue; m_BlendState3 = RenderTargetBlendState.defaultValue; m_BlendState4 = RenderTargetBlendState.defaultValue; m_BlendState5 = RenderTargetBlendState.defaultValue; m_BlendState6 = RenderTargetBlendState.defaultValue; m_BlendState7 = RenderTargetBlendState.defaultValue; m_SeparateMRTBlendStates = Convert.ToByte(separateMRTBlend); m_AlphaToMask = Convert.ToByte(alphaToMask); m_Padding = 0; } public bool Equals(BlendState other) { return m_BlendState0.Equals(other.m_BlendState0) && m_BlendState1.Equals(other.m_BlendState1) && m_BlendState2.Equals(other.m_BlendState2) && m_BlendState3.Equals(other.m_BlendState3) && m_BlendState4.Equals(other.m_BlendState4) && m_BlendState5.Equals(other.m_BlendState5) && m_BlendState6.Equals(other.m_BlendState6) && m_BlendState7.Equals(other.m_BlendState7) && m_SeparateMRTBlendStates == other.m_SeparateMRTBlendStates && m_AlphaToMask == other.m_AlphaToMask; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is BlendState && Equals((BlendState)obj); } public override int GetHashCode() { int hashCode = m_BlendState0.GetHashCode(); hashCode = (hashCode * 397) ^ m_BlendState1.GetHashCode(); hashCode = (hashCode * 397) ^ m_BlendState2.GetHashCode(); hashCode = (hashCode * 397) ^ m_BlendState3.GetHashCode(); hashCode = (hashCode * 397) ^ m_BlendState4.GetHashCode(); hashCode = (hashCode * 397) ^ m_BlendState5.GetHashCode(); hashCode = (hashCode * 397) ^ m_BlendState6.GetHashCode(); hashCode = (hashCode * 397) ^ m_BlendState7.GetHashCode(); hashCode = (hashCode * 397) ^ m_SeparateMRTBlendStates.GetHashCode(); return (hashCode * 397) ^ m_AlphaToMask.GetHashCode(); } public static bool operator ==(BlendState left, BlendState right) { return left.Equals(right); } public static bool operator !=(BlendState left, BlendState right) { return !left.Equals(right); } } [UsedByNativeCode] internal struct CoreCameraValues : IEquatable { private int filterMode; private uint cullingMask; private int instanceID; public bool Equals(CoreCameraValues other) { return filterMode == other.filterMode && cullingMask == other.cullingMask && instanceID == other.instanceID; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is CoreCameraValues && Equals((CoreCameraValues)obj); } public override int GetHashCode() { int num = filterMode; num = (num * 397) ^ (int)cullingMask; return (num * 397) ^ instanceID; } public static bool operator ==(CoreCameraValues left, CoreCameraValues right) { return left.Equals(right); } public static bool operator !=(CoreCameraValues left, CoreCameraValues right) { return !left.Equals(right); } } [UsedByNativeCode] public struct CameraProperties : IEquatable { private const int k_NumLayers = 32; private Rect screenRect; private Vector3 viewDir; private float projectionNear; private float projectionFar; private float cameraNear; private float cameraFar; private float cameraAspect; private Matrix4x4 cameraToWorld; private Matrix4x4 actualWorldToClip; private Matrix4x4 cameraClipToWorld; private Matrix4x4 cameraWorldToClip; private Matrix4x4 implicitProjection; private Matrix4x4 stereoWorldToClipLeft; private Matrix4x4 stereoWorldToClipRight; private Matrix4x4 worldToCamera; private Vector3 up; private Vector3 right; private Vector3 transformDirection; private Vector3 cameraEuler; private Vector3 velocity; private float farPlaneWorldSpaceLength; private uint rendererCount; private const int k_PlaneCount = 6; internal unsafe fixed byte m_ShadowCullPlanes[96]; internal unsafe fixed byte m_CameraCullPlanes[96]; private float baseFarDistance; private Vector3 shadowCullCenter; internal unsafe fixed float layerCullDistances[32]; private int layerCullSpherical; private CoreCameraValues coreCameraValues; private uint cameraType; private int projectionIsOblique; private int isImplicitProjectionMatrix; public unsafe Plane GetShadowCullingPlane(int index) { if (index < 0 || index >= 6) { throw new ArgumentOutOfRangeException(string.Format("{0} was {1}, but must be at least 0 and less than {2}", "index", index, 6)); } fixed (byte* shadowCullPlanes = m_ShadowCullPlanes) { Plane* ptr = (Plane*)shadowCullPlanes; return ptr[index]; } } public unsafe void SetShadowCullingPlane(int index, Plane plane) { if (index < 0 || index >= 6) { throw new ArgumentOutOfRangeException(string.Format("{0} was {1}, but must be at least 0 and less than {2}", "index", index, 6)); } fixed (byte* shadowCullPlanes = m_ShadowCullPlanes) { Plane* ptr = (Plane*)shadowCullPlanes; ptr[index] = plane; } } public unsafe Plane GetCameraCullingPlane(int index) { if (index < 0 || index >= 6) { throw new ArgumentOutOfRangeException(string.Format("{0} was {1}, but must be at least 0 and less than {2}", "index", index, 6)); } fixed (byte* cameraCullPlanes = m_CameraCullPlanes) { Plane* ptr = (Plane*)cameraCullPlanes; return ptr[index]; } } public unsafe void SetCameraCullingPlane(int index, Plane plane) { if (index < 0 || index >= 6) { throw new ArgumentOutOfRangeException(string.Format("{0} was {1}, but must be at least 0 and less than {2}", "index", index, 6)); } fixed (byte* cameraCullPlanes = m_CameraCullPlanes) { Plane* ptr = (Plane*)cameraCullPlanes; ptr[index] = plane; } } public unsafe bool Equals(CameraProperties other) { for (int i = 0; i < 6; i++) { if (!GetShadowCullingPlane(i).Equals(other.GetShadowCullingPlane(i))) { return false; } } for (int j = 0; j < 6; j++) { if (!GetCameraCullingPlane(j).Equals(other.GetCameraCullingPlane(j))) { return false; } } fixed (float* ptr = layerCullDistances) { for (int k = 0; k < 32; k++) { if (ptr[k] != other.layerCullDistances[k]) { return false; } } } return screenRect.Equals(other.screenRect) && viewDir.Equals(other.viewDir) && projectionNear.Equals(other.projectionNear) && projectionFar.Equals(other.projectionFar) && cameraNear.Equals(other.cameraNear) && cameraFar.Equals(other.cameraFar) && cameraAspect.Equals(other.cameraAspect) && cameraToWorld.Equals(other.cameraToWorld) && actualWorldToClip.Equals(other.actualWorldToClip) && cameraClipToWorld.Equals(other.cameraClipToWorld) && cameraWorldToClip.Equals(other.cameraWorldToClip) && implicitProjection.Equals(other.implicitProjection) && stereoWorldToClipLeft.Equals(other.stereoWorldToClipLeft) && stereoWorldToClipRight.Equals(other.stereoWorldToClipRight) && worldToCamera.Equals(other.worldToCamera) && up.Equals(other.up) && right.Equals(other.right) && transformDirection.Equals(other.transformDirection) && cameraEuler.Equals(other.cameraEuler) && velocity.Equals(other.velocity) && farPlaneWorldSpaceLength.Equals(other.farPlaneWorldSpaceLength) && rendererCount == other.rendererCount && baseFarDistance.Equals(other.baseFarDistance) && shadowCullCenter.Equals(other.shadowCullCenter) && layerCullSpherical == other.layerCullSpherical && coreCameraValues.Equals(other.coreCameraValues) && cameraType == other.cameraType && projectionIsOblique == other.projectionIsOblique && isImplicitProjectionMatrix == other.isImplicitProjectionMatrix; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is CameraProperties && Equals((CameraProperties)obj); } public unsafe override int GetHashCode() { int hashCode = screenRect.GetHashCode(); hashCode = (hashCode * 397) ^ viewDir.GetHashCode(); hashCode = (hashCode * 397) ^ projectionNear.GetHashCode(); hashCode = (hashCode * 397) ^ projectionFar.GetHashCode(); hashCode = (hashCode * 397) ^ cameraNear.GetHashCode(); hashCode = (hashCode * 397) ^ cameraFar.GetHashCode(); hashCode = (hashCode * 397) ^ cameraAspect.GetHashCode(); hashCode = (hashCode * 397) ^ cameraToWorld.GetHashCode(); hashCode = (hashCode * 397) ^ actualWorldToClip.GetHashCode(); hashCode = (hashCode * 397) ^ cameraClipToWorld.GetHashCode(); hashCode = (hashCode * 397) ^ cameraWorldToClip.GetHashCode(); hashCode = (hashCode * 397) ^ implicitProjection.GetHashCode(); hashCode = (hashCode * 397) ^ stereoWorldToClipLeft.GetHashCode(); hashCode = (hashCode * 397) ^ stereoWorldToClipRight.GetHashCode(); hashCode = (hashCode * 397) ^ worldToCamera.GetHashCode(); hashCode = (hashCode * 397) ^ up.GetHashCode(); hashCode = (hashCode * 397) ^ right.GetHashCode(); hashCode = (hashCode * 397) ^ transformDirection.GetHashCode(); hashCode = (hashCode * 397) ^ cameraEuler.GetHashCode(); hashCode = (hashCode * 397) ^ velocity.GetHashCode(); hashCode = (hashCode * 397) ^ farPlaneWorldSpaceLength.GetHashCode(); hashCode = (hashCode * 397) ^ (int)rendererCount; for (int i = 0; i < 6; i++) { hashCode = (hashCode * 397) ^ GetShadowCullingPlane(i).GetHashCode(); } for (int j = 0; j < 6; j++) { hashCode = (hashCode * 397) ^ GetCameraCullingPlane(j).GetHashCode(); } hashCode = (hashCode * 397) ^ baseFarDistance.GetHashCode(); hashCode = (hashCode * 397) ^ shadowCullCenter.GetHashCode(); fixed (float* ptr = layerCullDistances) { for (int k = 0; k < 32; k++) { hashCode = (hashCode * 397) ^ ptr[k].GetHashCode(); } } hashCode = (hashCode * 397) ^ layerCullSpherical; hashCode = (hashCode * 397) ^ coreCameraValues.GetHashCode(); hashCode = (hashCode * 397) ^ (int)cameraType; hashCode = (hashCode * 397) ^ projectionIsOblique; return (hashCode * 397) ^ isImplicitProjectionMatrix; } public static bool operator ==(CameraProperties left, CameraProperties right) { return left.Equals(right); } public static bool operator !=(CameraProperties left, CameraProperties right) { return !left.Equals(right); } } [Flags] public enum CullingOptions { None = 0, ForceEvenIfCameraIsNotActive = 1, OcclusionCull = 2, NeedsLighting = 4, NeedsReflectionProbes = 8, Stereo = 0x10, DisablePerObjectCulling = 0x20, ShadowCasters = 0x40 } [UsedByNativeCode] public struct ScriptableCullingParameters : IEquatable { private int m_IsOrthographic; private LODParameters m_LODParameters; private const int k_MaximumCullingPlaneCount = 10; public static readonly int maximumCullingPlaneCount = 10; internal unsafe fixed byte m_CullingPlanes[160]; private int m_CullingPlaneCount; private uint m_CullingMask; private ulong m_SceneMask; private const int k_LayerCount = 32; public static readonly int layerCount = 32; internal unsafe fixed float m_LayerFarCullDistances[32]; private int m_LayerCull; private Matrix4x4 m_CullingMatrix; private Vector3 m_Origin; private float m_ShadowDistance; private float m_ShadowNearPlaneOffset; private CullingOptions m_CullingOptions; private ReflectionProbeSortingCriteria m_ReflectionProbeSortingCriteria; private CameraProperties m_CameraProperties; private float m_AccurateOcclusionThreshold; private int m_MaximumPortalCullingJobs; private const int k_CullingJobCountLowerLimit = 1; private const int k_CullingJobCountUpperLimit = 16; private Matrix4x4 m_StereoViewMatrix; private Matrix4x4 m_StereoProjectionMatrix; private float m_StereoSeparationDistance; private int m_maximumVisibleLights; private bool m_ConservativeEnclosingSphere; private int m_NumIterationsEnclosingSphere; public int maximumVisibleLights { get { return m_maximumVisibleLights; } set { m_maximumVisibleLights = value; } } public bool conservativeEnclosingSphere { get { return m_ConservativeEnclosingSphere; } set { m_ConservativeEnclosingSphere = value; } } public int numIterationsEnclosingSphere { get { return m_NumIterationsEnclosingSphere; } set { m_NumIterationsEnclosingSphere = value; } } public int cullingPlaneCount { get { return m_CullingPlaneCount; } set { if (value < 0 || value > 10) { throw new ArgumentOutOfRangeException(string.Format("{0} was {1}, but must be at least 0 and less than {2}", "value", value, 10)); } m_CullingPlaneCount = value; } } public bool isOrthographic { get { return Convert.ToBoolean(m_IsOrthographic); } set { m_IsOrthographic = Convert.ToInt32(value); } } public LODParameters lodParameters { get { return m_LODParameters; } set { m_LODParameters = value; } } public uint cullingMask { get { return m_CullingMask; } set { m_CullingMask = value; } } public Matrix4x4 cullingMatrix { get { return m_CullingMatrix; } set { m_CullingMatrix = value; } } public Vector3 origin { get { return m_Origin; } set { m_Origin = value; } } public float shadowDistance { get { return m_ShadowDistance; } set { m_ShadowDistance = value; } } public float shadowNearPlaneOffset { get { return m_ShadowNearPlaneOffset; } set { m_ShadowNearPlaneOffset = value; } } public CullingOptions cullingOptions { get { return m_CullingOptions; } set { m_CullingOptions = value; } } public ReflectionProbeSortingCriteria reflectionProbeSortingCriteria { get { return m_ReflectionProbeSortingCriteria; } set { m_ReflectionProbeSortingCriteria = value; } } public CameraProperties cameraProperties { get { return m_CameraProperties; } set { m_CameraProperties = value; } } public Matrix4x4 stereoViewMatrix { get { return m_StereoViewMatrix; } set { m_StereoViewMatrix = value; } } public Matrix4x4 stereoProjectionMatrix { get { return m_StereoProjectionMatrix; } set { m_StereoProjectionMatrix = value; } } public float stereoSeparationDistance { get { return m_StereoSeparationDistance; } set { m_StereoSeparationDistance = value; } } public float accurateOcclusionThreshold { get { return m_AccurateOcclusionThreshold; } set { m_AccurateOcclusionThreshold = Mathf.Max(-1f, value); } } public int maximumPortalCullingJobs { get { return m_MaximumPortalCullingJobs; } set { if (value < 1 || value > 16) { throw new ArgumentOutOfRangeException(string.Format("{0} was {1}, but must be in range {2} to {3}", "maximumPortalCullingJobs", maximumPortalCullingJobs, 1, 16)); } m_MaximumPortalCullingJobs = value; } } public static int cullingJobsLowerLimit => 1; public static int cullingJobsUpperLimit => 16; public unsafe float GetLayerCullingDistance(int layerIndex) { if (layerIndex < 0 || layerIndex >= 32) { throw new ArgumentOutOfRangeException(string.Format("{0} was {1}, but must be at least 0 and less than {2}", "layerIndex", layerIndex, 32)); } fixed (float* layerFarCullDistances = m_LayerFarCullDistances) { return layerFarCullDistances[layerIndex]; } } public unsafe void SetLayerCullingDistance(int layerIndex, float distance) { if (layerIndex < 0 || layerIndex >= 32) { throw new ArgumentOutOfRangeException(string.Format("{0} was {1}, but must be at least 0 and less than {2}", "layerIndex", layerIndex, 32)); } fixed (float* layerFarCullDistances = m_LayerFarCullDistances) { layerFarCullDistances[layerIndex] = distance; } } public unsafe Plane GetCullingPlane(int index) { if (index < 0 || index >= cullingPlaneCount) { throw new ArgumentOutOfRangeException(string.Format("{0} was {1}, but must be at least 0 and less than {2}", "index", index, cullingPlaneCount)); } fixed (byte* cullingPlanes = m_CullingPlanes) { Plane* ptr = (Plane*)cullingPlanes; return ptr[index]; } } public unsafe void SetCullingPlane(int index, Plane plane) { if (index < 0 || index >= cullingPlaneCount) { throw new ArgumentOutOfRangeException(string.Format("{0} was {1}, but must be at least 0 and less than {2}", "index", index, cullingPlaneCount)); } fixed (byte* cullingPlanes = m_CullingPlanes) { Plane* ptr = (Plane*)cullingPlanes; ptr[index] = plane; } } public bool Equals(ScriptableCullingParameters other) { for (int i = 0; i < 32; i++) { if (!GetLayerCullingDistance(i).Equals(other.GetLayerCullingDistance(i))) { return false; } } for (int j = 0; j < cullingPlaneCount; j++) { if (!GetCullingPlane(j).Equals(other.GetCullingPlane(j))) { return false; } } return m_IsOrthographic == other.m_IsOrthographic && m_LODParameters.Equals(other.m_LODParameters) && m_CullingPlaneCount == other.m_CullingPlaneCount && m_CullingMask == other.m_CullingMask && m_SceneMask == other.m_SceneMask && m_LayerCull == other.m_LayerCull && m_CullingMatrix.Equals(other.m_CullingMatrix) && m_Origin.Equals(other.m_Origin) && m_ShadowDistance.Equals(other.m_ShadowDistance) && m_ShadowNearPlaneOffset.Equals(other.m_ShadowNearPlaneOffset) && m_CullingOptions == other.m_CullingOptions && m_ReflectionProbeSortingCriteria == other.m_ReflectionProbeSortingCriteria && m_CameraProperties.Equals(other.m_CameraProperties) && m_AccurateOcclusionThreshold.Equals(other.m_AccurateOcclusionThreshold) && m_StereoViewMatrix.Equals(other.m_StereoViewMatrix) && m_StereoProjectionMatrix.Equals(other.m_StereoProjectionMatrix) && m_StereoSeparationDistance.Equals(other.m_StereoSeparationDistance) && m_maximumVisibleLights == other.m_maximumVisibleLights && m_ConservativeEnclosingSphere == other.m_ConservativeEnclosingSphere && m_NumIterationsEnclosingSphere == other.m_NumIterationsEnclosingSphere; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is ScriptableCullingParameters && Equals((ScriptableCullingParameters)obj); } public override int GetHashCode() { int num = m_IsOrthographic; num = (num * 397) ^ m_LODParameters.GetHashCode(); num = (num * 397) ^ m_CullingPlaneCount; num = (num * 397) ^ (int)m_CullingMask; num = (num * 397) ^ m_SceneMask.GetHashCode(); num = (num * 397) ^ m_LayerCull; num = (num * 397) ^ m_CullingMatrix.GetHashCode(); num = (num * 397) ^ m_Origin.GetHashCode(); num = (num * 397) ^ m_ShadowDistance.GetHashCode(); num = (num * 397) ^ m_ShadowNearPlaneOffset.GetHashCode(); num = (num * 397) ^ (int)m_CullingOptions; num = (num * 397) ^ (int)m_ReflectionProbeSortingCriteria; num = (num * 397) ^ m_CameraProperties.GetHashCode(); num = (num * 397) ^ m_AccurateOcclusionThreshold.GetHashCode(); num = (num * 397) ^ m_MaximumPortalCullingJobs.GetHashCode(); num = (num * 397) ^ m_StereoViewMatrix.GetHashCode(); num = (num * 397) ^ m_StereoProjectionMatrix.GetHashCode(); num = (num * 397) ^ m_StereoSeparationDistance.GetHashCode(); num = (num * 397) ^ m_maximumVisibleLights; num = (num * 397) ^ m_ConservativeEnclosingSphere.GetHashCode(); return (num * 397) ^ m_NumIterationsEnclosingSphere.GetHashCode(); } public static bool operator ==(ScriptableCullingParameters left, ScriptableCullingParameters right) { return left.Equals(right); } public static bool operator !=(ScriptableCullingParameters left, ScriptableCullingParameters right) { return !left.Equals(right); } } [NativeHeader("Runtime/Scripting/ScriptingCommonStructDefinitions.h")] [NativeHeader("Runtime/Graphics/ScriptableRenderLoop/ScriptableCulling.h")] [NativeHeader("Runtime/Export/RenderPipeline/ScriptableRenderPipeline.bindings.h")] public struct CullingResults : IEquatable { internal IntPtr ptr; private unsafe CullingAllocationInfo* m_AllocationInfo; public unsafe NativeArray visibleLights => GetNativeArray(m_AllocationInfo->visibleLightsPtr, m_AllocationInfo->visibleLightCount); public unsafe NativeArray visibleOffscreenVertexLights => GetNativeArray(m_AllocationInfo->visibleOffscreenVertexLightsPtr, m_AllocationInfo->visibleOffscreenVertexLightCount); public unsafe NativeArray visibleReflectionProbes => GetNativeArray(m_AllocationInfo->visibleReflectionProbesPtr, m_AllocationInfo->visibleReflectionProbeCount); public int lightIndexCount => GetLightIndexCount(ptr); public int reflectionProbeIndexCount => GetReflectionProbeIndexCount(ptr); public int lightAndReflectionProbeIndexCount => GetLightIndexCount(ptr) + GetReflectionProbeIndexCount(ptr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptableRenderPipeline_Bindings::GetLightIndexCount")] private static extern int GetLightIndexCount(IntPtr cullingResultsPtr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptableRenderPipeline_Bindings::GetReflectionProbeIndexCount")] private static extern int GetReflectionProbeIndexCount(IntPtr cullingResultsPtr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("FillLightAndReflectionProbeIndices")] private static extern void FillLightAndReflectionProbeIndices(IntPtr cullingResultsPtr, ComputeBuffer computeBuffer); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("FillLightAndReflectionProbeIndices")] private static extern void FillLightAndReflectionProbeIndicesGraphicsBuffer(IntPtr cullingResultsPtr, GraphicsBuffer buffer); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetLightIndexMapSize")] private static extern int GetLightIndexMapSize(IntPtr cullingResultsPtr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetReflectionProbeIndexMapSize")] private static extern int GetReflectionProbeIndexMapSize(IntPtr cullingResultsPtr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("FillLightIndexMapScriptable")] private static extern void FillLightIndexMap(IntPtr cullingResultsPtr, IntPtr indexMapPtr, int indexMapSize); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("FillReflectionProbeIndexMapScriptable")] private static extern void FillReflectionProbeIndexMap(IntPtr cullingResultsPtr, IntPtr indexMapPtr, int indexMapSize); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SetLightIndexMapScriptable")] private static extern void SetLightIndexMap(IntPtr cullingResultsPtr, IntPtr indexMapPtr, int indexMapSize); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("SetReflectionProbeIndexMapScriptable")] private static extern void SetReflectionProbeIndexMap(IntPtr cullingResultsPtr, IntPtr indexMapPtr, int indexMapSize); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptableRenderPipeline_Bindings::GetShadowCasterBounds")] private static extern bool GetShadowCasterBounds(IntPtr cullingResultsPtr, int lightIndex, out Bounds bounds); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptableRenderPipeline_Bindings::ComputeSpotShadowMatricesAndCullingPrimitives")] private static extern bool ComputeSpotShadowMatricesAndCullingPrimitives(IntPtr cullingResultsPtr, int activeLightIndex, out Matrix4x4 viewMatrix, out Matrix4x4 projMatrix, out ShadowSplitData shadowSplitData); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptableRenderPipeline_Bindings::ComputePointShadowMatricesAndCullingPrimitives")] private static extern bool ComputePointShadowMatricesAndCullingPrimitives(IntPtr cullingResultsPtr, int activeLightIndex, CubemapFace cubemapFace, float fovBias, out Matrix4x4 viewMatrix, out Matrix4x4 projMatrix, out ShadowSplitData shadowSplitData); [FreeFunction("ScriptableRenderPipeline_Bindings::ComputeDirectionalShadowMatricesAndCullingPrimitives")] private static bool ComputeDirectionalShadowMatricesAndCullingPrimitives(IntPtr cullingResultsPtr, int activeLightIndex, int splitIndex, int splitCount, Vector3 splitRatio, int shadowResolution, float shadowNearPlaneOffset, out Matrix4x4 viewMatrix, out Matrix4x4 projMatrix, out ShadowSplitData shadowSplitData) { return ComputeDirectionalShadowMatricesAndCullingPrimitives_Injected(cullingResultsPtr, activeLightIndex, splitIndex, splitCount, ref splitRatio, shadowResolution, shadowNearPlaneOffset, out viewMatrix, out projMatrix, out shadowSplitData); } private unsafe NativeArray GetNativeArray(void* dataPointer, int length) where T : struct { return NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray(dataPointer, length, Allocator.Invalid); } public void FillLightAndReflectionProbeIndices(ComputeBuffer computeBuffer) { FillLightAndReflectionProbeIndices(ptr, computeBuffer); } public void FillLightAndReflectionProbeIndices(GraphicsBuffer buffer) { FillLightAndReflectionProbeIndicesGraphicsBuffer(ptr, buffer); } public unsafe NativeArray GetLightIndexMap(Allocator allocator) { int lightIndexMapSize = GetLightIndexMapSize(ptr); NativeArray nativeArray = new NativeArray(lightIndexMapSize, allocator, NativeArrayOptions.UninitializedMemory); FillLightIndexMap(ptr, (IntPtr)nativeArray.GetUnsafePtr(), lightIndexMapSize); return nativeArray; } public unsafe void SetLightIndexMap(NativeArray lightIndexMap) { SetLightIndexMap(ptr, (IntPtr)lightIndexMap.GetUnsafeReadOnlyPtr(), lightIndexMap.Length); } public unsafe NativeArray GetReflectionProbeIndexMap(Allocator allocator) { int reflectionProbeIndexMapSize = GetReflectionProbeIndexMapSize(ptr); NativeArray nativeArray = new NativeArray(reflectionProbeIndexMapSize, allocator, NativeArrayOptions.UninitializedMemory); FillReflectionProbeIndexMap(ptr, (IntPtr)nativeArray.GetUnsafePtr(), reflectionProbeIndexMapSize); return nativeArray; } public unsafe void SetReflectionProbeIndexMap(NativeArray lightIndexMap) { SetReflectionProbeIndexMap(ptr, (IntPtr)lightIndexMap.GetUnsafeReadOnlyPtr(), lightIndexMap.Length); } public bool GetShadowCasterBounds(int lightIndex, out Bounds outBounds) { return GetShadowCasterBounds(ptr, lightIndex, out outBounds); } public bool ComputeSpotShadowMatricesAndCullingPrimitives(int activeLightIndex, out Matrix4x4 viewMatrix, out Matrix4x4 projMatrix, out ShadowSplitData shadowSplitData) { return ComputeSpotShadowMatricesAndCullingPrimitives(ptr, activeLightIndex, out viewMatrix, out projMatrix, out shadowSplitData); } public bool ComputePointShadowMatricesAndCullingPrimitives(int activeLightIndex, CubemapFace cubemapFace, float fovBias, out Matrix4x4 viewMatrix, out Matrix4x4 projMatrix, out ShadowSplitData shadowSplitData) { return ComputePointShadowMatricesAndCullingPrimitives(ptr, activeLightIndex, cubemapFace, fovBias, out viewMatrix, out projMatrix, out shadowSplitData); } public bool ComputeDirectionalShadowMatricesAndCullingPrimitives(int activeLightIndex, int splitIndex, int splitCount, Vector3 splitRatio, int shadowResolution, float shadowNearPlaneOffset, out Matrix4x4 viewMatrix, out Matrix4x4 projMatrix, out ShadowSplitData shadowSplitData) { return ComputeDirectionalShadowMatricesAndCullingPrimitives(ptr, activeLightIndex, splitIndex, splitCount, splitRatio, shadowResolution, shadowNearPlaneOffset, out viewMatrix, out projMatrix, out shadowSplitData); } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] internal void Validate() { } public unsafe bool Equals(CullingResults other) { return ptr.Equals((object?)(nint)other.ptr) && m_AllocationInfo == other.m_AllocationInfo; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is CullingResults && Equals((CullingResults)obj); } public unsafe override int GetHashCode() { int hashCode = ptr.GetHashCode(); return (hashCode * 397) ^ (int)m_AllocationInfo; } public static bool operator ==(CullingResults left, CullingResults right) { return left.Equals(right); } public static bool operator !=(CullingResults left, CullingResults right) { return !left.Equals(right); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool ComputeDirectionalShadowMatricesAndCullingPrimitives_Injected(IntPtr cullingResultsPtr, int activeLightIndex, int splitIndex, int splitCount, ref Vector3 splitRatio, int shadowResolution, float shadowNearPlaneOffset, out Matrix4x4 viewMatrix, out Matrix4x4 projMatrix, out ShadowSplitData shadowSplitData); } internal struct CullingAllocationInfo { public unsafe VisibleLight* visibleLightsPtr; public unsafe VisibleLight* visibleOffscreenVertexLightsPtr; public unsafe VisibleReflectionProbe* visibleReflectionProbesPtr; public int visibleLightCount; public int visibleOffscreenVertexLightCount; public int visibleReflectionProbeCount; } public struct DepthState : IEquatable { private byte m_WriteEnabled; private sbyte m_CompareFunction; public static DepthState defaultValue => new DepthState(writeEnabled: true, CompareFunction.Less); public bool writeEnabled { get { return Convert.ToBoolean(m_WriteEnabled); } set { m_WriteEnabled = Convert.ToByte(value); } } public CompareFunction compareFunction { get { return (CompareFunction)m_CompareFunction; } set { m_CompareFunction = (sbyte)value; } } public DepthState(bool writeEnabled = true, CompareFunction compareFunction = CompareFunction.Less) { m_WriteEnabled = Convert.ToByte(writeEnabled); m_CompareFunction = (sbyte)compareFunction; } public bool Equals(DepthState other) { return m_WriteEnabled == other.m_WriteEnabled && m_CompareFunction == other.m_CompareFunction; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is DepthState && Equals((DepthState)obj); } public override int GetHashCode() { return (m_WriteEnabled.GetHashCode() * 397) ^ m_CompareFunction.GetHashCode(); } public static bool operator ==(DepthState left, DepthState right) { return left.Equals(right); } public static bool operator !=(DepthState left, DepthState right) { return !left.Equals(right); } } public struct DrawingSettings : IEquatable { private const int kMaxShaderPasses = 16; public static readonly int maxShaderPasses = 16; private SortingSettings m_SortingSettings; internal unsafe fixed int shaderPassNames[16]; private PerObjectData m_PerObjectData; private DrawRendererFlags m_Flags; private int m_OverrideMaterialInstanceId; private int m_OverrideMaterialPassIndex; private int m_fallbackMaterialInstanceId; private int m_MainLightIndex; private int m_UseSrpBatcher; public SortingSettings sortingSettings { get { return m_SortingSettings; } set { m_SortingSettings = value; } } public PerObjectData perObjectData { get { return m_PerObjectData; } set { m_PerObjectData = value; } } public bool enableDynamicBatching { get { return (m_Flags & DrawRendererFlags.EnableDynamicBatching) != 0; } set { if (value) { m_Flags |= DrawRendererFlags.EnableDynamicBatching; } else { m_Flags &= ~DrawRendererFlags.EnableDynamicBatching; } } } public bool enableInstancing { get { return (m_Flags & DrawRendererFlags.EnableInstancing) != 0; } set { if (value) { m_Flags |= DrawRendererFlags.EnableInstancing; } else { m_Flags &= ~DrawRendererFlags.EnableInstancing; } } } public Material overrideMaterial { get { return (m_OverrideMaterialInstanceId != 0) ? (Object.FindObjectFromInstanceID(m_OverrideMaterialInstanceId) as Material) : null; } set { m_OverrideMaterialInstanceId = value?.GetInstanceID() ?? 0; } } public int overrideMaterialPassIndex { get { return m_OverrideMaterialPassIndex; } set { m_OverrideMaterialPassIndex = value; } } public Material fallbackMaterial { get { return (m_fallbackMaterialInstanceId != 0) ? (Object.FindObjectFromInstanceID(m_fallbackMaterialInstanceId) as Material) : null; } set { m_fallbackMaterialInstanceId = value?.GetInstanceID() ?? 0; } } public int mainLightIndex { get { return m_MainLightIndex; } set { m_MainLightIndex = value; } } public unsafe DrawingSettings(ShaderTagId shaderPassName, SortingSettings sortingSettings) { m_SortingSettings = sortingSettings; m_PerObjectData = PerObjectData.None; m_Flags = DrawRendererFlags.EnableInstancing; m_OverrideMaterialInstanceId = 0; m_OverrideMaterialPassIndex = 0; m_fallbackMaterialInstanceId = 0; m_MainLightIndex = -1; fixed (int* ptr = shaderPassNames) { *ptr = shaderPassName.id; for (int i = 1; i < maxShaderPasses; i++) { ptr[i] = -1; } } m_PerObjectData = PerObjectData.None; m_Flags = DrawRendererFlags.EnableInstancing; m_UseSrpBatcher = 0; } public unsafe ShaderTagId GetShaderPassName(int index) { if (index >= maxShaderPasses || index < 0) { throw new ArgumentOutOfRangeException("index", $"Index should range from 0 to DrawSettings.maxShaderPasses ({maxShaderPasses}), was {index}"); } fixed (int* ptr = shaderPassNames) { return new ShaderTagId { id = ptr[index] }; } } public unsafe void SetShaderPassName(int index, ShaderTagId shaderPassName) { if (index >= maxShaderPasses || index < 0) { throw new ArgumentOutOfRangeException("index", $"Index should range from 0 to DrawSettings.maxShaderPasses ({maxShaderPasses}), was {index}"); } fixed (int* ptr = shaderPassNames) { ptr[index] = shaderPassName.id; } } public bool Equals(DrawingSettings other) { for (int i = 0; i < maxShaderPasses; i++) { if (!GetShaderPassName(i).Equals(other.GetShaderPassName(i))) { return false; } } return m_SortingSettings.Equals(other.m_SortingSettings) && m_PerObjectData == other.m_PerObjectData && m_Flags == other.m_Flags && m_OverrideMaterialInstanceId == other.m_OverrideMaterialInstanceId && m_OverrideMaterialPassIndex == other.m_OverrideMaterialPassIndex && m_fallbackMaterialInstanceId == other.m_fallbackMaterialInstanceId && m_UseSrpBatcher == other.m_UseSrpBatcher; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is DrawingSettings && Equals((DrawingSettings)obj); } public override int GetHashCode() { int hashCode = m_SortingSettings.GetHashCode(); hashCode = (hashCode * 397) ^ (int)m_PerObjectData; hashCode = (hashCode * 397) ^ (int)m_Flags; hashCode = (hashCode * 397) ^ m_OverrideMaterialInstanceId; hashCode = (hashCode * 397) ^ m_OverrideMaterialPassIndex; hashCode = (hashCode * 397) ^ m_fallbackMaterialInstanceId; return (hashCode * 397) ^ m_UseSrpBatcher; } public static bool operator ==(DrawingSettings left, DrawingSettings right) { return left.Equals(right); } public static bool operator !=(DrawingSettings left, DrawingSettings right) { return !left.Equals(right); } } [Flags] internal enum DrawRendererFlags { None = 0, EnableDynamicBatching = 1, EnableInstancing = 2 } public struct FilteringSettings : IEquatable { private RenderQueueRange m_RenderQueueRange; private int m_LayerMask; private uint m_RenderingLayerMask; private int m_ExcludeMotionVectorObjects; private SortingLayerRange m_SortingLayerRange; public static FilteringSettings defaultValue => new FilteringSettings(RenderQueueRange.all); public RenderQueueRange renderQueueRange { get { return m_RenderQueueRange; } set { m_RenderQueueRange = value; } } public int layerMask { get { return m_LayerMask; } set { m_LayerMask = value; } } public uint renderingLayerMask { get { return m_RenderingLayerMask; } set { m_RenderingLayerMask = value; } } public bool excludeMotionVectorObjects { get { return m_ExcludeMotionVectorObjects != 0; } set { m_ExcludeMotionVectorObjects = (value ? 1 : 0); } } public SortingLayerRange sortingLayerRange { get { return m_SortingLayerRange; } set { m_SortingLayerRange = value; } } public FilteringSettings([UnityEngine.Internal.DefaultValue("RenderQueueRange.all")] RenderQueueRange? renderQueueRange = null, int layerMask = -1, uint renderingLayerMask = uint.MaxValue, int excludeMotionVectorObjects = 0) { this = default(FilteringSettings); m_RenderQueueRange = renderQueueRange ?? RenderQueueRange.all; m_LayerMask = layerMask; m_RenderingLayerMask = renderingLayerMask; m_ExcludeMotionVectorObjects = excludeMotionVectorObjects; m_SortingLayerRange = SortingLayerRange.all; } public bool Equals(FilteringSettings other) { return m_RenderQueueRange.Equals(other.m_RenderQueueRange) && m_LayerMask == other.m_LayerMask && m_RenderingLayerMask == other.m_RenderingLayerMask && m_ExcludeMotionVectorObjects == other.m_ExcludeMotionVectorObjects; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is FilteringSettings && Equals((FilteringSettings)obj); } public override int GetHashCode() { int hashCode = m_RenderQueueRange.GetHashCode(); hashCode = (hashCode * 397) ^ m_LayerMask; hashCode = (hashCode * 397) ^ (int)m_RenderingLayerMask; return (hashCode * 397) ^ m_ExcludeMotionVectorObjects; } public static bool operator ==(FilteringSettings left, FilteringSettings right) { return left.Equals(right); } public static bool operator !=(FilteringSettings left, FilteringSettings right) { return !left.Equals(right); } } public enum GizmoSubset { PreImageEffects, PostImageEffects } public struct LODParameters : IEquatable { private int m_IsOrthographic; private Vector3 m_CameraPosition; private float m_FieldOfView; private float m_OrthoSize; private int m_CameraPixelHeight; public bool isOrthographic { get { return Convert.ToBoolean(m_IsOrthographic); } set { m_IsOrthographic = Convert.ToInt32(value); } } public Vector3 cameraPosition { get { return m_CameraPosition; } set { m_CameraPosition = value; } } public float fieldOfView { get { return m_FieldOfView; } set { m_FieldOfView = value; } } public float orthoSize { get { return m_OrthoSize; } set { m_OrthoSize = value; } } public int cameraPixelHeight { get { return m_CameraPixelHeight; } set { m_CameraPixelHeight = value; } } public bool Equals(LODParameters other) { return m_IsOrthographic == other.m_IsOrthographic && m_CameraPosition.Equals(other.m_CameraPosition) && m_FieldOfView.Equals(other.m_FieldOfView) && m_OrthoSize.Equals(other.m_OrthoSize) && m_CameraPixelHeight == other.m_CameraPixelHeight; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is LODParameters && Equals((LODParameters)obj); } public override int GetHashCode() { int num = m_IsOrthographic; num = (num * 397) ^ m_CameraPosition.GetHashCode(); num = (num * 397) ^ m_FieldOfView.GetHashCode(); num = (num * 397) ^ m_OrthoSize.GetHashCode(); return (num * 397) ^ m_CameraPixelHeight; } public static bool operator ==(LODParameters left, LODParameters right) { return left.Equals(right); } public static bool operator !=(LODParameters left, LODParameters right) { return !left.Equals(right); } } [Flags] public enum PerObjectData { None = 0, LightProbe = 1, ReflectionProbes = 2, LightProbeProxyVolume = 4, Lightmaps = 8, LightData = 0x10, MotionVectors = 0x20, LightIndices = 0x40, ReflectionProbeData = 0x80, OcclusionProbe = 0x100, OcclusionProbeProxyVolume = 0x200, ShadowMask = 0x400 } public struct RasterState : IEquatable { public static readonly RasterState defaultValue = new RasterState(CullMode.Back, 0, 0f, depthClip: true); private CullMode m_CullingMode; private int m_OffsetUnits; private float m_OffsetFactor; private byte m_DepthClip; private byte m_Conservative; private byte m_Padding1; private byte m_Padding2; public CullMode cullingMode { get { return m_CullingMode; } set { m_CullingMode = value; } } public bool depthClip { get { return Convert.ToBoolean(m_DepthClip); } set { m_DepthClip = Convert.ToByte(value); } } public bool conservative { get { return Convert.ToBoolean(m_Conservative); } set { m_Conservative = Convert.ToByte(value); } } public int offsetUnits { get { return m_OffsetUnits; } set { m_OffsetUnits = value; } } public float offsetFactor { get { return m_OffsetFactor; } set { m_OffsetFactor = value; } } public RasterState(CullMode cullingMode = CullMode.Back, int offsetUnits = 0, float offsetFactor = 0f, bool depthClip = true) { m_CullingMode = cullingMode; m_OffsetUnits = offsetUnits; m_OffsetFactor = offsetFactor; m_DepthClip = Convert.ToByte(depthClip); m_Conservative = Convert.ToByte(value: false); m_Padding1 = 0; m_Padding2 = 0; } public bool Equals(RasterState other) { return m_CullingMode == other.m_CullingMode && m_OffsetUnits == other.m_OffsetUnits && m_OffsetFactor.Equals(other.m_OffsetFactor) && m_DepthClip == other.m_DepthClip && m_Conservative == other.m_Conservative; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is RasterState && Equals((RasterState)obj); } public override int GetHashCode() { int num = (int)m_CullingMode; num = (num * 397) ^ m_OffsetUnits; num = (num * 397) ^ m_OffsetFactor.GetHashCode(); num = (num * 397) ^ m_DepthClip.GetHashCode(); return (num * 397) ^ m_Conservative.GetHashCode(); } public static bool operator ==(RasterState left, RasterState right) { return left.Equals(right); } public static bool operator !=(RasterState left, RasterState right) { return !left.Equals(right); } } public enum ReflectionProbeSortingCriteria { None, Importance, Size, ImportanceThenSize } public abstract class RenderPipeline { public bool disposed { get; private set; } public virtual RenderPipelineGlobalSettings defaultSettings => null; protected abstract void Render(ScriptableRenderContext context, Camera[] cameras); protected virtual void ProcessRenderRequests(ScriptableRenderContext context, Camera camera, List renderRequests) { } protected static void BeginFrameRendering(ScriptableRenderContext context, Camera[] cameras) { RenderPipelineManager.BeginContextRendering(context, new List(cameras)); } protected static void BeginContextRendering(ScriptableRenderContext context, List cameras) { RenderPipelineManager.BeginContextRendering(context, cameras); } protected static void BeginCameraRendering(ScriptableRenderContext context, Camera camera) { RenderPipelineManager.BeginCameraRendering(context, camera); } protected static void EndContextRendering(ScriptableRenderContext context, List cameras) { RenderPipelineManager.EndContextRendering(context, cameras); } protected static void EndFrameRendering(ScriptableRenderContext context, Camera[] cameras) { RenderPipelineManager.EndContextRendering(context, new List(cameras)); } protected static void EndCameraRendering(ScriptableRenderContext context, Camera camera) { RenderPipelineManager.EndCameraRendering(context, camera); } protected virtual void Render(ScriptableRenderContext context, List cameras) { Render(context, cameras.ToArray()); } internal void InternalRender(ScriptableRenderContext context, List cameras) { if (disposed) { throw new ObjectDisposedException($"{this} has been disposed. Do not call Render on disposed a RenderPipeline."); } Render(context, cameras); } internal void InternalRenderWithRequests(ScriptableRenderContext context, List cameras, List renderRequests) { if (disposed) { throw new ObjectDisposedException($"{this} has been disposed. Do not call Render on disposed a RenderPipeline."); } ProcessRenderRequests(context, (cameras == null || cameras.Count == 0) ? null : cameras[0], renderRequests); } internal void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); disposed = true; } protected virtual void Dispose(bool disposing) { } } public abstract class RenderPipelineAsset : ScriptableObject { public virtual string[] renderingLayerMaskNames => null; public virtual string[] prefixedRenderingLayerMaskNames => null; public virtual Material defaultMaterial => null; public virtual Shader autodeskInteractiveShader => null; public virtual Shader autodeskInteractiveTransparentShader => null; public virtual Shader autodeskInteractiveMaskedShader => null; public virtual Shader terrainDetailLitShader => null; public virtual Shader terrainDetailGrassShader => null; public virtual Shader terrainDetailGrassBillboardShader => null; public virtual Material defaultParticleMaterial => null; public virtual Material defaultLineMaterial => null; public virtual Material defaultTerrainMaterial => null; public virtual Material defaultUIMaterial => null; public virtual Material defaultUIOverdrawMaterial => null; public virtual Material defaultUIETC1SupportedMaterial => null; public virtual Material default2DMaterial => null; public virtual Material default2DMaskMaterial => null; public virtual Shader defaultShader => null; public virtual Shader defaultSpeedTree7Shader => null; public virtual Shader defaultSpeedTree8Shader => null; internal RenderPipeline InternalCreatePipeline() { RenderPipeline result = null; try { result = CreatePipeline(); } catch (Exception ex) { if (!ex.Data.Contains("InvalidImport") || !(ex.Data["InvalidImport"] is int) || (int)ex.Data["InvalidImport"] != 1) { Debug.LogException(ex); } } return result; } protected abstract RenderPipeline CreatePipeline(); protected virtual void OnValidate() { if (RenderPipelineManager.s_CurrentPipelineAsset == this) { RenderPipelineManager.CleanupRenderPipeline(); RenderPipelineManager.PrepareRenderPipeline(this); } } protected virtual void OnDisable() { RenderPipelineManager.CleanupRenderPipeline(); } } public abstract class RenderPipelineGlobalSettings : ScriptableObject { } public static class RenderPipelineManager { internal static RenderPipelineAsset s_CurrentPipelineAsset; private static List s_Cameras = new List(); private static string s_currentPipelineType = "Built-in Pipeline"; private const string s_builtinPipelineName = "Built-in Pipeline"; private static RenderPipeline s_currentPipeline = null; public static RenderPipeline currentPipeline { get { return s_currentPipeline; } private set { s_currentPipelineType = ((value != null) ? value.GetType().ToString() : "Built-in Pipeline"); s_currentPipeline = value; } } public static bool pipelineSwitchCompleted => (object)s_CurrentPipelineAsset == GraphicsSettings.currentRenderPipeline && !IsPipelineRequireCreation(); public static event Action> beginContextRendering; public static event Action> endContextRendering; public static event Action beginFrameRendering; public static event Action beginCameraRendering; public static event Action endFrameRendering; public static event Action endCameraRendering; public static event Action activeRenderPipelineTypeChanged; public static event Action activeRenderPipelineCreated; public static event Action activeRenderPipelineDisposed; internal static void BeginContextRendering(ScriptableRenderContext context, List cameras) { RenderPipelineManager.beginFrameRendering?.Invoke(context, cameras.ToArray()); RenderPipelineManager.beginContextRendering?.Invoke(context, cameras); } internal static void BeginCameraRendering(ScriptableRenderContext context, Camera camera) { RenderPipelineManager.beginCameraRendering?.Invoke(context, camera); } internal static void EndContextRendering(ScriptableRenderContext context, List cameras) { RenderPipelineManager.endFrameRendering?.Invoke(context, cameras.ToArray()); RenderPipelineManager.endContextRendering?.Invoke(context, cameras); } internal static void EndCameraRendering(ScriptableRenderContext context, Camera camera) { RenderPipelineManager.endCameraRendering?.Invoke(context, camera); } [RequiredByNativeCode] internal static void OnActiveRenderPipelineTypeChanged() { RenderPipelineManager.activeRenderPipelineTypeChanged?.Invoke(); } [RequiredByNativeCode] internal static void HandleRenderPipelineChange(RenderPipelineAsset pipelineAsset) { if ((object)s_CurrentPipelineAsset != pipelineAsset) { CleanupRenderPipeline(); s_CurrentPipelineAsset = pipelineAsset; } } [RequiredByNativeCode] internal static void CleanupRenderPipeline() { if (currentPipeline != null && !currentPipeline.disposed) { RenderPipelineManager.activeRenderPipelineDisposed?.Invoke(); currentPipeline.Dispose(); s_CurrentPipelineAsset = null; currentPipeline = null; SupportedRenderingFeatures.active = new SupportedRenderingFeatures(); } } [RequiredByNativeCode] private static string GetCurrentPipelineAssetType() { return s_currentPipelineType; } [RequiredByNativeCode] private static void DoRenderLoop_Internal(RenderPipelineAsset pipe, IntPtr loopPtr, List renderRequests) { PrepareRenderPipeline(pipe); if (currentPipeline != null) { ScriptableRenderContext context = new ScriptableRenderContext(loopPtr); s_Cameras.Clear(); context.GetCameras(s_Cameras); if (renderRequests == null) { currentPipeline.InternalRender(context, s_Cameras); } else { currentPipeline.InternalRenderWithRequests(context, s_Cameras, renderRequests); } s_Cameras.Clear(); } } internal static void PrepareRenderPipeline(RenderPipelineAsset pipelineAsset) { HandleRenderPipelineChange(pipelineAsset); if (IsPipelineRequireCreation()) { currentPipeline = s_CurrentPipelineAsset.InternalCreatePipeline(); RenderPipelineManager.activeRenderPipelineCreated?.Invoke(); } } private static bool IsPipelineRequireCreation() { return s_CurrentPipelineAsset != null && (currentPipeline == null || currentPipeline.disposed); } } public struct RenderQueueRange : IEquatable { private int m_LowerBound; private int m_UpperBound; private const int k_MinimumBound = 0; public static readonly int minimumBound = 0; private const int k_MaximumBound = 5000; public static readonly int maximumBound = 5000; public static RenderQueueRange all => new RenderQueueRange { m_LowerBound = 0, m_UpperBound = 5000 }; public static RenderQueueRange opaque => new RenderQueueRange { m_LowerBound = 0, m_UpperBound = 2500 }; public static RenderQueueRange transparent => new RenderQueueRange { m_LowerBound = 2501, m_UpperBound = 5000 }; public int lowerBound { get { return m_LowerBound; } set { if (value < 0 || value > 5000) { throw new ArgumentOutOfRangeException($"The lower bound must be at least {0} and at most {5000}."); } m_LowerBound = value; } } public int upperBound { get { return m_UpperBound; } set { if (value < 0 || value > 5000) { throw new ArgumentOutOfRangeException($"The upper bound must be at least {0} and at most {5000}."); } m_UpperBound = value; } } public RenderQueueRange(int lowerBound, int upperBound) { if (lowerBound < 0 || lowerBound > 5000) { throw new ArgumentOutOfRangeException("lowerBound", lowerBound, $"The lower bound must be at least {0} and at most {5000}."); } if (upperBound < 0 || upperBound > 5000) { throw new ArgumentOutOfRangeException("upperBound", upperBound, $"The upper bound must be at least {0} and at most {5000}."); } m_LowerBound = lowerBound; m_UpperBound = upperBound; } public bool Equals(RenderQueueRange other) { return m_LowerBound == other.m_LowerBound && m_UpperBound == other.m_UpperBound; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is RenderQueueRange && Equals((RenderQueueRange)obj); } public override int GetHashCode() { return (m_LowerBound * 397) ^ m_UpperBound; } public static bool operator ==(RenderQueueRange left, RenderQueueRange right) { return left.Equals(right); } public static bool operator !=(RenderQueueRange left, RenderQueueRange right) { return !left.Equals(right); } } public struct RenderStateBlock : IEquatable { private BlendState m_BlendState; private RasterState m_RasterState; private DepthState m_DepthState; private StencilState m_StencilState; private int m_StencilReference; private RenderStateMask m_Mask; public BlendState blendState { get { return m_BlendState; } set { m_BlendState = value; } } public RasterState rasterState { get { return m_RasterState; } set { m_RasterState = value; } } public DepthState depthState { get { return m_DepthState; } set { m_DepthState = value; } } public StencilState stencilState { get { return m_StencilState; } set { m_StencilState = value; } } public int stencilReference { get { return m_StencilReference; } set { m_StencilReference = value; } } public RenderStateMask mask { get { return m_Mask; } set { m_Mask = value; } } public RenderStateBlock(RenderStateMask mask) { m_BlendState = BlendState.defaultValue; m_RasterState = RasterState.defaultValue; m_DepthState = DepthState.defaultValue; m_StencilState = StencilState.defaultValue; m_StencilReference = 0; m_Mask = mask; } public bool Equals(RenderStateBlock other) { return m_BlendState.Equals(other.m_BlendState) && m_RasterState.Equals(other.m_RasterState) && m_DepthState.Equals(other.m_DepthState) && m_StencilState.Equals(other.m_StencilState) && m_StencilReference == other.m_StencilReference && m_Mask == other.m_Mask; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is RenderStateBlock && Equals((RenderStateBlock)obj); } public override int GetHashCode() { int hashCode = m_BlendState.GetHashCode(); hashCode = (hashCode * 397) ^ m_RasterState.GetHashCode(); hashCode = (hashCode * 397) ^ m_DepthState.GetHashCode(); hashCode = (hashCode * 397) ^ m_StencilState.GetHashCode(); hashCode = (hashCode * 397) ^ m_StencilReference; return (hashCode * 397) ^ (int)m_Mask; } public static bool operator ==(RenderStateBlock left, RenderStateBlock right) { return left.Equals(right); } public static bool operator !=(RenderStateBlock left, RenderStateBlock right) { return !left.Equals(right); } } [Flags] public enum RenderStateMask { Nothing = 0, Blend = 1, Raster = 2, Depth = 4, Stencil = 8, Everything = 0xF } public struct RenderTargetBlendState : IEquatable { private byte m_WriteMask; private byte m_SourceColorBlendMode; private byte m_DestinationColorBlendMode; private byte m_SourceAlphaBlendMode; private byte m_DestinationAlphaBlendMode; private byte m_ColorBlendOperation; private byte m_AlphaBlendOperation; private byte m_Padding; public static RenderTargetBlendState defaultValue => new RenderTargetBlendState(ColorWriteMask.All, BlendMode.One, BlendMode.Zero, BlendMode.One, BlendMode.Zero, BlendOp.Add, BlendOp.Add); public ColorWriteMask writeMask { get { return (ColorWriteMask)m_WriteMask; } set { m_WriteMask = (byte)value; } } public BlendMode sourceColorBlendMode { get { return (BlendMode)m_SourceColorBlendMode; } set { m_SourceColorBlendMode = (byte)value; } } public BlendMode destinationColorBlendMode { get { return (BlendMode)m_DestinationColorBlendMode; } set { m_DestinationColorBlendMode = (byte)value; } } public BlendMode sourceAlphaBlendMode { get { return (BlendMode)m_SourceAlphaBlendMode; } set { m_SourceAlphaBlendMode = (byte)value; } } public BlendMode destinationAlphaBlendMode { get { return (BlendMode)m_DestinationAlphaBlendMode; } set { m_DestinationAlphaBlendMode = (byte)value; } } public BlendOp colorBlendOperation { get { return (BlendOp)m_ColorBlendOperation; } set { m_ColorBlendOperation = (byte)value; } } public BlendOp alphaBlendOperation { get { return (BlendOp)m_AlphaBlendOperation; } set { m_AlphaBlendOperation = (byte)value; } } public RenderTargetBlendState(ColorWriteMask writeMask = ColorWriteMask.All, BlendMode sourceColorBlendMode = BlendMode.One, BlendMode destinationColorBlendMode = BlendMode.Zero, BlendMode sourceAlphaBlendMode = BlendMode.One, BlendMode destinationAlphaBlendMode = BlendMode.Zero, BlendOp colorBlendOperation = BlendOp.Add, BlendOp alphaBlendOperation = BlendOp.Add) { m_WriteMask = (byte)writeMask; m_SourceColorBlendMode = (byte)sourceColorBlendMode; m_DestinationColorBlendMode = (byte)destinationColorBlendMode; m_SourceAlphaBlendMode = (byte)sourceAlphaBlendMode; m_DestinationAlphaBlendMode = (byte)destinationAlphaBlendMode; m_ColorBlendOperation = (byte)colorBlendOperation; m_AlphaBlendOperation = (byte)alphaBlendOperation; m_Padding = 0; } public bool Equals(RenderTargetBlendState other) { return m_WriteMask == other.m_WriteMask && m_SourceColorBlendMode == other.m_SourceColorBlendMode && m_DestinationColorBlendMode == other.m_DestinationColorBlendMode && m_SourceAlphaBlendMode == other.m_SourceAlphaBlendMode && m_DestinationAlphaBlendMode == other.m_DestinationAlphaBlendMode && m_ColorBlendOperation == other.m_ColorBlendOperation && m_AlphaBlendOperation == other.m_AlphaBlendOperation; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is RenderTargetBlendState && Equals((RenderTargetBlendState)obj); } public override int GetHashCode() { int hashCode = m_WriteMask.GetHashCode(); hashCode = (hashCode * 397) ^ m_SourceColorBlendMode.GetHashCode(); hashCode = (hashCode * 397) ^ m_DestinationColorBlendMode.GetHashCode(); hashCode = (hashCode * 397) ^ m_SourceAlphaBlendMode.GetHashCode(); hashCode = (hashCode * 397) ^ m_DestinationAlphaBlendMode.GetHashCode(); hashCode = (hashCode * 397) ^ m_ColorBlendOperation.GetHashCode(); return (hashCode * 397) ^ m_AlphaBlendOperation.GetHashCode(); } public static bool operator ==(RenderTargetBlendState left, RenderTargetBlendState right) { return left.Equals(right); } public static bool operator !=(RenderTargetBlendState left, RenderTargetBlendState right) { return !left.Equals(right); } } public struct ScopedRenderPass : IDisposable { private ScriptableRenderContext m_Context; internal ScopedRenderPass(ScriptableRenderContext context) { m_Context = context; } public void Dispose() { try { m_Context.EndRenderPass(); } catch (Exception innerException) { throw new InvalidOperationException("The ScopedRenderPass instance is not valid. This can happen if it was constructed using the default constructor.", innerException); } } } public struct ScopedSubPass : IDisposable { private ScriptableRenderContext m_Context; internal ScopedSubPass(ScriptableRenderContext context) { m_Context = context; } public void Dispose() { try { m_Context.EndSubPass(); } catch (Exception innerException) { throw new InvalidOperationException("The ScopedSubPass instance is not valid. This can happen if it was constructed using the default constructor.", innerException); } } } [NativeHeader("Runtime/Export/RenderPipeline/ScriptableRenderPipeline.bindings.h")] [NativeHeader("Runtime/Export/RenderPipeline/ScriptableRenderContext.bindings.h")] [NativeHeader("Runtime/Graphics/ScriptableRenderLoop/ScriptableDrawRenderersUtility.h")] [NativeType("Runtime/Graphics/ScriptableRenderLoop/ScriptableRenderContext.h")] [NativeHeader("Modules/UI/Canvas.h")] [NativeHeader("Modules/UI/CanvasManager.h")] public struct ScriptableRenderContext : IEquatable { private static readonly ShaderTagId kRenderTypeTag = new ShaderTagId("RenderType"); private IntPtr m_Ptr; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptableRenderContext::BeginRenderPass")] private static extern void BeginRenderPass_Internal(IntPtr self, int width, int height, int samples, IntPtr colors, int colorCount, int depthAttachmentIndex); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptableRenderContext::BeginSubPass")] private static extern void BeginSubPass_Internal(IntPtr self, IntPtr colors, int colorCount, IntPtr inputs, int inputCount, bool isDepthReadOnly, bool isStencilReadOnly); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptableRenderContext::EndSubPass")] private static extern void EndSubPass_Internal(IntPtr self); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptableRenderContext::EndRenderPass")] private static extern void EndRenderPass_Internal(IntPtr self); [FreeFunction("ScriptableRenderPipeline_Bindings::Internal_Cull")] private static void Internal_Cull(ref ScriptableCullingParameters parameters, ScriptableRenderContext renderLoop, IntPtr results) { Internal_Cull_Injected(ref parameters, ref renderLoop, results); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("InitializeSortSettings")] internal static extern void InitializeSortSettings(Camera camera, out SortingSettings sortingSettings); private void Submit_Internal() { Submit_Internal_Injected(ref this); } private bool SubmitForRenderPassValidation_Internal() { return SubmitForRenderPassValidation_Internal_Injected(ref this); } private void GetCameras_Internal(Type listType, object resultList) { GetCameras_Internal_Injected(ref this, listType, resultList); } private void DrawRenderers_Internal(IntPtr cullResults, ref DrawingSettings drawingSettings, ref FilteringSettings filteringSettings, ShaderTagId tagName, bool isPassTagName, IntPtr tagValues, IntPtr stateBlocks, int stateCount) { DrawRenderers_Internal_Injected(ref this, cullResults, ref drawingSettings, ref filteringSettings, ref tagName, isPassTagName, tagValues, stateBlocks, stateCount); } private void DrawShadows_Internal(IntPtr shadowDrawingSettings) { DrawShadows_Internal_Injected(ref this, shadowDrawingSettings); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("PlayerEmitCanvasGeometryForCamera")] public static extern void EmitGeometryForCamera(Camera camera); [NativeThrows] private void ExecuteCommandBuffer_Internal(CommandBuffer commandBuffer) { ExecuteCommandBuffer_Internal_Injected(ref this, commandBuffer); } [NativeThrows] private void ExecuteCommandBufferAsync_Internal(CommandBuffer commandBuffer, ComputeQueueType queueType) { ExecuteCommandBufferAsync_Internal_Injected(ref this, commandBuffer, queueType); } private void SetupCameraProperties_Internal([NotNull("NullExceptionObject")] Camera camera, bool stereoSetup, int eye) { SetupCameraProperties_Internal_Injected(ref this, camera, stereoSetup, eye); } private void StereoEndRender_Internal([NotNull("NullExceptionObject")] Camera camera, int eye, bool isFinalPass) { StereoEndRender_Internal_Injected(ref this, camera, eye, isFinalPass); } private void StartMultiEye_Internal([NotNull("NullExceptionObject")] Camera camera, int eye) { StartMultiEye_Internal_Injected(ref this, camera, eye); } private void StopMultiEye_Internal([NotNull("NullExceptionObject")] Camera camera) { StopMultiEye_Internal_Injected(ref this, camera); } private void DrawSkybox_Internal([NotNull("NullExceptionObject")] Camera camera) { DrawSkybox_Internal_Injected(ref this, camera); } private void InvokeOnRenderObjectCallback_Internal() { InvokeOnRenderObjectCallback_Internal_Injected(ref this); } private void DrawGizmos_Internal([NotNull("NullExceptionObject")] Camera camera, GizmoSubset gizmoSubset) { DrawGizmos_Internal_Injected(ref this, camera, gizmoSubset); } private void DrawWireOverlay_Impl([NotNull("NullExceptionObject")] Camera camera) { DrawWireOverlay_Impl_Injected(ref this, camera); } private void DrawUIOverlay_Internal([NotNull("NullExceptionObject")] Camera camera) { DrawUIOverlay_Internal_Injected(ref this, camera); } internal IntPtr Internal_GetPtr() { return m_Ptr; } private RendererList CreateRendererList_Internal(IntPtr cullResults, ref DrawingSettings drawingSettings, ref FilteringSettings filteringSettings, ShaderTagId tagName, bool isPassTagName, IntPtr tagValues, IntPtr stateBlocks, int stateCount) { CreateRendererList_Internal_Injected(ref this, cullResults, ref drawingSettings, ref filteringSettings, ref tagName, isPassTagName, tagValues, stateBlocks, stateCount, out var ret); return ret; } private void PrepareRendererListsAsync_Internal(object rendererLists) { PrepareRendererListsAsync_Internal_Injected(ref this, rendererLists); } private RendererListStatus QueryRendererListStatus_Internal(RendererList handle) { return QueryRendererListStatus_Internal_Injected(ref this, ref handle); } internal ScriptableRenderContext(IntPtr ptr) { m_Ptr = ptr; } public unsafe void BeginRenderPass(int width, int height, int samples, NativeArray attachments, int depthAttachmentIndex = -1) { BeginRenderPass_Internal(m_Ptr, width, height, samples, (IntPtr)attachments.GetUnsafeReadOnlyPtr(), attachments.Length, depthAttachmentIndex); } public ScopedRenderPass BeginScopedRenderPass(int width, int height, int samples, NativeArray attachments, int depthAttachmentIndex = -1) { BeginRenderPass(width, height, samples, attachments, depthAttachmentIndex); return new ScopedRenderPass(this); } public unsafe void BeginSubPass(NativeArray colors, NativeArray inputs, bool isDepthReadOnly, bool isStencilReadOnly) { BeginSubPass_Internal(m_Ptr, (IntPtr)colors.GetUnsafeReadOnlyPtr(), colors.Length, (IntPtr)inputs.GetUnsafeReadOnlyPtr(), inputs.Length, isDepthReadOnly, isStencilReadOnly); } public unsafe void BeginSubPass(NativeArray colors, NativeArray inputs, bool isDepthStencilReadOnly = false) { BeginSubPass_Internal(m_Ptr, (IntPtr)colors.GetUnsafeReadOnlyPtr(), colors.Length, (IntPtr)inputs.GetUnsafeReadOnlyPtr(), inputs.Length, isDepthStencilReadOnly, isDepthStencilReadOnly); } public unsafe void BeginSubPass(NativeArray colors, bool isDepthReadOnly, bool isStencilReadOnly) { BeginSubPass_Internal(m_Ptr, (IntPtr)colors.GetUnsafeReadOnlyPtr(), colors.Length, IntPtr.Zero, 0, isDepthReadOnly, isStencilReadOnly); } public unsafe void BeginSubPass(NativeArray colors, bool isDepthStencilReadOnly = false) { BeginSubPass_Internal(m_Ptr, (IntPtr)colors.GetUnsafeReadOnlyPtr(), colors.Length, IntPtr.Zero, 0, isDepthStencilReadOnly, isDepthStencilReadOnly); } public ScopedSubPass BeginScopedSubPass(NativeArray colors, NativeArray inputs, bool isDepthReadOnly, bool isStencilReadOnly) { BeginSubPass(colors, inputs, isDepthReadOnly, isStencilReadOnly); return new ScopedSubPass(this); } public ScopedSubPass BeginScopedSubPass(NativeArray colors, NativeArray inputs, bool isDepthStencilReadOnly = false) { BeginSubPass(colors, inputs, isDepthStencilReadOnly); return new ScopedSubPass(this); } public ScopedSubPass BeginScopedSubPass(NativeArray colors, bool isDepthReadOnly, bool isStencilReadOnly) { BeginSubPass(colors, isDepthReadOnly, isStencilReadOnly); return new ScopedSubPass(this); } public ScopedSubPass BeginScopedSubPass(NativeArray colors, bool isDepthStencilReadOnly = false) { BeginSubPass(colors, isDepthStencilReadOnly); return new ScopedSubPass(this); } public void EndSubPass() { EndSubPass_Internal(m_Ptr); } public void EndRenderPass() { EndRenderPass_Internal(m_Ptr); } public void Submit() { Submit_Internal(); } public bool SubmitForRenderPassValidation() { return SubmitForRenderPassValidation_Internal(); } internal void GetCameras(List results) { GetCameras_Internal(typeof(Camera), results); } public void DrawRenderers(CullingResults cullingResults, ref DrawingSettings drawingSettings, ref FilteringSettings filteringSettings) { DrawRenderers_Internal(cullingResults.ptr, ref drawingSettings, ref filteringSettings, ShaderTagId.none, isPassTagName: false, IntPtr.Zero, IntPtr.Zero, 0); } public unsafe void DrawRenderers(CullingResults cullingResults, ref DrawingSettings drawingSettings, ref FilteringSettings filteringSettings, ref RenderStateBlock stateBlock) { ShaderTagId shaderTagId = default(ShaderTagId); fixed (RenderStateBlock* ptr = &stateBlock) { DrawRenderers_Internal(cullingResults.ptr, ref drawingSettings, ref filteringSettings, ShaderTagId.none, isPassTagName: false, (IntPtr)(&shaderTagId), (IntPtr)ptr, 1); } } public unsafe void DrawRenderers(CullingResults cullingResults, ref DrawingSettings drawingSettings, ref FilteringSettings filteringSettings, NativeArray renderTypes, NativeArray stateBlocks) { if (renderTypes.Length != stateBlocks.Length) { throw new ArgumentException(string.Format("Arrays {0} and {1} should have same length, but {2} had length {3} while {4} had length {5}.", "renderTypes", "stateBlocks", "renderTypes", renderTypes.Length, "stateBlocks", stateBlocks.Length)); } DrawRenderers_Internal(cullingResults.ptr, ref drawingSettings, ref filteringSettings, kRenderTypeTag, isPassTagName: false, (IntPtr)renderTypes.GetUnsafeReadOnlyPtr(), (IntPtr)stateBlocks.GetUnsafeReadOnlyPtr(), renderTypes.Length); } public unsafe void DrawRenderers(CullingResults cullingResults, ref DrawingSettings drawingSettings, ref FilteringSettings filteringSettings, ShaderTagId tagName, bool isPassTagName, NativeArray tagValues, NativeArray stateBlocks) { if (tagValues.Length != stateBlocks.Length) { throw new ArgumentException(string.Format("Arrays {0} and {1} should have same length, but {2} had length {3} while {4} had length {5}.", "tagValues", "stateBlocks", "tagValues", tagValues.Length, "stateBlocks", stateBlocks.Length)); } DrawRenderers_Internal(cullingResults.ptr, ref drawingSettings, ref filteringSettings, tagName, isPassTagName, (IntPtr)tagValues.GetUnsafeReadOnlyPtr(), (IntPtr)stateBlocks.GetUnsafeReadOnlyPtr(), tagValues.Length); } public unsafe void DrawShadows(ref ShadowDrawingSettings settings) { fixed (ShadowDrawingSettings* ptr = &settings) { DrawShadows_Internal((IntPtr)ptr); } } public void ExecuteCommandBuffer(CommandBuffer commandBuffer) { if (commandBuffer == null) { throw new ArgumentNullException("commandBuffer"); } if (commandBuffer.m_Ptr == IntPtr.Zero) { throw new ObjectDisposedException("commandBuffer"); } ExecuteCommandBuffer_Internal(commandBuffer); } public void ExecuteCommandBufferAsync(CommandBuffer commandBuffer, ComputeQueueType queueType) { if (commandBuffer == null) { throw new ArgumentNullException("commandBuffer"); } if (commandBuffer.m_Ptr == IntPtr.Zero) { throw new ObjectDisposedException("commandBuffer"); } ExecuteCommandBufferAsync_Internal(commandBuffer, queueType); } public void SetupCameraProperties(Camera camera, bool stereoSetup = false) { SetupCameraProperties(camera, stereoSetup, 0); } public void SetupCameraProperties(Camera camera, bool stereoSetup, int eye) { SetupCameraProperties_Internal(camera, stereoSetup, eye); } public void StereoEndRender(Camera camera) { StereoEndRender(camera, 0, isFinalPass: true); } public void StereoEndRender(Camera camera, int eye) { StereoEndRender(camera, eye, isFinalPass: true); } public void StereoEndRender(Camera camera, int eye, bool isFinalPass) { StereoEndRender_Internal(camera, eye, isFinalPass); } public void StartMultiEye(Camera camera) { StartMultiEye(camera, 0); } public void StartMultiEye(Camera camera, int eye) { StartMultiEye_Internal(camera, eye); } public void StopMultiEye(Camera camera) { StopMultiEye_Internal(camera); } public void DrawSkybox(Camera camera) { DrawSkybox_Internal(camera); } public void InvokeOnRenderObjectCallback() { InvokeOnRenderObjectCallback_Internal(); } public void DrawGizmos(Camera camera, GizmoSubset gizmoSubset) { DrawGizmos_Internal(camera, gizmoSubset); } public void DrawWireOverlay(Camera camera) { DrawWireOverlay_Impl(camera); } public void DrawUIOverlay(Camera camera) { DrawUIOverlay_Internal(camera); } public unsafe CullingResults Cull(ref ScriptableCullingParameters parameters) { CullingResults result = default(CullingResults); Internal_Cull(ref parameters, this, (IntPtr)(&result)); return result; } [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] internal void Validate() { } public bool Equals(ScriptableRenderContext other) { return m_Ptr.Equals((object?)(nint)other.m_Ptr); } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is ScriptableRenderContext && Equals((ScriptableRenderContext)obj); } public override int GetHashCode() { return m_Ptr.GetHashCode(); } public static bool operator ==(ScriptableRenderContext left, ScriptableRenderContext right) { return left.Equals(right); } public static bool operator !=(ScriptableRenderContext left, ScriptableRenderContext right) { return !left.Equals(right); } public unsafe RendererList CreateRendererList(RendererListDesc desc) { RendererListParams rendererListParams = RendererListParams.Create(in desc); if (!rendererListParams.stateBlock.HasValue) { return CreateRendererList_Internal(rendererListParams.cullingResult.ptr, ref rendererListParams.drawSettings, ref rendererListParams.filteringSettings, ShaderTagId.none, isPassTagName: false, IntPtr.Zero, IntPtr.Zero, 0); } ShaderTagId shaderTagId = default(ShaderTagId); RenderStateBlock value = rendererListParams.stateBlock.Value; RenderStateBlock* ptr = &value; return CreateRendererList_Internal(rendererListParams.cullingResult.ptr, ref rendererListParams.drawSettings, ref rendererListParams.filteringSettings, ShaderTagId.none, isPassTagName: false, (IntPtr)(&shaderTagId), (IntPtr)ptr, 1); } public void PrepareRendererListsAsync(List rendererLists) { PrepareRendererListsAsync_Internal(rendererLists); } public RendererListStatus QueryRendererListStatus(RendererList rendererList) { return QueryRendererListStatus_Internal(rendererList); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Internal_Cull_Injected(ref ScriptableCullingParameters parameters, ref ScriptableRenderContext renderLoop, IntPtr results); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Submit_Internal_Injected(ref ScriptableRenderContext _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool SubmitForRenderPassValidation_Internal_Injected(ref ScriptableRenderContext _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetCameras_Internal_Injected(ref ScriptableRenderContext _unity_self, Type listType, object resultList); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawRenderers_Internal_Injected(ref ScriptableRenderContext _unity_self, IntPtr cullResults, ref DrawingSettings drawingSettings, ref FilteringSettings filteringSettings, ref ShaderTagId tagName, bool isPassTagName, IntPtr tagValues, IntPtr stateBlocks, int stateCount); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawShadows_Internal_Injected(ref ScriptableRenderContext _unity_self, IntPtr shadowDrawingSettings); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ExecuteCommandBuffer_Internal_Injected(ref ScriptableRenderContext _unity_self, CommandBuffer commandBuffer); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ExecuteCommandBufferAsync_Internal_Injected(ref ScriptableRenderContext _unity_self, CommandBuffer commandBuffer, ComputeQueueType queueType); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetupCameraProperties_Internal_Injected(ref ScriptableRenderContext _unity_self, Camera camera, bool stereoSetup, int eye); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void StereoEndRender_Internal_Injected(ref ScriptableRenderContext _unity_self, Camera camera, int eye, bool isFinalPass); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void StartMultiEye_Internal_Injected(ref ScriptableRenderContext _unity_self, Camera camera, int eye); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void StopMultiEye_Internal_Injected(ref ScriptableRenderContext _unity_self, Camera camera); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawSkybox_Internal_Injected(ref ScriptableRenderContext _unity_self, Camera camera); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void InvokeOnRenderObjectCallback_Internal_Injected(ref ScriptableRenderContext _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawGizmos_Internal_Injected(ref ScriptableRenderContext _unity_self, Camera camera, GizmoSubset gizmoSubset); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawWireOverlay_Impl_Injected(ref ScriptableRenderContext _unity_self, Camera camera); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DrawUIOverlay_Internal_Injected(ref ScriptableRenderContext _unity_self, Camera camera); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CreateRendererList_Internal_Injected(ref ScriptableRenderContext _unity_self, IntPtr cullResults, ref DrawingSettings drawingSettings, ref FilteringSettings filteringSettings, ref ShaderTagId tagName, bool isPassTagName, IntPtr tagValues, IntPtr stateBlocks, int stateCount, out RendererList ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void PrepareRendererListsAsync_Internal_Injected(ref ScriptableRenderContext _unity_self, object rendererLists); [MethodImpl(MethodImplOptions.InternalCall)] private static extern RendererListStatus QueryRendererListStatus_Internal_Injected(ref ScriptableRenderContext _unity_self, ref RendererList handle); } public struct ShaderTagId : IEquatable { public static readonly ShaderTagId none; private int m_Id; internal int id { get { return m_Id; } set { m_Id = value; } } public string name => Shader.IDToTag(id); public ShaderTagId(string name) { m_Id = Shader.TagToID(name); } public override bool Equals(object obj) { return obj is ShaderTagId && Equals((ShaderTagId)obj); } public bool Equals(ShaderTagId other) { return m_Id == other.m_Id; } public override int GetHashCode() { int num = 2079669542; return num * -1521134295 + m_Id.GetHashCode(); } public static bool operator ==(ShaderTagId tag1, ShaderTagId tag2) { return tag1.Equals(tag2); } public static bool operator !=(ShaderTagId tag1, ShaderTagId tag2) { return !(tag1 == tag2); } public static explicit operator ShaderTagId(string name) { return new ShaderTagId(name); } public static explicit operator string(ShaderTagId tagId) { return tagId.name; } } [UsedByNativeCode] public struct ShadowDrawingSettings : IEquatable { private CullingResults m_CullingResults; private int m_LightIndex; private int m_UseRenderingLayerMaskTest; private ShadowSplitData m_SplitData; private ShadowObjectsFilter m_ObjectsFilter; public CullingResults cullingResults { get { return m_CullingResults; } set { m_CullingResults = value; } } public int lightIndex { get { return m_LightIndex; } set { m_LightIndex = value; } } public bool useRenderingLayerMaskTest { get { return m_UseRenderingLayerMaskTest != 0; } set { m_UseRenderingLayerMaskTest = (value ? 1 : 0); } } public ShadowSplitData splitData { get { return m_SplitData; } set { m_SplitData = value; } } public ShadowObjectsFilter objectsFilter { get { return m_ObjectsFilter; } set { m_ObjectsFilter = value; } } public ShadowDrawingSettings(CullingResults cullingResults, int lightIndex) { m_CullingResults = cullingResults; m_LightIndex = lightIndex; m_UseRenderingLayerMaskTest = 0; m_SplitData = default(ShadowSplitData); m_SplitData.shadowCascadeBlendCullingFactor = 1f; m_ObjectsFilter = ShadowObjectsFilter.AllObjects; } public bool Equals(ShadowDrawingSettings other) { return m_CullingResults.Equals(other.m_CullingResults) && m_LightIndex == other.m_LightIndex && m_SplitData.Equals(other.m_SplitData) && m_UseRenderingLayerMaskTest.Equals(other.m_UseRenderingLayerMaskTest) && m_ObjectsFilter.Equals(other.m_ObjectsFilter); } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is ShadowDrawingSettings && Equals((ShadowDrawingSettings)obj); } public override int GetHashCode() { int hashCode = m_CullingResults.GetHashCode(); hashCode = (hashCode * 397) ^ m_LightIndex; hashCode = (hashCode * 397) ^ m_UseRenderingLayerMaskTest; hashCode = (hashCode * 397) ^ m_SplitData.GetHashCode(); return (hashCode * 397) ^ (int)m_ObjectsFilter; } public static bool operator ==(ShadowDrawingSettings left, ShadowDrawingSettings right) { return left.Equals(right); } public static bool operator !=(ShadowDrawingSettings left, ShadowDrawingSettings right) { return !left.Equals(right); } } [UsedByNativeCode] public struct ShadowSplitData : IEquatable { private const int k_MaximumCullingPlaneCount = 10; public static readonly int maximumCullingPlaneCount = 10; private int m_CullingPlaneCount; internal unsafe fixed byte m_CullingPlanes[160]; private Vector4 m_CullingSphere; private float m_ShadowCascadeBlendCullingFactor; private float m_CullingNearPlane; public int cullingPlaneCount { get { return m_CullingPlaneCount; } set { if (value < 0 || value > 10) { throw new ArgumentException($"Value should range from {0} to ShadowSplitData.maximumCullingPlaneCount ({10}), but was {value}."); } m_CullingPlaneCount = value; } } public Vector4 cullingSphere { get { return m_CullingSphere; } set { m_CullingSphere = value; } } public float shadowCascadeBlendCullingFactor { get { return m_ShadowCascadeBlendCullingFactor; } set { if (value < 0f || value > 1f) { throw new ArgumentException($"Value should range from {0} to {1}, but was {value}."); } m_ShadowCascadeBlendCullingFactor = value; } } public unsafe Plane GetCullingPlane(int index) { if (index < 0 || index >= cullingPlaneCount) { throw new ArgumentException("index", $"Index should be at least {0} and less than cullingPlaneCount ({cullingPlaneCount}), but was {index}."); } fixed (byte* cullingPlanes = m_CullingPlanes) { Plane* ptr = (Plane*)cullingPlanes; return ptr[index]; } } public unsafe void SetCullingPlane(int index, Plane plane) { if (index < 0 || index >= cullingPlaneCount) { throw new ArgumentException("index", $"Index should be at least {0} and less than cullingPlaneCount ({cullingPlaneCount}), but was {index}."); } fixed (byte* cullingPlanes = m_CullingPlanes) { Plane* ptr = (Plane*)cullingPlanes; ptr[index] = plane; } } public bool Equals(ShadowSplitData other) { if (m_CullingPlaneCount != other.m_CullingPlaneCount) { return false; } for (int i = 0; i < cullingPlaneCount; i++) { if (!GetCullingPlane(i).Equals(other.GetCullingPlane(i))) { return false; } } return m_CullingSphere.Equals(other.m_CullingSphere); } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is ShadowSplitData && Equals((ShadowSplitData)obj); } public override int GetHashCode() { return (m_CullingPlaneCount * 397) ^ m_CullingSphere.GetHashCode(); } public static bool operator ==(ShadowSplitData left, ShadowSplitData right) { return left.Equals(right); } public static bool operator !=(ShadowSplitData left, ShadowSplitData right) { return !left.Equals(right); } } [Flags] public enum SortingCriteria { None = 0, SortingLayer = 1, RenderQueue = 2, BackToFront = 4, QuantizedFrontToBack = 8, OptimizeStateChanges = 0x10, CanvasOrder = 0x20, RendererPriority = 0x40, CommonOpaque = 0x3B, CommonTransparent = 0x17 } public struct SortingLayerRange : IEquatable { private short m_LowerBound; private short m_UpperBound; public short lowerBound { get { return m_LowerBound; } set { m_LowerBound = value; } } public short upperBound { get { return m_UpperBound; } set { m_UpperBound = value; } } public static SortingLayerRange all => new SortingLayerRange { m_LowerBound = short.MinValue, m_UpperBound = short.MaxValue }; public SortingLayerRange(short lowerBound, short upperBound) { m_LowerBound = lowerBound; m_UpperBound = upperBound; } public bool Equals(SortingLayerRange other) { return m_LowerBound == other.m_LowerBound && m_UpperBound == other.m_UpperBound; } public override bool Equals(object obj) { if (!(obj is SortingLayerRange)) { return false; } return Equals((SortingLayerRange)obj); } public static bool operator !=(SortingLayerRange lhs, SortingLayerRange rhs) { return !lhs.Equals(rhs); } public static bool operator ==(SortingLayerRange lhs, SortingLayerRange rhs) { return lhs.Equals(rhs); } public override int GetHashCode() { return (m_UpperBound << 16) | (m_LowerBound & 0xFFFF); } } public enum DistanceMetric { Perspective, Orthographic, CustomAxis } public struct SortingSettings : IEquatable { private Matrix4x4 m_WorldToCameraMatrix; private Vector3 m_CameraPosition; private Vector3 m_CustomAxis; private SortingCriteria m_Criteria; private DistanceMetric m_DistanceMetric; private Matrix4x4 m_PreviousVPMatrix; private Matrix4x4 m_NonJitteredVPMatrix; public Matrix4x4 worldToCameraMatrix { get { return m_WorldToCameraMatrix; } set { m_WorldToCameraMatrix = value; } } public Vector3 cameraPosition { get { return m_CameraPosition; } set { m_CameraPosition = value; } } public Vector3 customAxis { get { return m_CustomAxis; } set { m_CustomAxis = value; } } public SortingCriteria criteria { get { return m_Criteria; } set { m_Criteria = value; } } public DistanceMetric distanceMetric { get { return m_DistanceMetric; } set { m_DistanceMetric = value; } } public SortingSettings(Camera camera) { ScriptableRenderContext.InitializeSortSettings(camera, out this); m_Criteria = criteria; } public bool Equals(SortingSettings other) { return m_WorldToCameraMatrix.Equals(other.m_WorldToCameraMatrix) && m_CameraPosition.Equals(other.m_CameraPosition) && m_CustomAxis.Equals(other.m_CustomAxis) && m_Criteria == other.m_Criteria && m_DistanceMetric == other.m_DistanceMetric && m_PreviousVPMatrix.Equals(other.m_PreviousVPMatrix) && m_NonJitteredVPMatrix.Equals(other.m_NonJitteredVPMatrix); } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is SortingSettings && Equals((SortingSettings)obj); } public override int GetHashCode() { int hashCode = m_WorldToCameraMatrix.GetHashCode(); hashCode = (hashCode * 397) ^ m_CameraPosition.GetHashCode(); hashCode = (hashCode * 397) ^ m_CustomAxis.GetHashCode(); hashCode = (hashCode * 397) ^ (int)m_Criteria; hashCode = (hashCode * 397) ^ (int)m_DistanceMetric; hashCode = (hashCode * 397) ^ m_PreviousVPMatrix.GetHashCode(); return (hashCode * 397) ^ m_NonJitteredVPMatrix.GetHashCode(); } public static bool operator ==(SortingSettings left, SortingSettings right) { return left.Equals(right); } public static bool operator !=(SortingSettings left, SortingSettings right) { return !left.Equals(right); } } public struct StencilState : IEquatable { private byte m_Enabled; private byte m_ReadMask; private byte m_WriteMask; private byte m_Padding; private byte m_CompareFunctionFront; private byte m_PassOperationFront; private byte m_FailOperationFront; private byte m_ZFailOperationFront; private byte m_CompareFunctionBack; private byte m_PassOperationBack; private byte m_FailOperationBack; private byte m_ZFailOperationBack; public static StencilState defaultValue => new StencilState(enabled: true, byte.MaxValue, byte.MaxValue, CompareFunction.Always, StencilOp.Keep, StencilOp.Keep, StencilOp.Keep); public bool enabled { get { return Convert.ToBoolean(m_Enabled); } set { m_Enabled = Convert.ToByte(value); } } public byte readMask { get { return m_ReadMask; } set { m_ReadMask = value; } } public byte writeMask { get { return m_WriteMask; } set { m_WriteMask = value; } } public CompareFunction compareFunctionFront { get { return (CompareFunction)m_CompareFunctionFront; } set { m_CompareFunctionFront = (byte)value; } } public StencilOp passOperationFront { get { return (StencilOp)m_PassOperationFront; } set { m_PassOperationFront = (byte)value; } } public StencilOp failOperationFront { get { return (StencilOp)m_FailOperationFront; } set { m_FailOperationFront = (byte)value; } } public StencilOp zFailOperationFront { get { return (StencilOp)m_ZFailOperationFront; } set { m_ZFailOperationFront = (byte)value; } } public CompareFunction compareFunctionBack { get { return (CompareFunction)m_CompareFunctionBack; } set { m_CompareFunctionBack = (byte)value; } } public StencilOp passOperationBack { get { return (StencilOp)m_PassOperationBack; } set { m_PassOperationBack = (byte)value; } } public StencilOp failOperationBack { get { return (StencilOp)m_FailOperationBack; } set { m_FailOperationBack = (byte)value; } } public StencilOp zFailOperationBack { get { return (StencilOp)m_ZFailOperationBack; } set { m_ZFailOperationBack = (byte)value; } } public StencilState(bool enabled = true, byte readMask = byte.MaxValue, byte writeMask = byte.MaxValue, CompareFunction compareFunction = CompareFunction.Always, StencilOp passOperation = StencilOp.Keep, StencilOp failOperation = StencilOp.Keep, StencilOp zFailOperation = StencilOp.Keep) : this(enabled, readMask, writeMask, compareFunction, passOperation, failOperation, zFailOperation, compareFunction, passOperation, failOperation, zFailOperation) { } public StencilState(bool enabled, byte readMask, byte writeMask, CompareFunction compareFunctionFront, StencilOp passOperationFront, StencilOp failOperationFront, StencilOp zFailOperationFront, CompareFunction compareFunctionBack, StencilOp passOperationBack, StencilOp failOperationBack, StencilOp zFailOperationBack) { m_Enabled = Convert.ToByte(enabled); m_ReadMask = readMask; m_WriteMask = writeMask; m_Padding = 0; m_CompareFunctionFront = (byte)compareFunctionFront; m_PassOperationFront = (byte)passOperationFront; m_FailOperationFront = (byte)failOperationFront; m_ZFailOperationFront = (byte)zFailOperationFront; m_CompareFunctionBack = (byte)compareFunctionBack; m_PassOperationBack = (byte)passOperationBack; m_FailOperationBack = (byte)failOperationBack; m_ZFailOperationBack = (byte)zFailOperationBack; } public void SetCompareFunction(CompareFunction value) { compareFunctionFront = value; compareFunctionBack = value; } public void SetPassOperation(StencilOp value) { passOperationFront = value; passOperationBack = value; } public void SetFailOperation(StencilOp value) { failOperationFront = value; failOperationBack = value; } public void SetZFailOperation(StencilOp value) { zFailOperationFront = value; zFailOperationBack = value; } public bool Equals(StencilState other) { return m_Enabled == other.m_Enabled && m_ReadMask == other.m_ReadMask && m_WriteMask == other.m_WriteMask && m_CompareFunctionFront == other.m_CompareFunctionFront && m_PassOperationFront == other.m_PassOperationFront && m_FailOperationFront == other.m_FailOperationFront && m_ZFailOperationFront == other.m_ZFailOperationFront && m_CompareFunctionBack == other.m_CompareFunctionBack && m_PassOperationBack == other.m_PassOperationBack && m_FailOperationBack == other.m_FailOperationBack && m_ZFailOperationBack == other.m_ZFailOperationBack; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is StencilState && Equals((StencilState)obj); } public override int GetHashCode() { int hashCode = m_Enabled.GetHashCode(); hashCode = (hashCode * 397) ^ m_ReadMask.GetHashCode(); hashCode = (hashCode * 397) ^ m_WriteMask.GetHashCode(); hashCode = (hashCode * 397) ^ m_CompareFunctionFront.GetHashCode(); hashCode = (hashCode * 397) ^ m_PassOperationFront.GetHashCode(); hashCode = (hashCode * 397) ^ m_FailOperationFront.GetHashCode(); hashCode = (hashCode * 397) ^ m_ZFailOperationFront.GetHashCode(); hashCode = (hashCode * 397) ^ m_CompareFunctionBack.GetHashCode(); hashCode = (hashCode * 397) ^ m_PassOperationBack.GetHashCode(); hashCode = (hashCode * 397) ^ m_FailOperationBack.GetHashCode(); return (hashCode * 397) ^ m_ZFailOperationBack.GetHashCode(); } public static bool operator ==(StencilState left, StencilState right) { return left.Equals(right); } public static bool operator !=(StencilState left, StencilState right) { return !left.Equals(right); } } public class SupportedRenderingFeatures { [Flags] public enum ReflectionProbeModes { None = 0, Rotation = 1 } [Flags] public enum LightmapMixedBakeModes { None = 0, IndirectOnly = 1, Subtractive = 2, Shadowmask = 4 } private static SupportedRenderingFeatures s_Active = new SupportedRenderingFeatures(); public static SupportedRenderingFeatures active { get { if (s_Active == null) { s_Active = new SupportedRenderingFeatures(); } return s_Active; } set { s_Active = value; } } public ReflectionProbeModes reflectionProbeModes { get; set; } = ReflectionProbeModes.None; public LightmapMixedBakeModes defaultMixedLightingModes { get; set; } = LightmapMixedBakeModes.None; public LightmapMixedBakeModes mixedLightingModes { get; set; } = LightmapMixedBakeModes.IndirectOnly | LightmapMixedBakeModes.Subtractive | LightmapMixedBakeModes.Shadowmask; public LightmapBakeType lightmapBakeTypes { get; set; } = LightmapBakeType.Realtime | LightmapBakeType.Baked | LightmapBakeType.Mixed; public LightmapsMode lightmapsModes { get; set; } = LightmapsMode.CombinedDirectional; public bool enlightenLightmapper { get; set; } = true; public bool enlighten { get; set; } = true; public bool lightProbeProxyVolumes { get; set; } = true; public bool motionVectors { get; set; } = true; public bool receiveShadows { get; set; } = true; public bool reflectionProbes { get; set; } = true; public bool reflectionProbesBlendDistance { get; set; } = true; public bool rendererPriority { get; set; } = false; public bool rendersUIOverlay { get; set; } public bool overridesEnvironmentLighting { get; set; } = false; public bool overridesFog { get; set; } = false; public bool overridesRealtimeReflectionProbes { get; set; } = false; public bool overridesOtherLightingSettings { get; set; } = false; public bool editableMaterialRenderQueue { get; set; } = true; public bool overridesLODBias { get; set; } = false; public bool overridesMaximumLODLevel { get; set; } = false; public bool rendererProbes { get; set; } = true; public bool particleSystemInstancing { get; set; } = true; public bool autoAmbientProbeBaking { get; set; } = true; public bool autoDefaultReflectionProbeBaking { get; set; } = true; public bool overridesShadowmask { get; set; } = false; public string overrideShadowmaskMessage { get; set; } = ""; public string shadowmaskMessage { get { if (!overridesShadowmask) { return "The Shadowmask Mode used at run time can be set in the Quality Settings panel."; } return overrideShadowmaskMessage; } } [Obsolete("terrainDetailUnsupported is deprecated.")] public bool terrainDetailUnsupported { get { return true; } set { } } internal unsafe static MixedLightingMode FallbackMixedLightingMode() { MixedLightingMode result = default(MixedLightingMode); FallbackMixedLightingModeByRef(new IntPtr(&result)); return result; } [RequiredByNativeCode] internal unsafe static void FallbackMixedLightingModeByRef(IntPtr fallbackModePtr) { MixedLightingMode* ptr = (MixedLightingMode*)(void*)fallbackModePtr; if (active.defaultMixedLightingModes != LightmapMixedBakeModes.None && (active.mixedLightingModes & active.defaultMixedLightingModes) == active.defaultMixedLightingModes) { switch (active.defaultMixedLightingModes) { case LightmapMixedBakeModes.Shadowmask: *ptr = MixedLightingMode.Shadowmask; break; case LightmapMixedBakeModes.Subtractive: *ptr = MixedLightingMode.Subtractive; break; default: *ptr = MixedLightingMode.IndirectOnly; break; } } else if (IsMixedLightingModeSupported(MixedLightingMode.Shadowmask)) { *ptr = MixedLightingMode.Shadowmask; } else if (IsMixedLightingModeSupported(MixedLightingMode.Subtractive)) { *ptr = MixedLightingMode.Subtractive; } else { *ptr = MixedLightingMode.IndirectOnly; } } internal unsafe static bool IsMixedLightingModeSupported(MixedLightingMode mixedMode) { bool result = default(bool); IsMixedLightingModeSupportedByRef(mixedMode, new IntPtr(&result)); return result; } [RequiredByNativeCode] internal unsafe static void IsMixedLightingModeSupportedByRef(MixedLightingMode mixedMode, IntPtr isSupportedPtr) { bool* ptr = (bool*)(void*)isSupportedPtr; if (!IsLightmapBakeTypeSupported(LightmapBakeType.Mixed)) { *ptr = false; } else { *ptr = (mixedMode == MixedLightingMode.IndirectOnly && (active.mixedLightingModes & LightmapMixedBakeModes.IndirectOnly) == LightmapMixedBakeModes.IndirectOnly) || (mixedMode == MixedLightingMode.Subtractive && (active.mixedLightingModes & LightmapMixedBakeModes.Subtractive) == LightmapMixedBakeModes.Subtractive) || (mixedMode == MixedLightingMode.Shadowmask && (active.mixedLightingModes & LightmapMixedBakeModes.Shadowmask) == LightmapMixedBakeModes.Shadowmask); } } internal unsafe static bool IsLightmapBakeTypeSupported(LightmapBakeType bakeType) { bool result = default(bool); IsLightmapBakeTypeSupportedByRef(bakeType, new IntPtr(&result)); return result; } [RequiredByNativeCode] internal unsafe static void IsLightmapBakeTypeSupportedByRef(LightmapBakeType bakeType, IntPtr isSupportedPtr) { bool* ptr = (bool*)(void*)isSupportedPtr; if (bakeType == LightmapBakeType.Mixed && (!IsLightmapBakeTypeSupported(LightmapBakeType.Baked) || active.mixedLightingModes == LightmapMixedBakeModes.None)) { *ptr = false; return; } *ptr = (active.lightmapBakeTypes & bakeType) == bakeType; if (bakeType == LightmapBakeType.Realtime && !active.enlighten) { *ptr = false; } } internal unsafe static bool IsLightmapsModeSupported(LightmapsMode mode) { bool result = default(bool); IsLightmapsModeSupportedByRef(mode, new IntPtr(&result)); return result; } [RequiredByNativeCode] internal unsafe static void IsLightmapsModeSupportedByRef(LightmapsMode mode, IntPtr isSupportedPtr) { bool* ptr = (bool*)(void*)isSupportedPtr; *ptr = (active.lightmapsModes & mode) == mode; } internal unsafe static bool IsLightmapperSupported(int lightmapper) { bool result = default(bool); IsLightmapperSupportedByRef(lightmapper, new IntPtr(&result)); return result; } [RequiredByNativeCode] internal unsafe static void IsLightmapperSupportedByRef(int lightmapper, IntPtr isSupportedPtr) { bool* ptr = (bool*)(void*)isSupportedPtr; *ptr = lightmapper != 0 || active.enlightenLightmapper; } [RequiredByNativeCode] internal unsafe static void IsUIOverlayRenderedBySRP(IntPtr isSupportedPtr) { bool* ptr = (bool*)(void*)isSupportedPtr; *ptr = active.rendersUIOverlay; } [RequiredByNativeCode] internal unsafe static void IsAutoAmbientProbeBakingSupported(IntPtr isSupportedPtr) { bool* ptr = (bool*)(void*)isSupportedPtr; *ptr = active.autoAmbientProbeBaking; } [RequiredByNativeCode] internal unsafe static void IsAutoDefaultReflectionProbeBakingSupported(IntPtr isSupportedPtr) { bool* ptr = (bool*)(void*)isSupportedPtr; *ptr = active.autoDefaultReflectionProbeBaking; } internal unsafe static int FallbackLightmapper() { int result = default(int); FallbackLightmapperByRef(new IntPtr(&result)); return result; } [RequiredByNativeCode] internal unsafe static void FallbackLightmapperByRef(IntPtr lightmapperPtr) { int* ptr = (int*)(void*)lightmapperPtr; *ptr = 1; } } [UsedByNativeCode] public struct VisibleLight : IEquatable { private LightType m_LightType; private Color m_FinalColor; private Rect m_ScreenRect; private Matrix4x4 m_LocalToWorldMatrix; private float m_Range; private float m_SpotAngle; private int m_InstanceId; private VisibleLightFlags m_Flags; public Light light => (Light)Object.FindObjectFromInstanceID(m_InstanceId); public LightType lightType { get { return m_LightType; } set { m_LightType = value; } } public Color finalColor { get { return m_FinalColor; } set { m_FinalColor = value; } } public Rect screenRect { get { return m_ScreenRect; } set { m_ScreenRect = value; } } public Matrix4x4 localToWorldMatrix { get { return m_LocalToWorldMatrix; } set { m_LocalToWorldMatrix = value; } } public float range { get { return m_Range; } set { m_Range = value; } } public float spotAngle { get { return m_SpotAngle; } set { m_SpotAngle = value; } } public bool intersectsNearPlane { get { return (m_Flags & VisibleLightFlags.IntersectsNearPlane) > (VisibleLightFlags)0; } set { if (value) { m_Flags |= VisibleLightFlags.IntersectsNearPlane; } else { m_Flags &= ~VisibleLightFlags.IntersectsNearPlane; } } } public bool intersectsFarPlane { get { return (m_Flags & VisibleLightFlags.IntersectsFarPlane) > (VisibleLightFlags)0; } set { if (value) { m_Flags |= VisibleLightFlags.IntersectsFarPlane; } else { m_Flags &= ~VisibleLightFlags.IntersectsFarPlane; } } } public bool Equals(VisibleLight other) { return m_LightType == other.m_LightType && m_FinalColor.Equals(other.m_FinalColor) && m_ScreenRect.Equals(other.m_ScreenRect) && m_LocalToWorldMatrix.Equals(other.m_LocalToWorldMatrix) && m_Range.Equals(other.m_Range) && m_SpotAngle.Equals(other.m_SpotAngle) && m_InstanceId == other.m_InstanceId && m_Flags == other.m_Flags; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is VisibleLight && Equals((VisibleLight)obj); } public override int GetHashCode() { int num = (int)m_LightType; num = (num * 397) ^ m_FinalColor.GetHashCode(); num = (num * 397) ^ m_ScreenRect.GetHashCode(); num = (num * 397) ^ m_LocalToWorldMatrix.GetHashCode(); num = (num * 397) ^ m_Range.GetHashCode(); num = (num * 397) ^ m_SpotAngle.GetHashCode(); num = (num * 397) ^ m_InstanceId; return (num * 397) ^ (int)m_Flags; } public static bool operator ==(VisibleLight left, VisibleLight right) { return left.Equals(right); } public static bool operator !=(VisibleLight left, VisibleLight right) { return !left.Equals(right); } } [Flags] internal enum VisibleLightFlags { IntersectsNearPlane = 1, IntersectsFarPlane = 2 } [UsedByNativeCode] public struct VisibleReflectionProbe : IEquatable { private Bounds m_Bounds; private Matrix4x4 m_LocalToWorldMatrix; private Vector4 m_HdrData; private Vector3 m_Center; private float m_BlendDistance; private int m_Importance; private int m_BoxProjection; private int m_InstanceId; private int m_TextureId; public Texture texture => (Texture)Object.FindObjectFromInstanceID(m_TextureId); public ReflectionProbe reflectionProbe => (ReflectionProbe)Object.FindObjectFromInstanceID(m_InstanceId); public Bounds bounds { get { return m_Bounds; } set { m_Bounds = value; } } public Matrix4x4 localToWorldMatrix { get { return m_LocalToWorldMatrix; } set { m_LocalToWorldMatrix = value; } } public Vector4 hdrData { get { return m_HdrData; } set { m_HdrData = value; } } public Vector3 center { get { return m_Center; } set { m_Center = value; } } public float blendDistance { get { return m_BlendDistance; } set { m_BlendDistance = value; } } public int importance { get { return m_Importance; } set { m_Importance = value; } } public bool isBoxProjection { get { return Convert.ToBoolean(m_BoxProjection); } set { m_BoxProjection = Convert.ToInt32(value); } } public bool Equals(VisibleReflectionProbe other) { return m_Bounds.Equals(other.m_Bounds) && m_LocalToWorldMatrix.Equals(other.m_LocalToWorldMatrix) && m_HdrData.Equals(other.m_HdrData) && m_Center.Equals(other.m_Center) && m_BlendDistance.Equals(other.m_BlendDistance) && m_Importance == other.m_Importance && m_BoxProjection == other.m_BoxProjection && m_InstanceId == other.m_InstanceId && m_TextureId == other.m_TextureId; } public override bool Equals(object obj) { if (obj == null) { return false; } return obj is VisibleReflectionProbe && Equals((VisibleReflectionProbe)obj); } public override int GetHashCode() { int hashCode = m_Bounds.GetHashCode(); hashCode = (hashCode * 397) ^ m_LocalToWorldMatrix.GetHashCode(); hashCode = (hashCode * 397) ^ m_HdrData.GetHashCode(); hashCode = (hashCode * 397) ^ m_Center.GetHashCode(); hashCode = (hashCode * 397) ^ m_BlendDistance.GetHashCode(); hashCode = (hashCode * 397) ^ m_Importance; hashCode = (hashCode * 397) ^ m_BoxProjection; hashCode = (hashCode * 397) ^ m_InstanceId; return (hashCode * 397) ^ m_TextureId; } public static bool operator ==(VisibleReflectionProbe left, VisibleReflectionProbe right) { return left.Equals(right); } public static bool operator !=(VisibleReflectionProbe left, VisibleReflectionProbe right) { return !left.Equals(right); } } [UsedByNativeCode] [NativeHeader("Runtime/Graphics/ShaderScriptBindings.h")] [NativeHeader("Runtime/Shaders/Keywords/KeywordSpaceScriptBindings.h")] public readonly struct GlobalKeyword { internal readonly string m_Name; internal readonly uint m_Index; public string name => m_Name; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetGlobalKeywordCount")] private static extern uint GetGlobalKeywordCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetGlobalKeywordIndex")] private static extern uint GetGlobalKeywordIndex(string keyword); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::CreateGlobalKeyword")] private static extern void CreateGlobalKeyword(string keyword); public static GlobalKeyword Create(string name) { CreateGlobalKeyword(name); return new GlobalKeyword(name); } public GlobalKeyword(string name) { m_Name = name; m_Index = GetGlobalKeywordIndex(name); if (m_Index >= GetGlobalKeywordCount()) { Debug.LogErrorFormat("Global keyword {0} doesn't exist.", name); } } public override string ToString() { return m_Name; } } [UsedByNativeCode] [NativeHeader("Runtime/Graphics/ShaderScriptBindings.h")] [NativeHeader("Runtime/Shaders/Keywords/KeywordSpaceScriptBindings.h")] public readonly struct LocalKeyword : IEquatable { internal readonly LocalKeywordSpace m_SpaceInfo; internal readonly string m_Name; internal readonly uint m_Index; public string name => m_Name; public bool isOverridable => IsOverridable(this); public bool isValid => IsValid(m_SpaceInfo, m_Index); public ShaderKeywordType type => GetKeywordType(m_SpaceInfo, m_Index); [FreeFunction("keywords::IsKeywordOverridable")] private static bool IsOverridable(LocalKeyword kw) { return IsOverridable_Injected(ref kw); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetKeywordCount")] private static extern uint GetShaderKeywordCount(Shader shader); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetKeywordIndex")] private static extern uint GetShaderKeywordIndex(Shader shader, string keyword); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetKeywordCount")] private static extern uint GetComputeShaderKeywordCount(ComputeShader shader); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetKeywordIndex")] private static extern uint GetComputeShaderKeywordIndex(ComputeShader shader, string keyword); [FreeFunction("keywords::GetKeywordType")] private static ShaderKeywordType GetKeywordType(LocalKeywordSpace spaceInfo, uint keyword) { return GetKeywordType_Injected(ref spaceInfo, keyword); } [FreeFunction("keywords::IsKeywordValid")] private static bool IsValid(LocalKeywordSpace spaceInfo, uint keyword) { return IsValid_Injected(ref spaceInfo, keyword); } public LocalKeyword(Shader shader, string name) { if (shader == null) { Debug.LogError("Cannot initialize a LocalKeyword with a null Shader."); } m_SpaceInfo = shader.keywordSpace; m_Name = name; m_Index = GetShaderKeywordIndex(shader, name); if (m_Index >= GetShaderKeywordCount(shader)) { Debug.LogErrorFormat("Local keyword {0} doesn't exist in the shader.", name); } } public LocalKeyword(ComputeShader shader, string name) { if (shader == null) { Debug.LogError("Cannot initialize a LocalKeyword with a null ComputeShader."); } m_SpaceInfo = shader.keywordSpace; m_Name = name; m_Index = GetComputeShaderKeywordIndex(shader, name); if (m_Index >= GetComputeShaderKeywordCount(shader)) { Debug.LogErrorFormat("Local keyword {0} doesn't exist in the compute shader.", name); } } public override string ToString() { return m_Name; } public override bool Equals(object o) { return o is LocalKeyword rhs && Equals(rhs); } public bool Equals(LocalKeyword rhs) { return m_SpaceInfo == rhs.m_SpaceInfo && m_Index == rhs.m_Index; } public static bool operator ==(LocalKeyword lhs, LocalKeyword rhs) { return lhs.Equals(rhs); } public static bool operator !=(LocalKeyword lhs, LocalKeyword rhs) { return !(lhs == rhs); } public override int GetHashCode() { uint index = m_Index; return index.GetHashCode() ^ m_SpaceInfo.GetHashCode(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsOverridable_Injected(ref LocalKeyword kw); [MethodImpl(MethodImplOptions.InternalCall)] private static extern ShaderKeywordType GetKeywordType_Injected(ref LocalKeywordSpace spaceInfo, uint keyword); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsValid_Injected(ref LocalKeywordSpace spaceInfo, uint keyword); } [NativeHeader("Runtime/Shaders/Keywords/KeywordSpaceScriptBindings.h")] public readonly struct LocalKeywordSpace : IEquatable { private readonly IntPtr m_KeywordSpace; public LocalKeyword[] keywords => GetKeywords(); public string[] keywordNames => GetKeywordNames(); public uint keywordCount => GetKeywordCount(); [FreeFunction("keywords::GetKeywords", HasExplicitThis = true)] private LocalKeyword[] GetKeywords() { return GetKeywords_Injected(ref this); } [FreeFunction("keywords::GetKeywordNames", HasExplicitThis = true)] private string[] GetKeywordNames() { return GetKeywordNames_Injected(ref this); } [FreeFunction("keywords::GetKeywordCount", HasExplicitThis = true)] private uint GetKeywordCount() { return GetKeywordCount_Injected(ref this); } [FreeFunction("keywords::GetKeyword", HasExplicitThis = true)] private LocalKeyword GetKeyword(string name) { GetKeyword_Injected(ref this, name, out var ret); return ret; } public LocalKeyword FindKeyword(string name) { return GetKeyword(name); } public override bool Equals(object o) { return o is LocalKeywordSpace rhs && Equals(rhs); } public bool Equals(LocalKeywordSpace rhs) { return m_KeywordSpace == rhs.m_KeywordSpace; } public static bool operator ==(LocalKeywordSpace lhs, LocalKeywordSpace rhs) { return lhs.Equals(rhs); } public static bool operator !=(LocalKeywordSpace lhs, LocalKeywordSpace rhs) { return !(lhs == rhs); } public override int GetHashCode() { IntPtr keywordSpace = m_KeywordSpace; return keywordSpace.GetHashCode(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern LocalKeyword[] GetKeywords_Injected(ref LocalKeywordSpace _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern string[] GetKeywordNames_Injected(ref LocalKeywordSpace _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern uint GetKeywordCount_Injected(ref LocalKeywordSpace _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetKeyword_Injected(ref LocalKeywordSpace _unity_self, string name, out LocalKeyword ret); } [NativeHeader("Runtime/Shaders/PassIdentifier.h")] [UsedByNativeCode] public readonly struct PassIdentifier : IEquatable { internal readonly uint m_SubShaderIndex; internal readonly uint m_PassIndex; public uint SubshaderIndex => m_SubShaderIndex; public uint PassIndex => m_PassIndex; public override bool Equals(object o) { return o is PassIdentifier rhs && Equals(rhs); } public bool Equals(PassIdentifier rhs) { return m_SubShaderIndex == rhs.m_SubShaderIndex && m_PassIndex == rhs.m_PassIndex; } public static bool operator ==(PassIdentifier lhs, PassIdentifier rhs) { return lhs.Equals(rhs); } public static bool operator !=(PassIdentifier lhs, PassIdentifier rhs) { return !(lhs == rhs); } public override int GetHashCode() { uint subShaderIndex = m_SubShaderIndex; int hashCode = subShaderIndex.GetHashCode(); subShaderIndex = m_PassIndex; return hashCode ^ subShaderIndex.GetHashCode(); } } [UsedByNativeCode] public struct PlatformKeywordSet { private const int k_SizeInBits = 64; internal ulong m_Bits; private ulong ComputeKeywordMask(BuiltinShaderDefine define) { return (ulong)(1 << (int)define % 64); } public bool IsEnabled(BuiltinShaderDefine define) { return (m_Bits & ComputeKeywordMask(define)) != 0; } public void Enable(BuiltinShaderDefine define) { m_Bits |= ComputeKeywordMask(define); } public void Disable(BuiltinShaderDefine define) { m_Bits &= ~ComputeKeywordMask(define); } } [NativeHeader("Runtime/Shaders/Keywords/KeywordSpaceScriptBindings.h")] [UsedByNativeCode] public enum ShaderKeywordType { None = 0, BuiltinDefault = 2, [Obsolete("Shader keyword type BuiltinExtra is no longer used. Use BuiltinDefault instead. (UnityUpgradable) -> BuiltinDefault")] BuiltinExtra = 6, [Obsolete("Shader keyword type BuiltinAutoStripped is no longer used. Use BuiltinDefault instead. (UnityUpgradable) -> BuiltinDefault")] BuiltinAutoStripped = 10, UserDefined = 16, Plugin = 32 } [NativeHeader("Runtime/Shaders/Keywords/KeywordSpaceScriptBindings.h")] [UsedByNativeCode] [NativeHeader("Runtime/Graphics/ShaderScriptBindings.h")] public struct ShaderKeyword { internal string m_Name; internal uint m_Index; internal bool m_IsLocal; internal bool m_IsCompute; internal bool m_IsValid; public string name => m_Name; public int index => (int)m_Index; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetGlobalKeywordCount")] internal static extern uint GetGlobalKeywordCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetGlobalKeywordIndex")] internal static extern uint GetGlobalKeywordIndex(string keyword); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetKeywordCount")] internal static extern uint GetKeywordCount(Shader shader); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetKeywordIndex")] internal static extern uint GetKeywordIndex(Shader shader, string keyword); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetKeywordCount")] internal static extern uint GetComputeShaderKeywordCount(ComputeShader shader); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetKeywordIndex")] internal static extern uint GetComputeShaderKeywordIndex(ComputeShader shader, string keyword); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::CreateGlobalKeyword")] internal static extern void CreateGlobalKeyword(string keyword); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ShaderScripting::GetKeywordType")] internal static extern ShaderKeywordType GetGlobalShaderKeywordType(uint keyword); public static ShaderKeywordType GetGlobalKeywordType(ShaderKeyword index) { if (index.IsValid()) { return GetGlobalShaderKeywordType(index.m_Index); } return ShaderKeywordType.UserDefined; } public ShaderKeyword(string keywordName) { m_Name = keywordName; m_Index = GetGlobalKeywordIndex(keywordName); if (m_Index >= GetGlobalKeywordCount()) { CreateGlobalKeyword(keywordName); m_Index = GetGlobalKeywordIndex(keywordName); } m_IsValid = true; m_IsLocal = false; m_IsCompute = false; } public ShaderKeyword(Shader shader, string keywordName) { m_Name = keywordName; m_Index = GetKeywordIndex(shader, keywordName); m_IsValid = m_Index < GetKeywordCount(shader); m_IsLocal = true; m_IsCompute = false; } public ShaderKeyword(ComputeShader shader, string keywordName) { m_Name = keywordName; m_Index = GetComputeShaderKeywordIndex(shader, keywordName); m_IsValid = m_Index < GetComputeShaderKeywordCount(shader); m_IsLocal = true; m_IsCompute = true; } public static bool IsKeywordLocal(ShaderKeyword keyword) { return keyword.m_IsLocal; } public bool IsValid() { return m_IsValid; } public bool IsValid(ComputeShader shader) { return m_IsValid; } public bool IsValid(Shader shader) { return m_IsValid; } public override string ToString() { return m_Name; } [Obsolete("GetKeywordType is deprecated. Only global keywords can have a type. This method always returns ShaderKeywordType.UserDefined.")] public static ShaderKeywordType GetKeywordType(Shader shader, ShaderKeyword index) { return ShaderKeywordType.UserDefined; } [Obsolete("GetKeywordType is deprecated. Only global keywords can have a type. This method always returns ShaderKeywordType.UserDefined.")] public static ShaderKeywordType GetKeywordType(ComputeShader shader, ShaderKeyword index) { return ShaderKeywordType.UserDefined; } [Obsolete("GetGlobalKeywordName is deprecated. Use the ShaderKeyword.name property instead.")] public static string GetGlobalKeywordName(ShaderKeyword index) { return index.m_Name; } [Obsolete("GetKeywordName is deprecated. Use the ShaderKeyword.name property instead.")] public static string GetKeywordName(Shader shader, ShaderKeyword index) { return index.m_Name; } [Obsolete("GetKeywordName is deprecated. Use the ShaderKeyword.name property instead.")] public static string GetKeywordName(ComputeShader shader, ShaderKeyword index) { return index.m_Name; } [Obsolete("GetKeywordType is deprecated. Use ShaderKeyword.name instead.")] public ShaderKeywordType GetKeywordType() { return GetGlobalKeywordType(this); } [Obsolete("GetKeywordName is deprecated. Use ShaderKeyword.name instead.")] public string GetKeywordName() { return GetGlobalKeywordName(this); } [Obsolete("GetName() has been deprecated. Use ShaderKeyword.name instead.")] public string GetName() { return GetKeywordName(); } } [NativeHeader("Editor/Src/Graphics/ShaderCompilerData.h")] [UsedByNativeCode] public struct ShaderKeywordSet { private IntPtr m_KeywordState; private IntPtr m_Shader; private IntPtr m_ComputeShader; private ulong m_StateIndex; [FreeFunction("keywords::IsKeywordEnabled")] private static bool IsGlobalKeywordEnabled(ShaderKeywordSet state, uint index) { return IsGlobalKeywordEnabled_Injected(ref state, index); } [FreeFunction("keywords::IsKeywordEnabled")] private static bool IsKeywordEnabled(ShaderKeywordSet state, LocalKeywordSpace keywordSpace, uint index) { return IsKeywordEnabled_Injected(ref state, ref keywordSpace, index); } [FreeFunction("keywords::IsKeywordEnabled")] private static bool IsKeywordNameEnabled(ShaderKeywordSet state, string name) { return IsKeywordNameEnabled_Injected(ref state, name); } [FreeFunction("keywords::EnableKeyword")] private static void EnableGlobalKeyword(ShaderKeywordSet state, uint index) { EnableGlobalKeyword_Injected(ref state, index); } [FreeFunction("keywords::EnableKeyword")] private static void EnableKeywordName(ShaderKeywordSet state, string name) { EnableKeywordName_Injected(ref state, name); } [FreeFunction("keywords::DisableKeyword")] private static void DisableGlobalKeyword(ShaderKeywordSet state, uint index) { DisableGlobalKeyword_Injected(ref state, index); } [FreeFunction("keywords::DisableKeyword")] private static void DisableKeywordName(ShaderKeywordSet state, string name) { DisableKeywordName_Injected(ref state, name); } [FreeFunction("keywords::GetEnabledKeywords")] private static ShaderKeyword[] GetEnabledKeywords(ShaderKeywordSet state) { return GetEnabledKeywords_Injected(ref state); } private void CheckKeywordCompatible(ShaderKeyword keyword) { if (keyword.m_IsLocal) { if (m_Shader != IntPtr.Zero) { Assert.IsTrue(!keyword.m_IsCompute, "Trying to use a keyword that comes from a different shader."); } else { Assert.IsTrue(keyword.m_IsCompute, "Trying to use a keyword that comes from a different shader."); } } } public bool IsEnabled(ShaderKeyword keyword) { CheckKeywordCompatible(keyword); return IsKeywordNameEnabled(this, keyword.m_Name); } public bool IsEnabled(GlobalKeyword keyword) { return IsGlobalKeywordEnabled(this, keyword.m_Index); } public bool IsEnabled(LocalKeyword keyword) { return IsKeywordEnabled(this, keyword.m_SpaceInfo, keyword.m_Index); } public void Enable(ShaderKeyword keyword) { CheckKeywordCompatible(keyword); if (keyword.m_IsLocal || !keyword.IsValid()) { EnableKeywordName(this, keyword.m_Name); } else { EnableGlobalKeyword(this, keyword.m_Index); } } public void Disable(ShaderKeyword keyword) { if (keyword.m_IsLocal || !keyword.IsValid()) { DisableKeywordName(this, keyword.m_Name); } else { DisableGlobalKeyword(this, keyword.m_Index); } } public ShaderKeyword[] GetShaderKeywords() { return GetEnabledKeywords(this); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsGlobalKeywordEnabled_Injected(ref ShaderKeywordSet state, uint index); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsKeywordEnabled_Injected(ref ShaderKeywordSet state, ref LocalKeywordSpace keywordSpace, uint index); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsKeywordNameEnabled_Injected(ref ShaderKeywordSet state, string name); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EnableGlobalKeyword_Injected(ref ShaderKeywordSet state, uint index); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EnableKeywordName_Injected(ref ShaderKeywordSet state, string name); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DisableGlobalKeyword_Injected(ref ShaderKeywordSet state, uint index); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DisableKeywordName_Injected(ref ShaderKeywordSet state, string name); [MethodImpl(MethodImplOptions.InternalCall)] private static extern ShaderKeyword[] GetEnabledKeywords_Injected(ref ShaderKeywordSet state); } public enum ShaderPropertyType { Color, Vector, Float, Range, Texture, Int } [Flags] public enum ShaderPropertyFlags { None = 0, HideInInspector = 1, PerRendererData = 2, NoScaleOffset = 4, Normal = 8, HDR = 0x10, Gamma = 0x20, NonModifiableTextureData = 0x40, MainTexture = 0x80, MainColor = 0x100 } [RequireComponent(typeof(Transform))] [NativeType(Header = "Runtime/2D/Sorting/SortingGroup.h")] public sealed class SortingGroup : Behaviour { [StaticAccessor(/*Could not decode attribute arguments.*/)] internal static extern int invalidSortingGroupID { [MethodImpl(MethodImplOptions.InternalCall)] get; } public extern string sortingLayerName { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int sortingLayerID { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public extern int sortingOrder { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } internal extern int sortingGroupID { [MethodImpl(MethodImplOptions.InternalCall)] get; } internal extern int sortingGroupOrder { [MethodImpl(MethodImplOptions.InternalCall)] get; } internal extern int index { [MethodImpl(MethodImplOptions.InternalCall)] get; } [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern void UpdateAllSortingGroups(); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] internal static extern SortingGroup GetSortingGroupByIndex(int index); } } namespace UnityEngine.Rendering.RendererUtils { public enum RendererListStatus { kRendererListInvalid = -2, kRendererListProcessing, kRendererListEmpty, kRendererListPopulated } [NativeHeader("Runtime/Graphics/ScriptableRenderLoop/RendererList.h")] public struct RendererList { internal UIntPtr context; internal uint index; internal uint frame; public static readonly RendererList nullRendererList = new RendererList(UIntPtr.Zero, uint.MaxValue); public bool isValid => get_isValid_Injected(ref this); internal RendererList(UIntPtr ctx, uint indx) { context = ctx; index = indx; frame = 0u; } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern bool get_isValid_Injected(ref RendererList _unity_self); } public struct RendererListDesc { public SortingCriteria sortingCriteria; public PerObjectData rendererConfiguration; public RenderQueueRange renderQueueRange; public RenderStateBlock? stateBlock; public Material overrideMaterial; public bool excludeObjectMotionVectors; public int layerMask; public int overrideMaterialPassIndex; internal CullingResults cullingResult { get; private set; } internal Camera camera { get; set; } internal ShaderTagId passName { get; private set; } internal ShaderTagId[] passNames { get; private set; } public RendererListDesc(ShaderTagId passName, CullingResults cullingResult, Camera camera) { this = default(RendererListDesc); this.passName = passName; passNames = null; this.cullingResult = cullingResult; this.camera = camera; layerMask = -1; overrideMaterialPassIndex = 0; } public RendererListDesc(ShaderTagId[] passNames, CullingResults cullingResult, Camera camera) { this = default(RendererListDesc); this.passNames = passNames; passName = ShaderTagId.none; this.cullingResult = cullingResult; this.camera = camera; layerMask = -1; overrideMaterialPassIndex = 0; } public bool IsValid() { if (camera == null || (passName == ShaderTagId.none && (passNames == null || passNames.Length == 0))) { return false; } return true; } } internal struct RendererListParams { private static readonly ShaderTagId s_EmptyName = new ShaderTagId(""); public static readonly RendererListParams nullRendererList = default(RendererListParams); internal CullingResults cullingResult; internal DrawingSettings drawSettings; internal FilteringSettings filteringSettings; internal RenderStateBlock? stateBlock; public bool isValid { get; private set; } internal static RendererListParams Create(in RendererListDesc desc) { RendererListParams result = default(RendererListParams); if (!desc.IsValid()) { return result; } SortingSettings sortingSettings = new SortingSettings(desc.camera); sortingSettings.criteria = desc.sortingCriteria; SortingSettings sortingSettings2 = sortingSettings; DrawingSettings drawingSettings = new DrawingSettings(s_EmptyName, sortingSettings2); drawingSettings.perObjectData = desc.rendererConfiguration; DrawingSettings drawingSettings2 = drawingSettings; if (desc.passName != ShaderTagId.none) { Debug.Assert(desc.passNames == null); drawingSettings2.SetShaderPassName(0, desc.passName); } else { for (int i = 0; i < desc.passNames.Length; i++) { drawingSettings2.SetShaderPassName(i, desc.passNames[i]); } } if (desc.overrideMaterial != null) { drawingSettings2.overrideMaterial = desc.overrideMaterial; drawingSettings2.overrideMaterialPassIndex = desc.overrideMaterialPassIndex; } FilteringSettings filteringSettings = new FilteringSettings(desc.renderQueueRange, desc.layerMask); filteringSettings.excludeMotionVectorObjects = desc.excludeObjectMotionVectors; FilteringSettings filteringSettings2 = filteringSettings; result.isValid = true; result.cullingResult = desc.cullingResult; result.drawSettings = drawingSettings2; result.filteringSettings = filteringSettings2; result.stateBlock = desc.stateBlock; return result; } } } namespace UnityEngine.IO { [NativeHeader("Runtime/VirtualFileSystem/VirtualFileSystem.h")] internal enum ThreadIORestrictionMode { Allowed, TreatAsError } [NativeHeader("Runtime/VirtualFileSystem/VirtualFileSystem.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeConditional("ENABLE_PROFILER")] internal static class File { internal static ulong totalOpenCalls => GetTotalOpenCalls(); internal static ulong totalCloseCalls => GetTotalCloseCalls(); internal static ulong totalReadCalls => GetTotalReadCalls(); internal static ulong totalWriteCalls => GetTotalWriteCalls(); internal static ulong totalSeekCalls => GetTotalSeekCalls(); internal static ulong totalZeroSeekCalls => GetTotalZeroSeekCalls(); internal static ulong totalFilesOpened => GetTotalFilesOpened(); internal static ulong totalFilesClosed => GetTotalFilesClosed(); internal static ulong totalBytesRead => GetTotalBytesRead(); internal static ulong totalBytesWritten => GetTotalBytesWritten(); internal static bool recordZeroSeeks { get { return GetRecordZeroSeeks(); } set { SetRecordZeroSeeks(value); } } internal static ThreadIORestrictionMode MainThreadIORestrictionMode { get { return GetMainThreadFileIORestriction(); } set { SetMainThreadFileIORestriction(value); } } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void SetRecordZeroSeeks(bool enable); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool GetRecordZeroSeeks(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern ulong GetTotalOpenCalls(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern ulong GetTotalCloseCalls(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern ulong GetTotalReadCalls(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern ulong GetTotalWriteCalls(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern ulong GetTotalSeekCalls(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern ulong GetTotalZeroSeekCalls(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern ulong GetTotalFilesOpened(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern ulong GetTotalFilesClosed(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern ulong GetTotalBytesRead(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern ulong GetTotalBytesWritten(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetMainThreadFileIORestriction(ThreadIORestrictionMode mode); [MethodImpl(MethodImplOptions.InternalCall)] private static extern ThreadIORestrictionMode GetMainThreadFileIORestriction(); } } namespace UnityEngine.Playables { public struct FrameData { [Flags] internal enum Flags { Evaluate = 1, SeekOccured = 2, Loop = 4, Hold = 8, EffectivePlayStateDelayed = 0x10, EffectivePlayStatePlaying = 0x20 } public enum EvaluationType { Evaluate, Playback } internal ulong m_FrameID; internal double m_DeltaTime; internal float m_Weight; internal float m_EffectiveWeight; internal double m_EffectiveParentDelay; internal float m_EffectiveParentSpeed; internal float m_EffectiveSpeed; internal Flags m_Flags; internal PlayableOutput m_Output; public ulong frameId => m_FrameID; public float deltaTime => (float)m_DeltaTime; public float weight => m_Weight; public float effectiveWeight => m_EffectiveWeight; [Obsolete("effectiveParentDelay is obsolete; use a custom ScriptPlayable to implement this feature", false)] public double effectiveParentDelay => m_EffectiveParentDelay; public float effectiveParentSpeed => m_EffectiveParentSpeed; public float effectiveSpeed => m_EffectiveSpeed; public EvaluationType evaluationType => (!HasFlags(Flags.Evaluate)) ? EvaluationType.Playback : EvaluationType.Evaluate; public bool seekOccurred => HasFlags(Flags.SeekOccured); public bool timeLooped => HasFlags(Flags.Loop); public bool timeHeld => HasFlags(Flags.Hold); public PlayableOutput output => m_Output; public PlayState effectivePlayState { get { if (HasFlags(Flags.EffectivePlayStateDelayed)) { return PlayState.Delayed; } if (HasFlags(Flags.EffectivePlayStatePlaying)) { return PlayState.Playing; } return PlayState.Paused; } } private bool HasFlags(Flags flag) { return (m_Flags & flag) == flag; } } [NativeHeader("Runtime/Director/Core/FrameRate.h")] [UsedByNativeCode("FrameRate")] internal struct FrameRate : IEquatable { [Ignore] public static readonly FrameRate k_24Fps = new FrameRate(24u); [Ignore] public static readonly FrameRate k_23_976Fps = new FrameRate(24u, drop: true); [Ignore] public static readonly FrameRate k_25Fps = new FrameRate(25u); [Ignore] public static readonly FrameRate k_30Fps = new FrameRate(30u); [Ignore] public static readonly FrameRate k_29_97Fps = new FrameRate(30u, drop: true); [Ignore] public static readonly FrameRate k_50Fps = new FrameRate(50u); [Ignore] public static readonly FrameRate k_60Fps = new FrameRate(60u); [Ignore] public static readonly FrameRate k_59_94Fps = new FrameRate(60u, drop: true); [SerializeField] private int m_Rate; public bool dropFrame => m_Rate < 0; public double rate => dropFrame ? ((double)(-m_Rate) * 0.999000999000999) : ((double)m_Rate); public FrameRate(uint frameRate = 0u, bool drop = false) { m_Rate = ((!drop) ? 1 : (-1)) * (int)frameRate; } public bool IsValid() { return m_Rate != 0; } public bool Equals(FrameRate other) { return m_Rate == other.m_Rate; } public override bool Equals(object obj) { return obj is FrameRate && Equals((FrameRate)obj); } public static bool operator ==(FrameRate a, FrameRate b) { return a.Equals(b); } public static bool operator !=(FrameRate a, FrameRate b) { return !a.Equals(b); } public static bool operator <(FrameRate a, FrameRate b) { return a.rate < b.rate; } public static bool operator <=(FrameRate a, FrameRate b) { return a.rate <= b.rate; } public static bool operator >(FrameRate a, FrameRate b) { return a.rate > b.rate; } public static bool operator >=(FrameRate a, FrameRate b) { return a.rate <= b.rate; } public override int GetHashCode() { return m_Rate; } public override string ToString() { return ToString(null, null); } public string ToString(string format) { return ToString(format, null); } public string ToString(string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) { format = (dropFrame ? "F2" : "F0"); } if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture.NumberFormat; } return UnityString.Format("{0} Fps", new object[1] { rate.ToString(format, formatProvider) }); } internal static int FrameRateToInt(FrameRate framerate) { return framerate.m_Rate; } internal static FrameRate DoubleToFrameRate(double framerate) { uint num = (uint)Math.Ceiling(framerate); if (num == 0) { return new FrameRate(1u); } FrameRate result = new FrameRate(num, drop: true); if (Math.Abs(framerate - result.rate) < Math.Abs(framerate - (double)num)) { return result; } return new FrameRate(num); } } public interface INotification { PropertyName id { get; } } [RequiredByNativeCode] public interface INotificationReceiver { [RequiredByNativeCode] void OnNotify(Playable origin, INotification notification, object context); } public interface IPlayable { PlayableHandle GetHandle(); } public interface IPlayableBehaviour { [RequiredByNativeCode] void OnGraphStart(Playable playable); [RequiredByNativeCode] void OnGraphStop(Playable playable); [RequiredByNativeCode] void OnPlayableCreate(Playable playable); [RequiredByNativeCode] void OnPlayableDestroy(Playable playable); [RequiredByNativeCode] void OnBehaviourPlay(Playable playable, FrameData info); [RequiredByNativeCode] void OnBehaviourPause(Playable playable, FrameData info); [RequiredByNativeCode] void PrepareFrame(Playable playable, FrameData info); [RequiredByNativeCode] void ProcessFrame(Playable playable, FrameData info, object playerData); } public interface IPlayableOutput { PlayableOutputHandle GetHandle(); } public class Notification : INotification { public PropertyName id { get; } public Notification(string name) { id = new PropertyName(name); } } public enum DirectorWrapMode { Hold, Loop, None } [RequiredByNativeCode] public struct Playable : IPlayable, IEquatable { private PlayableHandle m_Handle; private static readonly Playable m_NullPlayable = new Playable(PlayableHandle.Null); public static Playable Null => m_NullPlayable; public static Playable Create(PlayableGraph graph, int inputCount = 0) { Playable playable = new Playable(graph.CreatePlayableHandle()); playable.SetInputCount(inputCount); return playable; } [VisibleToOtherModules] internal Playable(PlayableHandle handle) { m_Handle = handle; } public PlayableHandle GetHandle() { return m_Handle; } public bool IsPlayableOfType() where T : struct, IPlayable { return GetHandle().IsPlayableOfType(); } public Type GetPlayableType() { return GetHandle().GetPlayableType(); } public bool Equals(Playable other) { return GetHandle() == other.GetHandle(); } } public interface IPlayableAsset { double duration { get; } IEnumerable outputs { get; } Playable CreatePlayable(PlayableGraph graph, GameObject owner); } [Serializable] [RequiredByNativeCode] [AssetFileNameExtension("playable", new string[] { })] public abstract class PlayableAsset : ScriptableObject, IPlayableAsset { public virtual double duration => PlayableBinding.DefaultDuration; public virtual IEnumerable outputs => PlayableBinding.None; public abstract Playable CreatePlayable(PlayableGraph graph, GameObject owner); [RequiredByNativeCode] internal unsafe static void Internal_CreatePlayable(PlayableAsset asset, PlayableGraph graph, GameObject go, IntPtr ptr) { Playable playable = ((!(asset == null)) ? asset.CreatePlayable(graph, go) : Playable.Null); Playable* ptr2 = (Playable*)ptr.ToPointer(); *ptr2 = playable; } [RequiredByNativeCode] internal unsafe static void Internal_GetPlayableAssetDuration(PlayableAsset asset, IntPtr ptrToDouble) { double num = asset.duration; double* ptr = (double*)ptrToDouble.ToPointer(); *ptr = num; } } [Serializable] [RequiredByNativeCode] public abstract class PlayableBehaviour : IPlayableBehaviour, ICloneable { public PlayableBehaviour() { } public virtual void OnGraphStart(Playable playable) { } public virtual void OnGraphStop(Playable playable) { } public virtual void OnPlayableCreate(Playable playable) { } public virtual void OnPlayableDestroy(Playable playable) { } [Obsolete("OnBehaviourDelay is obsolete; use a custom ScriptPlayable to implement this feature", false)] public virtual void OnBehaviourDelay(Playable playable, FrameData info) { } public virtual void OnBehaviourPlay(Playable playable, FrameData info) { } public virtual void OnBehaviourPause(Playable playable, FrameData info) { } public virtual void PrepareData(Playable playable, FrameData info) { } public virtual void PrepareFrame(Playable playable, FrameData info) { } public virtual void ProcessFrame(Playable playable, FrameData info, object playerData) { } public virtual object Clone() { return MemberwiseClone(); } } [Obsolete("DataStreamType is no longer required and will be removed in a future release.", false)] public enum DataStreamType { Animation, Audio, Texture, None } public struct PlayableBinding { [VisibleToOtherModules] internal delegate PlayableOutput CreateOutputMethod(PlayableGraph graph, string name); private string m_StreamName; private Object m_SourceObject; private Type m_SourceBindingType; private CreateOutputMethod m_CreateOutputMethod; public static readonly PlayableBinding[] None = new PlayableBinding[0]; public static readonly double DefaultDuration = double.PositiveInfinity; public string streamName { get { return m_StreamName; } set { m_StreamName = value; } } public Object sourceObject { get { return m_SourceObject; } set { m_SourceObject = value; } } public Type outputTargetType => m_SourceBindingType; [Obsolete("sourceBindingType is no longer supported on PlayableBinding. Use outputBindingType instead to get the required output target type, and the appropriate binding create method (e.g. AnimationPlayableBinding.Create(name, key)) to create PlayableBindings", true)] [EditorBrowsable(EditorBrowsableState.Never)] public Type sourceBindingType { get { return m_SourceBindingType; } set { } } [Obsolete("streamType is no longer supported on PlayableBinding. Use the appropriate binding create method (e.g. AnimationPlayableBinding.Create(name, key)) instead.", true)] [EditorBrowsable(EditorBrowsableState.Never)] public DataStreamType streamType { get { return DataStreamType.None; } set { } } internal PlayableOutput CreateOutput(PlayableGraph graph) { if (m_CreateOutputMethod != null) { return m_CreateOutputMethod(graph, m_StreamName); } return PlayableOutput.Null; } [VisibleToOtherModules] internal static PlayableBinding CreateInternal(string name, Object sourceObject, Type sourceType, CreateOutputMethod createFunction) { return new PlayableBinding { m_StreamName = name, m_SourceObject = sourceObject, m_SourceBindingType = sourceType, m_CreateOutputMethod = createFunction }; } } public enum PlayableTraversalMode { Mix, Passthrough } public static class PlayableExtensions { public static bool IsNull(this U playable) where U : struct, IPlayable { return playable.GetHandle().IsNull(); } public static bool IsValid(this U playable) where U : struct, IPlayable { return playable.GetHandle().IsValid(); } public static void Destroy(this U playable) where U : struct, IPlayable { playable.GetHandle().Destroy(); } public static PlayableGraph GetGraph(this U playable) where U : struct, IPlayable { return playable.GetHandle().GetGraph(); } [Obsolete("SetPlayState() has been deprecated. Use Play(), Pause() or SetDelay() instead", false)] public static void SetPlayState(this U playable, PlayState value) where U : struct, IPlayable { if (value == PlayState.Delayed) { throw new ArgumentException("Can't set Delayed: use SetDelay() instead"); } switch (value) { case PlayState.Playing: playable.GetHandle().Play(); break; case PlayState.Paused: playable.GetHandle().Pause(); break; } } public static PlayState GetPlayState(this U playable) where U : struct, IPlayable { return playable.GetHandle().GetPlayState(); } public static void Play(this U playable) where U : struct, IPlayable { playable.GetHandle().Play(); } public static void Pause(this U playable) where U : struct, IPlayable { playable.GetHandle().Pause(); } public static void SetSpeed(this U playable, double value) where U : struct, IPlayable { playable.GetHandle().SetSpeed(value); } public static double GetSpeed(this U playable) where U : struct, IPlayable { return playable.GetHandle().GetSpeed(); } public static void SetDuration(this U playable, double value) where U : struct, IPlayable { playable.GetHandle().SetDuration(value); } public static double GetDuration(this U playable) where U : struct, IPlayable { return playable.GetHandle().GetDuration(); } public static void SetTime(this U playable, double value) where U : struct, IPlayable { playable.GetHandle().SetTime(value); } public static double GetTime(this U playable) where U : struct, IPlayable { return playable.GetHandle().GetTime(); } public static double GetPreviousTime(this U playable) where U : struct, IPlayable { return playable.GetHandle().GetPreviousTime(); } public static void SetDone(this U playable, bool value) where U : struct, IPlayable { playable.GetHandle().SetDone(value); } public static bool IsDone(this U playable) where U : struct, IPlayable { return playable.GetHandle().IsDone(); } public static void SetPropagateSetTime(this U playable, bool value) where U : struct, IPlayable { playable.GetHandle().SetPropagateSetTime(value); } public static bool GetPropagateSetTime(this U playable) where U : struct, IPlayable { return playable.GetHandle().GetPropagateSetTime(); } public static bool CanChangeInputs(this U playable) where U : struct, IPlayable { return playable.GetHandle().CanChangeInputs(); } public static bool CanSetWeights(this U playable) where U : struct, IPlayable { return playable.GetHandle().CanSetWeights(); } public static bool CanDestroy(this U playable) where U : struct, IPlayable { return playable.GetHandle().CanDestroy(); } public static void SetInputCount(this U playable, int value) where U : struct, IPlayable { playable.GetHandle().SetInputCount(value); } public static int GetInputCount(this U playable) where U : struct, IPlayable { return playable.GetHandle().GetInputCount(); } public static void SetOutputCount(this U playable, int value) where U : struct, IPlayable { playable.GetHandle().SetOutputCount(value); } public static int GetOutputCount(this U playable) where U : struct, IPlayable { return playable.GetHandle().GetOutputCount(); } public static Playable GetInput(this U playable, int inputPort) where U : struct, IPlayable { return playable.GetHandle().GetInput(inputPort); } public static Playable GetOutput(this U playable, int outputPort) where U : struct, IPlayable { return playable.GetHandle().GetOutput(outputPort); } public static void SetInputWeight(this U playable, int inputIndex, float weight) where U : struct, IPlayable { playable.GetHandle().SetInputWeight(inputIndex, weight); } public static void SetInputWeight(this U playable, V input, float weight) where U : struct, IPlayable where V : struct, IPlayable { playable.GetHandle().SetInputWeight(input.GetHandle(), weight); } public static float GetInputWeight(this U playable, int inputIndex) where U : struct, IPlayable { return playable.GetHandle().GetInputWeight(inputIndex); } public static void ConnectInput(this U playable, int inputIndex, V sourcePlayable, int sourceOutputIndex) where U : struct, IPlayable where V : struct, IPlayable { playable.ConnectInput(inputIndex, sourcePlayable, sourceOutputIndex, 0f); } public static void ConnectInput(this U playable, int inputIndex, V sourcePlayable, int sourceOutputIndex, float weight) where U : struct, IPlayable where V : struct, IPlayable { playable.GetGraph().Connect(sourcePlayable, sourceOutputIndex, playable, inputIndex); playable.SetInputWeight(inputIndex, weight); } public static void DisconnectInput(this U playable, int inputPort) where U : struct, IPlayable { playable.GetGraph().Disconnect(playable, inputPort); } public static int AddInput(this U playable, V sourcePlayable, int sourceOutputIndex, float weight = 0f) where U : struct, IPlayable where V : struct, IPlayable { int inputCount = playable.GetInputCount(); playable.SetInputCount(inputCount + 1); playable.ConnectInput(inputCount, sourcePlayable, sourceOutputIndex, weight); return inputCount; } [Obsolete("SetDelay is obsolete; use a custom ScriptPlayable to implement this feature", false)] public static void SetDelay(this U playable, double delay) where U : struct, IPlayable { playable.GetHandle().SetDelay(delay); } [Obsolete("GetDelay is obsolete; use a custom ScriptPlayable to implement this feature", false)] public static double GetDelay(this U playable) where U : struct, IPlayable { return playable.GetHandle().GetDelay(); } [Obsolete("IsDelayed is obsolete; use a custom ScriptPlayable to implement this feature", false)] public static bool IsDelayed(this U playable) where U : struct, IPlayable { return playable.GetHandle().IsDelayed(); } public static void SetLeadTime(this U playable, float value) where U : struct, IPlayable { playable.GetHandle().SetLeadTime(value); } public static float GetLeadTime(this U playable) where U : struct, IPlayable { return playable.GetHandle().GetLeadTime(); } public static PlayableTraversalMode GetTraversalMode(this U playable) where U : struct, IPlayable { return playable.GetHandle().GetTraversalMode(); } public static void SetTraversalMode(this U playable, PlayableTraversalMode mode) where U : struct, IPlayable { playable.GetHandle().SetTraversalMode(mode); } internal static DirectorWrapMode GetTimeWrapMode(this U playable) where U : struct, IPlayable { return playable.GetHandle().GetTimeWrapMode(); } internal static void SetTimeWrapMode(this U playable, DirectorWrapMode value) where U : struct, IPlayable { playable.GetHandle().SetTimeWrapMode(value); } } public enum DirectorUpdateMode { DSPClock, GameTime, UnscaledGameTime, Manual } [NativeHeader("Runtime/Export/Director/PlayableGraph.bindings.h")] [UsedByNativeCode] [NativeHeader("Runtime/Director/Core/HPlayableGraph.h")] [NativeHeader("Runtime/Director/Core/HPlayableOutput.h")] [NativeHeader("Runtime/Director/Core/HPlayable.h")] public struct PlayableGraph { internal IntPtr m_Handle; internal uint m_Version; public Playable GetRootPlayable(int index) { PlayableHandle rootPlayableInternal = GetRootPlayableInternal(index); return new Playable(rootPlayableInternal); } public bool Connect(U source, int sourceOutputPort, V destination, int destinationInputPort) where U : struct, IPlayable where V : struct, IPlayable { return ConnectInternal(source.GetHandle(), sourceOutputPort, destination.GetHandle(), destinationInputPort); } public void Disconnect(U input, int inputPort) where U : struct, IPlayable { DisconnectInternal(input.GetHandle(), inputPort); } public void DestroyPlayable(U playable) where U : struct, IPlayable { DestroyPlayableInternal(playable.GetHandle()); } public void DestroySubgraph(U playable) where U : struct, IPlayable { DestroySubgraphInternal(playable.GetHandle()); } public void DestroyOutput(U output) where U : struct, IPlayableOutput { DestroyOutputInternal(output.GetHandle()); } public int GetOutputCountByType() where T : struct, IPlayableOutput { return GetOutputCountByTypeInternal(typeof(T)); } public PlayableOutput GetOutput(int index) { if (!GetOutputInternal(index, out var handle)) { return PlayableOutput.Null; } return new PlayableOutput(handle); } public PlayableOutput GetOutputByType(int index) where T : struct, IPlayableOutput { if (!GetOutputByTypeInternal(typeof(T), index, out var handle)) { return PlayableOutput.Null; } return new PlayableOutput(handle); } public void Evaluate() { Evaluate(0f); } public static PlayableGraph Create() { return Create(null); } public static PlayableGraph Create(string name) { Create_Injected(name, out var ret); return ret; } [FreeFunction("PlayableGraphBindings::Destroy", HasExplicitThis = true, ThrowsException = true)] public void Destroy() { Destroy_Injected(ref this); } public bool IsValid() { return IsValid_Injected(ref this); } [FreeFunction("PlayableGraphBindings::IsPlaying", HasExplicitThis = true, ThrowsException = true)] public bool IsPlaying() { return IsPlaying_Injected(ref this); } [FreeFunction("PlayableGraphBindings::IsDone", HasExplicitThis = true, ThrowsException = true)] public bool IsDone() { return IsDone_Injected(ref this); } [FreeFunction("PlayableGraphBindings::Play", HasExplicitThis = true, ThrowsException = true)] public void Play() { Play_Injected(ref this); } [FreeFunction("PlayableGraphBindings::Stop", HasExplicitThis = true, ThrowsException = true)] public void Stop() { Stop_Injected(ref this); } [FreeFunction("PlayableGraphBindings::Evaluate", HasExplicitThis = true, ThrowsException = true)] public void Evaluate([System.ComponentModel.DefaultValue("0")] float deltaTime) { Evaluate_Injected(ref this, deltaTime); } [FreeFunction("PlayableGraphBindings::GetTimeUpdateMode", HasExplicitThis = true, ThrowsException = true)] public DirectorUpdateMode GetTimeUpdateMode() { return GetTimeUpdateMode_Injected(ref this); } [FreeFunction("PlayableGraphBindings::SetTimeUpdateMode", HasExplicitThis = true, ThrowsException = true)] public void SetTimeUpdateMode(DirectorUpdateMode value) { SetTimeUpdateMode_Injected(ref this, value); } [FreeFunction("PlayableGraphBindings::GetResolver", HasExplicitThis = true, ThrowsException = true)] public IExposedPropertyTable GetResolver() { return GetResolver_Injected(ref this); } [FreeFunction("PlayableGraphBindings::SetResolver", HasExplicitThis = true, ThrowsException = true)] public void SetResolver(IExposedPropertyTable value) { SetResolver_Injected(ref this, value); } [FreeFunction("PlayableGraphBindings::GetPlayableCount", HasExplicitThis = true, ThrowsException = true)] public int GetPlayableCount() { return GetPlayableCount_Injected(ref this); } [FreeFunction("PlayableGraphBindings::GetRootPlayableCount", HasExplicitThis = true, ThrowsException = true)] public int GetRootPlayableCount() { return GetRootPlayableCount_Injected(ref this); } [FreeFunction("PlayableGraphBindings::SynchronizeEvaluation", HasExplicitThis = true, ThrowsException = true)] internal void SynchronizeEvaluation(PlayableGraph playable) { SynchronizeEvaluation_Injected(ref this, ref playable); } [FreeFunction("PlayableGraphBindings::GetOutputCount", HasExplicitThis = true, ThrowsException = true)] public int GetOutputCount() { return GetOutputCount_Injected(ref this); } [FreeFunction("PlayableGraphBindings::CreatePlayableHandle", HasExplicitThis = true, ThrowsException = true)] internal PlayableHandle CreatePlayableHandle() { CreatePlayableHandle_Injected(ref this, out var ret); return ret; } [FreeFunction("PlayableGraphBindings::CreateScriptOutputInternal", HasExplicitThis = true, ThrowsException = true)] internal bool CreateScriptOutputInternal(string name, out PlayableOutputHandle handle) { return CreateScriptOutputInternal_Injected(ref this, name, out handle); } [FreeFunction("PlayableGraphBindings::GetRootPlayableInternal", HasExplicitThis = true, ThrowsException = true)] internal PlayableHandle GetRootPlayableInternal(int index) { GetRootPlayableInternal_Injected(ref this, index, out var ret); return ret; } [FreeFunction("PlayableGraphBindings::DestroyOutputInternal", HasExplicitThis = true, ThrowsException = true)] internal void DestroyOutputInternal(PlayableOutputHandle handle) { DestroyOutputInternal_Injected(ref this, ref handle); } [FreeFunction("PlayableGraphBindings::IsMatchFrameRateEnabled", HasExplicitThis = true, ThrowsException = true)] internal bool IsMatchFrameRateEnabled() { return IsMatchFrameRateEnabled_Injected(ref this); } [FreeFunction("PlayableGraphBindings::EnableMatchFrameRate", HasExplicitThis = true, ThrowsException = true)] internal void EnableMatchFrameRate(FrameRate frameRate) { EnableMatchFrameRate_Injected(ref this, ref frameRate); } [FreeFunction("PlayableGraphBindings::DisableMatchFrameRate", HasExplicitThis = true, ThrowsException = true)] internal void DisableMatchFrameRate() { DisableMatchFrameRate_Injected(ref this); } [FreeFunction("PlayableGraphBindings::GetFrameRate", HasExplicitThis = true, ThrowsException = true)] internal FrameRate GetFrameRate() { GetFrameRate_Injected(ref this, out var ret); return ret; } [FreeFunction("PlayableGraphBindings::GetOutputInternal", HasExplicitThis = true, ThrowsException = true)] private bool GetOutputInternal(int index, out PlayableOutputHandle handle) { return GetOutputInternal_Injected(ref this, index, out handle); } [FreeFunction("PlayableGraphBindings::GetOutputCountByTypeInternal", HasExplicitThis = true, ThrowsException = true)] private int GetOutputCountByTypeInternal(Type outputType) { return GetOutputCountByTypeInternal_Injected(ref this, outputType); } [FreeFunction("PlayableGraphBindings::GetOutputByTypeInternal", HasExplicitThis = true, ThrowsException = true)] private bool GetOutputByTypeInternal(Type outputType, int index, out PlayableOutputHandle handle) { return GetOutputByTypeInternal_Injected(ref this, outputType, index, out handle); } [FreeFunction("PlayableGraphBindings::ConnectInternal", HasExplicitThis = true, ThrowsException = true)] private bool ConnectInternal(PlayableHandle source, int sourceOutputPort, PlayableHandle destination, int destinationInputPort) { return ConnectInternal_Injected(ref this, ref source, sourceOutputPort, ref destination, destinationInputPort); } [FreeFunction("PlayableGraphBindings::DisconnectInternal", HasExplicitThis = true, ThrowsException = true)] private void DisconnectInternal(PlayableHandle playable, int inputPort) { DisconnectInternal_Injected(ref this, ref playable, inputPort); } [FreeFunction("PlayableGraphBindings::DestroyPlayableInternal", HasExplicitThis = true, ThrowsException = true)] private void DestroyPlayableInternal(PlayableHandle playable) { DestroyPlayableInternal_Injected(ref this, ref playable); } [FreeFunction("PlayableGraphBindings::DestroySubgraphInternal", HasExplicitThis = true, ThrowsException = true)] private void DestroySubgraphInternal(PlayableHandle playable) { DestroySubgraphInternal_Injected(ref this, ref playable); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Create_Injected(string name, out PlayableGraph ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Destroy_Injected(ref PlayableGraph _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsValid_Injected(ref PlayableGraph _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsPlaying_Injected(ref PlayableGraph _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsDone_Injected(ref PlayableGraph _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Play_Injected(ref PlayableGraph _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Stop_Injected(ref PlayableGraph _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Evaluate_Injected(ref PlayableGraph _unity_self, [System.ComponentModel.DefaultValue("0")] float deltaTime); [MethodImpl(MethodImplOptions.InternalCall)] private static extern DirectorUpdateMode GetTimeUpdateMode_Injected(ref PlayableGraph _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetTimeUpdateMode_Injected(ref PlayableGraph _unity_self, DirectorUpdateMode value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern IExposedPropertyTable GetResolver_Injected(ref PlayableGraph _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetResolver_Injected(ref PlayableGraph _unity_self, IExposedPropertyTable value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetPlayableCount_Injected(ref PlayableGraph _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetRootPlayableCount_Injected(ref PlayableGraph _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SynchronizeEvaluation_Injected(ref PlayableGraph _unity_self, ref PlayableGraph playable); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetOutputCount_Injected(ref PlayableGraph _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CreatePlayableHandle_Injected(ref PlayableGraph _unity_self, out PlayableHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool CreateScriptOutputInternal_Injected(ref PlayableGraph _unity_self, string name, out PlayableOutputHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetRootPlayableInternal_Injected(ref PlayableGraph _unity_self, int index, out PlayableHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DestroyOutputInternal_Injected(ref PlayableGraph _unity_self, ref PlayableOutputHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsMatchFrameRateEnabled_Injected(ref PlayableGraph _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void EnableMatchFrameRate_Injected(ref PlayableGraph _unity_self, ref FrameRate frameRate); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DisableMatchFrameRate_Injected(ref PlayableGraph _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetFrameRate_Injected(ref PlayableGraph _unity_self, out FrameRate ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool GetOutputInternal_Injected(ref PlayableGraph _unity_self, int index, out PlayableOutputHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetOutputCountByTypeInternal_Injected(ref PlayableGraph _unity_self, Type outputType); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool GetOutputByTypeInternal_Injected(ref PlayableGraph _unity_self, Type outputType, int index, out PlayableOutputHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool ConnectInternal_Injected(ref PlayableGraph _unity_self, ref PlayableHandle source, int sourceOutputPort, ref PlayableHandle destination, int destinationInputPort); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DisconnectInternal_Injected(ref PlayableGraph _unity_self, ref PlayableHandle playable, int inputPort); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DestroyPlayableInternal_Injected(ref PlayableGraph _unity_self, ref PlayableHandle playable); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void DestroySubgraphInternal_Injected(ref PlayableGraph _unity_self, ref PlayableHandle playable); } public enum PlayState { Paused, Playing, [Obsolete("Delayed is obsolete; use a custom ScriptPlayable to implement this feature", false)] Delayed } [NativeHeader("Runtime/Director/Core/HPlayable.h")] [NativeHeader("Runtime/Director/Core/HPlayableGraph.h")] [NativeHeader("Runtime/Export/Director/PlayableHandle.bindings.h")] [UsedByNativeCode] public struct PlayableHandle : IEquatable { internal IntPtr m_Handle; internal uint m_Version; private static readonly PlayableHandle m_Null = default(PlayableHandle); public static PlayableHandle Null => m_Null; internal T GetObject() where T : class, IPlayableBehaviour { if (!IsValid()) { return null; } object scriptInstance = GetScriptInstance(); if (scriptInstance == null) { return null; } return (T)scriptInstance; } [VisibleToOtherModules] internal bool IsPlayableOfType() { return (object)GetPlayableType() == typeof(T); } internal Playable GetInput(int inputPort) { return new Playable(GetInputHandle(inputPort)); } internal Playable GetOutput(int outputPort) { return new Playable(GetOutputHandle(outputPort)); } internal bool SetInputWeight(int inputIndex, float weight) { if (CheckInputBounds(inputIndex)) { SetInputWeightFromIndex(inputIndex, weight); return true; } return false; } internal float GetInputWeight(int inputIndex) { if (CheckInputBounds(inputIndex)) { return GetInputWeightFromIndex(inputIndex); } return 0f; } internal void Destroy() { GetGraph().DestroyPlayable(new Playable(this)); } public static bool operator ==(PlayableHandle x, PlayableHandle y) { return CompareVersion(x, y); } public static bool operator !=(PlayableHandle x, PlayableHandle y) { return !CompareVersion(x, y); } public override bool Equals(object p) { return p is PlayableHandle && Equals((PlayableHandle)p); } public bool Equals(PlayableHandle other) { return CompareVersion(this, other); } public override int GetHashCode() { return m_Handle.GetHashCode() ^ m_Version.GetHashCode(); } internal static bool CompareVersion(PlayableHandle lhs, PlayableHandle rhs) { return lhs.m_Handle == rhs.m_Handle && lhs.m_Version == rhs.m_Version; } internal bool CheckInputBounds(int inputIndex) { return CheckInputBounds(inputIndex, acceptAny: false); } internal bool CheckInputBounds(int inputIndex, bool acceptAny) { if (inputIndex == -1 && acceptAny) { return true; } if (inputIndex < 0) { throw new IndexOutOfRangeException("Index must be greater than 0"); } if (GetInputCount() <= inputIndex) { throw new IndexOutOfRangeException("inputIndex " + inputIndex + " is greater than the number of available inputs (" + GetInputCount() + ")."); } return true; } [VisibleToOtherModules] internal bool IsNull() { return IsNull_Injected(ref this); } [VisibleToOtherModules] internal bool IsValid() { return IsValid_Injected(ref this); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::GetPlayableType", HasExplicitThis = true, ThrowsException = true)] internal Type GetPlayableType() { return GetPlayableType_Injected(ref this); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::GetJobType", HasExplicitThis = true, ThrowsException = true)] internal Type GetJobType() { return GetJobType_Injected(ref this); } [FreeFunction("PlayableHandleBindings::SetScriptInstance", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal void SetScriptInstance(object scriptInstance) { SetScriptInstance_Injected(ref this, scriptInstance); } [FreeFunction("PlayableHandleBindings::CanChangeInputs", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal bool CanChangeInputs() { return CanChangeInputs_Injected(ref this); } [FreeFunction("PlayableHandleBindings::CanSetWeights", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal bool CanSetWeights() { return CanSetWeights_Injected(ref this); } [FreeFunction("PlayableHandleBindings::CanDestroy", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal bool CanDestroy() { return CanDestroy_Injected(ref this); } [FreeFunction("PlayableHandleBindings::GetPlayState", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal PlayState GetPlayState() { return GetPlayState_Injected(ref this); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::Play", HasExplicitThis = true, ThrowsException = true)] internal void Play() { Play_Injected(ref this); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::Pause", HasExplicitThis = true, ThrowsException = true)] internal void Pause() { Pause_Injected(ref this); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::GetSpeed", HasExplicitThis = true, ThrowsException = true)] internal double GetSpeed() { return GetSpeed_Injected(ref this); } [FreeFunction("PlayableHandleBindings::SetSpeed", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal void SetSpeed(double value) { SetSpeed_Injected(ref this, value); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::GetTime", HasExplicitThis = true, ThrowsException = true)] internal double GetTime() { return GetTime_Injected(ref this); } [FreeFunction("PlayableHandleBindings::SetTime", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal void SetTime(double value) { SetTime_Injected(ref this, value); } [FreeFunction("PlayableHandleBindings::IsDone", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal bool IsDone() { return IsDone_Injected(ref this); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::SetDone", HasExplicitThis = true, ThrowsException = true)] internal void SetDone(bool value) { SetDone_Injected(ref this, value); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::GetDuration", HasExplicitThis = true, ThrowsException = true)] internal double GetDuration() { return GetDuration_Injected(ref this); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::SetDuration", HasExplicitThis = true, ThrowsException = true)] internal void SetDuration(double value) { SetDuration_Injected(ref this, value); } [FreeFunction("PlayableHandleBindings::GetPropagateSetTime", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal bool GetPropagateSetTime() { return GetPropagateSetTime_Injected(ref this); } [FreeFunction("PlayableHandleBindings::SetPropagateSetTime", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal void SetPropagateSetTime(bool value) { SetPropagateSetTime_Injected(ref this, value); } [FreeFunction("PlayableHandleBindings::GetGraph", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal PlayableGraph GetGraph() { GetGraph_Injected(ref this, out var ret); return ret; } [FreeFunction("PlayableHandleBindings::GetInputCount", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal int GetInputCount() { return GetInputCount_Injected(ref this); } [FreeFunction("PlayableHandleBindings::SetInputCount", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal void SetInputCount(int value) { SetInputCount_Injected(ref this, value); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::GetOutputCount", HasExplicitThis = true, ThrowsException = true)] internal int GetOutputCount() { return GetOutputCount_Injected(ref this); } [FreeFunction("PlayableHandleBindings::SetOutputCount", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal void SetOutputCount(int value) { SetOutputCount_Injected(ref this, value); } [FreeFunction("PlayableHandleBindings::SetInputWeight", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal void SetInputWeight(PlayableHandle input, float weight) { SetInputWeight_Injected(ref this, ref input, weight); } [FreeFunction("PlayableHandleBindings::SetDelay", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal void SetDelay(double delay) { SetDelay_Injected(ref this, delay); } [FreeFunction("PlayableHandleBindings::GetDelay", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal double GetDelay() { return GetDelay_Injected(ref this); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::IsDelayed", HasExplicitThis = true, ThrowsException = true)] internal bool IsDelayed() { return IsDelayed_Injected(ref this); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::GetPreviousTime", HasExplicitThis = true, ThrowsException = true)] internal double GetPreviousTime() { return GetPreviousTime_Injected(ref this); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::SetLeadTime", HasExplicitThis = true, ThrowsException = true)] internal void SetLeadTime(float value) { SetLeadTime_Injected(ref this, value); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::GetLeadTime", HasExplicitThis = true, ThrowsException = true)] internal float GetLeadTime() { return GetLeadTime_Injected(ref this); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::GetTraversalMode", HasExplicitThis = true, ThrowsException = true)] internal PlayableTraversalMode GetTraversalMode() { return GetTraversalMode_Injected(ref this); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::SetTraversalMode", HasExplicitThis = true, ThrowsException = true)] internal void SetTraversalMode(PlayableTraversalMode mode) { SetTraversalMode_Injected(ref this, mode); } [VisibleToOtherModules] [FreeFunction("PlayableHandleBindings::GetJobData", HasExplicitThis = true, ThrowsException = true)] internal IntPtr GetJobData() { return GetJobData_Injected(ref this); } [FreeFunction("PlayableHandleBindings::GetTimeWrapMode", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal DirectorWrapMode GetTimeWrapMode() { return GetTimeWrapMode_Injected(ref this); } [FreeFunction("PlayableHandleBindings::SetTimeWrapMode", HasExplicitThis = true, ThrowsException = true)] [VisibleToOtherModules] internal void SetTimeWrapMode(DirectorWrapMode mode) { SetTimeWrapMode_Injected(ref this, mode); } [FreeFunction("PlayableHandleBindings::GetScriptInstance", HasExplicitThis = true, ThrowsException = true)] private object GetScriptInstance() { return GetScriptInstance_Injected(ref this); } [FreeFunction("PlayableHandleBindings::GetInputHandle", HasExplicitThis = true, ThrowsException = true)] private PlayableHandle GetInputHandle(int index) { GetInputHandle_Injected(ref this, index, out var ret); return ret; } [FreeFunction("PlayableHandleBindings::GetOutputHandle", HasExplicitThis = true, ThrowsException = true)] private PlayableHandle GetOutputHandle(int index) { GetOutputHandle_Injected(ref this, index, out var ret); return ret; } [FreeFunction("PlayableHandleBindings::SetInputWeightFromIndex", HasExplicitThis = true, ThrowsException = true)] private void SetInputWeightFromIndex(int index, float weight) { SetInputWeightFromIndex_Injected(ref this, index, weight); } [FreeFunction("PlayableHandleBindings::GetInputWeightFromIndex", HasExplicitThis = true, ThrowsException = true)] private float GetInputWeightFromIndex(int index) { return GetInputWeightFromIndex_Injected(ref this, index); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsNull_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsValid_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Type GetPlayableType_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Type GetJobType_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetScriptInstance_Injected(ref PlayableHandle _unity_self, object scriptInstance); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool CanChangeInputs_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool CanSetWeights_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool CanDestroy_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern PlayState GetPlayState_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Play_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Pause_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern double GetSpeed_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetSpeed_Injected(ref PlayableHandle _unity_self, double value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern double GetTime_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetTime_Injected(ref PlayableHandle _unity_self, double value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsDone_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetDone_Injected(ref PlayableHandle _unity_self, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern double GetDuration_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetDuration_Injected(ref PlayableHandle _unity_self, double value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool GetPropagateSetTime_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetPropagateSetTime_Injected(ref PlayableHandle _unity_self, bool value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetGraph_Injected(ref PlayableHandle _unity_self, out PlayableGraph ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetInputCount_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetInputCount_Injected(ref PlayableHandle _unity_self, int value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetOutputCount_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetOutputCount_Injected(ref PlayableHandle _unity_self, int value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetInputWeight_Injected(ref PlayableHandle _unity_self, ref PlayableHandle input, float weight); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetDelay_Injected(ref PlayableHandle _unity_self, double delay); [MethodImpl(MethodImplOptions.InternalCall)] private static extern double GetDelay_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsDelayed_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern double GetPreviousTime_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetLeadTime_Injected(ref PlayableHandle _unity_self, float value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern float GetLeadTime_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern PlayableTraversalMode GetTraversalMode_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetTraversalMode_Injected(ref PlayableHandle _unity_self, PlayableTraversalMode mode); [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr GetJobData_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern DirectorWrapMode GetTimeWrapMode_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetTimeWrapMode_Injected(ref PlayableHandle _unity_self, DirectorWrapMode mode); [MethodImpl(MethodImplOptions.InternalCall)] private static extern object GetScriptInstance_Injected(ref PlayableHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetInputHandle_Injected(ref PlayableHandle _unity_self, int index, out PlayableHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetOutputHandle_Injected(ref PlayableHandle _unity_self, int index, out PlayableHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetInputWeightFromIndex_Injected(ref PlayableHandle _unity_self, int index, float weight); [MethodImpl(MethodImplOptions.InternalCall)] private static extern float GetInputWeightFromIndex_Injected(ref PlayableHandle _unity_self, int index); } [RequiredByNativeCode] public struct PlayableOutput : IPlayableOutput, IEquatable { private PlayableOutputHandle m_Handle; private static readonly PlayableOutput m_NullPlayableOutput = new PlayableOutput(PlayableOutputHandle.Null); public static PlayableOutput Null => m_NullPlayableOutput; [VisibleToOtherModules] internal PlayableOutput(PlayableOutputHandle handle) { m_Handle = handle; } public PlayableOutputHandle GetHandle() { return m_Handle; } public bool IsPlayableOutputOfType() where T : struct, IPlayableOutput { return GetHandle().IsPlayableOutputOfType(); } public Type GetPlayableOutputType() { return GetHandle().GetPlayableOutputType(); } public bool Equals(PlayableOutput other) { return GetHandle() == other.GetHandle(); } } public static class PlayableOutputExtensions { public static bool IsOutputNull(this U output) where U : struct, IPlayableOutput { return output.GetHandle().IsNull(); } public static bool IsOutputValid(this U output) where U : struct, IPlayableOutput { return output.GetHandle().IsValid(); } public static Object GetReferenceObject(this U output) where U : struct, IPlayableOutput { return output.GetHandle().GetReferenceObject(); } public static void SetReferenceObject(this U output, Object value) where U : struct, IPlayableOutput { output.GetHandle().SetReferenceObject(value); } public static Object GetUserData(this U output) where U : struct, IPlayableOutput { return output.GetHandle().GetUserData(); } public static void SetUserData(this U output, Object value) where U : struct, IPlayableOutput { output.GetHandle().SetUserData(value); } public static Playable GetSourcePlayable(this U output) where U : struct, IPlayableOutput { return new Playable(output.GetHandle().GetSourcePlayable()); } public static void SetSourcePlayable(this U output, V value) where U : struct, IPlayableOutput where V : struct, IPlayable { output.GetHandle().SetSourcePlayable(value.GetHandle(), output.GetSourceOutputPort()); } public static void SetSourcePlayable(this U output, V value, int port) where U : struct, IPlayableOutput where V : struct, IPlayable { output.GetHandle().SetSourcePlayable(value.GetHandle(), port); } public static int GetSourceOutputPort(this U output) where U : struct, IPlayableOutput { return output.GetHandle().GetSourceOutputPort(); } public static float GetWeight(this U output) where U : struct, IPlayableOutput { return output.GetHandle().GetWeight(); } public static void SetWeight(this U output, float value) where U : struct, IPlayableOutput { output.GetHandle().SetWeight(value); } public static void PushNotification(this U output, Playable origin, INotification notification, object context = null) where U : struct, IPlayableOutput { output.GetHandle().PushNotification(origin.GetHandle(), notification, context); } public static INotificationReceiver[] GetNotificationReceivers(this U output) where U : struct, IPlayableOutput { return output.GetHandle().GetNotificationReceivers(); } public static void AddNotificationReceiver(this U output, INotificationReceiver receiver) where U : struct, IPlayableOutput { output.GetHandle().AddNotificationReceiver(receiver); } public static void RemoveNotificationReceiver(this U output, INotificationReceiver receiver) where U : struct, IPlayableOutput { output.GetHandle().RemoveNotificationReceiver(receiver); } [Obsolete("Method GetSourceInputPort has been renamed to GetSourceOutputPort (UnityUpgradable) -> GetSourceOutputPort(*)", false)] public static int GetSourceInputPort(this U output) where U : struct, IPlayableOutput { return output.GetHandle().GetSourceOutputPort(); } [Obsolete("Method SetSourceInputPort has been deprecated. Use SetSourcePlayable(Playable, Port) instead.", false)] public static void SetSourceInputPort(this U output, int value) where U : struct, IPlayableOutput { output.SetSourcePlayable(output.GetSourcePlayable(), value); } [Obsolete("Method SetSourceOutputPort has been deprecated. Use SetSourcePlayable(Playable, Port) instead.", false)] public static void SetSourceOutputPort(this U output, int value) where U : struct, IPlayableOutput { output.SetSourcePlayable(output.GetSourcePlayable(), value); } } [NativeHeader("Runtime/Director/Core/HPlayableOutput.h")] [NativeHeader("Runtime/Director/Core/HPlayable.h")] [NativeHeader("Runtime/Export/Director/PlayableOutputHandle.bindings.h")] [UsedByNativeCode] public struct PlayableOutputHandle : IEquatable { internal IntPtr m_Handle; internal uint m_Version; private static readonly PlayableOutputHandle m_Null = default(PlayableOutputHandle); public static PlayableOutputHandle Null => m_Null; [VisibleToOtherModules] internal bool IsPlayableOutputOfType() { return (object)GetPlayableOutputType() == typeof(T); } public override int GetHashCode() { return m_Handle.GetHashCode() ^ m_Version.GetHashCode(); } public static bool operator ==(PlayableOutputHandle lhs, PlayableOutputHandle rhs) { return CompareVersion(lhs, rhs); } public static bool operator !=(PlayableOutputHandle lhs, PlayableOutputHandle rhs) { return !CompareVersion(lhs, rhs); } public override bool Equals(object p) { return p is PlayableOutputHandle && Equals((PlayableOutputHandle)p); } public bool Equals(PlayableOutputHandle other) { return CompareVersion(this, other); } internal static bool CompareVersion(PlayableOutputHandle lhs, PlayableOutputHandle rhs) { return lhs.m_Handle == rhs.m_Handle && lhs.m_Version == rhs.m_Version; } [VisibleToOtherModules] internal bool IsNull() { return IsNull_Injected(ref this); } [VisibleToOtherModules] internal bool IsValid() { return IsValid_Injected(ref this); } [FreeFunction("PlayableOutputHandleBindings::GetPlayableOutputType", HasExplicitThis = true, ThrowsException = true)] internal Type GetPlayableOutputType() { return GetPlayableOutputType_Injected(ref this); } [FreeFunction("PlayableOutputHandleBindings::GetReferenceObject", HasExplicitThis = true, ThrowsException = true)] internal Object GetReferenceObject() { return GetReferenceObject_Injected(ref this); } [FreeFunction("PlayableOutputHandleBindings::SetReferenceObject", HasExplicitThis = true, ThrowsException = true)] internal void SetReferenceObject(Object target) { SetReferenceObject_Injected(ref this, target); } [FreeFunction("PlayableOutputHandleBindings::GetUserData", HasExplicitThis = true, ThrowsException = true)] internal Object GetUserData() { return GetUserData_Injected(ref this); } [FreeFunction("PlayableOutputHandleBindings::SetUserData", HasExplicitThis = true, ThrowsException = true)] internal void SetUserData([Writable] Object target) { SetUserData_Injected(ref this, target); } [FreeFunction("PlayableOutputHandleBindings::GetSourcePlayable", HasExplicitThis = true, ThrowsException = true)] internal PlayableHandle GetSourcePlayable() { GetSourcePlayable_Injected(ref this, out var ret); return ret; } [FreeFunction("PlayableOutputHandleBindings::SetSourcePlayable", HasExplicitThis = true, ThrowsException = true)] internal void SetSourcePlayable(PlayableHandle target, int port) { SetSourcePlayable_Injected(ref this, ref target, port); } [FreeFunction("PlayableOutputHandleBindings::GetSourceOutputPort", HasExplicitThis = true, ThrowsException = true)] internal int GetSourceOutputPort() { return GetSourceOutputPort_Injected(ref this); } [FreeFunction("PlayableOutputHandleBindings::GetWeight", HasExplicitThis = true, ThrowsException = true)] internal float GetWeight() { return GetWeight_Injected(ref this); } [FreeFunction("PlayableOutputHandleBindings::SetWeight", HasExplicitThis = true, ThrowsException = true)] internal void SetWeight(float weight) { SetWeight_Injected(ref this, weight); } [FreeFunction("PlayableOutputHandleBindings::PushNotification", HasExplicitThis = true, ThrowsException = true)] internal void PushNotification(PlayableHandle origin, INotification notification, object context) { PushNotification_Injected(ref this, ref origin, notification, context); } [FreeFunction("PlayableOutputHandleBindings::GetNotificationReceivers", HasExplicitThis = true, ThrowsException = true)] internal INotificationReceiver[] GetNotificationReceivers() { return GetNotificationReceivers_Injected(ref this); } [FreeFunction("PlayableOutputHandleBindings::AddNotificationReceiver", HasExplicitThis = true, ThrowsException = true)] internal void AddNotificationReceiver(INotificationReceiver receiver) { AddNotificationReceiver_Injected(ref this, receiver); } [FreeFunction("PlayableOutputHandleBindings::RemoveNotificationReceiver", HasExplicitThis = true, ThrowsException = true)] internal void RemoveNotificationReceiver(INotificationReceiver receiver) { RemoveNotificationReceiver_Injected(ref this, receiver); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsNull_Injected(ref PlayableOutputHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsValid_Injected(ref PlayableOutputHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Type GetPlayableOutputType_Injected(ref PlayableOutputHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Object GetReferenceObject_Injected(ref PlayableOutputHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetReferenceObject_Injected(ref PlayableOutputHandle _unity_self, Object target); [MethodImpl(MethodImplOptions.InternalCall)] private static extern Object GetUserData_Injected(ref PlayableOutputHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetUserData_Injected(ref PlayableOutputHandle _unity_self, [Writable] Object target); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetSourcePlayable_Injected(ref PlayableOutputHandle _unity_self, out PlayableHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetSourcePlayable_Injected(ref PlayableOutputHandle _unity_self, ref PlayableHandle target, int port); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetSourceOutputPort_Injected(ref PlayableOutputHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern float GetWeight_Injected(ref PlayableOutputHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetWeight_Injected(ref PlayableOutputHandle _unity_self, float weight); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void PushNotification_Injected(ref PlayableOutputHandle _unity_self, ref PlayableHandle origin, INotification notification, object context); [MethodImpl(MethodImplOptions.InternalCall)] private static extern INotificationReceiver[] GetNotificationReceivers_Injected(ref PlayableOutputHandle _unity_self); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void AddNotificationReceiver_Injected(ref PlayableOutputHandle _unity_self, INotificationReceiver receiver); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void RemoveNotificationReceiver_Injected(ref PlayableOutputHandle _unity_self, INotificationReceiver receiver); } public struct ScriptPlayable : IPlayable, IEquatable> where T : class, IPlayableBehaviour, new() { private PlayableHandle m_Handle; private static readonly ScriptPlayable m_NullPlayable = new ScriptPlayable(PlayableHandle.Null); public static ScriptPlayable Null => m_NullPlayable; public static ScriptPlayable Create(PlayableGraph graph, int inputCount = 0) { PlayableHandle handle = CreateHandle(graph, null, inputCount); return new ScriptPlayable(handle); } public static ScriptPlayable Create(PlayableGraph graph, T template, int inputCount = 0) { PlayableHandle handle = CreateHandle(graph, template, inputCount); return new ScriptPlayable(handle); } private static PlayableHandle CreateHandle(PlayableGraph graph, T template, int inputCount) { object obj = null; obj = ((template != null) ? CloneScriptInstance(template) : CreateScriptInstance()); if (obj == null) { Debug.LogError("Could not create a ScriptPlayable of Type " + typeof(T)); return PlayableHandle.Null; } PlayableHandle result = graph.CreatePlayableHandle(); if (!result.IsValid()) { return PlayableHandle.Null; } result.SetInputCount(inputCount); result.SetScriptInstance(obj); return result; } private static object CreateScriptInstance() { IPlayableBehaviour playableBehaviour = null; if (typeof(ScriptableObject).IsAssignableFrom(typeof(T))) { return ScriptableObject.CreateInstance(typeof(T)) as T; } return new T(); } private static object CloneScriptInstance(IPlayableBehaviour source) { Object obj = source as Object; if (obj != null) { return CloneScriptInstanceFromEngineObject(obj); } if (source is ICloneable source2) { return CloneScriptInstanceFromIClonable(source2); } return null; } private static object CloneScriptInstanceFromEngineObject(Object source) { Object obj = Object.Instantiate(source); if (obj != null) { obj.hideFlags |= HideFlags.DontSave; } return obj; } private static object CloneScriptInstanceFromIClonable(ICloneable source) { return source.Clone(); } internal ScriptPlayable(PlayableHandle handle) { if (handle.IsValid() && !typeof(T).IsAssignableFrom(handle.GetPlayableType())) { throw new InvalidCastException($"Incompatible handle: Trying to assign a playable data of type `{handle.GetPlayableType()}` that is not compatible with the PlayableBehaviour of type `{typeof(T)}`."); } m_Handle = handle; } public PlayableHandle GetHandle() { return m_Handle; } public T GetBehaviour() { return m_Handle.GetObject(); } public static implicit operator Playable(ScriptPlayable playable) { return new Playable(playable.GetHandle()); } public static explicit operator ScriptPlayable(Playable playable) { return new ScriptPlayable(playable.GetHandle()); } public bool Equals(ScriptPlayable other) { return GetHandle() == other.GetHandle(); } } public static class ScriptPlayableBinding { public static PlayableBinding Create(string name, Object key, Type type) { return PlayableBinding.CreateInternal(name, key, type, CreateScriptOutput); } private static PlayableOutput CreateScriptOutput(PlayableGraph graph, string name) { return ScriptPlayableOutput.Create(graph, name); } } [RequiredByNativeCode] public struct ScriptPlayableOutput : IPlayableOutput { private PlayableOutputHandle m_Handle; public static ScriptPlayableOutput Null => new ScriptPlayableOutput(PlayableOutputHandle.Null); public static ScriptPlayableOutput Create(PlayableGraph graph, string name) { if (!graph.CreateScriptOutputInternal(name, out var handle)) { return Null; } return new ScriptPlayableOutput(handle); } internal ScriptPlayableOutput(PlayableOutputHandle handle) { if (handle.IsValid() && !handle.IsPlayableOutputOfType()) { throw new InvalidCastException("Can't set handle: the playable is not a ScriptPlayableOutput."); } m_Handle = handle; } public PlayableOutputHandle GetHandle() { return m_Handle; } public static implicit operator PlayableOutput(ScriptPlayableOutput output) { return new PlayableOutput(output.GetHandle()); } public static explicit operator ScriptPlayableOutput(PlayableOutput output) { return new ScriptPlayableOutput(output.GetHandle()); } } } namespace UnityEngine.Diagnostics { public enum ForcedCrashCategory { AccessViolation, FatalError, Abort, PureVirtualFunction, MonoAbort } [NativeHeader("Runtime/Export/Diagnostics/DiagnosticsUtils.bindings.h")] public static class Utils { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("DiagnosticsUtils_Bindings::ForceCrash", ThrowsException = true)] public static extern void ForceCrash(ForcedCrashCategory crashCategory); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("DiagnosticsUtils_Bindings::NativeAssert")] public static extern void NativeAssert(string message); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("DiagnosticsUtils_Bindings::NativeError")] public static extern void NativeError(string message); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("DiagnosticsUtils_Bindings::NativeWarning")] public static extern void NativeWarning(string message); } public static class PlayerConnection { [Obsolete("Use UnityEngine.Networking.PlayerConnection.PlayerConnection.instance.isConnected instead.")] public static bool connected => UnityEngine.Networking.PlayerConnection.PlayerConnection.instance.isConnected; [Obsolete("PlayerConnection.SendFile is no longer supported.", true)] [EditorBrowsable(EditorBrowsableState.Never)] public static void SendFile(string remoteFilePath, byte[] data) { } } } namespace UnityEngine.Device { public static class Application { public static string absoluteURL => UnityEngine.Application.absoluteURL; public static ThreadPriority backgroundLoadingPriority { get { return UnityEngine.Application.backgroundLoadingPriority; } set { UnityEngine.Application.backgroundLoadingPriority = value; } } public static string buildGUID => UnityEngine.Application.buildGUID; public static string cloudProjectId => UnityEngine.Application.cloudProjectId; public static string companyName => UnityEngine.Application.companyName; public static string consoleLogPath => UnityEngine.Application.consoleLogPath; public static string dataPath => UnityEngine.Application.dataPath; public static bool genuine => UnityEngine.Application.genuine; public static bool genuineCheckAvailable => UnityEngine.Application.genuineCheckAvailable; public static string identifier => UnityEngine.Application.identifier; public static string installerName => UnityEngine.Application.installerName; public static ApplicationInstallMode installMode => UnityEngine.Application.installMode; public static NetworkReachability internetReachability => UnityEngine.Application.internetReachability; public static bool isBatchMode => UnityEngine.Application.isBatchMode; public static bool isConsolePlatform => UnityEngine.Application.isConsolePlatform; public static bool isEditor => UnityEngine.Application.isEditor; public static bool isFocused => UnityEngine.Application.isFocused; public static bool isMobilePlatform => UnityEngine.Application.isMobilePlatform; public static bool isPlaying => UnityEngine.Application.isPlaying; public static string persistentDataPath => UnityEngine.Application.persistentDataPath; public static RuntimePlatform platform => UnityEngine.Application.platform; public static string productName => UnityEngine.Application.productName; public static bool runInBackground { get { return UnityEngine.Application.runInBackground; } set { UnityEngine.Application.runInBackground = value; } } public static ApplicationSandboxType sandboxType => UnityEngine.Application.sandboxType; public static string streamingAssetsPath => UnityEngine.Application.streamingAssetsPath; public static SystemLanguage systemLanguage => UnityEngine.Application.systemLanguage; public static int targetFrameRate { get { return UnityEngine.Application.targetFrameRate; } set { UnityEngine.Application.targetFrameRate = value; } } public static string temporaryCachePath => UnityEngine.Application.temporaryCachePath; public static string unityVersion => UnityEngine.Application.unityVersion; public static string version => UnityEngine.Application.version; public static event Action deepLinkActivated { add { UnityEngine.Application.deepLinkActivated += value; } remove { UnityEngine.Application.deepLinkActivated -= value; } } public static event Action focusChanged { add { UnityEngine.Application.focusChanged += value; } remove { UnityEngine.Application.focusChanged -= value; } } public static event UnityEngine.Application.LogCallback logMessageReceived { add { UnityEngine.Application.logMessageReceived += value; } remove { UnityEngine.Application.logMessageReceived -= value; } } public static event UnityEngine.Application.LogCallback logMessageReceivedThreaded { add { UnityEngine.Application.logMessageReceivedThreaded += value; } remove { UnityEngine.Application.logMessageReceivedThreaded -= value; } } public static event UnityEngine.Application.LowMemoryCallback lowMemory { add { UnityEngine.Application.lowMemory += value; } remove { UnityEngine.Application.lowMemory -= value; } } public static event UnityAction onBeforeRender { add { UnityEngine.Application.onBeforeRender += value; } remove { UnityEngine.Application.onBeforeRender -= value; } } public static event Action quitting { add { UnityEngine.Application.quitting += value; } remove { UnityEngine.Application.quitting -= value; } } public static event Func wantsToQuit { add { UnityEngine.Application.wantsToQuit += value; } remove { UnityEngine.Application.wantsToQuit -= value; } } public static event Action unloading { add { UnityEngine.Application.unloading += value; } remove { UnityEngine.Application.unloading -= value; } } public static bool CanStreamedLevelBeLoaded(int levelIndex) { return UnityEngine.Application.CanStreamedLevelBeLoaded(levelIndex); } public static bool CanStreamedLevelBeLoaded(string levelName) { return UnityEngine.Application.CanStreamedLevelBeLoaded(levelName); } public static string[] GetBuildTags() { return UnityEngine.Application.GetBuildTags(); } public static StackTraceLogType GetStackTraceLogType(LogType logType) { return UnityEngine.Application.GetStackTraceLogType(logType); } public static bool HasProLicense() { return UnityEngine.Application.HasProLicense(); } public static bool HasUserAuthorization(UserAuthorization mode) { return UnityEngine.Application.HasUserAuthorization(mode); } public static bool IsPlaying(Object obj) { return UnityEngine.Application.IsPlaying(obj); } public static void OpenURL(string url) { UnityEngine.Application.OpenURL(url); } public static void Quit() { UnityEngine.Application.Quit(); } public static void Quit(int exitCode) { UnityEngine.Application.Quit(exitCode); } public static bool RequestAdvertisingIdentifierAsync(UnityEngine.Application.AdvertisingIdentifierCallback delegateMethod) { return UnityEngine.Application.RequestAdvertisingIdentifierAsync(delegateMethod); } public static AsyncOperation RequestUserAuthorization(UserAuthorization mode) { return UnityEngine.Application.RequestUserAuthorization(mode); } public static void SetBuildTags(string[] buildTags) { UnityEngine.Application.SetBuildTags(buildTags); } public static void SetStackTraceLogType(LogType logType, StackTraceLogType stackTraceType) { UnityEngine.Application.SetStackTraceLogType(logType, stackTraceType); } public static void Unload() { UnityEngine.Application.Unload(); } } public static class Screen { public static float brightness { get { return UnityEngine.Screen.brightness; } set { UnityEngine.Screen.brightness = value; } } public static bool autorotateToLandscapeLeft { get { return UnityEngine.Screen.autorotateToLandscapeLeft; } set { UnityEngine.Screen.autorotateToLandscapeLeft = value; } } public static bool autorotateToLandscapeRight { get { return UnityEngine.Screen.autorotateToLandscapeRight; } set { UnityEngine.Screen.autorotateToLandscapeRight = value; } } public static bool autorotateToPortrait { get { return UnityEngine.Screen.autorotateToPortrait; } set { UnityEngine.Screen.autorotateToPortrait = value; } } public static bool autorotateToPortraitUpsideDown { get { return UnityEngine.Screen.autorotateToPortraitUpsideDown; } set { UnityEngine.Screen.autorotateToPortraitUpsideDown = value; } } public static Resolution currentResolution => UnityEngine.Screen.currentResolution; public static Rect[] cutouts => UnityEngine.Screen.cutouts; public static float dpi => UnityEngine.Screen.dpi; public static bool fullScreen { get { return UnityEngine.Screen.fullScreen; } set { UnityEngine.Screen.fullScreen = value; } } public static FullScreenMode fullScreenMode { get { return UnityEngine.Screen.fullScreenMode; } set { UnityEngine.Screen.fullScreenMode = value; } } public static int height => UnityEngine.Screen.height; public static int width => UnityEngine.Screen.width; public static ScreenOrientation orientation { get { return UnityEngine.Screen.orientation; } set { UnityEngine.Screen.orientation = value; } } public static Resolution[] resolutions => UnityEngine.Screen.resolutions; public static Rect safeArea => UnityEngine.Screen.safeArea; public static int sleepTimeout { get { return UnityEngine.Screen.sleepTimeout; } set { UnityEngine.Screen.sleepTimeout = value; } } public static Vector2Int mainWindowPosition => UnityEngine.Screen.mainWindowPosition; public static DisplayInfo mainWindowDisplayInfo => UnityEngine.Screen.mainWindowDisplayInfo; public static void SetResolution(int width, int height, FullScreenMode fullscreenMode, [UnityEngine.Internal.DefaultValue("0")] int preferredRefreshRate) { UnityEngine.Screen.SetResolution(width, height, fullscreenMode, preferredRefreshRate); } public static void SetResolution(int width, int height, FullScreenMode fullscreenMode) { SetResolution(width, height, fullscreenMode, 0); } public static void SetResolution(int width, int height, bool fullscreen, [UnityEngine.Internal.DefaultValue("0")] int preferredRefreshRate) { SetResolution(width, height, fullscreen ? FullScreenMode.FullScreenWindow : FullScreenMode.Windowed, preferredRefreshRate); } public static void SetResolution(int width, int height, bool fullscreen) { SetResolution(width, height, fullscreen, 0); } public static void GetDisplayLayout(List displayLayout) { UnityEngine.Screen.GetDisplayLayout(displayLayout); } public static AsyncOperation MoveMainWindowTo(in DisplayInfo display, Vector2Int position) { return UnityEngine.Screen.MoveMainWindowTo(in display, position); } } public static class SystemInfo { public const string unsupportedIdentifier = "n/a"; public static float batteryLevel => UnityEngine.SystemInfo.batteryLevel; public static BatteryStatus batteryStatus => UnityEngine.SystemInfo.batteryStatus; public static string operatingSystem => UnityEngine.SystemInfo.operatingSystem; public static OperatingSystemFamily operatingSystemFamily => UnityEngine.SystemInfo.operatingSystemFamily; public static string processorType => UnityEngine.SystemInfo.processorType; public static int processorFrequency => UnityEngine.SystemInfo.processorFrequency; public static int processorCount => UnityEngine.SystemInfo.processorCount; public static int systemMemorySize => UnityEngine.SystemInfo.systemMemorySize; public static string deviceUniqueIdentifier => UnityEngine.SystemInfo.deviceUniqueIdentifier; public static string deviceName => UnityEngine.SystemInfo.deviceName; public static string deviceModel => UnityEngine.SystemInfo.deviceModel; public static bool supportsAccelerometer => UnityEngine.SystemInfo.supportsAccelerometer; public static bool supportsGyroscope => UnityEngine.SystemInfo.supportsGyroscope; public static bool supportsLocationService => UnityEngine.SystemInfo.supportsLocationService; public static bool supportsVibration => UnityEngine.SystemInfo.supportsVibration; public static bool supportsAudio => UnityEngine.SystemInfo.supportsAudio; public static DeviceType deviceType => UnityEngine.SystemInfo.deviceType; public static int graphicsMemorySize => UnityEngine.SystemInfo.graphicsMemorySize; public static string graphicsDeviceName => UnityEngine.SystemInfo.graphicsDeviceName; public static string graphicsDeviceVendor => UnityEngine.SystemInfo.graphicsDeviceVendor; public static int graphicsDeviceID => UnityEngine.SystemInfo.graphicsDeviceID; public static int graphicsDeviceVendorID => UnityEngine.SystemInfo.graphicsDeviceVendorID; public static GraphicsDeviceType graphicsDeviceType => UnityEngine.SystemInfo.graphicsDeviceType; public static bool graphicsUVStartsAtTop => UnityEngine.SystemInfo.graphicsUVStartsAtTop; public static string graphicsDeviceVersion => UnityEngine.SystemInfo.graphicsDeviceVersion; public static int graphicsShaderLevel => UnityEngine.SystemInfo.graphicsShaderLevel; public static bool graphicsMultiThreaded => UnityEngine.SystemInfo.graphicsMultiThreaded; public static RenderingThreadingMode renderingThreadingMode => UnityEngine.SystemInfo.renderingThreadingMode; public static bool hasHiddenSurfaceRemovalOnGPU => UnityEngine.SystemInfo.hasHiddenSurfaceRemovalOnGPU; public static bool hasDynamicUniformArrayIndexingInFragmentShaders => UnityEngine.SystemInfo.hasDynamicUniformArrayIndexingInFragmentShaders; public static bool supportsShadows => UnityEngine.SystemInfo.supportsShadows; public static bool supportsRawShadowDepthSampling => UnityEngine.SystemInfo.supportsRawShadowDepthSampling; public static bool supportsMotionVectors => UnityEngine.SystemInfo.supportsMotionVectors; public static bool supports3DTextures => UnityEngine.SystemInfo.supports3DTextures; public static bool supportsCompressed3DTextures => UnityEngine.SystemInfo.supportsCompressed3DTextures; public static bool supports2DArrayTextures => UnityEngine.SystemInfo.supports2DArrayTextures; public static bool supports3DRenderTextures => UnityEngine.SystemInfo.supports3DRenderTextures; public static bool supportsCubemapArrayTextures => UnityEngine.SystemInfo.supportsCubemapArrayTextures; public static bool supportsAnisotropicFilter => UnityEngine.SystemInfo.supportsAnisotropicFilter; public static CopyTextureSupport copyTextureSupport => UnityEngine.SystemInfo.copyTextureSupport; public static bool supportsComputeShaders => UnityEngine.SystemInfo.supportsComputeShaders; public static bool supportsGeometryShaders => UnityEngine.SystemInfo.supportsGeometryShaders; public static bool supportsTessellationShaders => UnityEngine.SystemInfo.supportsTessellationShaders; public static bool supportsRenderTargetArrayIndexFromVertexShader => UnityEngine.SystemInfo.supportsRenderTargetArrayIndexFromVertexShader; public static bool supportsInstancing => UnityEngine.SystemInfo.supportsInstancing; public static bool supportsHardwareQuadTopology => UnityEngine.SystemInfo.supportsHardwareQuadTopology; public static bool supports32bitsIndexBuffer => UnityEngine.SystemInfo.supports32bitsIndexBuffer; public static bool supportsSparseTextures => UnityEngine.SystemInfo.supportsSparseTextures; public static int supportedRenderTargetCount => UnityEngine.SystemInfo.supportedRenderTargetCount; public static bool supportsSeparatedRenderTargetsBlend => UnityEngine.SystemInfo.supportsSeparatedRenderTargetsBlend; public static int supportedRandomWriteTargetCount => UnityEngine.SystemInfo.supportedRandomWriteTargetCount; public static int supportsMultisampledTextures => UnityEngine.SystemInfo.supportsMultisampledTextures; public static bool supportsMultisampled2DArrayTextures => UnityEngine.SystemInfo.supportsMultisampled2DArrayTextures; public static bool supportsMultisampleAutoResolve => UnityEngine.SystemInfo.supportsMultisampleAutoResolve; public static int supportsTextureWrapMirrorOnce => UnityEngine.SystemInfo.supportsTextureWrapMirrorOnce; public static bool usesReversedZBuffer => UnityEngine.SystemInfo.usesReversedZBuffer; public static NPOTSupport npotSupport => UnityEngine.SystemInfo.npotSupport; public static int maxTextureSize => UnityEngine.SystemInfo.maxTextureSize; public static int maxTexture3DSize => UnityEngine.SystemInfo.maxTexture3DSize; public static int maxTextureArraySlices => UnityEngine.SystemInfo.maxTextureArraySlices; public static int maxCubemapSize => UnityEngine.SystemInfo.maxCubemapSize; public static int maxAnisotropyLevel => UnityEngine.SystemInfo.maxAnisotropyLevel; public static int maxComputeBufferInputsVertex => UnityEngine.SystemInfo.maxComputeBufferInputsVertex; public static int maxComputeBufferInputsFragment => UnityEngine.SystemInfo.maxComputeBufferInputsFragment; public static int maxComputeBufferInputsGeometry => UnityEngine.SystemInfo.maxComputeBufferInputsGeometry; public static int maxComputeBufferInputsDomain => UnityEngine.SystemInfo.maxComputeBufferInputsDomain; public static int maxComputeBufferInputsHull => UnityEngine.SystemInfo.maxComputeBufferInputsHull; public static int maxComputeBufferInputsCompute => UnityEngine.SystemInfo.maxComputeBufferInputsCompute; public static int maxComputeWorkGroupSize => UnityEngine.SystemInfo.maxComputeWorkGroupSize; public static int maxComputeWorkGroupSizeX => UnityEngine.SystemInfo.maxComputeWorkGroupSizeX; public static int maxComputeWorkGroupSizeY => UnityEngine.SystemInfo.maxComputeWorkGroupSizeY; public static int maxComputeWorkGroupSizeZ => UnityEngine.SystemInfo.maxComputeWorkGroupSizeZ; public static int computeSubGroupSize => UnityEngine.SystemInfo.computeSubGroupSize; public static bool supportsAsyncCompute => UnityEngine.SystemInfo.supportsAsyncCompute; public static bool supportsGpuRecorder => UnityEngine.SystemInfo.supportsGpuRecorder; public static bool supportsGraphicsFence => UnityEngine.SystemInfo.supportsGraphicsFence; public static bool supportsAsyncGPUReadback => UnityEngine.SystemInfo.supportsAsyncGPUReadback; public static bool supportsRayTracing => UnityEngine.SystemInfo.supportsRayTracing; public static bool supportsSetConstantBuffer => UnityEngine.SystemInfo.supportsSetConstantBuffer; public static int constantBufferOffsetAlignment => UnityEngine.SystemInfo.constantBufferOffsetAlignment; public static long maxGraphicsBufferSize => UnityEngine.SystemInfo.maxGraphicsBufferSize; public static bool hasMipMaxLevel => UnityEngine.SystemInfo.hasMipMaxLevel; public static bool supportsMipStreaming => UnityEngine.SystemInfo.supportsMipStreaming; public static bool usesLoadStoreActions => UnityEngine.SystemInfo.usesLoadStoreActions; public static HDRDisplaySupportFlags hdrDisplaySupportFlags => UnityEngine.SystemInfo.hdrDisplaySupportFlags; public static bool supportsConservativeRaster => UnityEngine.SystemInfo.supportsConservativeRaster; public static bool supportsMultiview => UnityEngine.SystemInfo.supportsMultiview; public static bool supportsStoreAndResolveAction => UnityEngine.SystemInfo.supportsStoreAndResolveAction; public static bool supportsMultisampleResolveDepth => UnityEngine.SystemInfo.supportsMultisampleResolveDepth; public static bool SupportsRenderTextureFormat(RenderTextureFormat format) { return UnityEngine.SystemInfo.SupportsRenderTextureFormat(format); } public static bool SupportsBlendingOnRenderTextureFormat(RenderTextureFormat format) { return UnityEngine.SystemInfo.SupportsBlendingOnRenderTextureFormat(format); } public static bool SupportsTextureFormat(TextureFormat format) { return UnityEngine.SystemInfo.SupportsTextureFormat(format); } public static bool SupportsVertexAttributeFormat(VertexAttributeFormat format, int dimension) { return UnityEngine.SystemInfo.SupportsVertexAttributeFormat(format, dimension); } public static bool IsFormatSupported(GraphicsFormat format, FormatUsage usage) { return UnityEngine.SystemInfo.IsFormatSupported(format, usage); } public static GraphicsFormat GetCompatibleFormat(GraphicsFormat format, FormatUsage usage) { return UnityEngine.SystemInfo.GetCompatibleFormat(format, usage); } public static GraphicsFormat GetGraphicsFormat(DefaultFormat format) { return UnityEngine.SystemInfo.GetGraphicsFormat(format); } public static int GetRenderTextureSupportedMSAASampleCount(RenderTextureDescriptor desc) { return UnityEngine.SystemInfo.GetRenderTextureSupportedMSAASampleCount(desc); } public static bool SupportsRandomWriteOnRenderTextureFormat(RenderTextureFormat format) { return UnityEngine.SystemInfo.SupportsRandomWriteOnRenderTextureFormat(format); } } } namespace UnityEngine.Experimental.U2D { [RequiredByNativeCode] [NativeHeader("Runtime/2D/Renderer/SpriteRendererGroup.h")] internal struct SpriteIntermediateRendererInfo { public int SpriteID; public int TextureID; public int MaterialID; public Color Color; public Matrix4x4 Transform; public Bounds Bounds; public int Layer; public int SortingLayer; public int SortingOrder; public ulong SceneCullingMask; public IntPtr IndexData; public IntPtr VertexData; public int IndexCount; public int VertexCount; public int ShaderChannelMask; } [StructLayout(LayoutKind.Sequential)] [NativeHeader("Runtime/2D/Renderer/SpriteRendererGroup.h")] [RequiredByNativeCode] internal class SpriteRendererGroup { public unsafe static void AddRenderers(NativeArray renderers) { AddRenderers(renderers.GetUnsafeReadOnlyPtr(), renderers.Length); } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void AddRenderers(void* renderers, int count); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Clear(); } } namespace UnityEngine.Experimental.GlobalIllumination { public enum LightType : byte { Directional, Point, Spot, Rectangle, Disc, SpotPyramidShape, SpotBoxShape } public enum LightMode : byte { Realtime, Mixed, Baked, Unknown } public enum FalloffType : byte { InverseSquared, InverseSquaredNoRangeAttenuation, Linear, Legacy, Undefined } public enum AngularFalloffType : byte { LUT, AnalyticAndInnerAngle } public struct LinearColor { private float m_red; private float m_green; private float m_blue; private float m_intensity; public float red { get { return m_red; } set { if (value < 0f || value > 1f) { throw new ArgumentOutOfRangeException("Red color (" + value + ") must be in range [0;1]."); } m_red = value; } } public float green { get { return m_green; } set { if (value < 0f || value > 1f) { throw new ArgumentOutOfRangeException("Green color (" + value + ") must be in range [0;1]."); } m_green = value; } } public float blue { get { return m_blue; } set { if (value < 0f || value > 1f) { throw new ArgumentOutOfRangeException("Blue color (" + value + ") must be in range [0;1]."); } m_blue = value; } } public float intensity { get { return m_intensity; } set { if (value < 0f) { throw new ArgumentOutOfRangeException("Intensity (" + value + ") must be positive."); } m_intensity = value; } } public static LinearColor Convert(Color color, float intensity) { Color color2 = (GraphicsSettings.lightsUseLinearIntensity ? color.linear.RGBMultiplied(intensity) : color.RGBMultiplied(intensity).linear); float maxColorComponent = color2.maxColorComponent; if (color2.r < 0f || color2.g < 0f || color2.b < 0f) { throw new ArgumentOutOfRangeException("The input color to be converted must not contain negative values (red: " + color2.r + ", green: " + color2.g + ", blue: " + color2.b + ")."); } if (maxColorComponent <= 1E-20f) { return Black(); } float num = 1f / color2.maxColorComponent; LinearColor result = default(LinearColor); result.m_red = color2.r * num; result.m_green = color2.g * num; result.m_blue = color2.b * num; result.m_intensity = maxColorComponent; return result; } public static LinearColor Black() { LinearColor result = default(LinearColor); result.m_red = (result.m_green = (result.m_blue = (result.m_intensity = 0f))); return result; } } public struct DirectionalLight { public int instanceID; public bool shadow; public LightMode mode; public Vector3 position; public Quaternion orientation; public LinearColor color; public LinearColor indirectColor; public float penumbraWidthRadian; [Obsolete("Directional lights support cookies now. In order to position the cookie projection in the world, a position and full orientation are necessary. Use the position and orientation members instead of the direction parameter.", true)] public Vector3 direction; } public struct PointLight { public int instanceID; public bool shadow; public LightMode mode; public Vector3 position; public Quaternion orientation; public LinearColor color; public LinearColor indirectColor; public float range; public float sphereRadius; public FalloffType falloff; } public struct SpotLight { public int instanceID; public bool shadow; public LightMode mode; public Vector3 position; public Quaternion orientation; public LinearColor color; public LinearColor indirectColor; public float range; public float sphereRadius; public float coneAngle; public float innerConeAngle; public FalloffType falloff; public AngularFalloffType angularFalloff; } public struct RectangleLight { public int instanceID; public bool shadow; public LightMode mode; public Vector3 position; public Quaternion orientation; public LinearColor color; public LinearColor indirectColor; public float range; public float width; public float height; public FalloffType falloff; } public struct DiscLight { public int instanceID; public bool shadow; public LightMode mode; public Vector3 position; public Quaternion orientation; public LinearColor color; public LinearColor indirectColor; public float range; public float radius; public FalloffType falloff; } public struct SpotLightBoxShape { public int instanceID; public bool shadow; public LightMode mode; public Vector3 position; public Quaternion orientation; public LinearColor color; public LinearColor indirectColor; public float range; public float width; public float height; } public struct SpotLightPyramidShape { public int instanceID; public bool shadow; public LightMode mode; public Vector3 position; public Quaternion orientation; public LinearColor color; public LinearColor indirectColor; public float range; public float angle; public float aspectRatio; public FalloffType falloff; } public struct Cookie { public int instanceID; public float scale; public Vector2 sizes; public static Cookie Defaults() { Cookie result = default(Cookie); result.instanceID = 0; result.scale = 1f; result.sizes = new Vector2(1f, 1f); return result; } } [UsedByNativeCode] public struct LightDataGI { public int instanceID; public int cookieID; public float cookieScale; public LinearColor color; public LinearColor indirectColor; public Quaternion orientation; public Vector3 position; public float range; public float coneAngle; public float innerConeAngle; public float shape0; public float shape1; public LightType type; public LightMode mode; public byte shadow; public FalloffType falloff; public void Init(ref DirectionalLight light, ref Cookie cookie) { instanceID = light.instanceID; cookieID = cookie.instanceID; cookieScale = cookie.scale; color = light.color; indirectColor = light.indirectColor; orientation = light.orientation; position = light.position; range = 0f; coneAngle = cookie.sizes.x; innerConeAngle = cookie.sizes.y; shape0 = light.penumbraWidthRadian; shape1 = 0f; type = LightType.Directional; mode = light.mode; shadow = (byte)(light.shadow ? 1u : 0u); falloff = FalloffType.Undefined; } public void Init(ref PointLight light, ref Cookie cookie) { instanceID = light.instanceID; cookieID = cookie.instanceID; cookieScale = cookie.scale; color = light.color; indirectColor = light.indirectColor; orientation = light.orientation; position = light.position; range = light.range; coneAngle = 0f; innerConeAngle = 0f; shape0 = light.sphereRadius; shape1 = 0f; type = LightType.Point; mode = light.mode; shadow = (byte)(light.shadow ? 1u : 0u); falloff = light.falloff; } public void Init(ref SpotLight light, ref Cookie cookie) { instanceID = light.instanceID; cookieID = cookie.instanceID; cookieScale = cookie.scale; color = light.color; indirectColor = light.indirectColor; orientation = light.orientation; position = light.position; range = light.range; coneAngle = light.coneAngle; innerConeAngle = light.innerConeAngle; shape0 = light.sphereRadius; shape1 = (int)light.angularFalloff; type = LightType.Spot; mode = light.mode; shadow = (byte)(light.shadow ? 1u : 0u); falloff = light.falloff; } public void Init(ref RectangleLight light, ref Cookie cookie) { instanceID = light.instanceID; cookieID = cookie.instanceID; cookieScale = cookie.scale; color = light.color; indirectColor = light.indirectColor; orientation = light.orientation; position = light.position; range = light.range; coneAngle = 0f; innerConeAngle = 0f; shape0 = light.width; shape1 = light.height; type = LightType.Rectangle; mode = light.mode; shadow = (byte)(light.shadow ? 1u : 0u); falloff = light.falloff; } public void Init(ref DiscLight light, ref Cookie cookie) { instanceID = light.instanceID; cookieID = cookie.instanceID; cookieScale = cookie.scale; color = light.color; indirectColor = light.indirectColor; orientation = light.orientation; position = light.position; range = light.range; coneAngle = 0f; innerConeAngle = 0f; shape0 = light.radius; shape1 = 0f; type = LightType.Disc; mode = light.mode; shadow = (byte)(light.shadow ? 1u : 0u); falloff = light.falloff; } public void Init(ref SpotLightBoxShape light, ref Cookie cookie) { instanceID = light.instanceID; cookieID = cookie.instanceID; cookieScale = cookie.scale; color = light.color; indirectColor = light.indirectColor; orientation = light.orientation; position = light.position; range = light.range; coneAngle = 0f; innerConeAngle = 0f; shape0 = light.width; shape1 = light.height; type = LightType.SpotBoxShape; mode = light.mode; shadow = (byte)(light.shadow ? 1u : 0u); falloff = FalloffType.Undefined; } public void Init(ref SpotLightPyramidShape light, ref Cookie cookie) { instanceID = light.instanceID; cookieID = cookie.instanceID; cookieScale = cookie.scale; color = light.color; indirectColor = light.indirectColor; orientation = light.orientation; position = light.position; range = light.range; coneAngle = light.angle; innerConeAngle = 0f; shape0 = light.aspectRatio; shape1 = 0f; type = LightType.SpotPyramidShape; mode = light.mode; shadow = (byte)(light.shadow ? 1u : 0u); falloff = light.falloff; } public void Init(ref DirectionalLight light) { Cookie cookie = Cookie.Defaults(); Init(ref light, ref cookie); } public void Init(ref PointLight light) { Cookie cookie = Cookie.Defaults(); Init(ref light, ref cookie); } public void Init(ref SpotLight light) { Cookie cookie = Cookie.Defaults(); Init(ref light, ref cookie); } public void Init(ref RectangleLight light) { Cookie cookie = Cookie.Defaults(); Init(ref light, ref cookie); } public void Init(ref DiscLight light) { Cookie cookie = Cookie.Defaults(); Init(ref light, ref cookie); } public void Init(ref SpotLightBoxShape light) { Cookie cookie = Cookie.Defaults(); Init(ref light, ref cookie); } public void Init(ref SpotLightPyramidShape light) { Cookie cookie = Cookie.Defaults(); Init(ref light, ref cookie); } public void InitNoBake(int lightInstanceID) { instanceID = lightInstanceID; mode = LightMode.Unknown; } } public static class LightmapperUtils { public static LightMode Extract(LightmapBakeType baketype) { return baketype switch { LightmapBakeType.Mixed => LightMode.Mixed, LightmapBakeType.Realtime => LightMode.Realtime, _ => LightMode.Baked, }; } public static LinearColor ExtractIndirect(Light l) { return LinearColor.Convert(l.color, l.intensity * l.bounceIntensity); } public static float ExtractInnerCone(Light l) { return 2f * Mathf.Atan(Mathf.Tan(l.spotAngle * 0.5f * ((float)Math.PI / 180f)) * 46f / 64f); } private static Color ExtractColorTemperature(Light l) { Color result = new Color(1f, 1f, 1f); if (l.useColorTemperature && GraphicsSettings.lightsUseLinearIntensity) { return Mathf.CorrelatedColorTemperatureToRGB(l.colorTemperature); } return result; } private static void ApplyColorTemperature(Color cct, ref LinearColor lightColor) { lightColor.red *= cct.r; lightColor.green *= cct.g; lightColor.blue *= cct.b; } public static void Extract(Light l, ref DirectionalLight dir) { dir.instanceID = l.GetInstanceID(); dir.mode = Extract(l.bakingOutput.lightmapBakeType); dir.shadow = l.shadows != LightShadows.None; dir.position = l.transform.position; dir.orientation = l.transform.rotation; Color cct = ExtractColorTemperature(l); LinearColor lightColor = LinearColor.Convert(l.color, l.intensity); LinearColor lightColor2 = ExtractIndirect(l); ApplyColorTemperature(cct, ref lightColor); ApplyColorTemperature(cct, ref lightColor2); dir.color = lightColor; dir.indirectColor = lightColor2; dir.penumbraWidthRadian = 0f; } public static void Extract(Light l, ref PointLight point) { point.instanceID = l.GetInstanceID(); point.mode = Extract(l.bakingOutput.lightmapBakeType); point.shadow = l.shadows != LightShadows.None; point.position = l.transform.position; point.orientation = l.transform.rotation; Color cct = ExtractColorTemperature(l); LinearColor lightColor = LinearColor.Convert(l.color, l.intensity); LinearColor lightColor2 = ExtractIndirect(l); ApplyColorTemperature(cct, ref lightColor); ApplyColorTemperature(cct, ref lightColor2); point.color = lightColor; point.indirectColor = lightColor2; point.range = l.range; point.sphereRadius = 0f; point.falloff = FalloffType.Legacy; } public static void Extract(Light l, ref SpotLight spot) { spot.instanceID = l.GetInstanceID(); spot.mode = Extract(l.bakingOutput.lightmapBakeType); spot.shadow = l.shadows != LightShadows.None; spot.position = l.transform.position; spot.orientation = l.transform.rotation; Color cct = ExtractColorTemperature(l); LinearColor lightColor = LinearColor.Convert(l.color, l.intensity); LinearColor lightColor2 = ExtractIndirect(l); ApplyColorTemperature(cct, ref lightColor); ApplyColorTemperature(cct, ref lightColor2); spot.color = lightColor; spot.indirectColor = lightColor2; spot.range = l.range; spot.sphereRadius = 0f; spot.coneAngle = l.spotAngle * ((float)Math.PI / 180f); spot.innerConeAngle = ExtractInnerCone(l); spot.falloff = FalloffType.Legacy; spot.angularFalloff = AngularFalloffType.LUT; } public static void Extract(Light l, ref RectangleLight rect) { rect.instanceID = l.GetInstanceID(); rect.mode = Extract(l.bakingOutput.lightmapBakeType); rect.shadow = l.shadows != LightShadows.None; rect.position = l.transform.position; rect.orientation = l.transform.rotation; Color cct = ExtractColorTemperature(l); LinearColor lightColor = LinearColor.Convert(l.color, l.intensity); LinearColor lightColor2 = ExtractIndirect(l); ApplyColorTemperature(cct, ref lightColor); ApplyColorTemperature(cct, ref lightColor2); rect.color = lightColor; rect.indirectColor = lightColor2; rect.range = l.range; rect.width = 0f; rect.height = 0f; rect.falloff = FalloffType.Legacy; } public static void Extract(Light l, ref DiscLight disc) { disc.instanceID = l.GetInstanceID(); disc.mode = Extract(l.bakingOutput.lightmapBakeType); disc.shadow = l.shadows != LightShadows.None; disc.position = l.transform.position; disc.orientation = l.transform.rotation; Color cct = ExtractColorTemperature(l); LinearColor lightColor = LinearColor.Convert(l.color, l.intensity); LinearColor lightColor2 = ExtractIndirect(l); ApplyColorTemperature(cct, ref lightColor); ApplyColorTemperature(cct, ref lightColor2); disc.color = lightColor; disc.indirectColor = lightColor2; disc.range = l.range; disc.radius = 0f; disc.falloff = FalloffType.Legacy; } public static void Extract(Light l, out Cookie cookie) { cookie.instanceID = (l.cookie ? l.cookie.GetInstanceID() : 0); cookie.scale = 1f; cookie.sizes = ((l.type == UnityEngine.LightType.Directional && (bool)l.cookie) ? new Vector2(l.cookieSize, l.cookieSize) : new Vector2(1f, 1f)); } } public static class Lightmapping { public delegate void RequestLightsDelegate(Light[] requests, NativeArray lightsOutput); [RequiredByNativeCode] private static readonly RequestLightsDelegate s_DefaultDelegate = delegate(Light[] requests, NativeArray lightsOutput) { DirectionalLight dir = default(DirectionalLight); PointLight point = default(PointLight); SpotLight spot = default(SpotLight); RectangleLight rect = default(RectangleLight); DiscLight disc = default(DiscLight); Cookie cookie = default(Cookie); LightDataGI value = default(LightDataGI); for (int i = 0; i < requests.Length; i++) { Light light = requests[i]; switch (light.type) { case UnityEngine.LightType.Directional: LightmapperUtils.Extract(light, ref dir); LightmapperUtils.Extract(light, out cookie); value.Init(ref dir, ref cookie); break; case UnityEngine.LightType.Point: LightmapperUtils.Extract(light, ref point); LightmapperUtils.Extract(light, out cookie); value.Init(ref point, ref cookie); break; case UnityEngine.LightType.Spot: LightmapperUtils.Extract(light, ref spot); LightmapperUtils.Extract(light, out cookie); value.Init(ref spot, ref cookie); break; case UnityEngine.LightType.Area: LightmapperUtils.Extract(light, ref rect); LightmapperUtils.Extract(light, out cookie); value.Init(ref rect, ref cookie); break; case UnityEngine.LightType.Disc: LightmapperUtils.Extract(light, ref disc); LightmapperUtils.Extract(light, out cookie); value.Init(ref disc, ref cookie); break; default: value.InitNoBake(light.GetInstanceID()); break; } lightsOutput[i] = value; } }; [RequiredByNativeCode] private static RequestLightsDelegate s_RequestLightsDelegate = s_DefaultDelegate; [RequiredByNativeCode] public static void SetDelegate(RequestLightsDelegate del) { s_RequestLightsDelegate = ((del != null) ? del : s_DefaultDelegate); } [RequiredByNativeCode] public static RequestLightsDelegate GetDelegate() { return s_RequestLightsDelegate; } [RequiredByNativeCode] public static void ResetDelegate() { s_RequestLightsDelegate = s_DefaultDelegate; } [RequiredByNativeCode] internal unsafe static void RequestLights(Light[] lights, IntPtr outLightsPtr, int outLightsCount) { NativeArray lightsOutput = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray((void*)outLightsPtr, outLightsCount, Allocator.None); s_RequestLightsDelegate(lights, lightsOutput); } } [NativeHeader("Runtime/Camera/RenderSettings.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] public class RenderSettings { public static extern bool useRadianceAmbientProbe { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } } } namespace UnityEngine.Experimental.Playables { [NativeHeader("Runtime/Export/Director/CameraPlayable.bindings.h")] [RequiredByNativeCode] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("Runtime/Director/Core/HPlayable.h")] [NativeHeader("Runtime/Camera//Director/CameraPlayable.h")] public struct CameraPlayable : IPlayable, IEquatable { private PlayableHandle m_Handle; public static CameraPlayable Create(PlayableGraph graph, Camera camera) { PlayableHandle handle = CreateHandle(graph, camera); return new CameraPlayable(handle); } private static PlayableHandle CreateHandle(PlayableGraph graph, Camera camera) { PlayableHandle handle = PlayableHandle.Null; if (!InternalCreateCameraPlayable(ref graph, camera, ref handle)) { return PlayableHandle.Null; } return handle; } internal CameraPlayable(PlayableHandle handle) { if (handle.IsValid() && !handle.IsPlayableOfType()) { throw new InvalidCastException("Can't set handle: the playable is not an CameraPlayable."); } m_Handle = handle; } public PlayableHandle GetHandle() { return m_Handle; } public static implicit operator Playable(CameraPlayable playable) { return new Playable(playable.GetHandle()); } public static explicit operator CameraPlayable(Playable playable) { return new CameraPlayable(playable.GetHandle()); } public bool Equals(CameraPlayable other) { return GetHandle() == other.GetHandle(); } public Camera GetCamera() { return GetCameraInternal(ref m_Handle); } public void SetCamera(Camera value) { SetCameraInternal(ref m_Handle, value); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern Camera GetCameraInternal(ref PlayableHandle hdl); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern void SetCameraInternal(ref PlayableHandle hdl, Camera camera); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern bool InternalCreateCameraPlayable(ref PlayableGraph graph, Camera camera, ref PlayableHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern bool ValidateType(ref PlayableHandle hdl); } [NativeHeader("Runtime/Shaders/Director/MaterialEffectPlayable.h")] [NativeHeader("Runtime/Export/Director/MaterialEffectPlayable.bindings.h")] [NativeHeader("Runtime/Director/Core/HPlayable.h")] [RequiredByNativeCode] [StaticAccessor(/*Could not decode attribute arguments.*/)] public struct MaterialEffectPlayable : IPlayable, IEquatable { private PlayableHandle m_Handle; public static MaterialEffectPlayable Create(PlayableGraph graph, Material material, int pass = -1) { PlayableHandle handle = CreateHandle(graph, material, pass); return new MaterialEffectPlayable(handle); } private static PlayableHandle CreateHandle(PlayableGraph graph, Material material, int pass) { PlayableHandle handle = PlayableHandle.Null; if (!InternalCreateMaterialEffectPlayable(ref graph, material, pass, ref handle)) { return PlayableHandle.Null; } return handle; } internal MaterialEffectPlayable(PlayableHandle handle) { if (handle.IsValid() && !handle.IsPlayableOfType()) { throw new InvalidCastException("Can't set handle: the playable is not an MaterialEffectPlayable."); } m_Handle = handle; } public PlayableHandle GetHandle() { return m_Handle; } public static implicit operator Playable(MaterialEffectPlayable playable) { return new Playable(playable.GetHandle()); } public static explicit operator MaterialEffectPlayable(Playable playable) { return new MaterialEffectPlayable(playable.GetHandle()); } public bool Equals(MaterialEffectPlayable other) { return GetHandle() == other.GetHandle(); } public Material GetMaterial() { return GetMaterialInternal(ref m_Handle); } public void SetMaterial(Material value) { SetMaterialInternal(ref m_Handle, value); } public int GetPass() { return GetPassInternal(ref m_Handle); } public void SetPass(int value) { SetPassInternal(ref m_Handle, value); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern Material GetMaterialInternal(ref PlayableHandle hdl); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern void SetMaterialInternal(ref PlayableHandle hdl, Material material); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern int GetPassInternal(ref PlayableHandle hdl); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern void SetPassInternal(ref PlayableHandle hdl, int pass); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern bool InternalCreateMaterialEffectPlayable(ref PlayableGraph graph, Material material, int pass, ref PlayableHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern bool ValidateType(ref PlayableHandle hdl); } [NativeHeader("Runtime/Graphics/Director/TextureMixerPlayable.h")] [NativeHeader("Runtime/Director/Core/HPlayable.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("Runtime/Export/Director/TextureMixerPlayable.bindings.h")] [RequiredByNativeCode] public struct TextureMixerPlayable : IPlayable, IEquatable { private PlayableHandle m_Handle; public static TextureMixerPlayable Create(PlayableGraph graph) { PlayableHandle handle = CreateHandle(graph); return new TextureMixerPlayable(handle); } private static PlayableHandle CreateHandle(PlayableGraph graph) { PlayableHandle handle = PlayableHandle.Null; if (!CreateTextureMixerPlayableInternal(ref graph, ref handle)) { return PlayableHandle.Null; } return handle; } internal TextureMixerPlayable(PlayableHandle handle) { if (handle.IsValid() && !handle.IsPlayableOfType()) { throw new InvalidCastException("Can't set handle: the playable is not an TextureMixerPlayable."); } m_Handle = handle; } public PlayableHandle GetHandle() { return m_Handle; } public static implicit operator Playable(TextureMixerPlayable playable) { return new Playable(playable.GetHandle()); } public static explicit operator TextureMixerPlayable(Playable playable) { return new TextureMixerPlayable(playable.GetHandle()); } public bool Equals(TextureMixerPlayable other) { return GetHandle() == other.GetHandle(); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern bool CreateTextureMixerPlayableInternal(ref PlayableGraph graph, ref PlayableHandle handle); } public static class TexturePlayableBinding { public static PlayableBinding Create(string name, Object key) { return PlayableBinding.CreateInternal(name, key, typeof(RenderTexture), CreateTextureOutput); } private static PlayableOutput CreateTextureOutput(PlayableGraph graph, string name) { return TexturePlayableOutput.Create(graph, name, null); } } [NativeHeader("Runtime/Export/Director/TexturePlayableGraphExtensions.bindings.h")] [NativeHeader("Runtime/Director/Core/HPlayableOutput.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] internal static class TexturePlayableGraphExtensions { [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] internal static extern bool InternalCreateTextureOutput(ref PlayableGraph graph, string name, out PlayableOutputHandle handle); } [RequiredByNativeCode] [NativeHeader("Runtime/Graphics/Director/TexturePlayableOutput.h")] [NativeHeader("Runtime/Export/Director/TexturePlayableOutput.bindings.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeHeader("Runtime/Graphics/RenderTexture.h")] public struct TexturePlayableOutput : IPlayableOutput { private PlayableOutputHandle m_Handle; public static TexturePlayableOutput Null => new TexturePlayableOutput(PlayableOutputHandle.Null); public static TexturePlayableOutput Create(PlayableGraph graph, string name, RenderTexture target) { if (!TexturePlayableGraphExtensions.InternalCreateTextureOutput(ref graph, name, out var handle)) { return Null; } TexturePlayableOutput result = new TexturePlayableOutput(handle); result.SetTarget(target); return result; } internal TexturePlayableOutput(PlayableOutputHandle handle) { if (handle.IsValid() && !handle.IsPlayableOutputOfType()) { throw new InvalidCastException("Can't set handle: the playable is not an TexturePlayableOutput."); } m_Handle = handle; } public PlayableOutputHandle GetHandle() { return m_Handle; } public static implicit operator PlayableOutput(TexturePlayableOutput output) { return new PlayableOutput(output.GetHandle()); } public static explicit operator TexturePlayableOutput(PlayableOutput output) { return new TexturePlayableOutput(output.GetHandle()); } public RenderTexture GetTarget() { return InternalGetTarget(ref m_Handle); } public void SetTarget(RenderTexture value) { InternalSetTarget(ref m_Handle, value); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern RenderTexture InternalGetTarget(ref PlayableOutputHandle output); [MethodImpl(MethodImplOptions.InternalCall)] [NativeThrows] private static extern void InternalSetTarget(ref PlayableOutputHandle output, RenderTexture target); } } namespace UnityEngine.Experimental.Rendering { [NativeHeader("Runtime/Camera/ReflectionProbes.h")] internal class BuiltinRuntimeReflectionSystem : IScriptableRuntimeReflectionSystem, IDisposable { public bool TickRealtimeProbes() { return BuiltinUpdate(); } public void Dispose() { Dispose(disposing: true); } private void Dispose(bool disposing) { } [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern bool BuiltinUpdate(); [RequiredByNativeCode] private static BuiltinRuntimeReflectionSystem Internal_BuiltinRuntimeReflectionSystem_New() { return new BuiltinRuntimeReflectionSystem(); } } public interface IScriptableRuntimeReflectionSystem : IDisposable { bool TickRealtimeProbes(); } public abstract class ScriptableRuntimeReflectionSystem : IScriptableRuntimeReflectionSystem, IDisposable { public virtual bool TickRealtimeProbes() { return false; } protected virtual void Dispose(bool disposing) { } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } [RequiredByNativeCode] [NativeHeader("Runtime/Camera/ScriptableRuntimeReflectionSystem.h")] public static class ScriptableRuntimeReflectionSystemSettings { private static ScriptableRuntimeReflectionSystemWrapper s_Instance = new ScriptableRuntimeReflectionSystemWrapper(); public static IScriptableRuntimeReflectionSystem system { get { return Internal_ScriptableRuntimeReflectionSystemSettings_system; } set { if (value == null || value.Equals(null)) { Debug.LogError("'null' cannot be assigned to ScriptableRuntimeReflectionSystemSettings.system"); return; } if (!(system is BuiltinRuntimeReflectionSystem) && !(value is BuiltinRuntimeReflectionSystem) && system != value) { Debug.LogWarningFormat("ScriptableRuntimeReflectionSystemSettings.system is assigned more than once. Only a the last instance will be used. (Last instance {0}, New instance {1})", system, value); } Internal_ScriptableRuntimeReflectionSystemSettings_system = value; } } private static IScriptableRuntimeReflectionSystem Internal_ScriptableRuntimeReflectionSystemSettings_system { get { return s_Instance.implementation; } [RequiredByNativeCode] set { if (s_Instance.implementation != value && s_Instance.implementation != null) { s_Instance.implementation.Dispose(); } s_Instance.implementation = value; } } private static ScriptableRuntimeReflectionSystemWrapper Internal_ScriptableRuntimeReflectionSystemSettings_instance { [RequiredByNativeCode] get { return s_Instance; } } [MethodImpl(MethodImplOptions.InternalCall)] [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] [StaticAccessor(/*Could not decode attribute arguments.*/)] private static extern void ScriptingDirtyReflectionSystemInstance(); } [RequiredByNativeCode] internal class ScriptableRuntimeReflectionSystemWrapper { internal IScriptableRuntimeReflectionSystem implementation { get; set; } [RequiredByNativeCode] private void Internal_ScriptableRuntimeReflectionSystemWrapper_TickRealtimeProbes(out bool result) { result = implementation != null && implementation.TickRealtimeProbes(); } } [NativeHeader("Runtime/Graphics/GraphicsScriptBindings.h")] public static class ExternalGPUProfiler { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ExternalGPUProfilerBindings::BeginGPUCapture")] public static extern void BeginGPUCapture(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ExternalGPUProfilerBindings::EndGPUCapture")] public static extern void EndGPUCapture(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ExternalGPUProfilerBindings::IsAttached")] public static extern bool IsAttached(); } public enum WaitForPresentSyncPoint { BeginFrame, EndFrame } public enum GraphicsJobsSyncPoint { EndOfFrame, AfterScriptUpdate, AfterScriptLateUpdate, WaitForPresent } public static class GraphicsDeviceSettings { [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern WaitForPresentSyncPoint waitForPresentSyncPoint { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [StaticAccessor(/*Could not decode attribute arguments.*/)] public static extern GraphicsJobsSyncPoint graphicsJobsSyncPoint { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } } [Flags] public enum TextureCreationFlags { None = 0, MipChain = 1, Crunch = 0x40 } public enum FormatUsage { Sample = 0, Linear = 1, Sparse = 2, Render = 4, Blend = 5, GetPixels = 6, SetPixels = 7, SetPixels32 = 8, ReadPixels = 9, LoadStore = 10, MSAA2x = 11, MSAA4x = 12, MSAA8x = 13, StencilSampling = 16 } public enum DefaultFormat { LDR, HDR, DepthStencil, Shadow, Video } public enum GraphicsFormat { None = 0, R8_SRGB = 1, R8G8_SRGB = 2, R8G8B8_SRGB = 3, R8G8B8A8_SRGB = 4, R8_UNorm = 5, R8G8_UNorm = 6, R8G8B8_UNorm = 7, R8G8B8A8_UNorm = 8, R8_SNorm = 9, R8G8_SNorm = 10, R8G8B8_SNorm = 11, R8G8B8A8_SNorm = 12, R8_UInt = 13, R8G8_UInt = 14, R8G8B8_UInt = 15, R8G8B8A8_UInt = 16, R8_SInt = 17, R8G8_SInt = 18, R8G8B8_SInt = 19, R8G8B8A8_SInt = 20, R16_UNorm = 21, R16G16_UNorm = 22, R16G16B16_UNorm = 23, R16G16B16A16_UNorm = 24, R16_SNorm = 25, R16G16_SNorm = 26, R16G16B16_SNorm = 27, R16G16B16A16_SNorm = 28, R16_UInt = 29, R16G16_UInt = 30, R16G16B16_UInt = 31, R16G16B16A16_UInt = 32, R16_SInt = 33, R16G16_SInt = 34, R16G16B16_SInt = 35, R16G16B16A16_SInt = 36, R32_UInt = 37, R32G32_UInt = 38, R32G32B32_UInt = 39, R32G32B32A32_UInt = 40, R32_SInt = 41, R32G32_SInt = 42, R32G32B32_SInt = 43, R32G32B32A32_SInt = 44, R16_SFloat = 45, R16G16_SFloat = 46, R16G16B16_SFloat = 47, R16G16B16A16_SFloat = 48, R32_SFloat = 49, R32G32_SFloat = 50, R32G32B32_SFloat = 51, R32G32B32A32_SFloat = 52, B8G8R8_SRGB = 56, B8G8R8A8_SRGB = 57, B8G8R8_UNorm = 58, B8G8R8A8_UNorm = 59, B8G8R8_SNorm = 60, B8G8R8A8_SNorm = 61, B8G8R8_UInt = 62, B8G8R8A8_UInt = 63, B8G8R8_SInt = 64, B8G8R8A8_SInt = 65, R4G4B4A4_UNormPack16 = 66, B4G4R4A4_UNormPack16 = 67, R5G6B5_UNormPack16 = 68, B5G6R5_UNormPack16 = 69, R5G5B5A1_UNormPack16 = 70, B5G5R5A1_UNormPack16 = 71, A1R5G5B5_UNormPack16 = 72, E5B9G9R9_UFloatPack32 = 73, B10G11R11_UFloatPack32 = 74, A2B10G10R10_UNormPack32 = 75, A2B10G10R10_UIntPack32 = 76, A2B10G10R10_SIntPack32 = 77, A2R10G10B10_UNormPack32 = 78, A2R10G10B10_UIntPack32 = 79, A2R10G10B10_SIntPack32 = 80, A2R10G10B10_XRSRGBPack32 = 81, A2R10G10B10_XRUNormPack32 = 82, R10G10B10_XRSRGBPack32 = 83, R10G10B10_XRUNormPack32 = 84, A10R10G10B10_XRSRGBPack32 = 85, A10R10G10B10_XRUNormPack32 = 86, D16_UNorm = 90, D24_UNorm = 91, D24_UNorm_S8_UInt = 92, D32_SFloat = 93, D32_SFloat_S8_UInt = 94, S8_UInt = 95, [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Enum member GraphicsFormat.RGB_DXT1_SRGB has been deprecated. Use GraphicsFormat.RGBA_DXT1_SRGB instead (UnityUpgradable) -> RGBA_DXT1_SRGB", true)] RGB_DXT1_SRGB = 96, RGBA_DXT1_SRGB = 96, [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Enum member GraphicsFormat.RGB_DXT1_UNorm has been deprecated. Use GraphicsFormat.RGBA_DXT1_UNorm instead (UnityUpgradable) -> RGBA_DXT1_UNorm", true)] RGB_DXT1_UNorm = 97, RGBA_DXT1_UNorm = 97, RGBA_DXT3_SRGB = 98, RGBA_DXT3_UNorm = 99, RGBA_DXT5_SRGB = 100, RGBA_DXT5_UNorm = 101, R_BC4_UNorm = 102, R_BC4_SNorm = 103, RG_BC5_UNorm = 104, RG_BC5_SNorm = 105, RGB_BC6H_UFloat = 106, RGB_BC6H_SFloat = 107, RGBA_BC7_SRGB = 108, RGBA_BC7_UNorm = 109, RGB_PVRTC_2Bpp_SRGB = 110, RGB_PVRTC_2Bpp_UNorm = 111, RGB_PVRTC_4Bpp_SRGB = 112, RGB_PVRTC_4Bpp_UNorm = 113, RGBA_PVRTC_2Bpp_SRGB = 114, RGBA_PVRTC_2Bpp_UNorm = 115, RGBA_PVRTC_4Bpp_SRGB = 116, RGBA_PVRTC_4Bpp_UNorm = 117, RGB_ETC_UNorm = 118, RGB_ETC2_SRGB = 119, RGB_ETC2_UNorm = 120, RGB_A1_ETC2_SRGB = 121, RGB_A1_ETC2_UNorm = 122, RGBA_ETC2_SRGB = 123, RGBA_ETC2_UNorm = 124, R_EAC_UNorm = 125, R_EAC_SNorm = 126, RG_EAC_UNorm = 127, RG_EAC_SNorm = 128, RGBA_ASTC4X4_SRGB = 129, RGBA_ASTC4X4_UNorm = 130, RGBA_ASTC5X5_SRGB = 131, RGBA_ASTC5X5_UNorm = 132, RGBA_ASTC6X6_SRGB = 133, RGBA_ASTC6X6_UNorm = 134, RGBA_ASTC8X8_SRGB = 135, RGBA_ASTC8X8_UNorm = 136, RGBA_ASTC10X10_SRGB = 137, RGBA_ASTC10X10_UNorm = 138, RGBA_ASTC12X12_SRGB = 139, RGBA_ASTC12X12_UNorm = 140, YUV2 = 141, [Obsolete("Enum member GraphicsFormat.DepthAuto has been deprecated. Use GraphicsFormat.None as a color format to indicate depth only rendering and DefaultFormat to get the default depth buffer format.", false)] DepthAuto = 142, [Obsolete("Enum member GraphicsFormat.ShadowAuto has been deprecated. Use GraphicsFormat.None as a color format to indicate depth only rendering and DefaultFormat to get the default shadow buffer format.", false)] ShadowAuto = 143, [Obsolete("Enum member GraphicsFormat.VideoAuto has been deprecated. Use DefaultFormat instead.", false)] VideoAuto = 144, RGBA_ASTC4X4_UFloat = 145, RGBA_ASTC5X5_UFloat = 146, RGBA_ASTC6X6_UFloat = 147, RGBA_ASTC8X8_UFloat = 148, RGBA_ASTC10X10_UFloat = 149, RGBA_ASTC12X12_UFloat = 150 } public enum RayTracingMode { Off, Static, DynamicTransform, DynamicGeometry } [NativeHeader("Runtime/Graphics/TextureFormat.h")] [NativeHeader("Runtime/Graphics/GraphicsFormatUtility.bindings.h")] [NativeHeader("Runtime/Graphics/Format.h")] public class GraphicsFormatUtility { private static readonly GraphicsFormat[] tableNoStencil = new GraphicsFormat[5] { GraphicsFormat.None, GraphicsFormat.D16_UNorm, GraphicsFormat.D16_UNorm, GraphicsFormat.D24_UNorm, GraphicsFormat.D32_SFloat }; private static readonly GraphicsFormat[] tableStencil = new GraphicsFormat[5] { GraphicsFormat.None, GraphicsFormat.D24_UNorm_S8_UInt, GraphicsFormat.D24_UNorm_S8_UInt, GraphicsFormat.D24_UNorm_S8_UInt, GraphicsFormat.D32_SFloat_S8_UInt }; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetTextureGraphicsFormat")] internal static extern GraphicsFormat GetFormat([NotNull("NullExceptionObject")] Texture texture); public static GraphicsFormat GetGraphicsFormat(TextureFormat format, bool isSRGB) { return GetGraphicsFormat_Native_TextureFormat(format, isSRGB); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] private static extern GraphicsFormat GetGraphicsFormat_Native_TextureFormat(TextureFormat format, bool isSRGB); public static TextureFormat GetTextureFormat(GraphicsFormat format) { return GetTextureFormat_Native_GraphicsFormat(format); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] private static extern TextureFormat GetTextureFormat_Native_GraphicsFormat(GraphicsFormat format); public static GraphicsFormat GetGraphicsFormat(RenderTextureFormat format, bool isSRGB) { return GetGraphicsFormat_Native_RenderTextureFormat(format, isSRGB); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern GraphicsFormat GetGraphicsFormat_Native_RenderTextureFormat(RenderTextureFormat format, bool isSRGB); public static GraphicsFormat GetGraphicsFormat(RenderTextureFormat format, RenderTextureReadWrite readWrite) { bool flag = QualitySettings.activeColorSpace == ColorSpace.Linear; bool isSRGB = ((readWrite == RenderTextureReadWrite.Default) ? flag : (readWrite == RenderTextureReadWrite.sRGB)); return GetGraphicsFormat(format, isSRGB); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] private static extern GraphicsFormat GetDepthStencilFormatFromBitsLegacy_Native(int minimumDepthBits); internal static GraphicsFormat GetDepthStencilFormat(int minimumDepthBits) { return GetDepthStencilFormatFromBitsLegacy_Native(minimumDepthBits); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern int GetDepthBits(GraphicsFormat format); public static GraphicsFormat GetDepthStencilFormat(int minimumDepthBits, int minimumStencilBits) { if (minimumDepthBits == 0 && minimumStencilBits == 0) { return GraphicsFormat.None; } if (minimumDepthBits < 0 || minimumStencilBits < 0) { throw new ArgumentException("Number of bits in DepthStencil format can't be negative."); } if (minimumDepthBits > 32) { throw new ArgumentException("Number of depth buffer bits cannot exceed 32."); } if (minimumStencilBits > 8) { throw new ArgumentException("Number of stencil buffer bits cannot exceed 8."); } minimumDepthBits = ((minimumDepthBits <= 16) ? 16 : ((minimumDepthBits > 24) ? 32 : 24)); if (minimumStencilBits != 0) { minimumStencilBits = 8; } Debug.Assert(tableNoStencil.Length == tableStencil.Length); GraphicsFormat[] array = ((minimumStencilBits > 0) ? tableStencil : tableNoStencil); int num = minimumDepthBits / 8; for (int i = num; i < array.Length; i++) { GraphicsFormat graphicsFormat = array[i]; if (SystemInfo.IsFormatSupported(graphicsFormat, FormatUsage.Render)) { return graphicsFormat; } } return GraphicsFormat.None; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsSRGBFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsSwizzleFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern GraphicsFormat GetSRGBFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern GraphicsFormat GetLinearFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern RenderTextureFormat GetRenderTextureFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern uint GetColorComponentCount(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern uint GetAlphaComponentCount(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern uint GetComponentCount(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern string GetFormatString(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsCompressedFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("IsAnyCompressedTextureFormat", true)] internal static extern bool IsCompressedTextureFormat(TextureFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] private static extern bool CanDecompressFormat(GraphicsFormat format, bool wholeImage); internal static bool CanDecompressFormat(GraphicsFormat format) { return CanDecompressFormat(format, wholeImage: true); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsPackedFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool Is16BitPackedFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern GraphicsFormat ConvertToAlphaFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsAlphaOnlyFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsAlphaTestFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool HasAlphaChannel(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsDepthFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsStencilFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsIEEE754Format(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsFloatFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsHalfFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsUnsignedFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsSignedFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsNormFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsUNormFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsSNormFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsIntegerFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsUIntFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsSIntFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsXRFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsDXTCFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsRGTCFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsBPTCFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsBCFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsPVRTCFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsETCFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsEACFormat(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern bool IsASTCFormat(GraphicsFormat format); public static bool IsCrunchFormat(TextureFormat format) { return format == TextureFormat.DXT1Crunched || format == TextureFormat.DXT5Crunched || format == TextureFormat.ETC_RGB4Crunched || format == TextureFormat.ETC2_RGBA8Crunched; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern FormatSwizzle GetSwizzleR(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern FormatSwizzle GetSwizzleG(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern FormatSwizzle GetSwizzleB(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern FormatSwizzle GetSwizzleA(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern uint GetBlockSize(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern uint GetBlockWidth(GraphicsFormat format); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern uint GetBlockHeight(GraphicsFormat format); public static uint ComputeMipmapSize(int width, int height, GraphicsFormat format) { return ComputeMipmapSize_Native_2D(width, height, format); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern uint ComputeMipmapSize_Native_2D(int width, int height, GraphicsFormat format); public static uint ComputeMipmapSize(int width, int height, int depth, GraphicsFormat format) { return ComputeMipmapSize_Native_3D(width, height, depth, format); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] private static extern uint ComputeMipmapSize_Native_3D(int width, int height, int depth, GraphicsFormat format); } [NativeHeader("Runtime/Shaders/RayTracingAccelerationStructure.h")] [NativeHeader("Runtime/Export/Graphics/RayTracingAccelerationStructure.bindings.h")] [UsedByNativeCode] [Flags] public enum RayTracingSubMeshFlags { Disabled = 0, Enabled = 1, ClosestHitOnly = 2, UniqueAnyHitCalls = 4 } public sealed class RayTracingAccelerationStructure : IDisposable { [Flags] public enum RayTracingModeMask { Nothing = 0, Static = 2, DynamicTransform = 4, DynamicGeometry = 8, Everything = 0xE } public enum ManagementMode { Manual, Automatic } public struct RASSettings { public ManagementMode managementMode; public RayTracingModeMask rayTracingModeMask; public int layerMask; public RASSettings(ManagementMode sceneManagementMode, RayTracingModeMask rayTracingModeMask, int layerMask) { managementMode = sceneManagementMode; this.rayTracingModeMask = rayTracingModeMask; this.layerMask = layerMask; } } internal IntPtr m_Ptr; ~RayTracingAccelerationStructure() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposing) { Destroy(this); } m_Ptr = IntPtr.Zero; } public RayTracingAccelerationStructure(RASSettings settings) { m_Ptr = Create(settings); } public RayTracingAccelerationStructure() { m_Ptr = Create(new RASSettings { rayTracingModeMask = RayTracingModeMask.Everything, managementMode = ManagementMode.Manual, layerMask = -1 }); } [FreeFunction("RayTracingAccelerationStructure_Bindings::Create")] private static IntPtr Create(RASSettings desc) { return Create_Injected(ref desc); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("RayTracingAccelerationStructure_Bindings::Destroy")] private static extern void Destroy(RayTracingAccelerationStructure accelStruct); public void Release() { Dispose(); } public void Build() { Build(Vector3.zero); } [Obsolete("Method Update has been deprecated. Use Build instead (UnityUpgradable) -> Build()", true)] public void Update() { Build(Vector3.zero); } [FreeFunction(Name = "RayTracingAccelerationStructure_Bindings::Build", HasExplicitThis = true)] public void Build(Vector3 relativeOrigin) { Build_Injected(ref relativeOrigin); } [FreeFunction(Name = "RayTracingAccelerationStructure_Bindings::Update", HasExplicitThis = true)] [Obsolete("Method Update has been deprecated. Use Build instead (UnityUpgradable) -> Build(*)", true)] public void Update(Vector3 relativeOrigin) { Update_Injected(ref relativeOrigin); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingAccelerationStructure_Bindings::AddInstanceDeprecated", HasExplicitThis = true)] public extern void AddInstance([NotNull("ArgumentNullException")] Renderer targetRenderer, bool[] subMeshMask = null, bool[] subMeshTransparencyFlags = null, bool enableTriangleCulling = true, bool frontTriangleCounterClockwise = false, uint mask = 255u, uint id = uint.MaxValue); public void AddInstance(Renderer targetRenderer, RayTracingSubMeshFlags[] subMeshFlags, bool enableTriangleCulling = true, bool frontTriangleCounterClockwise = false, uint mask = 255u, uint id = uint.MaxValue) { AddInstanceSubMeshFlagsArray(targetRenderer, subMeshFlags, enableTriangleCulling, frontTriangleCounterClockwise, mask, id); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingAccelerationStructure_Bindings::RemoveInstance", HasExplicitThis = true)] public extern void RemoveInstance([NotNull("ArgumentNullException")] Renderer targetRenderer); public void AddInstance(GraphicsBuffer aabbBuffer, uint numElements, Material material, bool isCutOff, bool enableTriangleCulling = true, bool frontTriangleCounterClockwise = false, uint mask = 255u, bool reuseBounds = false, uint id = uint.MaxValue) { AddInstance_Procedural(aabbBuffer, numElements, material, Matrix4x4.identity, isCutOff, enableTriangleCulling, frontTriangleCounterClockwise, mask, reuseBounds, id); } public void AddInstance(GraphicsBuffer aabbBuffer, uint numElements, Material material, Matrix4x4 instanceTransform, bool isCutOff, bool enableTriangleCulling = true, bool frontTriangleCounterClockwise = false, uint mask = 255u, bool reuseBounds = false, uint id = uint.MaxValue) { AddInstance_Procedural(aabbBuffer, numElements, material, instanceTransform, isCutOff, enableTriangleCulling, frontTriangleCounterClockwise, mask, reuseBounds, id); } [FreeFunction(Name = "RayTracingAccelerationStructure_Bindings::AddInstance", HasExplicitThis = true)] private void AddInstance_Procedural([NotNull("ArgumentNullException")] GraphicsBuffer aabbBuffer, uint numElements, [NotNull("ArgumentNullException")] Material material, Matrix4x4 instanceTransform, bool isCutOff, bool enableTriangleCulling = true, bool frontTriangleCounterClockwise = false, uint mask = 255u, bool reuseBounds = false, uint id = uint.MaxValue) { AddInstance_Procedural_Injected(aabbBuffer, numElements, material, ref instanceTransform, isCutOff, enableTriangleCulling, frontTriangleCounterClockwise, mask, reuseBounds, id); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingAccelerationStructure_Bindings::UpdateInstanceTransform", HasExplicitThis = true)] public extern void UpdateInstanceTransform([NotNull("ArgumentNullException")] Renderer renderer); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingAccelerationStructure_Bindings::UpdateInstanceMask", HasExplicitThis = true)] public extern void UpdateInstanceMask([NotNull("ArgumentNullException")] Renderer renderer, uint mask); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingAccelerationStructure_Bindings::UpdateInstanceID", HasExplicitThis = true)] public extern void UpdateInstanceID([NotNull("ArgumentNullException")] Renderer renderer, uint instanceID); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingAccelerationStructure_Bindings::GetSize", HasExplicitThis = true)] public extern ulong GetSize(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingAccelerationStructure_Bindings::GetInstanceCount", HasExplicitThis = true)] public extern uint GetInstanceCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingAccelerationStructure_Bindings::AddInstanceSubMeshFlagsArray", HasExplicitThis = true)] private extern void AddInstanceSubMeshFlagsArray([NotNull("ArgumentNullException")] Renderer targetRenderer, RayTracingSubMeshFlags[] subMeshFlags, bool enableTriangleCulling = true, bool frontTriangleCounterClockwise = false, uint mask = 255u, uint id = uint.MaxValue); [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr Create_Injected(ref RASSettings desc); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Build_Injected(ref Vector3 relativeOrigin); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Update_Injected(ref Vector3 relativeOrigin); [MethodImpl(MethodImplOptions.InternalCall)] private extern void AddInstance_Procedural_Injected(GraphicsBuffer aabbBuffer, uint numElements, Material material, ref Matrix4x4 instanceTransform, bool isCutOff, bool enableTriangleCulling = true, bool frontTriangleCounterClockwise = false, uint mask = 255u, bool reuseBounds = false, uint id = uint.MaxValue); } public struct ShaderWarmupSetup { public VertexAttributeDescriptor[] vdecl; } [NativeHeader("Runtime/Graphics/ShaderScriptBindings.h")] public static class ShaderWarmup { [FreeFunction(Name = "ShaderWarmupScripting::WarmupShader")] public static void WarmupShader(Shader shader, ShaderWarmupSetup setup) { WarmupShader_Injected(shader, ref setup); } [FreeFunction(Name = "ShaderWarmupScripting::WarmupShaderFromCollection")] public static void WarmupShaderFromCollection(ShaderVariantCollection collection, Shader shader, ShaderWarmupSetup setup) { WarmupShaderFromCollection_Injected(collection, shader, ref setup); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void WarmupShader_Injected(Shader shader, ref ShaderWarmupSetup setup); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void WarmupShaderFromCollection_Injected(ShaderVariantCollection collection, Shader shader, ref ShaderWarmupSetup setup); } [NativeHeader("Runtime/Graphics/ShaderScriptBindings.h")] [NativeHeader("Runtime/Shaders/RayTracingAccelerationStructure.h")] [NativeHeader("Runtime/Shaders/RayTracingShader.h")] public sealed class RayTracingShader : Object { public extern float maxRecursionDepth { [MethodImpl(MethodImplOptions.InternalCall)] get; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingShaderScripting::SetFloat", HasExplicitThis = true)] public extern void SetFloat(int nameID, float val); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingShaderScripting::SetInt", HasExplicitThis = true)] public extern void SetInt(int nameID, int val); [FreeFunction(Name = "RayTracingShaderScripting::SetVector", HasExplicitThis = true)] public void SetVector(int nameID, Vector4 val) { SetVector_Injected(nameID, ref val); } [FreeFunction(Name = "RayTracingShaderScripting::SetMatrix", HasExplicitThis = true)] public void SetMatrix(int nameID, Matrix4x4 val) { SetMatrix_Injected(nameID, ref val); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingShaderScripting::SetFloatArray", HasExplicitThis = true)] private extern void SetFloatArray(int nameID, float[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingShaderScripting::SetIntArray", HasExplicitThis = true)] private extern void SetIntArray(int nameID, int[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingShaderScripting::SetVectorArray", HasExplicitThis = true)] public extern void SetVectorArray(int nameID, Vector4[] values); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingShaderScripting::SetMatrixArray", HasExplicitThis = true)] public extern void SetMatrixArray(int nameID, Matrix4x4[] values); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "RayTracingShaderScripting::SetTexture", HasExplicitThis = true, IsFreeFunction = true)] public extern void SetTexture(int nameID, [NotNull("ArgumentNullException")] Texture texture); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "RayTracingShaderScripting::SetBuffer", HasExplicitThis = true, IsFreeFunction = true)] public extern void SetBuffer(int nameID, [NotNull("ArgumentNullException")] ComputeBuffer buffer); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "RayTracingShaderScripting::SetBuffer", HasExplicitThis = true, IsFreeFunction = true)] private extern void SetGraphicsBuffer(int nameID, [NotNull("ArgumentNullException")] GraphicsBuffer buffer); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingShaderScripting::SetConstantBuffer", HasExplicitThis = true)] private extern void SetConstantComputeBuffer(int nameID, [NotNull("ArgumentNullException")] ComputeBuffer buffer, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(Name = "RayTracingShaderScripting::SetConstantBuffer", HasExplicitThis = true)] private extern void SetConstantGraphicsBuffer(int nameID, [NotNull("ArgumentNullException")] GraphicsBuffer buffer, int offset, int size); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "RayTracingShaderScripting::SetAccelerationStructure", HasExplicitThis = true, IsFreeFunction = true)] public extern void SetAccelerationStructure(int nameID, [NotNull("ArgumentNullException")] RayTracingAccelerationStructure accelerationStructure); [MethodImpl(MethodImplOptions.InternalCall)] public extern void SetShaderPass(string passName); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(Name = "RayTracingShaderScripting::SetTextureFromGlobal", HasExplicitThis = true, IsFreeFunction = true)] public extern void SetTextureFromGlobal(int nameID, int globalTextureNameID); [MethodImpl(MethodImplOptions.InternalCall)] [NativeName("DispatchRays")] public extern void Dispatch(string rayGenFunctionName, int width, int height, int depth, Camera camera = null); public void SetBuffer(int nameID, GraphicsBuffer buffer) { SetGraphicsBuffer(nameID, buffer); } private RayTracingShader() { } public void SetFloat(string name, float val) { SetFloat(Shader.PropertyToID(name), val); } public void SetInt(string name, int val) { SetInt(Shader.PropertyToID(name), val); } public void SetVector(string name, Vector4 val) { SetVector(Shader.PropertyToID(name), val); } public void SetMatrix(string name, Matrix4x4 val) { SetMatrix(Shader.PropertyToID(name), val); } public void SetVectorArray(string name, Vector4[] values) { SetVectorArray(Shader.PropertyToID(name), values); } public void SetMatrixArray(string name, Matrix4x4[] values) { SetMatrixArray(Shader.PropertyToID(name), values); } public void SetFloats(string name, params float[] values) { SetFloatArray(Shader.PropertyToID(name), values); } public void SetFloats(int nameID, params float[] values) { SetFloatArray(nameID, values); } public void SetInts(string name, params int[] values) { SetIntArray(Shader.PropertyToID(name), values); } public void SetInts(int nameID, params int[] values) { SetIntArray(nameID, values); } public void SetBool(string name, bool val) { SetInt(Shader.PropertyToID(name), val ? 1 : 0); } public void SetBool(int nameID, bool val) { SetInt(nameID, val ? 1 : 0); } public void SetTexture(string name, Texture texture) { SetTexture(Shader.PropertyToID(name), texture); } public void SetBuffer(string name, ComputeBuffer buffer) { SetBuffer(Shader.PropertyToID(name), buffer); } public void SetBuffer(string name, GraphicsBuffer buffer) { SetBuffer(Shader.PropertyToID(name), buffer); } public void SetConstantBuffer(int nameID, ComputeBuffer buffer, int offset, int size) { SetConstantComputeBuffer(nameID, buffer, offset, size); } public void SetConstantBuffer(string name, ComputeBuffer buffer, int offset, int size) { SetConstantComputeBuffer(Shader.PropertyToID(name), buffer, offset, size); } public void SetConstantBuffer(int nameID, GraphicsBuffer buffer, int offset, int size) { SetConstantGraphicsBuffer(nameID, buffer, offset, size); } public void SetConstantBuffer(string name, GraphicsBuffer buffer, int offset, int size) { SetConstantGraphicsBuffer(Shader.PropertyToID(name), buffer, offset, size); } public void SetAccelerationStructure(string name, RayTracingAccelerationStructure accelerationStructure) { SetAccelerationStructure(Shader.PropertyToID(name), accelerationStructure); } public void SetTextureFromGlobal(string name, string globalTextureName) { SetTextureFromGlobal(Shader.PropertyToID(name), Shader.PropertyToID(globalTextureName)); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetVector_Injected(int nameID, ref Vector4 val); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetMatrix_Injected(int nameID, ref Matrix4x4 val); } } namespace UnityEngine.Assertions { [DebuggerStepThrough] public static class Assert { internal const string UNITY_ASSERTIONS = "UNITY_ASSERTIONS"; [Obsolete("Future versions of Unity are expected to always throw exceptions and not have this field.")] public static bool raiseExceptions = true; private static void Fail(string message, string userMessage) { if (!raiseExceptions) { if (message == null) { message = "Assertion has failed\n"; } if (userMessage != null) { message = userMessage + "\n" + message; } Debug.LogAssertion(message); return; } throw new AssertionException(message, userMessage); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Assert.Equals should not be used for Assertions", true)] public new static bool Equals(object obj1, object obj2) { throw new InvalidOperationException("Assert.Equals should not be used for Assertions"); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Assert.ReferenceEquals should not be used for Assertions", true)] public new static bool ReferenceEquals(object obj1, object obj2) { throw new InvalidOperationException("Assert.ReferenceEquals should not be used for Assertions"); } [Conditional("UNITY_ASSERTIONS")] public static void IsTrue(bool condition) { if (!condition) { IsTrue(condition, null); } } [Conditional("UNITY_ASSERTIONS")] public static void IsTrue(bool condition, string message) { if (!condition) { Fail(AssertionMessageUtil.BooleanFailureMessage(expected: true), message); } } [Conditional("UNITY_ASSERTIONS")] public static void IsFalse(bool condition) { if (condition) { IsFalse(condition, null); } } [Conditional("UNITY_ASSERTIONS")] public static void IsFalse(bool condition, string message) { if (condition) { Fail(AssertionMessageUtil.BooleanFailureMessage(expected: false), message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreApproximatelyEqual(float expected, float actual) { AreEqual(expected, actual, null, FloatComparer.s_ComparerWithDefaultTolerance); } [Conditional("UNITY_ASSERTIONS")] public static void AreApproximatelyEqual(float expected, float actual, string message) { AreEqual(expected, actual, message, FloatComparer.s_ComparerWithDefaultTolerance); } [Conditional("UNITY_ASSERTIONS")] public static void AreApproximatelyEqual(float expected, float actual, float tolerance) { AreApproximatelyEqual(expected, actual, tolerance, null); } [Conditional("UNITY_ASSERTIONS")] public static void AreApproximatelyEqual(float expected, float actual, float tolerance, string message) { AreEqual(expected, actual, message, new FloatComparer(tolerance)); } [Conditional("UNITY_ASSERTIONS")] public static void AreNotApproximatelyEqual(float expected, float actual) { AreNotEqual(expected, actual, null, FloatComparer.s_ComparerWithDefaultTolerance); } [Conditional("UNITY_ASSERTIONS")] public static void AreNotApproximatelyEqual(float expected, float actual, string message) { AreNotEqual(expected, actual, message, FloatComparer.s_ComparerWithDefaultTolerance); } [Conditional("UNITY_ASSERTIONS")] public static void AreNotApproximatelyEqual(float expected, float actual, float tolerance) { AreNotApproximatelyEqual(expected, actual, tolerance, null); } [Conditional("UNITY_ASSERTIONS")] public static void AreNotApproximatelyEqual(float expected, float actual, float tolerance, string message) { AreNotEqual(expected, actual, message, new FloatComparer(tolerance)); } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(T expected, T actual) { AreEqual(expected, actual, null); } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(T expected, T actual, string message) { AreEqual(expected, actual, message, EqualityComparer.Default); } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(T expected, T actual, string message, IEqualityComparer comparer) { if (typeof(Object).IsAssignableFrom(typeof(T))) { AreEqual(expected as Object, actual as Object, message); } else if (!comparer.Equals(actual, expected)) { Fail(AssertionMessageUtil.GetEqualityMessage(actual, expected, expectEqual: true), message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(Object expected, Object actual, string message) { if (actual != expected) { Fail(AssertionMessageUtil.GetEqualityMessage(actual, expected, expectEqual: true), message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(T expected, T actual) { AreNotEqual(expected, actual, null); } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(T expected, T actual, string message) { AreNotEqual(expected, actual, message, EqualityComparer.Default); } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(T expected, T actual, string message, IEqualityComparer comparer) { if (typeof(Object).IsAssignableFrom(typeof(T))) { AreNotEqual(expected as Object, actual as Object, message); } else if (comparer.Equals(actual, expected)) { Fail(AssertionMessageUtil.GetEqualityMessage(actual, expected, expectEqual: false), message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(Object expected, Object actual, string message) { if (actual == expected) { Fail(AssertionMessageUtil.GetEqualityMessage(actual, expected, expectEqual: false), message); } } [Conditional("UNITY_ASSERTIONS")] public static void IsNull(T value) where T : class { IsNull(value, null); } [Conditional("UNITY_ASSERTIONS")] public static void IsNull(T value, string message) where T : class { if (typeof(Object).IsAssignableFrom(typeof(T))) { IsNull(value as Object, message); } else if (value != null) { Fail(AssertionMessageUtil.NullFailureMessage(value, expectNull: true), message); } } [Conditional("UNITY_ASSERTIONS")] public static void IsNull(Object value, string message) { if (value != null) { Fail(AssertionMessageUtil.NullFailureMessage(value, expectNull: true), message); } } [Conditional("UNITY_ASSERTIONS")] public static void IsNotNull(T value) where T : class { IsNotNull(value, null); } [Conditional("UNITY_ASSERTIONS")] public static void IsNotNull(T value, string message) where T : class { if (typeof(Object).IsAssignableFrom(typeof(T))) { IsNotNull(value as Object, message); } else if (value == null) { Fail(AssertionMessageUtil.NullFailureMessage(value, expectNull: false), message); } } [Conditional("UNITY_ASSERTIONS")] public static void IsNotNull(Object value, string message) { if (value == null) { Fail(AssertionMessageUtil.NullFailureMessage(value, expectNull: false), message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(sbyte expected, sbyte actual) { if (expected != actual) { Assert.AreEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(sbyte expected, sbyte actual, string message) { if (expected != actual) { Assert.AreEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(sbyte expected, sbyte actual) { if (expected == actual) { Assert.AreNotEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(sbyte expected, sbyte actual, string message) { if (expected == actual) { Assert.AreNotEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(byte expected, byte actual) { if (expected != actual) { Assert.AreEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(byte expected, byte actual, string message) { if (expected != actual) { Assert.AreEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(byte expected, byte actual) { if (expected == actual) { Assert.AreNotEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(byte expected, byte actual, string message) { if (expected == actual) { Assert.AreNotEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(char expected, char actual) { if (expected != actual) { Assert.AreEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(char expected, char actual, string message) { if (expected != actual) { Assert.AreEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(char expected, char actual) { if (expected == actual) { Assert.AreNotEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(char expected, char actual, string message) { if (expected == actual) { Assert.AreNotEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(short expected, short actual) { if (expected != actual) { Assert.AreEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(short expected, short actual, string message) { if (expected != actual) { Assert.AreEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(short expected, short actual) { if (expected == actual) { Assert.AreNotEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(short expected, short actual, string message) { if (expected == actual) { Assert.AreNotEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(ushort expected, ushort actual) { if (expected != actual) { Assert.AreEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(ushort expected, ushort actual, string message) { if (expected != actual) { Assert.AreEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(ushort expected, ushort actual) { if (expected == actual) { Assert.AreNotEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(ushort expected, ushort actual, string message) { if (expected == actual) { Assert.AreNotEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(int expected, int actual) { if (expected != actual) { Assert.AreEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(int expected, int actual, string message) { if (expected != actual) { Assert.AreEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(int expected, int actual) { if (expected == actual) { Assert.AreNotEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(int expected, int actual, string message) { if (expected == actual) { Assert.AreNotEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(uint expected, uint actual) { if (expected != actual) { Assert.AreEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(uint expected, uint actual, string message) { if (expected != actual) { Assert.AreEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(uint expected, uint actual) { if (expected == actual) { Assert.AreNotEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(uint expected, uint actual, string message) { if (expected == actual) { Assert.AreNotEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(long expected, long actual) { if (expected != actual) { Assert.AreEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(long expected, long actual, string message) { if (expected != actual) { Assert.AreEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(long expected, long actual) { if (expected == actual) { Assert.AreNotEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(long expected, long actual, string message) { if (expected == actual) { Assert.AreNotEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(ulong expected, ulong actual) { if (expected != actual) { Assert.AreEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreEqual(ulong expected, ulong actual, string message) { if (expected != actual) { Assert.AreEqual(expected, actual, message); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(ulong expected, ulong actual) { if (expected == actual) { Assert.AreNotEqual(expected, actual, (string)null); } } [Conditional("UNITY_ASSERTIONS")] public static void AreNotEqual(ulong expected, ulong actual, string message) { if (expected == actual) { Assert.AreNotEqual(expected, actual, message); } } } public class AssertionException : Exception { private string m_UserMessage; public override string Message { get { string text = base.Message; if (m_UserMessage != null) { text = m_UserMessage + "\n" + text; } return text; } } public AssertionException(string message, string userMessage) : base(message) { m_UserMessage = userMessage; } } internal class AssertionMessageUtil { private const string k_Expected = "Expected:"; private const string k_AssertionFailed = "Assertion failure."; public static string GetMessage(string failureMessage) { return UnityString.Format("{0} {1}", new object[2] { "Assertion failure.", failureMessage }); } public static string GetMessage(string failureMessage, string expected) { return GetMessage(UnityString.Format("{0}{1}{2} {3}", new object[4] { failureMessage, Environment.NewLine, "Expected:", expected })); } public static string GetEqualityMessage(object actual, object expected, bool expectEqual) { return GetMessage(UnityString.Format("Values are {0}equal.", new object[1] { expectEqual ? "not " : "" }), UnityString.Format("{0} {2} {1}", new object[3] { actual, expected, expectEqual ? "==" : "!=" })); } public static string NullFailureMessage(object value, bool expectNull) { return GetMessage(UnityString.Format("Value was {0}Null", new object[1] { expectNull ? "not " : "" }), UnityString.Format("Value was {0}Null", new object[1] { expectNull ? "" : "not " })); } public static string BooleanFailureMessage(bool expected) { return GetMessage("Value was " + !expected, expected.ToString()); } } } namespace UnityEngine.Assertions.Must { [DebuggerStepThrough] [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] public static class MustExtensions { [Conditional("UNITY_ASSERTIONS")] [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] public static void MustBeTrue(this bool value) { Assert.IsTrue(value); } [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] [Conditional("UNITY_ASSERTIONS")] public static void MustBeTrue(this bool value, string message) { Assert.IsTrue(value, message); } [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] [Conditional("UNITY_ASSERTIONS")] public static void MustBeFalse(this bool value) { Assert.IsFalse(value); } [Conditional("UNITY_ASSERTIONS")] [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] public static void MustBeFalse(this bool value, string message) { Assert.IsFalse(value, message); } [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] [Conditional("UNITY_ASSERTIONS")] public static void MustBeApproximatelyEqual(this float actual, float expected) { Assert.AreApproximatelyEqual(actual, expected); } [Conditional("UNITY_ASSERTIONS")] [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] public static void MustBeApproximatelyEqual(this float actual, float expected, string message) { Assert.AreApproximatelyEqual(actual, expected, message); } [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] [Conditional("UNITY_ASSERTIONS")] public static void MustBeApproximatelyEqual(this float actual, float expected, float tolerance) { Assert.AreApproximatelyEqual(actual, expected, tolerance); } [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] [Conditional("UNITY_ASSERTIONS")] public static void MustBeApproximatelyEqual(this float actual, float expected, float tolerance, string message) { Assert.AreApproximatelyEqual(expected, actual, tolerance, message); } [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] [Conditional("UNITY_ASSERTIONS")] public static void MustNotBeApproximatelyEqual(this float actual, float expected) { Assert.AreNotApproximatelyEqual(expected, actual); } [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] [Conditional("UNITY_ASSERTIONS")] public static void MustNotBeApproximatelyEqual(this float actual, float expected, string message) { Assert.AreNotApproximatelyEqual(expected, actual, message); } [Conditional("UNITY_ASSERTIONS")] [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] public static void MustNotBeApproximatelyEqual(this float actual, float expected, float tolerance) { Assert.AreNotApproximatelyEqual(expected, actual, tolerance); } [Conditional("UNITY_ASSERTIONS")] [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] public static void MustNotBeApproximatelyEqual(this float actual, float expected, float tolerance, string message) { Assert.AreNotApproximatelyEqual(expected, actual, tolerance, message); } [Conditional("UNITY_ASSERTIONS")] [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] public static void MustBeEqual(this T actual, T expected) { Assert.AreEqual(actual, expected); } [Conditional("UNITY_ASSERTIONS")] [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] public static void MustBeEqual(this T actual, T expected, string message) { Assert.AreEqual(expected, actual, message); } [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] [Conditional("UNITY_ASSERTIONS")] public static void MustNotBeEqual(this T actual, T expected) { Assert.AreNotEqual(actual, expected); } [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] [Conditional("UNITY_ASSERTIONS")] public static void MustNotBeEqual(this T actual, T expected, string message) { Assert.AreNotEqual(expected, actual, message); } [Conditional("UNITY_ASSERTIONS")] [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] public static void MustBeNull(this T expected) where T : class { Assert.IsNull(expected); } [Conditional("UNITY_ASSERTIONS")] [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] public static void MustBeNull(this T expected, string message) where T : class { Assert.IsNull(expected, message); } [Conditional("UNITY_ASSERTIONS")] [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] public static void MustNotBeNull(this T expected) where T : class { Assert.IsNotNull(expected); } [Conditional("UNITY_ASSERTIONS")] [Obsolete("Must extensions are deprecated. Use UnityEngine.Assertions.Assert instead")] public static void MustNotBeNull(this T expected, string message) where T : class { Assert.IsNotNull(expected, message); } } } namespace UnityEngine.Assertions.Comparers { public class FloatComparer : IEqualityComparer { private readonly float m_Error; private readonly bool m_Relative; public static readonly FloatComparer s_ComparerWithDefaultTolerance = new FloatComparer(1E-05f); public const float kEpsilon = 1E-05f; public FloatComparer() : this(1E-05f, relative: false) { } public FloatComparer(bool relative) : this(1E-05f, relative) { } public FloatComparer(float error) : this(error, relative: false) { } public FloatComparer(float error, bool relative) { m_Error = error; m_Relative = relative; } public bool Equals(float a, float b) { return m_Relative ? AreEqualRelative(a, b, m_Error) : AreEqual(a, b, m_Error); } public int GetHashCode(float obj) { return base.GetHashCode(); } public static bool AreEqual(float expected, float actual, float error) { return Math.Abs(actual - expected) <= error; } public static bool AreEqualRelative(float expected, float actual, float error) { if (expected == actual) { return true; } float num = Math.Abs(expected); float num2 = Math.Abs(actual); float num3 = Math.Abs((actual - expected) / ((num > num2) ? num : num2)); return num3 <= error; } } } namespace UnityEngine.Apple { [NativeHeader("Runtime/Export/Apple/FrameCaptureMetalScriptBindings.h")] public enum FrameCaptureDestination { DevTools = 1, GPUTraceDocument } [NativeHeader("Runtime/Export/Apple/FrameCaptureMetalScriptBindings.h")] [NativeConditional("PLATFORM_IOS || PLATFORM_TVOS || PLATFORM_OSX")] public class FrameCapture { private FrameCapture() { } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("FrameCaptureMetalScripting::IsDestinationSupported")] private static extern bool IsDestinationSupportedImpl(FrameCaptureDestination dest); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("FrameCaptureMetalScripting::BeginCapture")] private static extern void BeginCaptureImpl(FrameCaptureDestination dest, string path); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("FrameCaptureMetalScripting::EndCapture")] private static extern void EndCaptureImpl(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("FrameCaptureMetalScripting::CaptureNextFrame")] private static extern void CaptureNextFrameImpl(FrameCaptureDestination dest, string path); public static bool IsDestinationSupported(FrameCaptureDestination dest) { if (dest != FrameCaptureDestination.DevTools && dest != FrameCaptureDestination.GPUTraceDocument) { throw new ArgumentException("dest", "Argument dest has bad value (not one of FrameCaptureDestination enum values)"); } return IsDestinationSupportedImpl(dest); } public static void BeginCaptureToXcode() { if (!IsDestinationSupported(FrameCaptureDestination.DevTools)) { throw new InvalidOperationException("Frame Capture with DevTools is not supported."); } BeginCaptureImpl(FrameCaptureDestination.DevTools, null); } public static void BeginCaptureToFile(string path) { if (!IsDestinationSupported(FrameCaptureDestination.GPUTraceDocument)) { throw new InvalidOperationException("Frame Capture to file is not supported."); } if (string.IsNullOrEmpty(path)) { throw new ArgumentException("path", "Path must be supplied when capture destination is GPUTraceDocument."); } if (Path.GetExtension(path) != ".gputrace") { throw new ArgumentException("path", "Destination file should have .gputrace extension."); } BeginCaptureImpl(FrameCaptureDestination.GPUTraceDocument, new Uri(path).AbsoluteUri); } public static void EndCapture() { EndCaptureImpl(); } public static void CaptureNextFrameToXcode() { if (!IsDestinationSupported(FrameCaptureDestination.DevTools)) { throw new InvalidOperationException("Frame Capture with DevTools is not supported."); } CaptureNextFrameImpl(FrameCaptureDestination.DevTools, null); } public static void CaptureNextFrameToFile(string path) { if (!IsDestinationSupported(FrameCaptureDestination.GPUTraceDocument)) { throw new InvalidOperationException("Frame Capture to file is not supported."); } if (string.IsNullOrEmpty(path)) { throw new ArgumentException("path", "Path must be supplied when capture destination is GPUTraceDocument."); } if (Path.GetExtension(path) != ".gputrace") { throw new ArgumentException("path", "Destination file should have .gputrace extension."); } CaptureNextFrameImpl(FrameCaptureDestination.GPUTraceDocument, new Uri(path).AbsoluteUri); } } } namespace UnityEngine.TestTools { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method)] [UsedByNativeCode] public class ExcludeFromCoverageAttribute : Attribute { } [NativeType(/*Could not decode attribute arguments.*/)] public struct CoveredSequencePoint { public MethodBase method; public uint ilOffset; public uint hitCount; public string filename; public uint line; public uint column; } [NativeType(/*Could not decode attribute arguments.*/)] public struct CoveredMethodStats { public MethodBase method; public int totalSequencePoints; public int uncoveredSequencePoints; private string GetTypeDisplayName(Type t) { if ((object)t == typeof(int)) { return "int"; } if ((object)t == typeof(bool)) { return "bool"; } if ((object)t == typeof(float)) { return "float"; } if ((object)t == typeof(double)) { return "double"; } if ((object)t == typeof(void)) { return "void"; } if ((object)t == typeof(string)) { return "string"; } if (t.IsGenericType && (object)t.GetGenericTypeDefinition() == typeof(List<>)) { return "System.Collections.Generic.List<" + GetTypeDisplayName(t.GetGenericArguments()[0]) + ">"; } if (t.IsArray && t.GetArrayRank() == 1) { return GetTypeDisplayName(t.GetElementType()) + "[]"; } return t.FullName; } public override string ToString() { if ((object)method == null) { return ""; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(GetTypeDisplayName(method.DeclaringType)); stringBuilder.Append("."); stringBuilder.Append(method.Name); stringBuilder.Append("("); bool flag = false; ParameterInfo[] parameters = method.GetParameters(); foreach (ParameterInfo parameterInfo in parameters) { if (flag) { stringBuilder.Append(", "); } stringBuilder.Append(GetTypeDisplayName(parameterInfo.ParameterType)); stringBuilder.Append(" "); stringBuilder.Append(parameterInfo.Name); flag = true; } stringBuilder.Append(")"); return stringBuilder.ToString(); } } [NativeType("Runtime/Scripting/ScriptingCoverage.h")] [NativeClass("ScriptingCoverage")] public static class Coverage { public static extern bool enabled { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingCoverageGetCoverageForMethodInfoObject", ThrowsException = true)] private static extern CoveredSequencePoint[] GetSequencePointsFor_Internal(MethodBase method); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingCoverageResetForMethodInfoObject", ThrowsException = true)] private static extern void ResetFor_Internal(MethodBase method); [FreeFunction("ScriptingCoverageGetStatsForMethodInfoObject", ThrowsException = true)] private static CoveredMethodStats GetStatsFor_Internal(MethodBase method) { GetStatsFor_Internal_Injected(method, out var ret); return ret; } public static CoveredSequencePoint[] GetSequencePointsFor(MethodBase method) { if ((object)method == null) { throw new ArgumentNullException("method"); } return GetSequencePointsFor_Internal(method); } public static CoveredMethodStats GetStatsFor(MethodBase method) { if ((object)method == null) { throw new ArgumentNullException("method"); } return GetStatsFor_Internal(method); } public static CoveredMethodStats[] GetStatsFor(MethodBase[] methods) { if (methods == null) { throw new ArgumentNullException("methods"); } CoveredMethodStats[] array = new CoveredMethodStats[methods.Length]; for (int i = 0; i < methods.Length; i++) { array[i] = GetStatsFor(methods[i]); } return array; } public static CoveredMethodStats[] GetStatsFor(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } return GetStatsFor(type.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).OfType().ToArray()); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingCoverageGetStatsForAllCoveredMethodsFromScripting", ThrowsException = true)] public static extern CoveredMethodStats[] GetStatsForAllCoveredMethods(); public static void ResetFor(MethodBase method) { if ((object)method == null) { throw new ArgumentNullException("method"); } ResetFor_Internal(method); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("ScriptingCoverageResetAllFromScripting", ThrowsException = true)] public static extern void ResetAll(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetStatsFor_Internal_Injected(MethodBase method, out CoveredMethodStats ret); } }